pilotswarm-web 0.1.0

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.
Files changed (57) hide show
  1. package/README.md +144 -0
  2. package/auth/authz/engine.js +139 -0
  3. package/auth/config.js +110 -0
  4. package/auth/index.js +153 -0
  5. package/auth/normalize/entra.js +22 -0
  6. package/auth/providers/entra.js +76 -0
  7. package/auth/providers/none.js +24 -0
  8. package/auth.js +10 -0
  9. package/bin/serve.js +53 -0
  10. package/config.js +20 -0
  11. package/dist/app.js +469 -0
  12. package/dist/assets/index-BSVg-lGb.css +1 -0
  13. package/dist/assets/index-BXD5YP7A.js +24 -0
  14. package/dist/assets/msal-CytV9RFv.js +7 -0
  15. package/dist/assets/pilotswarm-WX3NED6m.js +40 -0
  16. package/dist/assets/react-jg0oazEi.js +1 -0
  17. package/dist/index.html +16 -0
  18. package/node_modules/pilotswarm-ui-core/README.md +6 -0
  19. package/node_modules/pilotswarm-ui-core/package.json +32 -0
  20. package/node_modules/pilotswarm-ui-core/src/commands.js +72 -0
  21. package/node_modules/pilotswarm-ui-core/src/context-usage.js +212 -0
  22. package/node_modules/pilotswarm-ui-core/src/controller.js +3613 -0
  23. package/node_modules/pilotswarm-ui-core/src/formatting.js +872 -0
  24. package/node_modules/pilotswarm-ui-core/src/history.js +571 -0
  25. package/node_modules/pilotswarm-ui-core/src/index.js +13 -0
  26. package/node_modules/pilotswarm-ui-core/src/layout.js +196 -0
  27. package/node_modules/pilotswarm-ui-core/src/reducer.js +1027 -0
  28. package/node_modules/pilotswarm-ui-core/src/selectors.js +2786 -0
  29. package/node_modules/pilotswarm-ui-core/src/session-tree.js +109 -0
  30. package/node_modules/pilotswarm-ui-core/src/state.js +80 -0
  31. package/node_modules/pilotswarm-ui-core/src/store.js +23 -0
  32. package/node_modules/pilotswarm-ui-core/src/system-titles.js +24 -0
  33. package/node_modules/pilotswarm-ui-core/src/themes/catppuccin-mocha.js +56 -0
  34. package/node_modules/pilotswarm-ui-core/src/themes/cobalt2.js +56 -0
  35. package/node_modules/pilotswarm-ui-core/src/themes/dark-high-contrast.js +56 -0
  36. package/node_modules/pilotswarm-ui-core/src/themes/dracula.js +56 -0
  37. package/node_modules/pilotswarm-ui-core/src/themes/github-dark.js +56 -0
  38. package/node_modules/pilotswarm-ui-core/src/themes/gruvbox-dark.js +56 -0
  39. package/node_modules/pilotswarm-ui-core/src/themes/hacker-x-matrix.js +56 -0
  40. package/node_modules/pilotswarm-ui-core/src/themes/hacker-x-orion-prime.js +56 -0
  41. package/node_modules/pilotswarm-ui-core/src/themes/helpers.js +77 -0
  42. package/node_modules/pilotswarm-ui-core/src/themes/index.js +42 -0
  43. package/node_modules/pilotswarm-ui-core/src/themes/noctis-viola.js +56 -0
  44. package/node_modules/pilotswarm-ui-core/src/themes/noctis.js +56 -0
  45. package/node_modules/pilotswarm-ui-core/src/themes/nord.js +56 -0
  46. package/node_modules/pilotswarm-ui-core/src/themes/solarized-dark.js +56 -0
  47. package/node_modules/pilotswarm-ui-core/src/themes/tokyo-night.js +56 -0
  48. package/node_modules/pilotswarm-ui-react/README.md +5 -0
  49. package/node_modules/pilotswarm-ui-react/package.json +36 -0
  50. package/node_modules/pilotswarm-ui-react/src/components.js +1316 -0
  51. package/node_modules/pilotswarm-ui-react/src/index.js +4 -0
  52. package/node_modules/pilotswarm-ui-react/src/platform.js +15 -0
  53. package/node_modules/pilotswarm-ui-react/src/use-controller-state.js +38 -0
  54. package/node_modules/pilotswarm-ui-react/src/web-app.js +2661 -0
  55. package/package.json +64 -0
  56. package/runtime.js +146 -0
  57. package/server.js +311 -0
@@ -0,0 +1,40 @@
1
+ function Yn(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ct={exports:{}},k={};var is;function Xn(){if(is)return k;is=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),i=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"),f=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),h=Symbol.iterator;function m(p){return p===null||typeof p!="object"?null:(p=h&&p[h]||p["@@iterator"],typeof p=="function"?p:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},w=Object.assign,x={};function b(p,I,C){this.props=p,this.context=I,this.refs=x,this.updater=C||g}b.prototype.isReactComponent={},b.prototype.setState=function(p,I){if(typeof p!="object"&&typeof p!="function"&&p!=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,p,I,"setState")},b.prototype.forceUpdate=function(p){this.updater.enqueueForceUpdate(this,p,"forceUpdate")};function v(){}v.prototype=b.prototype;function M(p,I,C){this.props=p,this.context=I,this.refs=x,this.updater=C||g}var E=M.prototype=new v;E.constructor=M,w(E,b.prototype),E.isPureReactComponent=!0;var O=Array.isArray;function H(){}var P={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function K(p,I,C){var A=C.ref;return{$$typeof:t,type:p,key:I,ref:A!==void 0?A:null,props:C}}function B(p,I){return K(p.type,I,p.props)}function W(p){return typeof p=="object"&&p!==null&&p.$$typeof===t}function Ne(p){var I={"=":"=0",":":"=2"};return"$"+p.replace(/[=:]/g,function(C){return I[C]})}var re=/\/+/g;function _(p,I){return typeof p=="object"&&p!==null&&p.key!=null?Ne(""+p.key):I.toString(36)}function Ie(p){switch(p.status){case"fulfilled":return p.value;case"rejected":throw p.reason;default:switch(typeof p.status=="string"?p.then(H,H):(p.status="pending",p.then(function(I){p.status==="pending"&&(p.status="fulfilled",p.value=I)},function(I){p.status==="pending"&&(p.status="rejected",p.reason=I)})),p.status){case"fulfilled":return p.value;case"rejected":throw p.reason}}throw p}function se(p,I,C,A,N){var L=typeof p;(L==="undefined"||L==="boolean")&&(p=null);var F=!1;if(p===null)F=!0;else switch(L){case"bigint":case"string":case"number":F=!0;break;case"object":switch(p.$$typeof){case t:case e:F=!0;break;case f:return F=p._init,se(F(p._payload),I,C,A,N)}}if(F)return N=N(p),F=A===""?"."+_(p,0):A,O(N)?(C="",F!=null&&(C=F.replace(re,"$&/")+"/"),se(N,I,C,"",function(Kn){return Kn})):N!=null&&(W(N)&&(N=B(N,C+(N.key==null||p&&p.key===N.key?"":(""+N.key).replace(re,"$&/")+"/")+F)),I.push(N)),1;F=0;var J=A===""?".":A+":";if(O(p))for(var q=0;q<p.length;q++)A=p[q],L=J+_(A,q),F+=se(A,I,C,L,N);else if(q=m(p),typeof q=="function")for(p=q.call(p),q=0;!(A=p.next()).done;)A=A.value,L=J+_(A,q++),F+=se(A,I,C,L,N);else if(L==="object"){if(typeof p.then=="function")return se(Ie(p),I,C,A,N);throw I=String(p),Error("Objects are not valid as a React child (found: "+(I==="[object Object]"?"object with keys {"+Object.keys(p).join(", ")+"}":I)+"). If you meant to render a collection of children, use an array instead.")}return F}function je(p,I,C){if(p==null)return p;var A=[],N=0;return se(p,A,"","",function(L){return I.call(C,L,N++)}),A}function zn(p){if(p._status===-1){var I=p._result;I=I(),I.then(function(C){(p._status===0||p._status===-1)&&(p._status=1,p._result=C)},function(C){(p._status===0||p._status===-1)&&(p._status=2,p._result=C)}),p._status===-1&&(p._status=0,p._result=I)}if(p._status===1)return p._result.default;throw p._result}var os=typeof reportError=="function"?reportError:function(p){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var I=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof p=="object"&&p!==null&&typeof p.message=="string"?String(p.message):String(p),error:p});if(!window.dispatchEvent(I))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",p);return}console.error(p)},Gn={map:je,forEach:function(p,I,C){je(p,function(){I.apply(this,arguments)},C)},count:function(p){var I=0;return je(p,function(){I++}),I},toArray:function(p){return je(p,function(I){return I})||[]},only:function(p){if(!W(p))throw Error("React.Children.only expected to receive a single React element child.");return p}};return k.Activity=d,k.Children=Gn,k.Component=b,k.Fragment=s,k.Profiler=o,k.PureComponent=M,k.StrictMode=n,k.Suspense=l,k.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=P,k.__COMPILER_RUNTIME={__proto__:null,c:function(p){return P.H.useMemoCache(p)}},k.cache=function(p){return function(){return p.apply(null,arguments)}},k.cacheSignal=function(){return null},k.cloneElement=function(p,I,C){if(p==null)throw Error("The argument must be a React element, but you passed "+p+".");var A=w({},p.props),N=p.key;if(I!=null)for(L in I.key!==void 0&&(N=""+I.key),I)!T.call(I,L)||L==="key"||L==="__self"||L==="__source"||L==="ref"&&I.ref===void 0||(A[L]=I[L]);var L=arguments.length-2;if(L===1)A.children=C;else if(1<L){for(var F=Array(L),J=0;J<L;J++)F[J]=arguments[J+2];A.children=F}return K(p.type,N,A)},k.createContext=function(p){return p={$$typeof:r,_currentValue:p,_currentValue2:p,_threadCount:0,Provider:null,Consumer:null},p.Provider=p,p.Consumer={$$typeof:i,_context:p},p},k.createElement=function(p,I,C){var A,N={},L=null;if(I!=null)for(A in I.key!==void 0&&(L=""+I.key),I)T.call(I,A)&&A!=="key"&&A!=="__self"&&A!=="__source"&&(N[A]=I[A]);var F=arguments.length-2;if(F===1)N.children=C;else if(1<F){for(var J=Array(F),q=0;q<F;q++)J[q]=arguments[q+2];N.children=J}if(p&&p.defaultProps)for(A in F=p.defaultProps,F)N[A]===void 0&&(N[A]=F[A]);return K(p,L,N)},k.createRef=function(){return{current:null}},k.forwardRef=function(p){return{$$typeof:a,render:p}},k.isValidElement=W,k.lazy=function(p){return{$$typeof:f,_payload:{_status:-1,_result:p},_init:zn}},k.memo=function(p,I){return{$$typeof:c,type:p,compare:I===void 0?null:I}},k.startTransition=function(p){var I=P.T,C={};P.T=C;try{var A=p(),N=P.S;N!==null&&N(C,A),typeof A=="object"&&A!==null&&typeof A.then=="function"&&A.then(H,os)}catch(L){os(L)}finally{I!==null&&C.types!==null&&(I.types=C.types),P.T=I}},k.unstable_useCacheRefresh=function(){return P.H.useCacheRefresh()},k.use=function(p){return P.H.use(p)},k.useActionState=function(p,I,C){return P.H.useActionState(p,I,C)},k.useCallback=function(p,I){return P.H.useCallback(p,I)},k.useContext=function(p){return P.H.useContext(p)},k.useDebugValue=function(){},k.useDeferredValue=function(p,I){return P.H.useDeferredValue(p,I)},k.useEffect=function(p,I){return P.H.useEffect(p,I)},k.useEffectEvent=function(p){return P.H.useEffectEvent(p)},k.useId=function(){return P.H.useId()},k.useImperativeHandle=function(p,I,C){return P.H.useImperativeHandle(p,I,C)},k.useInsertionEffect=function(p,I){return P.H.useInsertionEffect(p,I)},k.useLayoutEffect=function(p,I){return P.H.useLayoutEffect(p,I)},k.useMemo=function(p,I){return P.H.useMemo(p,I)},k.useOptimistic=function(p,I){return P.H.useOptimistic(p,I)},k.useReducer=function(p,I,C){return P.H.useReducer(p,I,C)},k.useRef=function(p){return P.H.useRef(p)},k.useState=function(p){return P.H.useState(p)},k.useSyncExternalStore=function(p,I,C){return P.H.useSyncExternalStore(p,I,C)},k.useTransition=function(){return P.H.useTransition()},k.version="19.2.4",k}var rs;function Qn(){return rs||(rs=1,ct.exports=Xn()),ct.exports}var Jn=Qn();const u=Yn(Jn),Zn=u.createContext(null);function te(){const t=u.useContext(Zn);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function R(t,e,s=Object.is){const n=u.useRef(e),o=u.useRef(s);n.current=e,o.current=s;const[i,r]=u.useState(()=>e(t.getState())),a=u.useRef(i);return u.useEffect(()=>{a.current=i},[i]),u.useEffect(()=>t.subscribe(l=>{const c=n.current(l);o.current(a.current,c)||(a.current=c,r(c))}),[t]),i}const S={SESSIONS:"sessions",CHAT:"chat",INSPECTOR:"inspector",ACTIVITY:"activity",PROMPT:"prompt"},ee=["sequence","logs","nodes","history","files"],y={REFRESH:"refresh",NEW_SESSION:"newSession",OPEN_MODEL_PICKER:"openModelPicker",OPEN_THEME_PICKER:"openThemePicker",OPEN_RENAME_SESSION:"openRenameSession",OPEN_ARTIFACT_UPLOAD:"openArtifactUpload",CLOSE_MODAL:"closeModal",MODAL_PREV:"modalPrev",MODAL_NEXT:"modalNext",MODAL_PANE_PREV:"modalPanePrev",MODAL_PANE_NEXT:"modalPaneNext",MODAL_CONFIRM:"modalConfirm",SEND_PROMPT:"sendPrompt",FOCUS_NEXT:"focusNext",FOCUS_PREV:"focusPrev",FOCUS_LEFT:"focusLeft",FOCUS_RIGHT:"focusRight",FOCUS_PROMPT:"focusPrompt",FOCUS_SESSIONS:"focusSessions",MOVE_SESSION_UP:"moveSessionUp",MOVE_SESSION_DOWN:"moveSessionDown",EXPAND_SESSION:"expandSession",COLLAPSE_SESSION:"collapseSession",NEXT_INSPECTOR_TAB:"nextInspectorTab",PREV_INSPECTOR_TAB:"prevInspectorTab",CYCLE_INSPECTOR_TAB:"cycleInspectorTab",GROW_LEFT_PANE:"growLeftPane",GROW_RIGHT_PANE:"growRightPane",GROW_SESSION_PANE:"growSessionPane",SHRINK_SESSION_PANE:"shrinkSessionPane",OPEN_ARTIFACT_PICKER:"openArtifactPicker",TOGGLE_LOG_TAIL:"toggleLogTail",OPEN_LOG_FILTER:"openLogFilter",OPEN_FILES_FILTER:"openFilesFilter",MOVE_FILE_UP:"moveFileUp",MOVE_FILE_DOWN:"moveFileDown",DOWNLOAD_SELECTED_FILE:"downloadSelectedFile",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",DELETE_SESSION:"deleteSession",OPEN_HISTORY_FORMAT:"openHistoryFormat",REFRESH_EXECUTION_HISTORY:"refreshExecutionHistory",EXPORT_EXECUTION_HISTORY:"exportExecutionHistory"};function Re(t,e,s){const n=t.indexOf(e),i=((n===-1?0:n)+s+t.length)%t.length;return t[i]}function $t(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 Tt(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 eo(t){const e=$t(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function to(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=$t(t);return e==null?null:{text:`ctx ${Tt(t.currentTokens)}/${Tt(t.tokenLimit)} ${e}%`,color:eo(t)}}function so(t){if(!t)return null;const e=t.compaction;if(e?.state==="running")return{text:"[compact]",color:"magenta"};if(e?.state==="failed")return{text:"[compact !]",color:"red"};const s=$t(t);return s==null||s<70?null:{text:`[ctx ${s}%]`,color:s>=85?"red":"yellow"}}function no(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 Gs(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function oo(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function Ks(t,e,s={},n={}){if(!e)return null;const o=Gs(t)||{},i=oo(n.timestamp);return e==="session.usage_info"?typeof s.tokenLimit!="number"||typeof s.currentTokens!="number"||typeof s.messagesLength!="number"?null:(o.tokenLimit=s.tokenLimit,o.currentTokens=s.currentTokens,o.messagesLength=s.messagesLength,o.utilization=s.tokenLimit>0?s.currentTokens/s.tokenLimit:0,typeof s.systemTokens=="number"&&(o.systemTokens=s.systemTokens),typeof s.conversationTokens=="number"&&(o.conversationTokens=s.conversationTokens),typeof s.toolDefinitionsTokens=="number"&&(o.toolDefinitionsTokens=s.toolDefinitionsTokens),typeof s.isInitial=="boolean"&&(o.isInitial=s.isInitial),o):e==="assistant.usage"?(typeof s.inputTokens=="number"&&(o.lastInputTokens=s.inputTokens),typeof s.outputTokens=="number"&&(o.lastOutputTokens=s.outputTokens),typeof s.cacheReadTokens=="number"&&(o.lastCacheReadTokens=s.cacheReadTokens),typeof s.cacheWriteTokens=="number"&&(o.lastCacheWriteTokens=s.cacheWriteTokens),o):e==="session.compaction_start"?(o.compaction={...o.compaction||{},state:"running",startedAt:i,completedAt:void 0,error:void 0},o):e==="session.compaction_complete"?(o.compaction={...o.compaction||{},state:s.success===!1?"failed":"succeeded",completedAt:i,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 o.tokenLimit=="number"&&o.tokenLimit>0&&(o.currentTokens=s.postCompactionTokens,o.utilization=s.postCompactionTokens/o.tokenLimit),typeof s.preCompactionMessagesLength=="number"&&typeof s.messagesRemoved=="number"&&(o.messagesLength=Math.max(0,s.preCompactionMessagesLength-s.messagesRemoved)),typeof s.systemTokens=="number"&&(o.systemTokens=s.systemTokens),typeof s.conversationTokens=="number"&&(o.conversationTokens=s.conversationTokens),typeof s.toolDefinitionsTokens=="number"&&(o.toolDefinitionsTokens=s.toolDefinitionsTokens),o):null}function io(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 ${Tt(s.tokensRemoved)}`,color:"gray"}]:[]]}const kt=/\{(\/?)([a-z-]+)\}/g,ro={color:null,bold:!1,underline:!1},Ze=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,as=/session:\/\/([A-Za-z0-9-]+)/g,ao={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function Ke(t){return{color:t.color,bold:t.bold,underline:t.underline}}function co(t,e,s){const n=Ke(t);if(e==="bold")return n.bold=!s,n;if(e==="underline")return n.underline=!s,n;if(e.endsWith("-fg")){const o=e.slice(0,-3);return n.color=s?null:ao[o]||null,n}return n}function Ys(t){return String(t||"").replace(kt,"")}function Xs(t){const e=[],n=String(t||"").split(`
2
+ `);for(const o of n){const i=[];let r=Ke(ro),a=0,l;for(;(l=kt.exec(o))!==null;){const[c,f,d]=l;l.index>a&&i.push({text:o.slice(a,l.index),...Ke(r)}),r=co(r,d,f==="/"),a=l.index+c.length}(a<o.length||i.length===0)&&i.push({text:o.slice(a),...Ke(r)}),e.push(i),kt.lastIndex=0}return e}function D(t){return String(t||"").slice(0,8)}function lo(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}function oe(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 uo(t,e={}){if(!t)return"";try{return(t instanceof Date?t:new Date(t)).toLocaleString("en-GB",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,...e})}catch{return""}}function Ye(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),o=e%60;return s>0?`${s}h ${n}m`:n>0?`${n}m ${o}s`:`${o}s`}function fo(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function lt(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function ho(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function Le(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.text+=e;return}t.push({text:e,color:s.color||null,bold:!!s.bold,underline:!!s.underline,backgroundColor:s.backgroundColor||void 0})}function Qs(t){return(t||[]).map(e=>e?.text||"").join("")}function Xe(t){return z(Qs(t))}function po(t,e){const s=Math.max(0,Number(e)||0);if(s<=0)return[];const n=[];let o=s;for(const i of t||[]){if(o<=0)break;const r=String(i?.text||"");if(!r)continue;const a=We(r,o);a&&(n.push({...i,text:a}),o-=z(a))}return n}function mo(t,e){const s=Math.max(0,Number(e)||0),n=po(t,s),o=Xe(n),i=Math.max(0,s-o);return i>0&&n.push({text:" ".repeat(i),color:null,bold:!1,underline:!1}),n}function go(t,e){const s=Math.max(1,Number(e)||1),n=[];let o=[],i=0;function r(){if(o.length===0){n.push([{text:"",color:null,bold:!1,underline:!1}]);return}n.push(o),o=[],i=0}for(const a of t||[]){let l=String(a?.text||"");if(l)for(;l.length>0;){const c=Math.max(1,s-i),f=We(l,c);if(!f)break;if(f.length===l.length||z(f)<c){o.push({...a,text:f}),i+=z(f),l=l.slice(f.length),i>=s&&r();continue}const d=f.lastIndexOf(" ");if(d>0&&(i>0||d>0)){const h=f.slice(0,d+1);o.push({...a,text:h}),i+=z(h),l=l.slice(h.length),r()}else o.push({...a,text:f}),i+=z(f),l=l.slice(f.length),i>=s&&r()}}return(o.length>0||n.length===0)&&r(),n}function yo(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function Js(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 So(t){const e=String(t||"");return Ze.lastIndex=0,[...e.matchAll(Ze)].map(s=>{const n=s[1],o=Js(s[2]);return!n||!o?null:{sessionId:n,filename:o,uri:`artifact://${n}/${o}`}}).filter(Boolean)}function At(t){const e=String(t||"");if(!e)return e;Ze.lastIndex=0;const s=e.replace(Ze,(n,o,i)=>{const r=Js(i);return!o||!r?n:`[artifact: ${r}](artifact://${o}/${r}) (press a to download)`});return as.lastIndex=0,s.replace(as,(n,o)=>o?`[session: ${D(o)}](session://${o})`:n)}function Oe(t){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const i=ho(e,"`",n),r="`".repeat(i),a=lt(e,r,n+i);if(a>n+i-1){Le(s,e.slice(n+i,a),{color:"cyan"}),n=a+i;continue}}if(e.startsWith("**",n)||e.startsWith("__",n)){const i=e.slice(n,n+2),r=lt(e,i,n+2);if(r>n+2){Le(s,e.slice(n+2,r),{bold:!0}),n=r+2;continue}}if(e[n]==="["){const i=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(i){Le(s,i[1],{color:"cyan",underline:!0}),n+=i[0].length;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]){const i=e[n],r=lt(e,i,n+1);if(r>n+1){Le(s,e.slice(n+1,r),{underline:!0}),n=r+1;continue}}let o=e.length;for(const i of["**","__","`","[","*","_"]){const r=e.indexOf(i,n+1);r!==-1&&r<o&&(o=r)}Le(s,e.slice(n,o)),n=o}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function ut(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function dt(t){const e=String(t||"").trim().replace(/^\|/,"").replace(/\|$/,""),s=[];let n="",o=!1;for(const i of e){if(o){n+=i,o=!1;continue}if(i==="\\"){o=!0;continue}if(i==="|"){s.push(n.trim()),n="";continue}n+=i}return s.push(n.trim()),s}function cs(t){return t.length>0&&t.every(e=>/^:?-{3,}:?$/.test(String(e||"").replace(/\s+/g,"")))}function z(t){return Array.from(String(t||"")).length}function We(t,e){if(e<=0)return"";let s="",n=0;for(const o of Array.from(String(t||""))){if(n+1>e)break;s+=o,n+=1}return s}function Zs(t,e){const s=String(t||""),n=Math.max(0,e-z(s));return s+" ".repeat(n)}function bo(t){return Qs(Oe(t))}function wo(t,e){const s=bo(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),o=[];let i="";const r=a=>{let l=a;for(;z(l)>e;){const c=We(l,e);if(!c)break;i&&(o.push(i),i=""),o.push(c),l=l.slice(c.length)}return l};for(const a of n){const l=r(a);if(!l)continue;if(!i){i=l;continue}const c=`${i} ${l}`;z(c)<=e?i=c:(o.push(i),i=l)}return i&&o.push(i),o.length>0?o:[""]}function Io(t,e){const s=Math.max(1,...t.map(f=>f.length)),n=Math.max(s*3,e-(s*3+1)),o=Array.from({length:s},(f,d)=>Math.max(3,...t.map(h=>z(h[d]||"")))),i=Array.from({length:s},(f,d)=>Math.max(3,...t.map(h=>Math.max(0,...String(h[d]||"").split(/\s+/).filter(Boolean).map(m=>z(m)))))),r=Array.from({length:s},(f,d)=>Math.max(3,Math.min(Math.max(z(t[0]?.[d]||"")||3,i[d]),24)));if(o.reduce((f,d)=>f+d,0)<=n)return o;const l=r.slice();let c=n-l.reduce((f,d)=>f+d,0);if(c<0){const f=Math.max(3,Math.floor(n/s));return l.map((d,h)=>h===s-1?Math.max(3,n-f*(s-1)):f)}for(;c>0;){let f=0,d=-1/0;for(let h=0;h<s;h++){const m=o[h]-l[h];m>d&&(d=m,f=h)}if(d<=0){l[s-1]+=c;break}l[f]+=1,c-=1}return l}function xo(t,e){if(!t||t.length===0)return"";const s=Math.max(1,...t.map(d=>d.length)),n=t.map(d=>Array.from({length:s},(h,m)=>d[m]||"")),o=Io(n,e),i=[],r=`┌${o.map(d=>"─".repeat(d+2)).join("┬")}┐`,a=`├${o.map(d=>"─".repeat(d+2)).join("┼")}┤`,l=`└${o.map(d=>"─".repeat(d+2)).join("┴")}┘`,c=d=>{const h=d.map((g,w)=>wo(g,o[w])),m=Math.max(...h.map(g=>g.length));for(let g=0;g<m;g++){const w=h.map((x,b)=>Zs(x[g]||"",o[b]));i.push(`│ ${w.join(" │ ")} │`)}};i.push(r),c(n[0]),i.push(a);const f=n.slice(1);for(const[d,h]of f.entries())c(h),d<f.length-1&&i.push(a);return i.push(l),i.join(`
3
+ `)}function vo(t,e){const s=String(t||"").split(`
4
+ `),n=[];let o=!1;for(let i=0;i<s.length;i++){const r=s[i];if(r.trim().startsWith("```")){o=!o,n.push(r);continue}if(o){n.push(r);continue}const l=s[i+1];if(!ut(r)||!ut(l)){n.push(r);continue}const c=dt(r),f=dt(l);if(!cs(f)||c.length!==f.length){n.push(r);continue}const d=[c];for(i+=1;i+1<s.length&&ut(s[i+1]);){i+=1;const h=dt(s[i]);cs(h)||d.push(h)}n.push(xo(d,e))}return n.join(`
5
+ `)}function Eo(t,e){const s=String(t||"");if(!s)return[""];const n=[];let o=s;for(;o.length>0;){const i=We(o,e);if(!i)break;n.push(i),o=o.slice(i.length)}return n.length>0?n:[""]}function ls(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",o=We(n,Math.max(1,s-4)),i=Math.max(0,s-o.length-2);return[{text:`┌${o}${"─".repeat(i)}┐`,color:"gray"}]}function us(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function ds(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),o=[];for(const i of t){const r=Eo(i,n);for(const a of r)o.push([{text:"│",color:"gray"},{text:Zs(a,n),color:"cyan"},{text:"│",color:"gray"}]);r.length===0&&o.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}])}return o.length===0&&o.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}]),o}function Ht(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),i=vo(String(t||""),n).split(`
6
+ `);let r=!1,a="",l=[];for(const c of i){const f=c.trim();if(f.startsWith("```")){r?(s.push(ls(a,Math.max(8,n))),s.push(...ds(l,Math.max(8,n))),s.push(us(Math.max(8,n))),r=!1,a="",l=[]):(r=!0,a=f.slice(3).trim(),l=[]);continue}if(r){l.push(c);continue}if(!c){s.push([{text:"",color:null}]);continue}const d=/^(#{1,6})\s+(.*)$/.exec(c);if(d){s.push([{text:d[2],color:"white",bold:!0}]);continue}const h=/^>\s?(.*)$/.exec(c);if(h){s.push([{text:"> ",color:"gray"},...Oe(h[1]).map(w=>({...w,color:w.color||"gray"}))]);continue}const m=/^\s*[-*]\s+(.*)$/.exec(c);if(m){s.push([{text:"• ",color:"gray"},...Oe(m[1])]);continue}const g=/^\s*(\d+)\.\s+(.*)$/.exec(c);if(g){s.push([{text:`${g[1]}. `,color:"gray"},...Oe(g[2])]);continue}s.push(Oe(c))}return r&&(s.push(ls(a,Math.max(8,n))),s.push(...ds(l,Math.max(8,n))),s.push(us(Math.max(8,n)))),s}function Ct({title:t="SYSTEM",timestamp:e="",body:s="",width:n=80,titleColor:o="yellow",borderColor:i="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),f=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:o,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]],d=Ht(String(s||""),{width:c}),h=d.length>0?d.flatMap(v=>go(v,c)):[[{text:"",color:null}]],m=r?h.map(v=>yo(v,r)):h,g=m.reduce((v,M)=>Math.max(v,Xe(M)),0),w=a?Math.min(l,Math.max(12,Xe(f)+3,g+4)):l,x=Math.max(1,w-4),b=Math.max(0,w-Xe(f)-3);return[[{text:"┌─",color:i},...f,{text:`${"─".repeat(b)}┐`,color:i}],...m.map(v=>[{text:"│ ",color:i},...mo(v,x),{text:" │",color:i}]),[{text:`└${"─".repeat(Math.max(1,w-2))}┘`,color:i}],[{text:"",color:null}]]}function Ue(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 o=String(t?.title||"").trim();return/^pilotswarm(?: agent)?$/i.test(o)?s:/^sweeper agent$/i.test(o)||/^sweeper$/i.test(o)?"Sweeper Agent":/^resource manager agent$/i.test(o)||/^resourcemgr$/i.test(o)?"Resource Manager Agent":/^facts manager$/i.test(o)||/^facts-manager$/i.test(o)?"Facts Manager":o||"System Agent"}function To(t){const e=Ue(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}const $=300,ko=[$,1e3,3e3,1e4];function me(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max($,Number(e)||$);return s.length>n?s.slice(-n):s}function ye(t){return String(t||"").replace(/\r\n/g,`
7
+ `).trim()}function Bt(t){const e=String(t||"").replace(/\r\n/g,`
8
+ `).trim(),s='The user was asked: "',n=`"
9
+ The user responded: "`;if(!e.startsWith(s)||!e.endsWith('"'))return null;const o=e.indexOf(n,s.length);if(o===-1)return null;const i=e.slice(s.length,o),r=e.slice(o+n.length,-1);return!i.trim()||!r.trim()?null:{question:i,answer:r}}function Ao(t){return ye(Ys(t)).length>0}function en(t){const e=ye(t);return e?/^\[SYSTEM:/i.test(e)||/^\[CHILD_UPDATE\b/i.test(e)||/^Buffered child updates arrived /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)||/^(spawn_agent|message_agent|check_agents|wait_for_agents|complete_agent|cancel_agent|delete_agent) failed/i.test(e):!1}function Co(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&en(s)?"system":e}function Po(t,e){if(!t||!e||t.role!==e.role)return!1;const s=ye(t.text),n=ye(e.text);if(!s||!n||s!==n)return!1;const o=Number(t.createdAt||0),i=Number(e.createdAt||0);return t.optimistic||e.optimistic?!0:!o||!i?!1:Math.abs(o-i)<=5e3}function Ee(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!Po(n,s)){e.push(s);continue}if(n?.optimistic&&!s?.optimistic){e[e.length-1]=s;continue}if(!n?.optimistic&&s?.optimistic)continue;const o=Number(n?.createdAt||0),i=Number(s?.createdAt||0);e[e.length-1]=i>=o?s:n}return e}function Te(t,e){const s=String(Dt(t)||"").replace(/\r\n/g,`
10
+ `);return Ao(s)?{id:`${t.sessionId}:${t.seq}`,role:Co(t,e,s),text:s,time:oe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}:null}function tn(t){return t?.eventType==="system.message"&&en(Dt(t))}function Mo(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=ye(e.text),n=Bt(e.text),o=n?ye(n.answer):"";let i=!1;return t.filter(r=>{if(i||!r?.optimistic||r.role!==e.role)return!0;const a=ye(r.text);return a!==s&&a!==o?!0:(i=!0,!1)})}function Dt(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 fo(e)}function No(t){return(t||[]).map(e=>e?.text||"").join("")}function Ro(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function sn(t=[]){const e=new Set,s=[];for(const n of t){const o=String(n||"").trim();if(!o)continue;const i=o.toLowerCase();e.has(i)||(e.add(i),s.push(o))}return s.join(" | ")}function Lo(t,e=""){return sn([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function Fo(t,e=""){return sn([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function Oo(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 _o(t,e){if(!e||typeof e!="object")return"";if(t==="wait"){const o=e.seconds!=null?`${e.seconds}s`:"?",i=e.preserveWorkerAffinity===!0?" preserve=true":"",r=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${o}${i}${r}`}if(t==="cron"){if(e.action==="cancel")return" cancel";const o=e.seconds!=null?`${e.seconds}s`:"?",i=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${o}${i}`}const s=Object.entries(e).slice(0,4).map(([o,i])=>`${o}=${Oo(i)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function Wt(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function U(t,e,s,n="",o="white"){return[...Wt(t),{text:e,color:s},...n?[{text:` ${n}`,color:o}]:[]]}function $o(t,e=96){return Ro(Ys(Dt(t)),e)||""}function fs(t,e,s="start"){const n=e?.data?.toolName||e?.data?.name||"tool",o=e?.data?.arguments||e?.data?.args,i=e?.data?.durableSessionId,r=_o(n,o);return[...Wt(t),{text:s==="start"?`▶ ${n}${r}`:`✓ ${n}`,color:s==="start"?"yellow":"green"},...i?[{text:` [${D(i)}]`,color:"gray"}]:[]]}function et(t){const e=oe(t.createdAt),s=$o(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"abort":case"assistant.turn_end":return null;case"tool.execution_start":n=fs(e,t,"start");break;case"tool.execution_complete":n=fs(e,t,"complete");break;case"assistant.reasoning":n=U(e,"[reasoning]","gray",s||"…","white");break;case"assistant.turn_start":n=U(e,"[turn start]","gray",s);break;case"session.turn_completed":n=U(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=U(e,"[lossy handoff]","yellow",Fo(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=U(e,"[dehydrated]","cyan",Lo(t,s));break;case"session.hydrated":case"session.rehydrated":n=U(e,"[rehydrated]","green",s);break;case"session.wait_started":{const o=t?.data?.seconds!=null?`${t.data.seconds}s`:"?",i=typeof t?.data?.reason=="string"&&t.data.reason?` reason=${JSON.stringify(t.data.reason)}`:"",r=t?.data?.preserveAffinity?" preserve=true":"";n=U(e,"[wait]","yellow",`${o}${r}${i}`.trim());break}case"session.input_required_started":n=U(e,"[input]","yellow",s);break;case"session.agent_spawned":n=U(e,"[spawn]","cyan",t?.data?.agentId||D(t?.data?.childSessionId),"white");break;case"session.cron_started":n=U(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_fired":n=U(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_cancelled":n=U(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=U(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=U(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.compaction_start":case"session.compaction_complete":n=io(e,t.eventType,t.data||{});break;case"session.error":n=U(e,"[error]","red",s||"session error","white");break;case"system.message":n=U(e,"[system]","gray",s||"system message");break;default:n=[...Wt(e),{text:`[${t.eventType}]`,color:"gray"},...s?[{text:` ${s}`,color:"white"}]:[]];break}return{id:`${t.sessionId}:${t.seq}`,eventType:t.eventType,time:e,text:No(n),line:n}}function Ho(t=$){const e=Math.max($,Number(t)||$);return ko.find(n=>n>e)||Math.min(1e5,e*2)}function qe(t=[],e={}){const s=Math.max($,Number(e.requestedLimit??e.eventLimit??$)||$),n=[],o=[],i=[];for(const r of t){if(i.push(r),r.eventType==="user.message"){const l=Te(r,"user");l&&n.push(l);continue}if(r.eventType==="assistant.message"){const l=Te(r,"assistant");l&&n.push(l);continue}if(r.eventType==="system.message"){if(tn(r)){const l=et(r);l&&o.push(l)}else{const l=Te(r,"system");l&&n.push(l)}continue}const a=et(r);a&&o.push(a)}return{chat:Ee(n),activity:o,events:i.slice(-s),loadedEventLimit:s,loadedEventCount:i.length,hasOlderEvents:i.length>=s}}function Bo(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max($,Number(t?.loadedEventLimit??$)||$),o=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),i={chat:me(t?.chat||[],n),activity:me(t?.activity||[],n),events:o,lastSeq:e.seq,loadedEventLimit:n,loadedEventCount:Math.max(Number(t?.loadedEventCount||0),o.length),hasOlderEvents:!!t?.hasOlderEvents};if(e.eventType==="user.message"){const a=Te(e,"user");return a&&(i.chat=Mo(i.chat,a),i.chat.push(a),i.chat=me(Ee(i.chat),n)),i}if(e.eventType==="assistant.message"){const a=Te(e,"assistant");return a&&(i.chat.push(a),i.chat=me(Ee(i.chat),n)),i}if(e.eventType==="system.message"){if(tn(e)){const a=et(e);a&&(i.activity.push(a),i.activity=me(i.activity,n))}else{const a=Te(e,"system");if(!a)return i;i.chat.push(a),i.chat=me(Ee(i.chat),n)}return i}const r=et(e);return r&&(i.activity.push(r),i.activity=me(i.activity,n)),i}function ft(t,e=null){const s=typeof e?.splash=="string"&&e.splash.trim()?e.splash:t?.splash;return s?[{id:`splash:${e?.isSystem?Ue(e,t?.title||"PilotSwarm"):e?.title||t?.title||"PilotSwarm"}`,role:"system",text:`${s}
11
+
12
+ {gray-fg}Start interacting with this session to replace the splash screen.{/gray-fg}`,time:"",splash:!0}]:[]}const Do=.7,Wo=30,hs=36,ht=18,pt=18,mt=0,nn=3,gt=6,ps=10,Uo=.25;function Qe(t,e,s){return Math.max(e,Math.min(s,t))}function jo(t){return[S.SESSIONS,S.CHAT,S.INSPECTOR,S.ACTIVITY].includes(t)?t:null}function qo(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function ke(t=""){const e=String(t||"").split(`
13
+ `).length;return Qe(e,1,nn)}function He(t,e=0,s=1,n=0,o=null){const i=qo(t),r=i.width,a=i.height,l=Qe(Number(s)||1,1,nn),c=jo(o),f=5+l,d=Math.max(18,a-f),m=Math.floor(r*Do)+(Number(e)||0),g=r-m-mt;let w=!1,x=!1;m<=ht&&g>pt?w=!0:g<=pt&&m>ht?x=!0:m<=ht&&g<=pt&&(x=e>=0,w=!x);let b,v;w?(b=0,v=r):x?(b=r,v=0):(b=Qe(m,Wo,r-hs-mt),v=Math.max(hs,r-b-mt));const M=Math.max(gt,Math.floor(d*Uo)),E=Qe(M+(Number(n)||0),gt,Math.max(gt,d-ps)),O=Math.max(6,Math.floor(d*.28));return{viewport:i,totalWidth:r,totalHeight:a,reservedRows:f,bodyHeight:d,promptRows:l,fullscreenPane:c,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,leftHidden:w,rightHidden:x,leftWidth:b,rightWidth:v,sessionPaneHeight:E,chatPaneHeight:Math.max(ps,d-E),activityPaneHeight:O,inspectorPaneHeight:Math.max(10,d-O)}}function Pt(t){return t?.fullscreenPane?[t.fullscreenPane,S.PROMPT]:t?.leftHidden?[S.INSPECTOR,S.ACTIVITY,S.PROMPT]:t?.rightHidden?[S.SESSIONS,S.CHAT,S.PROMPT]:[S.SESSIONS,S.CHAT,S.INSPECTOR,S.ACTIVITY,S.PROMPT]}function ge(t,e){const s=Pt(e);return s.includes(t)?t:s[0]||S.PROMPT}function Vo(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[S.PROMPT]:S.PROMPT,[S.ACTIVITY]:S.INSPECTOR,[S.INSPECTOR]:S.INSPECTOR}[t]||S.INSPECTOR:e?.rightHidden?{[S.PROMPT]:S.PROMPT,[S.CHAT]:S.SESSIONS,[S.SESSIONS]:S.SESSIONS}[t]||S.SESSIONS:{[S.PROMPT]:S.SESSIONS,[S.ACTIVITY]:S.CHAT,[S.INSPECTOR]:S.CHAT,[S.CHAT]:S.SESSIONS,[S.SESSIONS]:S.SESSIONS}[t]||S.SESSIONS}function zo(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[S.PROMPT]:S.PROMPT,[S.INSPECTOR]:S.ACTIVITY,[S.ACTIVITY]:S.ACTIVITY}[t]||S.INSPECTOR:e?.rightHidden?{[S.PROMPT]:S.PROMPT,[S.SESSIONS]:S.CHAT,[S.CHAT]:S.CHAT}[t]||S.CHAT:{[S.PROMPT]:S.PROMPT,[S.SESSIONS]:S.CHAT,[S.CHAT]:S.INSPECTOR,[S.INSPECTOR]:S.ACTIVITY,[S.ACTIVITY]:S.ACTIVITY}[t]||S.CHAT}function ms(t){return t?.isSystem?To(t):Number.MAX_SAFE_INTEGER}function gs(t){return t.isSystem?0:1}function Go(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 Ko(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return Go(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 ys(t,e,s){const n=gs(t),o=gs(e);if(n!==o)return n-o;const i=ms(t),r=ms(e);if(i!==r)return i-r;const a=s.get(t.sessionId),l=s.get(e.sessionId);if(typeof a=="number"&&typeof l=="number"&&a!==l)return a-l;const c=(e.createdAt||0)-(t.createdAt||0);if(c!==0)return c;const f=String(t.title||""),d=String(e.title||""),h=f.localeCompare(d);return h!==0?h:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function Ve(t=[],e=new Set,s=[]){const n=new Map,o=new Map,i=Ko(s);for(const c of t)n.set(c.sessionId,c);for(const c of t){const f=c.parentSessionId;!f||!n.has(f)||(o.has(f)||o.set(f,[]),o.get(f).push(c))}for(const c of o.values())c.sort((f,d)=>ys(f,d,i));const r=t.filter(c=>!c.parentSessionId||!n.has(c.parentSessionId)).sort((c,f)=>ys(c,f,i)),a=[];function l(c,f){const d=o.get(c.sessionId)||[];if(a.push({sessionId:c.sessionId,depth:f,hasChildren:d.length>0,collapsed:e.has(c.sessionId)}),!e.has(c.sessionId))for(const h of d)l(h,f+1)}for(const c of r)l(c,0);return a}function Yo(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function V({id:t,label:e,description:s,page:n,terminal:o,tui:i={}}){const r={background:n?.background||o?.background||"#000000",surface:o?.background||n?.background||"#000000",foreground:o?.foreground||n?.foreground||"#ffffff",white:o?.foreground||n?.foreground||"#ffffff",gray:n?.hintColor||o?.brightBlack||o?.white||"#999999",black:o?.black||"#000000",red:o?.red||"#ff5555",green:o?.green||"#55ff55",yellow:o?.yellow||"#ffff55",blue:o?.blue||"#5555ff",magenta:o?.magenta||"#ff55ff",cyan:o?.cyan||"#55ffff",activeHighlightBackground:o?.blue||"#5555ff",activeHighlightForeground:o?.background||"#000000",selectionBackground:o?.cursor||o?.blue||"#5555ff",selectionForeground:o?.cursorAccent||o?.background||"#000000",promptCursorBackground:o?.cursor||o?.green||"#55ff55",promptCursorForeground:o?.cursorAccent||o?.background||"#000000"};return Yo({id:t,label:e,description:s,page:n,terminal:o,tui:{...r,...i}})}const Xo=V({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"}}),Qo=V({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"}}),on=V({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"}}),Jo=V({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"}}),Zo=V({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"}}),ei=V({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"}}),ti=V({id:"nord",label:"Nord",description:"Arctic blue-gray palette with frosty accents and clean contrast.",page:{background:"#2e3440",foreground:"#d8dee9",overlayBackground:"#2e3440",overlayForeground:"#d8dee9",hintColor:"#8f9ab5",modalBackdrop:"rgba(46, 52, 64, 0.74)",modalBackground:"#3b4252",modalBorder:"#4c566a",modalForeground:"#d8dee9",modalMuted:"#8f9ab5",modalSelectedBackground:"#434c5e",modalSelectedBorder:"#88c0d0",modalSelectedForeground:"#eceff4"},terminal:{background:"#2e3440",foreground:"#d8dee9",cursor:"#d8dee9",cursorAccent:"#2e3440",selectionBackground:"rgba(136, 192, 208, 0.22)",black:"#3b4252",red:"#bf616a",green:"#a3be8c",yellow:"#ebcb8b",blue:"#81a1c1",magenta:"#b48ead",cyan:"#88c0d0",white:"#e5e9f0",brightBlack:"#4c566a",brightRed:"#bf616a",brightGreen:"#a3be8c",brightYellow:"#ebcb8b",brightBlue:"#81a1c1",brightMagenta:"#b48ead",brightCyan:"#8fbcbb",brightWhite:"#eceff4"},tui:{surface:"#2e3440",activeHighlightBackground:"#434c5e",activeHighlightForeground:"#eceff4",selectionBackground:"#88c0d0",selectionForeground:"#2e3440",promptCursorBackground:"#d8dee9",promptCursorForeground:"#2e3440"}}),si=V({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"}}),ni=V({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"}}),oi=V({id:"solarized-dark",label:"Solarized Dark",description:"Ethan Schoonover's precision-engineered dark palette with warm accents.",page:{background:"#002b36",foreground:"#839496",overlayBackground:"#002b36",overlayForeground:"#839496",hintColor:"#839496",modalBackdrop:"rgba(0, 43, 54, 0.74)",modalBackground:"#073642",modalBorder:"#586e75",modalForeground:"#839496",modalMuted:"#839496",modalSelectedBackground:"#073642",modalSelectedBorder:"#268bd2",modalSelectedForeground:"#93a1a1"},terminal:{background:"#002b36",foreground:"#839496",cursor:"#839496",cursorAccent:"#002b36",selectionBackground:"rgba(38, 139, 210, 0.22)",black:"#073642",red:"#dc322f",green:"#859900",yellow:"#b58900",blue:"#268bd2",magenta:"#d33682",cyan:"#2aa198",white:"#eee8d5",brightBlack:"#586e75",brightRed:"#cb4b16",brightGreen:"#586e75",brightYellow:"#657b83",brightBlue:"#839496",brightMagenta:"#6c71c4",brightCyan:"#93a1a1",brightWhite:"#fdf6e3"},tui:{surface:"#002b36",activeHighlightBackground:"#073642",activeHighlightForeground:"#93a1a1",selectionBackground:"#268bd2",selectionForeground:"#fdf6e3",promptCursorBackground:"#839496",promptCursorForeground:"#002b36"}}),ii=V({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"}}),ri=V({id:"noctis-viola",label:"Noctis Viola",description:"Saturated dark violet palette with purple and warm accents.",page:{background:"#30243d",foreground:"#ccbfd9",overlayBackground:"#30243d",overlayForeground:"#ccbfd9",hintColor:"#bf8ef1",modalBackdrop:"rgba(28, 18, 38, 0.72)",modalBackground:"#3d2e4d",modalBorder:"#8767a8",modalForeground:"#ccbfd9",modalMuted:"#ad9cc0",modalSelectedBackground:"#593a78",modalSelectedBorder:"#bf8ef1",modalSelectedForeground:"#edebff"},terminal:{background:"#291d35",foreground:"#ccbfd9",cursor:"#d9b3ff",cursorAccent:"#291d35",selectionBackground:"rgba(135, 103, 168, 0.33)",black:"#362f3d",red:"#e66533",green:"#49e9a6",yellow:"#e4b781",blue:"#49ace9",magenta:"#df769b",cyan:"#49d6e9",white:"#bfafcf",brightBlack:"#8f869b",brightRed:"#e97749",brightGreen:"#60ebb1",brightYellow:"#e69533",brightBlue:"#60b6eb",brightMagenta:"#e798b3",brightCyan:"#60dbeb",brightWhite:"#ccbfd9"},tui:{surface:"#291d35",activeHighlightBackground:"#402d53",activeHighlightForeground:"#edebff",selectionBackground:"#8767a8",selectionForeground:"#30243d",promptCursorBackground:"#d9b3ff",promptCursorForeground:"#291d35"}}),ai=V({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"}}),rn=Object.freeze([on,Xo,Qo,ei,Zo,Jo,ti,si,ni,oi,ii,ri,ai]),ci=new Map(rn.map(t=>[t.id,t])),li=on.id;function ui(){return rn}function pe(t){return t?ci.get(t)??null:null}function di({mode:t="local",branding:e=null,themeId:s=null}={}){return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},ui:{focusRegion:S.SESSIONS,inspectorTab:ee[0],prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],statusText:"Starting PilotSwarm...",themeId:s||li,modal:null,fullscreenPane:null,layout:{paneAdjust:0,sessionPaneAdjust:0,viewportWidth:120,viewportHeight:40},scroll:{chat:0,inspector:0,activity:0,filePreview:0}},connection:{mode:t,connected:!1,workersOnline:null,error:null},sessions:{byId:{},flat:[],activeSessionId:null,collapsedIds:new Set,orderById:{},nextOrderOrdinal:0,filterQuery:""},history:{bySessionId:new Map},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"}}}}function Ss(t){return new Map(t)}function yt(t){return new Set(t)}function fi(t){return{...t||{}}}function ne(t){return{...t||{}}}function ze(t){return{...t||{}}}function St(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function hi(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function pi(t){return[S.SESSIONS,S.CHAT,S.INSPECTOR,S.ACTIVITY].includes(t)?t:null}function bt(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max($,Number(e)||$);return s.length>n?s.slice(-n):s}function Mt(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 o=0;o<t.length;o+=1)if(!Mt(t[o],e[o]))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 o of s)if(!Object.prototype.hasOwnProperty.call(e,o)||!Mt(t[o],e[o]))return!1;return!0}function bs(t={},e={}){let s=t||{};for(const[n,o]of Object.entries(e||{}))o!==void 0&&(Mt(t?.[n],o)||(s===t&&(s={...t||{}}),s[n]=o));return s}function mi(t=[]){return(t||[]).find(s=>s?.sessionId&&!s.isSystem)?.sessionId||null}function ws(t={},e=0,s=[]){const n=fi(t);let o=Number.isFinite(e)?e:0;for(const i of s||[]){const r=i?.sessionId;r&&typeof n[r]!="number"&&(n[r]=o,o+=1)}return{orderById:n,nextOrderOrdinal:o}}function gi(t,e,s=null){const n=String(t||""),o=Number.isFinite(e)?e:Number.isFinite(s)?s:n.length;return Math.max(0,Math.min(o,n.length))}function Is(t,e){const s=String(t||"");return(Array.isArray(e)?e.filter(Boolean):[]).filter(o=>{const i=String(o?.token||"").trim();return i&&s.includes(i)})}function yi(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"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"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,o=Math.max(40,e.width??s),i=Math.max(18,e.height??n);return o===s&&i===n?t:{...t,ui:{...t.ui,layout:{...t.ui.layout||{},viewportWidth:o,viewportHeight:i}}}}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/focus":return{...t,ui:{...t.ui,focusRegion:e.focusRegion}};case"sessions/filterQuery":return{...t,sessions:{...t.sessions,filterQuery:typeof e.query=="string"?e.query:""}};case"ui/modalSelection":{const s=t.ui.modal;if(!s||!Array.isArray(s.items)||s.items.length===0)return t;const n=Math.max(0,Math.min(e.index??0,s.items.length-1));return{...t,ui:{...t.ui,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/inspectorTab":return{...t,ui:{...t.ui,inspectorTab:e.inspectorTab,fullscreenPane:e.inspectorTab==="files"&&t.ui.fullscreenPane===S.INSPECTOR?null:t.ui.fullscreenPane,scroll:{...t.ui.scroll,inspector:0}},files:e.inspectorTab==="files"?t.files:{...t.files,fullscreen:!1}};case"ui/prompt":return{...t,ui:{...t.ui,prompt:e.prompt,promptCursor:gi(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:ke(e.prompt),promptAttachments:Is(e.prompt,t.ui.promptAttachments)}};case"ui/promptAttachments":return{...t,ui:{...t.ui,promptAttachments:Is(t.ui.prompt,e.attachments)}};case"sessions/loaded":{const s={};let n=!1;for(const g of e.sessions){const w=t.sessions.byId[g.sessionId],x=bs(w,g);s[g.sessionId]=x,!n&&x!==w&&(n=!0)}t.sessions.activeSessionId&&t.sessions.byId[t.sessions.activeSessionId]&&!s[t.sessions.activeSessionId]&&(s[t.sessions.activeSessionId]={...t.sessions.byId[t.sessions.activeSessionId]},n=!0);const o=Object.keys(t.sessions.byId),i=Object.keys(s);if(o.length!==i.length&&(n=!0),!n){for(const g of i)if(!t.sessions.byId[g]){n=!0;break}}if(!n)return t;const r=Object.values(s),{orderById:a,nextOrderOrdinal:l}=ws(t.sessions.orderById,t.sessions.nextOrderOrdinal,r),c=yt(t.sessions.collapsedIds),f=new Set(Object.values(t.sessions.byId).map(g=>g.parentSessionId).filter(g=>!!g)),d=new Set(r.map(g=>g.parentSessionId).filter(g=>!!g));for(const g of d)f.has(g)||c.add(g);const h=Ve(r,c,a),m=t.sessions.activeSessionId&&h.some(g=>g.sessionId===t.sessions.activeSessionId)?t.sessions.activeSessionId:mi(r);return{...t,sessions:{...t.sessions,byId:s,collapsedIds:c,flat:h,activeSessionId:m,orderById:a,nextOrderOrdinal:l}}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=bs(s,e.session);if(n===s)return t;const o={...t.sessions.byId,[e.session.sessionId]:n},{orderById:i,nextOrderOrdinal:r}=ws(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(o));return{...t,sessions:{...t.sessions,byId:o,flat:Ve(Object.values(o),t.sessions.collapsedIds,i),orderById:i,nextOrderOrdinal:r}}}case"sessions/selected":return{...t,sessions:{...t.sessions,activeSessionId:e.sessionId},ui:{...t.ui,scroll:{...t.ui.scroll,chat:0,inspector:0,activity:0}}};case"ui/fullscreenPane":{const s=pi(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=yt(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,flat:Ve(Object.values(t.sessions.byId),s,t.sessions.orderById)}}}case"sessions/expand":{const s=yt(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,flat:Ve(Object.values(t.sessions.byId),s,t.sessions.orderById)}}}case"history/set":{const s=t.history.bySessionId.get(e.sessionId)||null,n=s?.chat||[],o=Math.max($,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??$)||$),i=bt(Ee(e.history?.chat||[]),o),r=n[n.length-1]?.id||null,a=i[i.length-1]?.id||null,l=e.sessionId===t.sessions.activeSessionId&&a!==r,c=Ss(t.history.bySessionId);return c.set(e.sessionId,{...e.history||{},chat:i,activity:bt(e.history?.activity||[],o),events:bt(e.history?.events||[],o),loadedEventLimit:o}),{...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=Ss(t.history.bySessionId);for(const o of s)n.delete(o);return{...t,history:{...t.history,bySessionId:n}}}case"orchestration/statsLoading":{const s=ze(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=ze(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=ze(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=ze(t.orchestration.bySessionId);for(const o of s)delete n[o];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||[],o=1e3,i=n.length>o?n.slice(-o):n;return s[e.sessionId]={loading:!1,error:null,fetchedAt:e.fetchedAt||Date.now(),events:i},{...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 o of s)delete n[o];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"files/evictPreviews":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=ne(t.files.bySessionId);for(const o of s)n[o]&&(n[o]={...n[o],previews:{}});return{...t,files:{...t.files,bySessionId:n}}}case"files/sessionLoading":{const s=ne(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=ne(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},o=Array.isArray(e.entries)?[...e.entries]:[],i=n.selectedFilename&&o.includes(n.selectedFilename)?n.selectedFilename:e.selectedFilename&&o.includes(e.selectedFilename)?e.selectedFilename:o[0]||null;return s[e.sessionId]={...n,entries:o,selectedFilename:i,loading:!1,loaded:!0,error:null},{...t,files:{...t.files,bySessionId:s}}}case"files/sessionError":{const s=ne(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=ne(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},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=ne(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},o={...n.previews||{},[e.filename]:{...n.previews?.[e.filename]||{},loading:!0,error:null}};return s[e.sessionId]={...n,previews:o},{...t,files:{...t.files,bySessionId:s}}}case"files/previewLoaded":{const s=ne(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},o={...n.previews||{},[e.filename]:{loading:!1,error:null,content:e.content||"",contentType:e.contentType||"text/plain",renderMode:e.renderMode||"text"}};return s[e.sessionId]={...n,previews:o},{...t,files:{...t.files,bySessionId:s}}}case"files/previewError":{const s=ne(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},o={...n.previews||{},[e.filename]:{...n.previews?.[e.filename]||{},loading:!1,error:e.error||"Failed to load file preview"}};return s[e.sessionId]={...n,previews:o},{...t,files:{...t.files,bySessionId:s}}}case"files/downloaded":{const s=ne(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},o={...n.downloads||{},[e.filename]:{localPath:e.localPath||null,downloadedAt:e.downloadedAt||Date.now()}};return s[e.sessionId]={...n,downloads:o},{...t,files:{...t.files,bySessionId:s}}}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:{...St(t.files.filter),...St(e.filter)},...St(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:hi(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],o=n.length>1e3?n.slice(-1e3):n;return{...t,logs:{...t.logs,entries:o}}}default:return t}}function Si(t,e){let s=e;const n=new Set;return{getState(){return s},dispatch(o){const i=t(s,o);if(Object.is(i,s))return o;s=i;for(const r of n)r(s,o);return o},subscribe(o){return n.add(o),()=>n.delete(o)}}}const an="activeHighlightBackground",Ut="activeHighlightForeground",wt="#b392f0",bi="#d2b9ff",xs=new WeakMap,vs=new WeakMap;function wi(t){return t||Ut}function Ii(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?wi(s?.color):Ut,backgroundColor:an,bold:s?.bold??!0}))}function we(t,{color:e=Ut,bold:s=!0}={}){return{text:t,color:e,backgroundColor:an,bold:s}}function cn(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function xi(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function jt(t){const e=cn(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"?"warning":null}function ln(t,e="local"){const s=jt(t);if(s)return s;const n=cn(t);if(e==="remote"&&xi(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 tt(t,e="local"){switch(ln(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 un(t,e="local"){switch(ln(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 qt(t,e){const s=D(t?.sessionId);if(t?.isSystem)return`${Ue(t,e)} (${s})`;const n=String(t?.title||"");return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function vi(t){return(t||[]).map(e=>e?.text||"").join("")}function dn(t){const e=new Map,s=new Map;for(const n of Object.values(t||{})){const o=n?.parentSessionId;o&&(s.set(n.sessionId,o),e.has(o)||e.set(o,[]),e.get(o).push(n.sessionId))}return{childMap:e,parentMap:s}}function Es(t){const{childMap:e}=dn(t),s=new Map;function n(o){if(s.has(o))return s.get(o);const r=(e.get(o)||[]).reduce((a,l)=>a+1+n(l),0);return s.set(o,r),r}for(const o of Object.keys(t||{}))n(o);return s}function Ts(t=[],e={}){const{parentMap:s}=dn(e),n=new Map;for(const o of t){let i=s.get(o.sessionId);for(;i;)n.set(i,(n.get(i)||0)+1),i=s.get(i)}return n}function Vt(t={}){if(!t||typeof t!="object")return Es(t);const e=xs.get(t);if(e)return e;const s=Es(t);return xs.set(t,s),s}function zt(t=[],e={}){if(!Array.isArray(t))return Ts(t,e);const s=vs.get(t);if(s)return s;const n=Ts(t,e);return vs.set(t,n),n}function fn(t,e,s,n){const o=s.get(t)||0,i=n.get(t)||0,r=Math.max(0,o-i),a=e?.collapsed?o:r;return a?{text:`[+${a}]`,color:"cyan"}:null}function Ei(t){return t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${Ye(t.cronInterval)}]`,color:"magenta"}:null}function Ti(t,e,s,n,o){const i=[],r=s.connection?.mode||"local",a=t.depth>0?`${" ".repeat(Math.max(0,t.depth-1))}└ `:"";if(a&&i.push({text:a,color:"gray"}),e?.isSystem)i.push({text:"≈ ",color:"yellow",bold:!0});else{const d=un(e,r);i.push({text:d?`${d} `:" ",color:tt(e,r)})}const l=e?.isSystem?"yellow":tt(e,r),c=qt(e,s.branding?.title||"PilotSwarm"),f=e?.createdAt?` ${uo(e.createdAt)}`:"";i.push({text:`${c}${f}`,color:l,bold:!!e?.isSystem});for(const d of[Ei(e),so(e?.contextUsage),fn(e?.sessionId,t,n,o)])d&&i.push({text:` ${d.text}`,color:d.color,bold:d.bold});return i}function ki(t){return String(t||"").trim().toLowerCase()}function ve(t,e){const s=ki(e);return s?String(t||"").toLowerCase().includes(s):!0}function Gt(t){const e=Vt(t.sessions.byId),s=zt(t.sessions.flat,t.sessions.byId),n=t.sessions?.filterQuery||"";return t.sessions.flat.map(o=>{const i=t.sessions.byId[o.sessionId],r=Ti(o,i,t,e,s);return{sessionId:o.sessionId,text:vi(r),runs:r,depth:o.depth,status:i?.status,statusColor:tt(i,t.connection?.mode||"local"),active:o.sessionId===t.sessions.activeSessionId,isSystem:!!i?.isSystem,hasChildren:o.hasChildren,collapsed:o.collapsed}}).filter(o=>ve(o.text,n)||ve(o.sessionId,n))}function Nt(t,e=8){const s=Gt(t);if(s.length===0)return[];const n=new Set(s.map(d=>d.sessionId)),o=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(d=>n.has(d.sessionId)),i=o.findIndex(d=>d.sessionId===t.sessions.activeSessionId),r=Math.max(0,i);if(o.length<=e)return s;const a=Math.floor(e/2);let l=Math.max(0,r-a),c=Math.min(o.length,l+e);c>o.length&&(c=o.length,l=Math.max(0,c-e));const f=o.slice(l,c);return Vt(t.sessions.byId),zt(o,t.sessions.byId),s.filter(d=>f.some(h=>h.sessionId===d.sessionId))}function de(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function Ai(t){const e=t?.pendingQuestion;if(!e?.question)return null;const s=[String(e.question).trim()],n=Array.isArray(e.choices)?e.choices.filter(o=>typeof o=="string"&&o.trim()):[];if(n.length>0){s.push("","Choices:");for(const o of n)s.push(`- ${o}`)}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(`
14
+ `),time:"",createdAt:t.updatedAt||Date.now(),cardTitle:"Question",cardTitleColor:"cyan",cardBorderColor:"cyan"}}function Ci(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>Bt(n?.text||"")?.question?.trim()===s):!1}function Pi(t){const e=String(t?.error||"").trim();if(!e)return null;const s=jt(t);if(!s)return null;const n=s==="failed",o=n?e:`${e}
15
+
16
+ The orchestration is still running, so this may be transient.`;return{id:`session-error:${t.sessionId}:${t.updatedAt||""}:${e}`,role:"system",text:o,time:"",createdAt:t.updatedAt||Date.now(),cardTitle:n?"Error":"Warning",cardTitleColor:n?"red":"yellow",cardBorderColor:n?"red":"yellow"}}function hn(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return ft(t.branding);const n=t.history.bySessionId.get(e),o=n?.chat||[],i=s?.pendingQuestion?.question&&!Ci(o,s.pendingQuestion.question)?Ai(s):null,r=Pi(s);if((!n||o.length===0)&&!i&&!r)return ft(t.branding,s);const a=o.length>0?[...o]:ft(t.branding,s);return i&&a.push(i),r&&a.push(r),a}function ks(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function Mi(t){const e=oe(t?.createdAt||t?.time),s=t?.role==="user"?"You":t?.role==="assistant"?"Agent":t?.role==="system"?"System":"PilotSwarm",n=t?.role==="user"?bi:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white",o=e?`[${e}] `:"";return[...ks(o,"gray"),...ks(`${s}: `,n,{bold:!0})]}function fe(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):String(t?.text||"")}function Rt(){return[{text:"",color:null}]}function Ni(t){const e=(t||[]).find(n=>fe(n).trim().length>0),s=fe(e).trimStart();return/^[┌│└]/.test(s)}function pn(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(fe(s).trim().length>0)break;e.shift()}return e}function Ri(t){const e=String(t||"").replace(/\r\n/g,`
17
+ `).split(`
18
+ `),s=[];let n=[];function o(){n.length!==0&&(s.push({kind:"text",text:n.join(`
19
+ `)}),n=[])}for(let i=0;i<e.length;){const r=e[i];if(!/^\s*\[SYSTEM:/i.test(r)){n.push(r),i+=1;continue}const a=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(r);if(a){o(),s.push({kind:"system",text:a[1].trim()}),i+=1;continue}const l=[r.replace(/^\s*\[SYSTEM:\s*/i,"")];let c=-1;for(let f=i+1;f<e.length;f+=1){const d=e[f];if(d.trim()==="]"){c=f;break}l.push(d)}if(c===-1){n.push(r),i+=1;continue}o(),s.push({kind:"system",text:l.join(`
20
+ `).trim()}),i=c+1}return o(),s}function Li(t){const e=String(t||"").replace(/\s+/g," ").trim();if(!e)return"System notice.";if(e.startsWith("The session was dehydrated and has been rehydrated on a new worker."))return"Session rehydrated on a new worker.";const n=/^(.{1,160}?[.!?])(?:\s|$)/.exec(e)?.[1]?.trim()||e;return n.length>=e.length?n.length>160?`${n.slice(0,159).trimEnd()}…`:n:`${n}…`}function As(t,e=""){const s=Li(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:At(t),color:"gray"}}function Fi(t,e){return e?(t||[]).map(s=>(s||[]).map(n=>({...n,color:n?.color||e}))):t}function Oi(t){const e=(t||[]).find(s=>fe(s).trim().length>0);return e?fe(e).trimStart().startsWith("┌"):!1}function mn(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&Oi(e)&&fe(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function Lt(t,e,s={}){if(t?.splash)return[{kind:"markup",value:t.text}];if(t?.role==="user"){const r=Bt(t?.text||"");if(r)return[...Ct({title:"Question",timestamp:oe(t?.createdAt||t?.time),body:r.question,width:Math.max(20,e),titleColor:wt,borderColor:wt}),...Lt({...t,text:r.answer},e)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const r=Ri(t?.text||"");if(r.some(a=>a.kind==="system")){const a=[];let l=!1;for(const[c,f]of r.entries()){if(f.kind==="system"){a.length>0&&fe(a[a.length-1]).trim().length>0&&a.push(Rt()),a.push(As(f.text,oe(t?.createdAt||t?.time))),r.slice(c+1).some(h=>h.kind!=="text"||h.text.trim())&&a.push(Rt());continue}f.text.trim()&&(mn(a,Lt({...t,text:f.text},e,{allowLeadingSystemNotices:!1,skipPrefix:l})),l=!0)}if(a.length>0)return a}}if(t?.role!=="user"&&t?.role!=="assistant"){if(t?.role==="system")return[As(t?.text||"",oe(t?.createdAt||t?.time))];const r=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return Ct({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:oe(t?.createdAt||t?.time),body:At(t?.text||""),width:Math.max(20,e),titleColor:t?.cardTitleColor||(t?.role==="system"?"yellow":"cyan"),borderColor:t?.cardBorderColor||"gray",...r?{bodyColor:"gray",fitToContent:!0}:{}})}const n=pn(Ht(At(t?.text||""),{width:e})),o=Fi(n,t?.role==="user"?wt:null),i=s.skipPrefix?[]:Mi(t);return o.length===0?i.length>0?[i]:[]:Ni(o)?i.length>0?[i,...o]:o:o.map((r,a)=>a===0&&i.length>0?[...i,...r]:r)}function Kt(t,e=80){const s=hn(t);if(!s||s.length===0)return[{text:"No messages yet.",color:"gray"}];const n=[];for(const[o,i]of s.entries()){const r=Lt(i,e);mn(n,r),s[o+1]&&fe(n[n.length-1]).trim().length>0&&n.push(Rt())}return n.length>0?n:[{text:"No messages yet.",color:"gray"}]}function _i(t){const e=hn(t),s=[],n=new Set;for(const o of e||[])for(const i of So(o?.text||"")){const r=`${i.sessionId}/${i.filename}`;n.has(r)||(n.add(r),s.push(i))}return s}function gn(t){const e=de(t),s=Vt(t.sessions.byId),n=zt(t.sessions.flat,t.sessions.byId);if(!e)return{color:"cyan",title:[{text:"Chat",color:"cyan",bold:!0}]};const o=D(e.sessionId),i=e.isSystem?"yellow":"cyan",r=[{text:e.isSystem?`≈ ${Ue(e,t.branding?.title||"PilotSwarm")}`:e.title||"Chat",color:i,bold:!0}],a=t.sessions.flat.find(h=>h.sessionId===e.sessionId),l=fn(e.sessionId,a,s,n);l&&r.push({text:` ${l.text}`,color:l.color}),r.push({text:` [${o}]`,color:"gray"});const c=lo(e.model);c&&r.push({text:` ${c}`,color:"cyan"});const f=to(e.contextUsage);f&&r.push({text:` ${f.text}`,color:"gray"});const d=no(e.contextUsage);return d&&r.push({text:` ${d.text}`,color:"gray"}),(t.ui.inspectorTab==="sequence"||t.ui.inspectorTab==="nodes")&&r.push({text:" [last 5m window]",color:"gray"}),{color:e.isSystem?"yellow":"cyan",title:r}}function $i(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function Yt(t,e=12){const s=$i(t),n=de(t),o=[{text:"Activity",color:"gray",bold:!0}];return n?.statusVersion!=null&&o.push({text:` [current session v${n.statusVersion}]`,color:"gray"}),{title:o,lines:s.length>0?s.map(i=>i.line||[{text:i.text,color:"white"}]):[{text:"No activity yet",color:"gray"}]}}function yn(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 Sn(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":yn(e)}function Hi(t){return t==="raw"?"raw summary":"pretty text"}function Bi(t){return t?.sessionId?`session-${t.sessionId}`:null}function Di(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},o=Bi(e);return s.filter(i=>!(!i||n.source==="currentOrchestration"&&o&&i.orchId!==o||n.level&&n.level!=="all"&&String(i.level||"").toLowerCase()!==n.level))}function Wi(t){const e=nt(t?.podName)||t?.podName||"node",s=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):""),n=String(t?.level||"info").toUpperCase(),o=t?.category==="orchestration"?"◆":t?.category==="activity"?"●":"•";return[{text:`[${t?.time||"--:--:--"}] `,color:"gray"},{text:`${o} `,color:Sn(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${D(s)}] `,color:"gray"}]:[],{text:`${n} `,color:yn(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function Ui(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${D(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:Sn(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function ji(t,e){const s=t.logs||{},n=s.filter||{},o=[{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:Hi(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"},o];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"},o];const i=Di(t,e);return i.length===0?[{text:"Tailing logs…",color:"cyan"},{text:"No logs match the current filter yet.",color:"gray"},{text:"",color:"gray"},o]:[o,{text:"",color:"gray"},...i.map(r=>n.format==="raw"?Wi(r):Ui(r))]}function Cs(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function qi(t){return/\.(json|jsonl)$/i.test(String(t||""))}function Vi(t){return ee.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function zi(t=""){const e=String(t||"").split(`
21
+ `);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function Ps(t,{selected:e=!1,width:s=24,label:n=null}={}){const o=Math.max(8,s),i=Cs(t)?"# ":qi(t)?"{ ":"• ",r=wn(`${i}${n||t}`,o).padEnd(o," ");return e?we(r):{text:r,color:Cs(t)?"cyan":"white",bold:!1}}function Z(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function De(t){const e=Z(t),n=de(t)?.sessionId||null,o=t.files?.filter?.query||"";if(e!=="allSessions")return(Array.isArray(t.files?.bySessionId?.[n]?.entries)?t.files.bySessionId[n].entries:[]).map(l=>({id:`${n||"none"}/${l}`,sessionId:n,filename:l,label:l})).filter(l=>ve(l.filename,o));const i=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(a=>a?.sessionId||a):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),r=[];for(const a of i){const l=Array.isArray(t.files?.bySessionId?.[a]?.entries)?t.files.bySessionId[a].entries:[];for(const c of l)r.push({id:`${a}/${c}`,sessionId:a,filename:c,label:`[${D(a)}] ${c}`})}return r.filter(a=>ve(a.filename,o)||ve(a.sessionId,o)||ve(a.label,o))}function xe(t){const e=De(t);if(e.length===0)return null;if(Z(t)==="allSessions"){const i=t.files?.selectedArtifactId||null;if(i){const l=e.find(c=>c.id===i);if(l)return l}const r=de(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 n=de(t)?.sessionId||null,o=n&&t.files?.bySessionId?.[n]?.selectedFilename||null;return e.find(i=>i.filename===o)||e[0]}function Xt(t,e={}){const s=de(t),n=Math.max(12,Number(e?.listWidth)||Number(e?.width)||24),o=Math.max(18,Number(e?.previewWidth)||Number(e?.width)||36),i=e?.showHints!==!1,r=s?.sessionId||null,a=Z(t),l=t.files?.filter?.query||"",c=De(t),f=xe(t),d=f?.filename||null,h=Math.max(0,c.findIndex(T=>T.id===f?.id)),m=f?.sessionId&&d&&t.files?.bySessionId?.[f.sessionId]?.previews?.[d]||null,g=s?D(s.sessionId):"",w=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(T=>T?.sessionId||T):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),x=a==="allSessions"&&w.some(T=>!t.files?.bySessionId?.[T]?.loaded||t.files?.bySessionId?.[T]?.loading),b=a==="allSessions"&&w.map(T=>t.files?.bySessionId?.[T]?.error).find(Boolean)||null,v=[Vi("files"),...s||a==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(a==="allSessions")x&&c.length===0?v.push({text:"Loading exported files across all sessions…",color:"gray"}):b&&c.length===0?v.push({text:b,color:"red"}):c.length===0?(v.push({text:l?`No artifacts matched "${l}" across any session.`:"No exported files across any session yet.",color:"gray"}),v.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"})):v.push(...c.map((T,K)=>Ps(T.filename,{selected:K===h,width:n,label:T.label})));else if(s){const T=r?t.files?.bySessionId?.[r]:null,K=Array.isArray(T?.entries)?T.entries:[],B=c.filter(W=>W.sessionId===r);T?.loading?v.push({text:"Loading exported files…",color:"gray"}):T?.error?v.push({text:T.error,color:"red"}):K.length===0||B.length===0?(v.push({text:l?`No artifacts matched "${l}" for this session.`:"No exported files for this session yet.",color:"gray"}),v.push({text:l?"Clear the query or upload an artifact to this session.":"Agents must write/export artifacts before they appear here.",color:"gray"})):v.push(...B.map((W,Ne)=>Ps(W.filename,{selected:Ne===h,width:n})))}let M,E;!s&&a!=="allSessions"?(E=[{text:"Preview",color:"cyan",bold:!0}],M=[{text:"No session selected.",color:"gray"}]):d?m?.loading?(E=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...a==="allSessions"&&f?.sessionId?[{text:` · ${D(f.sessionId)}`,color:"gray"}]:[]],M=[{text:"Loading file preview…",color:"gray"}]):m?.error?(E=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...a==="allSessions"&&f?.sessionId?[{text:` · ${D(f.sessionId)}`,color:"gray"}]:[]],M=[{text:m.error,color:"red"}]):(E=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...a==="allSessions"&&f?.sessionId?[{text:` · ${D(f.sessionId)}`,color:"gray"}]:[],...m?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:m?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],M=m?.renderMode==="markdown"?pn(Ht(m?.content||"",{width:o})):zi(m?.content||"")):(E=[{text:"Preview",color:"cyan",bold:!0}],M=[{text:"Select a file to preview it here.",color:"gray"}]);const O=a==="allSessions"?`Files: all sessions${c.length>0?` [${c.length}]`:""}`:s?`Files: ${g}${c.length>0?` [${c.length}]`:""}`:"Files",H=a==="allSessions"?`Artifacts: all sessions${c.length>0?` [${c.length}]`:""}`:s?`Artifacts: ${g}${c.length>0?` [${c.length}]`:""}`:"Artifacts",P=l?` · @${l}`:"";return{panelTitle:[{text:`${O}${P}`,color:"magenta",bold:!0}],listTitle:[{text:`${H}${P}`,color:"cyan",bold:!0}],listLines:v,listBodyLines:v.slice(1),selectedIndex:h,selectedFilename:d,selectedSessionId:f?.sessionId||null,scope:a,previewTitle:E,previewLines:M,previewContent:m?.content||"",previewContentType:m?.contentType||"",previewRenderMode:m?.renderMode||null,previewError:m?.error||null,previewLoading:!!m?.loading,previewScrollOffset:t.ui.scroll.filePreview||0,fullscreen:!!t.files?.fullscreen,fullscreenTitle:[{text:O,color:"magenta",bold:!0},...d?[{text:" · ",color:"gray"},{text:d,color:"cyan",bold:!0}]:[],...i?[{text:" [f filter] [u upload] [a download] [o open] [v/esc close fullscreen]",color:"gray"}]:[]]}}function bn(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=!!de(t)?.pendingQuestion?.question,o=s===e?"v/esc close fullscreen":"v fullscreen";if(t.ui.modal?.type==="artifactUpload")return{left:"Upload a local file into this session's artifact store",right:"type path · left/right move · enter upload · esc cancel"};if(t.ui.modal?.type==="renameSession")return{left:"Rename the selected session title",right:"type title · left/right move · enter save · esc cancel"};if(t.ui.modal?.type==="artifactPicker")return{left:"Select a linked artifact to download",right:"up/down move · enter download · a/esc close"};if(t.ui.modal?.type==="modelPicker")return{left:"Select a model 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==="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"};const i={[S.SESSIONS]:`up/down switch · ctrl-u/ctrl-d page · d done · D delete · r refresh · t title · ${o} · {/} session pane · [/] side pane · T themes · a linked artifacts · drag copy · tab next pane · p prompt`,[S.CHAT]:`j/k scroll · ctrl-u/ctrl-d page · e older history · g/G top/bottom · d done · ${o} · {/} session pane · [/] side pane · T themes · a linked artifacts · drag copy · tab next pane · p prompt`,[S.INSPECTOR]:t.ui.inspectorTab==="logs"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · t tail · f filter · ${o} · left/right tab · [/] side pane · T themes · a linked artifacts · drag copy · tab next pane`:t.ui.inspectorTab==="files"?t.files?.fullscreen?"j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f filter · u/ctrl-a upload · a download · o open · d done · v/esc close fullscreen · left/right tab · {/} session pane · [/] side pane · T themes · tab next pane":"j/k files · ctrl-u/ctrl-d page preview · g/G preview top/bottom · f filter · u/ctrl-a upload · a download · o open · d done · v fullscreen · left/right tab · {/} session pane · [/] side pane · T themes · tab next pane":t.ui.inspectorTab==="history"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f format · r refresh · a save artifact · d done · ${o} · left/right tab · [/] side pane · T themes · m next tab · tab next pane`:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${o} · left/right tab · [/] side pane · T themes · h/l focus · a linked artifacts · drag copy · m next tab · tab next pane`,[S.ACTIVITY]:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${o} · {/} session pane · [/] side pane · T themes · a linked artifacts · drag copy · h left · tab next pane`,[S.PROMPT]:n?`type answer · enter reply · alt-enter newline · T themes · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:`type message · enter send · alt-enter newline · T themes · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`};return{left:t.ui.statusText,right:i[e]||i[S.SESSIONS]}}function Qt(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function Ae(t,e){if(e<=0)return[];const s=[];let n=e;for(const o of t||[]){if(n<=0)break;const i=String(o?.text||"");if(!i)continue;const r=i.length>n&&n>1?`${i.slice(0,n-1)}…`:i.slice(0,n);r&&(s.push({...o,text:r}),n-=r.length)}return s}function be(t){return Array.from(String(t||"")).length}function wn(t,e){const s=String(t||"");return e<=0?"":be(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function Se(t,e){const s=wn(t,e),n=Math.max(0,e-be(s));return s+" ".repeat(n)}function Y(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function It(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 In(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?be(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function Gi(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 xn(t=[]){const e=new Set,s=[];for(const n of t){const o=String(n||"").trim();if(!o)continue;const i=o.toLowerCase();e.has(i)||(e.add(i),s.push(o))}return s.join(" | ")}function Ki(t,e=""){return xn([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function Yi(t,e=""){return xn([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function nt(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 Xi=300*1e3,Qi="last 5m";function Jt(t){let e=0;for(const s of t.history.bySessionId.values())for(const n of s?.events||[]){const o=n?.createdAt instanceof Date?n.createdAt.getTime():new Date(n?.createdAt||0).getTime();Number.isFinite(o)&&(e=Math.max(e,o))}return(!Number.isFinite(e)||e<=0)&&(e=Date.now()),{startMs:e-Xi,endMs:e,label:Qi}}function Ji(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 vn(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 Zi=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done"]);function er(t){return Zi.has(t)}function tr(t){const e=oe(t?.createdAt),s=nt(t?.workerNodeId),n=Gi(t),o=In(n,20),i=t?.createdAt instanceof Date?t.createdAt.getTime():new Date(t?.createdAt||0).getTime(),r={time:e,createdAtMs:Number.isFinite(i)?i: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":return{...r,type:"turn_end",color:"gray",detail:`turn ${t?.data?.iteration??"?"} done`};case"user.message":return{...r,type:"user_msg",color:"white",detail:o?`>> ${o}`:">> user"};case"assistant.message":return{...r,type:"response",color:"green",detail:o?`< ${o}`:"< response"};case"system.message":return{...r,type:"system",color:"yellow",detail:o||"system"};case"session.wait_started":return{...r,type:"wait",color:"yellow",detail:`wait ${Ye(t?.data?.seconds??0)}`};case"session.wait_completed":return{...r,type:"timer",color:"yellow",detail:`${Ye(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const a=Yi(t,o);return{...r,type:"dehydrate",color:"yellow",detail:a?`lossy ${a}`:"lossy handoff"}}case"session.dehydrated":return{...r,type:"dehydrate",color:"cyan",detail:`ZZ ${Ki(t,o)}`.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||D(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...r,type:"cron_start",color:"magenta",detail:`cron ${Ye(t?.data?.intervalSeconds??0)}`};case"session.cron_fired":return{...r,type:"cron_fire",color:"magenta",detail:"cron fired"};case"session.cron_cancelled":return{...r,type:"cron_cancel",color:"magenta",detail:"cron off"};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:o||"error"};default:return null}}function En(t=[]){const e=[];for(const s of t||[]){const n=tr(s);n&&e.push({...n,nodeLabel:er(n.type)?"orch":n.nodeLabel||"orch"})}return e}function sr(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 o=1;for(;s+o<t.length;){const i=t[s+o];if(i?.type!=="spawn"||i?.nodeLabel!=="orch"||i?.time!==n.time)break;o+=1}if(o===1){e.push(n);continue}e.push({...n,detail:`spawn x${o}`}),s+=o-1}return e}function nr(t){const e=String(t?.error||"").trim();if(!e)return null;const s=jt(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),o=Number.isFinite(n)?n:Date.now();return{time:oe(o),createdAtMs:o,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${In(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function or(t,e){const s=nr(e);return!s||(t||[]).some(o=>!o||o.nodeLabel!=="orch"||o.detail!==s.detail?!1:Math.abs(Number(o.createdAtMs||0)-s.createdAtMs)<=6e4)?t:[...t||[],s]}function ir(t,e,s){if(!Number.isFinite(e)||!Number.isFinite(s)||s<e)return[];const n=new Set;for(const o of t.history.bySessionId.values()){const i=En(o?.events||[]);for(const r of i){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((o,i)=>o.localeCompare(i))}function rr(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const o of n?.events||[]){if(!vn(o,e))continue;const i=nt(o?.workerNodeId);i&&s.add(i)}return Array.from(s).sort((n,o)=>n.localeCompare(o))}function ar(t,e,s){const n=[{text:Se("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((o,i)=>{i>0&&n.push({text:" ",color:null}),n.push({text:Se(o,s),color:"white",bold:!0})}),n}function cr(t,e,s){return Y(`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`,"gray")}function lr(t,e,s){const n=t?.orchestration?.bySessionId?.[e?.sessionId]||null;let o="loading orchestration stats...";if(n)if(n.loading&&!n.stats)o="loading orchestration stats...";else if(!n.stats)o=n.error?"orchestration stats unavailable":"loading orchestration stats...";else{const i=n.stats,r=[`hist ${Number(i.historyEventCount)||0} ev`,It(i.historySizeBytes),`q ${Number(i.queuePendingCount)||0}`,`kv ${Number(i.kvUserKeyCount)||0} keys`,It(i.kvTotalValueBytes)],a=[`h${Number(i.historyEventCount)||0}`,It(i.historySizeBytes),`q${Number(i.queuePendingCount)||0}`,`kv${Number(i.kvUserKeyCount)||0}`];o=s<=40?a.join(" · "):r.join(" | ")}return s<=52?[Ae([{text:"Stats ",color:"cyan",bold:!0},{text:o,color:"white"}],Math.max(18,s))]:Ct({title:"Stats",body:o,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function ur(t,e,s,n){const o=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],i=[{text:Se(t.time||"",s),color:"white"},{text:" ",color:null}];return e.forEach((r,a)=>{a>0&&i.push({text:" ",color:null}),r===o?i.push({text:Se(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline}):i.push({text:Se("│",n),color:"gray"})}),i}function dr(t,e){const s=[];return t.forEach((n,o)=>{o>0&&s.push({text:" ",color:null}),s.push({text:Se(n,e),color:"white",bold:!0})}),s}function fr(t,e,s,n={}){const o=!!n?.allowWideColumns,i=lr(t,e,s),r=t.history.bySessionId.get(e.sessionId),a=or(sr(En(r?.events||[])),e);if(a.length===0)return{stickyLines:i,lines:[Y("No events yet - interact with this session to populate the sequence diagram.")]};const l=Jt(t),c=a.filter(E=>Ji(E,l)),f=(c.length>0?c:a).slice(-48),d=ir(t,l.startMs,l.endMs),h=Array.from(new Set(f.map(E=>E.nodeLabel).filter(E=>E&&E!=="orch"))).sort((E,O)=>E.localeCompare(O)),m=d.length>0?d:h,g=8,w=Math.max(18,s),x=Math.max(1,Math.floor((w-g-1)/6));let b=["orch",...m];if(!o&&b.length>x){const E=Math.max(1,x-1);b=[...b.slice(0,E),"…"]}const v=Math.max(0,b.length-1),M=Math.max(4,Math.floor((w-g-1-v)/Math.max(1,b.length)));return{stickyLines:[...i,Y(`Window: ${l.label}`,"gray"),ar(b,g,M),cr(b,g,M)],lines:f.map(E=>ur(E,b,g,M))}}function hr(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 pr(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!vn(s[n],e))continue;const o=nt(s[n]?.workerNodeId);if(o)return o}return null}function mr(t,e,s,n){const o=s>=16?t?.isSystem?Ue(t,e):t?.title||D(t?.sessionId):D(t?.sessionId),i=t?.isSystem?"≈ ":`${un(t)||"."} `,r=Se(`${i}${o}`,s);return n?we(r):{text:r,color:t?.isSystem?"yellow":tt(t),bold:!!t?.isSystem}}function gr(t,e,s={}){const n=!!s?.allowWideColumns,o=hr(t);if(o.length===0)return[Y("No sessions available for the node map.","gray")];const i=Jt(t),r=new Map,a=rr(t,i);let l=0,c=0;for(const b of o){const v=t.sessions.byId[b];if(!v)continue;const M=t.history.bySessionId.get(b);M?.events||(l+=1);const E=pr(M,i);!E||!a.includes(E)||(c+=1,r.has(E)||r.set(E,[]),r.get(E).push(v))}if(a.length===0)return[Y(`No worker activity in the ${i.label} window.`,"gray")];const f=Math.max(18,e),d=Math.max(1,Math.floor((f+1)/10));let h=a;if(!n&&a.length>d){const b=Math.max(0,d-1),v=[],M=a.slice(0,b);for(const E of a.slice(b))v.push(...r.get(E)||[]);r.set("…",v),h=[...M,"…"]}const m=Math.max(0,h.length-1),g=Math.max(8,Math.floor((f-m)/Math.max(1,h.length))),w=h.reduce((b,v)=>Math.max(b,(r.get(v)||[]).length),0),x=[Y(`Window: ${i.label}`,"gray"),dr(h,g),Y(h.map(()=>"─".repeat(g)).join(" "),"gray")];for(let b=0;b<w;b+=1){const v=[];h.forEach((M,E)=>{E>0&&v.push({text:" ",color:null});const O=(r.get(M)||[])[b];if(!O){v.push({text:" ".repeat(g),color:null});return}v.push(mr(O,t.branding?.title||"PilotSwarm",g,O.sessionId===t.sessions.activeSessionId))}),x.push(v)}return l>0&&(x.push(Y("","gray")),x.push(Y(`Loading worker history for ${l} session(s)…`,"gray"))),c===0&&(x.push(Y("","gray")),x.push(Y(`No sessions mapped onto worker nodes in the ${i.label} window.`,"gray"))),x}function yr(t,e=72){const s=t.ui.modal;if(!s||s.type!=="modelPicker")return null;const n=Array.isArray(s.groups)?s.groups:[],o=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(24,e-4),r=[];let a=0;for(const f of n){const d=Ae([{text:`${f.providerId}`,color:"cyan",bold:!0},{text:` (${f.providerType||"provider"})`,color:"gray"}],i);r.push(d);for(const h of f.models||[]){const g=(Array.isArray(s.items)?s.items.findIndex(b=>b.id===h.id):-1)===o,w=Ae([{text:" · ",color:"gray"},{text:h.modelName||h.qualifiedName||h.id,color:"white",bold:!!h.isDefault},...h.cost?[{text:` [${h.cost}]`,color:"gray"}]:[],...h.isDefault?[{text:" ← current default",color:"gray"}]:[]],i),x=g?we(w.map(b=>b.text).join("").padEnd(i," ")):w;g&&(a=r.length),r.push(x)}}const l=Array.isArray(s.items)&&s.items[o]||null,c=l?[[{text:l.modelName||l.qualifiedName||l.id,color:"white",bold:!0}],[{text:`${l.providerId} (${l.providerType||"provider"})`,color:"gray"}],...l.cost?[[{text:`Cost: ${l.cost}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:l.description||"No description available for this model.",color:l.description?"white":"gray"}]]:[[{text:"No model selected.",color:"gray"}]];return{title:s.title||"Select model for new session",rows:r,selectedRowIndex:a,detailsTitle:"Model Details",detailsLines:c,idealWidth:Math.min(Math.max(46,r.reduce((f,d)=>Array.isArray(d)?Math.max(f,Qt(d)):Math.max(f,String(d?.text||"").length),0)+4),e)}}function Sr(t,e=76){const s=t.ui.modal;if(!s||s.type!=="sessionAgentPicker")return null;const n=Array.isArray(s.items)?s.items:[],o=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(24,e-4),r=n.map((f,d)=>{const h=d===o,m=Ae([{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"}]],i);return h?we(m.map(g=>g.text).join("").padEnd(i," ")):m}),a=n[o]||null,l=s.sessionOptions?.model||null,c=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"}]]:[],[{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:o,detailsTitle:"Agent Details",detailsLines:c,idealWidth:Math.min(Math.max(52,r.reduce((f,d)=>Array.isArray(d)?Math.max(f,Qt(d)):Math.max(f,String(d?.text||"").length),0)+4),e)}}function br(t,e=76){const s=t.ui.modal;if(!s||s.type!=="renameSession")return null;const n=String(s.value||""),o=typeof s.agentTitlePrefix=="string"&&s.agentTitlePrefix.trim()?s.agentTitlePrefix.trim():null,i=String(s.currentTitle||"").trim(),r=n.trim()?o?`${o}: ${n.trim()}`:n.trim():o?`${o}: …`:"…",a=[[{text:"Current: ",color:"gray"},{text:i||"(untitled session)",color:i?"white":"gray"}],[{text:"Saved as: ",color:"gray"},{text:r,color:"white",bold:!0}],...o?[[{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:o?"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,be(i||"(untitled session)")+18,be(r)+18),e)}}function wr(t,e=82){const s=t.ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=String(s.value||""),o=s.sessionId||t.ui.promptAttachments?.[0]?.sessionId||t.sessions?.activeSessionId||null,i=o&&t.sessions?.byId?.[o]||null,r=o?i?qt(i,t.branding?.title):D(o):"A new session will be created on upload",a=[[{text:"Target: ",color:"gray"},{text:r,color:o?"white":"gray",bold:!!o}]];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,be(n||"~/path/to/file.md")+20,be(r)+20),e)}}function Zt(t,e={},s=96,n="Filters",o="Choose how this pane is filtered and rendered."){const i=Array.isArray(t.items)?t.items:[],r=Math.max(0,Number(t.selectedIndex)||0),a=i[r]||null,l=i.map((c,f)=>{const d=e?.[c.id]||c.options?.[0]?.id,h=(c.options||[]).map(m=>m.id===d?we(m.label):{text:m.label,color:"white"});return{id:c.id,title:c.label,focused:f===r,description:c.description||"",lines:h.length>0?h:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(c.label||"").length+4,...(c.options||[]).map(m=>String(m?.label||"").length+4))}});return{title:t.title||n,panes:l,helpTitle:a?.label||n,helpLines:[[{text:a?.description||o,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,f)=>c+f.idealWidth,0)+Math.max(0,l.length-1)*2+4),s)}}function Ir(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:Zt(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function xr(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:Zt(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows only the selected session or aggregates artifacts across all sessions.")}function vr(t,e=88){const s=t.ui.modal;if(!s||s.type!=="artifactPicker")return null;const n=Array.isArray(s.items)?s.items:[],o=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(28,e-4),r=n.filter(h=>h.kind==="artifact"),a=r.reduce((h,m)=>{const g=t.files?.bySessionId?.[m.sessionId]?.downloads?.[m.filename];return h+(g?.localPath?1:0)},0),l=Math.max(0,r.length-a),c=n.map((h,m)=>{let g;if(h.kind==="downloadAll")g=Ae([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${l} pending]`,color:"gray"}],i);else{const w=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];g=Ae([{text:w?.localPath?"ok ":"dl ",color:w?.localPath?"green":"cyan",bold:!0},{text:`${D(h.sessionId)}/`,color:"gray"},{text:h.filename,color:"white"}],i)}return m!==o?g:we(g.map(w=>w.text).join("").padEnd(i," "))}),f=n[o]||null;let d=[[{text:"No artifact selected.",color:"gray"}]];if(f?.kind==="downloadAll")d=[[{text:`${r.length} artifacts available`,color:"white",bold:!0}],[{text:`${a} already downloaded`,color:"gray"}],[{text:`${l} 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==="artifact"){const h=t.sessions?.byId?.[f.sessionId]||null,m=t.files?.bySessionId?.[f.sessionId]?.downloads?.[f.filename]||null;d=[[{text:f.filename,color:"white",bold:!0}],[{text:h?qt(h,t.branding?.title):D(f.sessionId),color:"gray"}],...m?.localPath?[[{text:`Saved to: ${m.localPath}`,color:"white"}]]:s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:m?.localPath?"Press Enter to download this artifact again.":"Press Enter to download this artifact.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]]}return{title:s.title||"Artifact Downloads",rows:c.length>0?c:[{text:"No artifacts available.",color:"gray"}],selectedRowIndex:o,detailsTitle:"Artifact Details",detailsLines:d,idealWidth:Math.min(Math.max(54,c.reduce((h,m)=>Array.isArray(m)?Math.max(h,Qt(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function Me(t,e={}){const s=de(t),n=t.ui.inspectorTab,o=Math.max(18,Number(e?.width)||36),i=!!e?.allowWideColumns,r=s?D(s.sessionId):"",a=n==="sequence"||n==="nodes"?Jt(t):null,l=n==="nodes"?[{text:"Node Map",color:"magenta",bold:!0},{text:` [${a.label}]`,color:"gray"}]:s?n==="sequence"?[{text:`Sequence: ${r}`,color:"magenta",bold:!0},{text:` [${a.label}]`,color:"gray"}]:n==="logs"?`Logs: ${r}`:n==="history"?[{text:`History: ${r}`,color:"magenta",bold:!0}]:`Files: ${r}`:"No session selected";let c,f=[];switch(n){case"sequence":{const d=s?fr(t,s,o,{allowWideColumns:i}):{stickyLines:[],lines:["No session selected."]};f=d.stickyLines||[],c=d.lines;break}case"logs":c=s?ji(t,s):["No session selected."];break;case"nodes":c=gr(t,o,{allowWideColumns:i});break;case"files":c=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":c=s?Ar(t,s):["No session selected."];break;default:c=["Inspector view is scaffolded in the new architecture."];break}return{title:l,activeTab:n,tabs:ee,stickyLines:f,lines:c}}const Er={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"};function Tr(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=Er[t.kind]||"gray",n=[],o=[{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&&o.push({text:` ←#${t.sourceEventId}`,color:"cyan"}),n.push(o),t.data)try{const i=JSON.parse(t.data);if(typeof i=="object"&&i!==null)for(const[r,a]of Object.entries(i)){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(i).slice(0,120)}`,color:"white"})}catch{const i=t.data.length>120?t.data.slice(0,117)+"...":t.data;n.push({text:` ${i}`,color:"white"})}return n}function kr(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function Ar(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 o=t.executionHistory?.format||"pretty",i=[];if(i.push({text:`${n.length} event(s) · format: ${o}`,color:"gray"}),i.push(""),o==="raw")for(let r=0;r<n.length;r++){const a=kr(n[r]).split(`
22
+ `);for(const l of a)i.push({text:l,color:"gray"});r<n.length-1&&i.push({text:"────────────────────────────────",color:"gray"})}else for(let r=0;r<n.length;r++){const a=Tr(n[r]);for(const l of a)i.push(l);r<n.length-1&&i.push({text:"────────────────────────────────",color:"gray"})}return i}function Cr(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:Zt(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function Ms(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 Pr(t,e=80){const s=t.ui.modal;if(!s||s.type!=="themePicker")return null;const n=Array.isArray(s.items)?s.items:[],o=Math.max(0,Number(s.selectedIndex)||0),i=n[o]||null,r=s.currentThemeId||t.ui.themeId||null,a=n.find(d=>d.id===r)||null,l=Math.max(24,e-4),c=n.map((d,h)=>{const m=d.id===r?" [current]":"",g=`${d.label}${m}`.slice(0,l);return h===o?we(g.padEnd(l," ")):[{text:g,color:d.id===r?"cyan":"white",bold:d.id===r}]}),f=i?[[{text:`theme: ${i.description||"Shared theme for the portal and native TUI."}`,color:"white"}],{text:"",color:"gray"},[{text:a?.id===i.id?"Currently active in this TUI session.":`Current theme: ${a?.label||"Unknown"}`,color:a?.id===i.id?"green":"gray"}],Ms([{label:"bg",color:i.tui?.background||i.terminal?.background||"#000000"},{label:"surface",color:i.tui?.surface||i.terminal?.background||"#000000"},{label:"fg",color:i.tui?.white||i.terminal?.foreground||"#ffffff"}]),Ms([{label:"blue",color:i.tui?.blue||i.terminal?.blue||"#5555ff"},{label:"green",color:i.tui?.green||i.terminal?.green||"#55ff55"},{label:"magenta",color:i.tui?.magenta||i.terminal?.magenta||"#ff55ff"},{label:"yellow",color:i.tui?.yellow||i.terminal?.yellow||"#ffff55"}]),{text:"",color:"gray"},[{text:"Press Enter to apply. The portal browser picker uses this same shared registry.",color:"gray"}]]:[{text:"No themes available.",color:"gray"}];return{title:s.title||"Theme Picker",idealWidth:Math.max(60,Math.min(e,80)),rows:c,selectedRowIndex:o,detailsTitle:"Theme Details",detailsLines:f}}const Mr=2e4,Ns="Session refresh failed",Nr=new Set([S.SESSIONS,S.CHAT,S.INSPECTOR,S.ACTIVITY]);function Rr(t=[]){const e=[],s=new Map;for(const n of t){const o=n?.providerId||"models";let i=s.get(o);i||(i={providerId:o,providerType:n?.providerType||"provider",models:[]},s.set(o,i),e.push(i)),i.models.push(n)}return e}function Tn(t=[]){for(let e=t.length-1;e>=0;e-=1){const s=t[e]?.data;if(s&&typeof s=="object"){if(typeof s.model=="string"&&s.model)return s.model;if(typeof s.currentModel=="string"&&s.currentModel)return s.currentModel;if(typeof s.newModel=="string"&&s.newModel)return s.newModel}}}function Lr(t){return Tn([t])}function Fr(t,e=[]){let s=Gs(t);for(const n of e){const o=Ks(s,n?.eventType,n?.data,{timestamp:n?.createdAt});o&&(s=o)}return s}function Ft(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 o=0;o<t.length;o+=1)if(!Ft(t[o],e[o]))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 o of s)if(!Object.prototype.hasOwnProperty.call(e,o)||!Ft(t[o],e[o]))return!1;return!0}function Rs(t,e){if(!e?.sessionId)return null;const s={sessionId:e.sessionId};let n=!1;for(const[i,r]of Object.entries(e))i==="sessionId"||r===void 0||Ft(t?.[i],r)||(s[i]=r,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&(s.pendingQuestion=null,n=!0),e.waitReason===void 0&&t?.waitReason&&e.status!=="waiting"&&e.status!=="input_required"&&(s.waitReason=null,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),e.cronActive!==!0&&(t?.cronReason&&(s.cronReason=null,n=!0),t?.cronInterval!=null&&e.cronInterval===void 0&&(s.cronInterval=null,n=!0)),(Or(e.status)||kn(e.orchestrationStatus))&&t?.contextUsage?.compaction?.state==="running"&&e.contextUsage===void 0){const i={...t.contextUsage};delete i.compaction,s.contextUsage=Object.keys(i).length>0?i:null,n=!0}return n?s:null}function kn(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function Or(t){return t==="completed"||t==="failed"||t==="cancelled"}function _r(t){const e=String(t?.message||t||"");return/instance is terminal|terminal orchestration|cannot accept new messages/i.test(e)}function $r(t,e){return{...t||{},chat:[...t&&Array.isArray(t.chat)?t.chat:[],e]}}function ae(t,e){return`- ${t}: ${e}`}function Hr(t,e){const s=String(t?.sessionId||"unknown").slice(0,8),n=String(t?.orchestrationStatus||"Unknown"),o=String(t?.status||"unknown"),i=t?.parentSessionId?String(t.parentSessionId).slice(0,8):"root",r=t?.cronActive===!0||typeof t?.cronInterval=="number"?`active${typeof t?.cronInterval=="number"?` (${t.cronInterval}s)`:""}`:"inactive",a=[`Cannot send a new message because session ${s} is attached to a terminal orchestration instance.`,"","Reference:",ae("Session status",o),ae("Orchestration status",n),ae("Parent session",i),ae("Cron",r)];return typeof t?.waitReason=="string"&&t.waitReason.trim()&&a.push(ae("Wait reason",t.waitReason.trim())),typeof t?.error=="string"&&t.error.trim()?a.push(ae("Error",t.error.trim().split(`
23
+ `)[0])):e?.message&&a.push(ae("Reject reason",String(e.message).trim())),typeof t?.result=="string"&&t.result.trim()&&a.push(ae("Result","completed response available")),a.push("","Create a new session to continue."),{id:`send-error:${t?.sessionId||"unknown"}:${Date.now()}`,role:"system",text:a.join(`
24
+ `),time:"",createdAt:Date.now(),cardTitle:"Error",cardTitleColor:"red",cardBorderColor:"red"}}function X(t){return String(t||"").slice(0,8)}function es(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 Br(t){const e=es(t);return e?Math.max(1,60-`${e}: `.length):60}function Dr(t){const e=String(t?.title||"").trim();if(!e)return"";const s=es(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===X(t?.sessionId)?"":n}return e===X(t?.sessionId)?"":e}function Ls(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 Fs(t){return`📎 ${String(t||"").trim()}`}function Os(t,e){const s=String(t||""),n=j(s,e,s.length),i=s.slice(0,n).match(/(^|\s)(@@?)([^\s]*)$/u);if(!i)return null;const r=i[2],a=String(i[3]||"");return{kind:r==="@@"?"sessions":"artifacts",query:a,signature:`${r}${a}`,tokenStart:(i.index||0)+String(i[1]||"").length,tokenEnd:n}}function Wr(t,e,s,n){const o=String(t||""),i=j(o,e),r=j(o,s),a=String(n||"");return{prompt:`${o.slice(0,i)}${a}${o.slice(r)}`,cursor:i+a.length}}function Ur(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function jr(t){const e=String(t?.sessionId||"").trim(),s=X(e)||"session";return`Referenced session: ${Ur(t?.title,s)} — session://${e}`}function _s(t,e,s){if(!e)return _e(t,String(t||"").length,s);const n=String(t||""),o=n.slice(e.tokenEnd,e.tokenEnd+1),i=!o||/\s/u.test(o);return Wr(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${i?" ":""}`)}function qr(t,e=[]){let s=String(t||"");for(const n of e||[]){const o=String(n?.token||"").trim();o&&(s=s.split(o).join(" "))}return s.replace(/[ \t]+\n/g,`
25
+ `).replace(/\n[ \t]+/g,`
26
+ `).replace(/[ \t]{2,}/g," ").trim()}function Vr(t,e=[]){const s=Array.isArray(e)?e.filter(i=>i?.sessionId&&i?.filename):[];if(s.length===0)return String(t||"");const n=s.map(i=>`[Attached file: ${i.filename} — artifact://${i.sessionId}/${i.filename}]`),o=qr(t,s);return n.join(`
27
+ `)+(o?`
28
+
29
+ ${o}`:"")}function $s(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function An(t){return Array.from(String(t||"")).length}function zr(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=Xs(s.value||"");for(const o of n)e.push(o);continue}if(Array.isArray(s)){e.push(s);continue}e.push(s)}return e}function Gr(t,e){const s=Math.max(1,Number(e)||1),n=An(t);return Math.max(1,Math.ceil(n/s))}function Fe(t,e){const s=Math.max(1,Number(e)||1);return zr(t).reduce((n,o)=>{if(!o)return n+1;if(Array.isArray(o)){const i=o.reduce((r,a)=>r+An(a?.text||""),0);return n+Math.max(1,Math.ceil(i/s))}return n+Gr(o.text||"",s)},0)}function j(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function Cn(t){return String(t||"").split(`
30
+ `)}function Kr(t,e){const n=String(t||"").slice(0,j(t,e)).split(`
31
+ `),o=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:o.length}}function Yr(t,e,s){const n=Cn(t),o=Math.max(0,Math.min(Number(e)||0,Math.max(0,n.length-1))),i=Math.max(0,Math.min(Number(s)||0,n[o]?.length||0));let r=0;for(let a=0;a<o;a+=1)r+=(n[a]?.length||0)+1;return j(t,r+i)}function _e(t,e,s){const n=String(t||""),o=j(n,e),i=String(s||"");return{prompt:`${n.slice(0,o)}${i}${n.slice(o)}`,cursor:o+i.length}}function xt(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 Ge(t){return/\s/u.test(t||"")}function Pn(t,e,s){const n=String(t||"");let o=j(n,e);if(s<0){for(;o>0&&Ge(n[o-1]);)o-=1;for(;o>0&&!Ge(n[o-1]);)o-=1;return o}for(;o<n.length&&Ge(n[o]);)o+=1;for(;o<n.length&&!Ge(n[o]);)o+=1;return o}function Xr(t,e){const s=String(t||""),n=j(s,e),o=Pn(s,n,-1);return o===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,o)}${s.slice(n)}`,cursor:o}}function Qr(t,e,s){const n=Cn(t);if(n.length<=1)return j(t,e);const o=Kr(t,e),i=Math.max(0,Math.min(o.line+s,n.length-1));return i===o.line?j(t,e):Yr(t,i,o.column)}const Jr=3e3,Zr=new Set(["logs","sequence"]),ea=2e5,ta=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),sa=new Set([".json",".jsonl"]),na=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function Mn(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function Nn(t,e=""){const s=Mn(t),n=String(e||"").toLowerCase();return na.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}function Hs(t,e=ea){const s=String(t??"");return s.length<=e?s:`${s.slice(0,e)}
32
+
33
+ [Preview truncated at ${e.toLocaleString()} characters. Open the artifact directly if you need the full file.]`}function Bs(t,e,s=""){const n=String(s||"").toLowerCase(),o=Mn(t);if(Nn(t,s))return{content:`Preview is not available in the terminal UI for ${t}.
34
+
35
+ This artifact looks binary or non-text, so use the downloadable artifact instead.`,contentType:s||"application/octet-stream",renderMode:"note"};const i=Hs(e);if(ta.has(o)||n.includes("markdown"))return{content:i,contentType:s||"text/markdown",renderMode:"markdown"};if(sa.has(o)||n.includes("json"))try{return{content:Hs(JSON.stringify(JSON.parse(String(e??"")),null,2)),contentType:s||"application/json",renderMode:"text"}}catch{return{content:i,contentType:s||"application/json",renderMode:"text"}}return{content:i,contentType:s||"text/plain",renderMode:"text"}}class oa{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.logUnsubscribe=null,this.promptReferenceSignature=null,this.promptReferenceSyncVersion=0}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:[]})}getPromptReferenceContext(){const e=this.getState();return Os(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=xe(s),o=n?.sessionId||s.sessions.activeSessionId||null,i=n?.filename||null;if(!o||!i)return!1;const r=Fs(i),a=_s(s.ui.prompt,e,r),l=this.getPromptAttachments(),c=l.findIndex(h=>h?.sessionId===o&&h?.filename===i),f={...c>=0?l[c]:{},id:`${o}/${i}`,sessionId:o,filename:i,resolvedPath:i,token:r},d=c>=0?l.map((h,m)=>m===c?f:h):[...l,f];return this.setPrompt(a.prompt,a.cursor),this.setPromptAttachments(d),this.setFocus(S.PROMPT),this.dispatch({type:"ui/status",text:`Attached ${i}`}),!0}acceptSessionPromptReference(e=this.getPromptReferenceContext()){if(!e||e.kind!=="sessions")return!1;const s=this.getState(),o=Gt(s)[0]||null,i=o?.sessionId&&s.sessions.byId[o.sessionId]||null;if(!i?.sessionId)return!1;const r=jr(i),a=_s(s.ui.prompt,e,r);return this.setPrompt(a.prompt,a.cursor),this.setFocus(S.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${X(i.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}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=Os(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 o=++this.promptReferenceSyncVersion;this.ensureFilesForSession(n).then(async()=>{if(this.promptReferenceSyncVersion!==o)return;const r=De(this.getState()).filter(a=>a.sessionId===n)[0]||null;r?.filename&&(this.dispatch({type:"files/select",sessionId:n,filename:r.filename}),await this.ensureFilePreview(n,r.filename).catch(()=>{}))}).catch(()=>{})}async start(){await this.transport.start();const e=typeof this.transport.getLogConfig=="function"?this.transport.getLogConfig():null;e&&this.dispatch({type:"logs/config",available:e.available,availabilityReason:e.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(s=>{this.dispatch({type:"connection/error",error:s?.message||String(s),statusText:Ns})})},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===Ns,o=this.getState().sessions.activeSessionId;let i=await this.transport.listSessions();const r=o;if(r&&!i.some(c=>c?.sessionId===r)&&typeof this.transport.getSession=="function"){const c=await this.transport.getSession(r).catch(()=>null);c?.sessionId&&(i=[...i,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:i});const a=this.getState().sessions.activeSessionId,l=new Set;if(a){if(a!==o){await this.loadSession(a);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 f=this.getState(),d=f.sessions.byId[a]||null;if(d?.parentSessionId&&typeof this.transport.getSession=="function"){const h=Object.values(f.sessions.byId).filter(m=>m?.parentSessionId===d.parentSessionId).map(m=>m.sessionId).filter(m=>m&&m!==a).slice(0,6);await Promise.all(h.map(m=>this.syncSessionDetail(m).catch(()=>{})));for(const m of h)l.add(m)}}await this.syncVisibleSessionDetails(l).catch(()=>{}),this.ensureInspectorData().catch(()=>{}),this.evictStaleSessionState()}evictStaleSessionState(){const e=this.getState(),s=e.sessions.activeSessionId,n=Date.now(),o=6e4,i=20,r=Object.entries(e.orchestration.bySessionId||{});if(r.length>i){const f=r.filter(([d,h])=>d!==s&&!h?.loading).sort((d,h)=>(d[1]?.fetchedAt||0)-(h[1]?.fetchedAt||0)).slice(0,r.length-i).filter(([,d])=>n-(d?.fetchedAt||0)>o);f.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:f.map(([d])=>d)})}const a=Object.entries(e.executionHistory?.bySessionId||{});if(a.length>i){const f=a.filter(([d,h])=>d!==s&&!h?.loading).sort((d,h)=>(d[1]?.fetchedAt||0)-(h[1]?.fetchedAt||0)).slice(0,a.length-i).filter(([,d])=>n-(d?.fetchedAt||0)>o);f.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:f.map(([d])=>d)})}const l=Object.entries(e.files.bySessionId||{});if(l.length>i){const f=l.filter(([d])=>d!==s).slice(0,l.length-i);f.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:f.map(([d])=>d)})}const c=[...e.history.bySessionId.entries()];if(c.length>i*2){const f=c.filter(([d])=>d!==s).slice(0,c.length-i*2).map(([d])=>d);f.length>0&&this.dispatch({type:"history/evict",sessionIds:f})}}async syncVisibleSessionDetails(e=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=He({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??ke(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.fullscreenPane),o=this.getSessionListMaxRows(n),i=Nt(s,o),r=[...new Set(i.map(a=>a.sessionId).filter(a=>a&&!e.has(a)))];r.length!==0&&await Promise.all(r.map(a=>this.syncSessionDetail(a).catch(()=>{})))}async ensureSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),o=Math.max($,Number(n?.loadedEventLimit??$)||$);if(!s&&n?.events)return n;if(!s&&this.sessionHistoryLoads.has(e))return this.sessionHistoryLoads.get(e);const i=(async()=>{const r=await this.transport.getSessionEvents(e,void 0,o),a={...qe(r,{requestedLimit:o}),lastSeq:r[r.length-1]?.seq||0};this.dispatch({type:"history/set",sessionId:e,history:a});const l=Tn(r),c=this.getState().sessions.byId[e]||{},f=Fr(c.contextUsage,r);return(l||f)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...l?{model:l}:{},...f?{contextUsage:f}:{}}}),a})().finally(()=>{this.sessionHistoryLoads.delete(e)});return this.sessionHistoryLoads.set(e,i),i}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=He({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??ke(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.fullscreenPane),o=this.getSessionListMaxRows(n),i=Nt(s,o),r=[...new Set(i.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(Z(this.getState())),e==="history"){const s=this.getState().sessions.activeSessionId,n=s&&this.getState().executionHistory?.bySessionId?.[s]||null;s&&!n&&await this.ensureExecutionHistory(s)}}async ensureOrchestrationStats(e,{force:s=!1}={}){if(!e||typeof this.transport.getOrchestrationStats!="function")return null;const n=this.getState().orchestration.bySessionId?.[e]||null,o=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&o-n.fetchedAt<Mr)return n;if(!s&&this.sessionOrchestrationStatsLoads.has(e))return this.sessionOrchestrationStatsLoads.get(e);this.dispatch({type:"orchestration/statsLoading",sessionId:e});const i=(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,i),i}async ensureExecutionHistory(e,{force:s=!1}={}){if(!e||typeof this.transport.getExecutionHistory!="function")return null;const n=this.getState().executionHistory?.bySessionId?.[e]||null,o=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&o-n.fetchedAt<15e3)return n;this.dispatch({type:"executionHistory/loading",sessionId:e});try{const i=await this.transport.getExecutionHistory(e);this.dispatch({type:"executionHistory/loaded",sessionId:e,events:i||[],fetchedAt:Date.now()})}catch(i){console.error("[executionHistory] fetch error:",i?.message||i),this.dispatch({type:"executionHistory/error",sessionId:e,error:i?.message||String(i),fetchedAt:Date.now()})}return this.getState().executionHistory?.bySessionId?.[e]||null}async ensureFilesForScope(e=Z(this.getState()),{force:s=!1}={}){if(e==="allSessions"){const o=[...new Set([...Array.isArray(this.getState().sessions.flat)?this.getState().sessions.flat:[],...Object.keys(this.getState().files.bySessionId||{})])].filter(Boolean);return o.length===0?[]:Promise.allSettled(o.map(i=>this.ensureFilesForSession(i,{force:s})))}const n=this.getState().sessions.activeSessionId;return n?this.ensureFilesForSession(n,{force:s}):null}async ensureSelectedFilePreview(){const e=xe(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 o=await this.transport.listArtifacts(e);this.dispatch({type:"files/sessionLoaded",sessionId:e,entries:o});const i=this.getState().files.bySessionId[e];return i?.selectedFilename&&await this.ensureFilePreview(e,i.selectedFilename).catch(()=>{}),i}catch(o){return this.dispatch({type:"files/sessionError",sessionId:e,error:o?.message||String(o)}),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]?.previews?.[s];if(!n&&i?.loading||!n&&i&&(i.content!==void 0||i.error))return i;this.dispatch({type:"files/previewLoading",sessionId:e,filename:s});try{const r=Nn(s)?Bs(s,"",""):Bs(s,await this.transport.downloadArtifact(e,s),"");return this.dispatch({type:"files/previewLoaded",sessionId:e,filename:s,...r}),r}catch(r){return this.dispatch({type:"files/previewError",sessionId:e,filename:s,error:r?.message||String(r)}),null}}buildArtifactPickerItems(e=[]){const s=(e||[]).map(n=>({id:`${n.sessionId}/${n.filename}`,kind:"artifact",sessionId:n.sessionId,filename:n.filename}));return s.length>1&&s.push({id:"__downloadAll__",kind:"downloadAll"}),s}buildArtifactPickerModal({artifactLinks:e,previousFocus:s,selectedId:n}={}){const o=this.buildArtifactPickerItems(e);if(o.length===0)return null;const i=o.findIndex(r=>r.id===n);return{type:"artifactPicker",title:"Artifact Downloads",previousFocus:s,artifactLinks:e,items:o,selectedIndex:i>=0?i: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||[],previousFocus:s.previousFocus,selectedId:e||this.getArtifactPickerSelectionId()});if(!n){this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/status",text:"No artifact links 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 o=this.getState().sessions.activeSessionId;return(e===o||this.getState().ui.inspectorTab==="files")&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),e===o&&(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=xe(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||Z(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:o}=s,i=Z(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?.[o]?.localPath||null;if(r||(this.dispatch({type:"ui/status",text:`Downloading ${o} to open it...`}),r=(await this.saveArtifactDownload(n,o))?.localPath||null),!r){this.dispatch({type:"ui/status",text:`Open failed: could not save ${o} locally`});return}try{await this.transport.openPathInDefaultApp(r),this.dispatch({type:"ui/status",text:i==="allSessions"?`Opened ${X(n)} ${o} in the default app`:`Opened ${o} in the default app`})}catch(a){this.dispatch({type:"ui/status",text:`Open failed: ${a?.message||String(a)}`})}}async downloadSelectedArtifact(){const e=xe(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 openArtifactPicker(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=_i(e);if(n.length===0){this.dispatch({type:"ui/status",text:"No artifact links in the current chat view"});return}const o=this.getState().files.bySessionId[s]?.selectedFilename||null,i=o?`${s}/${o}`:null,r=this.buildArtifactPickerModal({artifactLinks:n,previousFocus:e.ui.focusRegion,selectedId:i});if(!r){this.dispatch({type:"ui/status",text:"No artifact links in the current chat view"});return}this.dispatch({type:"ui/modal",modal:r}),this.dispatch({type:"ui/status",text:"Select a linked artifact and press Enter to download"})}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==="downloadAll"){const o=(e.items||[]).filter(r=>r.kind!=="artifact"?!1:!this.getState().files.bySessionId[r.sessionId]?.downloads?.[r.filename]?.localPath);if(o.length===0){this.dispatch({type:"ui/status",text:"All artifacts already downloaded"});return}this.dispatch({type:"ui/status",text:`Downloading ${o.length} artifacts...`});let i=0;for(const r of o)(await this.saveArtifactDownload(r.sessionId,r.filename))?.localPath&&(i+=1);this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${i}/${o.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=Z(this.getState());await this.ensureFilesForScope(s);const n=De(this.getState());if(n.length===0)return;const o=xe(this.getState())||n[0],i=Math.max(0,n.findIndex(l=>l.id===o?.id)),r=Math.max(0,Math.min(n.length-1,i+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 ${X(a.sessionId)} ${a.filename}`:`Previewing ${a.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;const s=Z(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 ${X(e.sessionId)} ${e.filename}`:`Previewing ${e.filename}`})}toggleFilePreviewFullscreen(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.files.bySessionId[s];if(!n?.selectedFilename)return;const o=!e.files.fullscreen;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,o=s===S.PROMPT?n:s;if(!Nr.has(o)||o===S.INSPECTOR&&e.ui.inspectorTab==="files")return;const i=n===o?null:o;this.dispatch({type:"ui/fullscreenPane",fullscreenPane:i}),this.dispatch({type:"ui/status",text:i?`Fullscreen ${o} pane`:`Closed fullscreen ${o} pane`}),!i&&s===S.PROMPT&&this.setFocus(o)}openFilesFilter(){const e=Z(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 only the selected session or aggregates exported files across all sessions.",options:[{id:"selectedSession",label:"Selected session"},{id:"allSessions",label:"All sessions"}]}]}}),this.dispatch({type:"ui/status",text:`Editing files filter: Scope = ${e==="allSessions"?"All sessions":"Selected session"}`})}async loadSession(e){if(!e)return;this.getState().sessions.activeSessionId!==e&&this.dispatch({type:"sessions/selected",sessionId:e}),await this.ensureSessionHistory(e,{force:!0}),await this.syncSessionDetail(e).catch(()=>{}),this.attachActiveSession(e),this.ensureInspectorData().catch(()=>{})}mergeSessionEvent(e,s){if(!e||!s)return!1;const o=this.getState().history.bySessionId.get(e)||{chat:[],activity:[],lastSeq:0};if(s.seq<=(o.lastSeq||0))return!1;this.dispatch({type:"history/set",sessionId:e,history:Bo(o,s)});const i=Lr(s),r=this.getState().sessions.byId[e]||{},a=Ks(r.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(i||a)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...i?{model:i}:{},...a?{contextUsage:a}:{}}}),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),o=await this.transport.getSessionEvents(e,n,200);if(!(!Array.isArray(o)||o.length===0))for(const i of o)this.mergeSessionEvent(e,i)}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,o=Rs(n,s);o&&this.dispatch({type:"sessions/merged",session:o})}async createSession(e={}){const s=await this.transport.createSession(e);await this.refreshSessions(),await this.loadSession(s.sessionId),this.setFocus(S.PROMPT),this.dispatch({type:"ui/status",text:`Created session ${s.sessionId.slice(0,8)}`})}async createSessionForAgent(e,s={}){if(typeof this.transport.createSessionForAgent!="function")throw new Error("Named-agent session creation is not supported by this transport");const n=await this.transport.createSessionForAgent(e,s);await this.refreshSessions(),await this.loadSession(n.sessionId),this.setFocus(S.PROMPT),this.dispatch({type:"ui/status",text:`Created ${Ls(e,s.title)} session ${n.sessionId.slice(0,8)}`})}async openSessionAgentPicker(e={}){const s=typeof this.transport.listCreatableAgents=="function"?await this.transport.listCreatableAgents():[],o=(typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0;if(!Array.isArray(s)||s.length===0){if(!o){this.dispatch({type:"ui/status",text:"No user-creatable agents are available for this app"});return}await this.createSession(e);return}const i=[];o&&i.push({id:"__generic__",kind:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,initialPrompt:null});for(const r of s){const a=String(r?.name||"").trim();a&&i.push({id:a,kind:"agent",agentName:a,title:Ls(a,r?.title),description:String(r?.description||"").trim(),tools:Array.isArray(r?.tools)?r.tools.filter(Boolean):[],splash:typeof r?.splash=="string"&&r.splash.trim()?r.splash:null,initialPrompt:typeof r?.initialPrompt=="string"&&r.initialPrompt.trim()?r.initialPrompt:null})}this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",items:i,selectedIndex:0,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select an agent and press Enter"})}async openNewSessionFlow(e={}){await this.openSessionAgentPicker(e)}async openModelPicker(){if(typeof this.transport.listModels!="function"){await this.openNewSessionFlow();return}const e=await this.transport.listModels();if(!Array.isArray(e)||e.length===0){this.dispatch({type:"ui/status",text:"No models available"});return}const s=typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0,n=typeof this.transport.getModelsByProvider=="function"?this.transport.getModelsByProvider():Rr(e),o=[],i=n.map(a=>({providerId:a.providerId,providerType:a.type||a.providerType,models:(a.models||[]).map(l=>{const c={id:l.qualifiedName,qualifiedName:l.qualifiedName,modelName:l.modelName||l.qualifiedName,providerId:l.providerId||a.providerId,providerType:l.providerType||a.type||a.providerType,description:l.description||"",cost:l.cost||null,isDefault:s===l.qualifiedName};return o.push(c),c})})).filter(a=>a.models.length>0),r=Math.max(0,o.findIndex(a=>a.qualifiedName===s));this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:"Select model for new session",items:o,groups:i,selectedIndex:r,previousFocus:this.getState().ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}openThemePicker(){const e=ui().map(o=>({id:o.id,label:o.label,description:o.description,page:o.page,terminal:o.terminal,tui:o.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(o=>o.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 (${X(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 o=String(e||"").replace(/\r?\n/g,""),i=j(o,s);this.updateArtifactUploadModal({value:o,cursorIndex:i})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=_e(s.value||"",s.cursorIndex||0,String(e||"").replace(/\r?\n/g,""));this.setArtifactUploadValue(n.prompt,n.cursor)}deleteArtifactUploadChar(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=xt(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.transport.createSession({});return await this.refreshSessions(),await this.loadSession(n.sessionId),this.setFocus(S.PROMPT),n.sessionId}async finalizeArtifactUpload(e,{sessionId:s=null,suppressStatus:n=!1}={}){const o=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!o||!e?.filename)throw new Error("Upload did not return a session id and filename");return this.getState().sessions.activeSessionId!==o&&await this.loadSession(o),await this.ensureFilesForSession(o,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:o,filename:e.filename}),await this.ensureFilePreview(o,e.filename,{force:!0}).catch(()=>null),n||this.dispatch({type:"ui/status",text:`Uploaded ${e.filename}`}),{sessionId:o,filename:e.filename}}async applyUploadedPromptAttachment(e,{sessionId:s=null,suppressStatus:n=!1}={}){const o=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!o||!e?.filename)throw new Error("Upload did not return a session id and filename");const i=Fs(e.filename),r=this.getState().ui.prompt,a=this.getState().ui.promptCursor,l=this.getPromptAttachments(),c=l.findIndex(d=>d?.sessionId===o&&d?.filename===e.filename);if(this.getState().sessions.activeSessionId!==o&&await this.loadSession(o),c===-1||!r.includes(l[c]?.token||i)){const d=_e(r,a,`${i} `);this.setPrompt(d.prompt,d.cursor)}const f=c>=0?l.map((d,h)=>h===c?{...d,sessionId:o,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:i}:d):[...l,{id:`${o}/${e.filename}`,sessionId:o,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:i}];return this.setPromptAttachments(f),await this.ensureFilesForSession(o,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:o,filename:e.filename}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(o,e.filename,{force:!0}).catch(()=>null),this.setFocus(S.PROMPT),n||this.dispatch({type:"ui/status",text:c>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:o,existingAttachmentIndex:c,token:i}}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 o=s||await this.ensurePromptAttachmentSessionId(),i=[];let r=0,a=null;for(const l of n)try{const c=await this.transport.uploadArtifactFromFile(o,l);i.push(c),await this.finalizeArtifactUpload(c,{sessionId:o,suppressStatus:!0})}catch(c){r+=1,a=c}return i.length>0?this.dispatch({type:"ui/status",text:r>0?`Uploaded ${i.length}/${n.length} file(s); last error: ${a?.message||String(a)}`:i.length===1?`Uploaded ${i[0].filename}`:`Uploaded ${i.length} files`}):a&&this.dispatch({type:"ui/status",text:`Upload failed: ${a?.message||String(a)}`}),i}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(),o=await this.transport.uploadArtifactFromPath(n,s),i=await this.finalizeArtifactUpload(o,{sessionId:n,suppressStatus:!0});this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/status",text:`Uploaded ${i.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 o=Dr(n),i=es(n),r=Br(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:`Rename (${X(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:o,cursorIndex:o.length,agentTitlePrefix:i,currentTitle:String(n.title||"").trim(),maxLength:r}}),this.dispatch({type:"ui/status",text:i?`Rename title for ${i}; the agent-name prefix stays fixed`:"Type a new session title and press Enter to save"})}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 o=$s(e,n.maxLength),i=j(o,s);this.updateRenameSessionModal({value:o,cursorIndex:i})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=_e(s.value||"",s.cursorIndex||0,$s(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=xt(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}if(typeof this.transport.renameSession!="function"){this.dispatch({type:"ui/status",text:"Session renaming is not supported by this transport"});return}const o=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),o&&this.setFocus(o),this.dispatch({type:"ui/status",text:`Renaming ${X(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${X(s)}`})}catch(i){this.dispatch({type:"ui/status",text:`Rename failed: ${i?.message||String(i)}`})}}closeModal(){const e=this.getState().ui.modal;e&&(this.dispatch({type:"ui/modal",modal:null}),e.previousFocus&&this.setFocus(e.previousFocus),this.dispatch({type:"ui/status",text:"Connected"}))}moveModalSelection(e){const s=this.getState().ui.modal;if(!s||!Array.isArray(s.items)||s.items.length===0)return;if(s.type==="logFilter"||s.type==="filesFilter"||s.type==="historyFormat"){const i=Math.max(0,Math.min(Number(s.selectedIndex)||0,s.items.length-1)),r=s.items[i];if(!r||!Array.isArray(r.options)||r.options.length===0)return;const a=r.options.map(d=>d.id).filter(Boolean);if(a.length===0)return;const l=s.type==="filesFilter"?this.getState().files.filter?.[r.id]||a[0]:s.type==="historyFormat"?this.getState().executionHistory?.format||a[0]:this.getState().logs.filter?.[r.id]||a[0],c=Re(a,l,e),f=r.options.find(d=>d.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} = ${f?.label||c}`});return}const n=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(0,Math.min(n+e,s.items.length-1));this.dispatch({type:"ui/modalSelection",index:o})}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 o=(Math.max(0,Number(s.selectedIndex)||0)+e+s.items.length)%s.items.length,i=s.items[o],r=s.type==="filesFilter"?this.getState().files.filter?.[i.id]||i.options?.[0]?.id:s.type==="historyFormat"?this.getState().executionHistory?.format||i.options?.[0]?.id:this.getState().logs.filter?.[i.id]||i.options?.[0]?.id,a=i.options?.find(l=>l.id===r)||i.options?.[0];this.dispatch({type:"ui/modalSelection",index:o}),this.dispatch({type:"ui/status",text:`Editing ${i.label}: ${a?.label||r||""}`})}async confirmModal(){const e=this.getState().ui.modal;if(e){if(e.type==="artifactUpload"){await this.confirmArtifactUploadModal();return}if(e.type==="renameSession"){await this.confirmRenameSessionModal();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=pe(s?.id);if(!n){this.dispatch({type:"ui/status",text:"Unable to apply that theme"});return}const o=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/theme",themeId:n.id}),o&&this.setFocus(o),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;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),await this.openNewSessionFlow(s?.id?{model:s.id}:{});return}if(e.type==="sessionAgentPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,o=e.sessionOptions||{};if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s||s.kind==="generic"){await this.createSession(o);return}await this.createSessionForAgent(s.agentName,{...o,...s.title?{title:s.title}:{},...s.splash?{splash:s.splash}:{},...s.initialPrompt?{initialPrompt:s.initialPrompt}:{}});return}if(e.type==="logFilter"){this.closeModal();return}if(e.type==="historyFormat"){this.closeModal();return}e.type==="artifactPicker"&&await this.downloadArtifactModalSelection()}}openLogFilter(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"logFilter",title:"Log Filters",previousFocus:e,selectedIndex:0,items:[{id:"source",label:"Source nodes",description:"Choose whether the log pane shows logs from all nodes or only the current orchestration.",options:[{id:"allNodes",label:"All nodes"},{id:"currentOrchestration",label:"Current orchestration"}]},{id:"level",label:"Levels",description:"Filter logs by severity/verbosity level.",options:[{id:"all",label:"All"},{id:"info",label:"Info"},{id:"warn",label:"Warn"},{id:"error",label:"Error"},{id:"debug",label:"Debug"},{id:"trace",label:"Trace"}]},{id:"format",label:"Format",description:"Raw shows the structured time/node/level summary. Pretty shows the cleaned message text, colored by orchestration vs activity.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw summary"}]}]}}),this.dispatch({type:"ui/status",text:"Tab/Shift-Tab switch filters · Up/Down change values · Enter close · Esc cancel"})}openHistoryFormat(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"historyFormat",title:"Execution History Format",previousFocus:e,selectedIndex:0,items:[{id:"format",label:"Format",description:"Pretty prints a human-readable view with colored event kinds. Raw JSON shows the full event objects.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw JSON"}]}]}}),this.dispatch({type:"ui/status",text:"Up/Down change format · Enter close · Esc cancel"})}toggleLogTail(){const e=this.getState().logs;if(!e.available){this.dispatch({type:"ui/status",text:e.availabilityReason||"Log tailing is not available in this environment"});return}if(e.tailing){this.detachLogStream(),typeof this.transport.stopLogTail=="function"&&this.transport.stopLogTail().catch(()=>{}),this.dispatch({type:"logs/tailing",tailing:!1}),this.dispatch({type:"ui/status",text:"Log tailing stopped"});return}if(typeof this.transport.startLogTail!="function"){this.dispatch({type:"ui/status",text:"Log tailing is not supported by this transport"});return}this.logUnsubscribe=this.transport.startLogTail(s=>{const n=Array.isArray(s)?s:[s];n.length>0&&this.dispatch({type:"logs/append",entries:n})}),this.dispatch({type:"logs/tailing",tailing:!0}),this.dispatch({type:"ui/status",text:"Log tailing started"})}async sendPrompt(){const e=this.getState(),s=e.ui.prompt,n=e.ui.promptCursor,o=this.getPromptAttachments(),i=o[0]?.sessionId||null,r=Vr(s,o);if(!r.trim())return;let a=e.sessions.activeSessionId;i&&(a=i,e.sessions.activeSessionId!==i&&await this.loadSession(i));let l=a&&e.sessions.byId[a]||null;a&&!l&&(l=this.getState().sessions.byId[a]||null),a||(a=(await this.transport.createSession({})).sessionId,await this.refreshSessions(),await this.loadSession(a),l=this.getState().sessions.byId[a]||null);const c=!!l?.pendingQuestion?.question,f=this.getState().history.bySessionId.get(a)||{chat:[],activity:[],lastSeq:0};this.dispatch({type:"history/set",sessionId:a,history:{...f,chat:[...f.chat,{id:`optimistic:${Date.now()}`,role:"user",text:r,time:"",createdAt:Date.now(),optimistic:!0}]}}),this.setPrompt("",0),this.dispatch({type:"ui/status",text:"Sending..."});try{if(c&&typeof this.transport.sendAnswer=="function"){await this.transport.sendAnswer(a,r),this.dispatch({type:"sessions/merged",session:{sessionId:a,pendingQuestion:null}}),this.scheduleSessionDetailSync(a,100),this.syncSessionEvents(a).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"});return}await this.transport.sendMessage(a,r,{enqueueOnly:!!(l?.isSystem||l?.status==="running")}),this.syncSessionEvents(a).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Prompt sent"})}catch(d){this.setPrompt(s,n),this.setPromptAttachments(o),await this.ensureSessionHistory(a,{force:!0}).catch(()=>{});let h=null;if(typeof this.transport.getSession=="function"){h=await this.transport.getSession(a).catch(()=>null);const g=Rs(this.getState().sessions.byId[a]||null,h);g&&this.dispatch({type:"sessions/merged",session:g})}const m=h||this.getState().sessions.byId[a]||l||{sessionId:a};if(kn(m?.orchestrationStatus)||_r(d)){const g=this.getState().history.bySessionId.get(a)||{chat:[],activity:[],lastSeq:0};this.dispatch({type:"history/set",sessionId:a,history:$r(g,Hr(m,d))})}this.dispatch({type:"ui/status",text:d?.message||String(d)})}}setPrompt(e,s=String(e||"").length){const n=String(e||""),o=Math.max(0,Math.min(Number.isFinite(s)?s:n.length,n.length)),i=this.getState().ui;i.prompt===n&&i.promptCursor===o||(this.dispatch({type:"ui/prompt",prompt:n,promptCursor:o}),this.syncPromptReferenceBrowser())}insertPromptText(e){const s=this.getState().ui,n=_e(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=xt(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=Xr(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,Pn(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui;this.setPrompt(s.prompt,Qr(s.prompt,s.promptCursor,e))}getCurrentLayout(e={}){const s=this.getState().ui.layout||{},n=this.getState().ui,o=e.prompt??n.prompt;return He({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??ke(o),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===S.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),o=this.getState().ui.layout||{};(o.viewportWidth!==s||o.viewportHeight!==n)&&this.dispatch({type:"ui/viewport",width:s,height:n});const i=this.getCurrentLayout({width:s,height:n}),r=this.getState().ui.focusRegion,a=ge(r,i);a!==r&&this.setFocus(a)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:ge(e,this.getCurrentLayout())})}focusNext(){const e=this.getCurrentLayout(),s=ge(this.getState().ui.focusRegion,e),n=Pt(e);this.setFocus(Re(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=ge(this.getState().ui.focusRegion,e),n=Pt(e);this.setFocus(Re(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=ge(this.getState().ui.focusRegion,e);this.setFocus(Vo(s,e))}focusRight(){const e=this.getCurrentLayout(),s=ge(this.getState().ui.focusRegion,e);this.setFocus(zo(s,e))}adjustPaneSplit(e){const s=this.getState().ui.layout||{},n=s.viewportWidth??120,o=Math.max(-n,Math.min(n,(s.paneAdjust||0)+e));this.dispatch({type:"ui/paneAdjust",paneAdjust:o});const i=this.getCurrentLayout({paneAdjust:o}),r=this.getState().ui.focusRegion,a=ge(r,i);a!==r&&this.setFocus(a)}adjustSessionPaneSplit(e){const s=this.getState().ui.layout||{},o=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,i=Math.max(-o,Math.min(o,(s.sessionPaneAdjust||0)+e));this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:i})}nextInspectorTab(){const e=Re(ee,this.getState().ui.inspectorTab,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),this.ensureInspectorData(e).catch(()=>{})}prevInspectorTab(){const e=Re(ee,this.getState().ui.inspectorTab,-1);this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),this.ensureInspectorData(e).catch(()=>{})}cycleInspectorTab(){this.nextInspectorTab()}async selectInspectorTab(e){ee.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=s.sessions.flat;if(n.length===0)return;const o=s.sessions.activeSessionId||n[0].sessionId,i=Math.max(0,n.findIndex(l=>l.sessionId===o)),r=Math.max(0,Math.min(n.length-1,i+e)),a=n[r].sessionId;await this.loadSession(a)}getSessionPageSize(){const e=this.getCurrentLayout(),s=e.fullscreenPane===S.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 Zr.has(this.getState().ui.inspectorTab)}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(),o=this.getPaneMaxScrollOffset(e,n),i=Math.max(0,Math.min(Number(n.ui.scroll?.[e])||0,o)),r=Math.max(0,Math.min(i+s,o));this.dispatch({type:"ui/scroll",pane:e,offset:r}),e==="chat"&&s>0&&this.maybeAutoExpandActiveHistory(r).catch(()=>{})}scrollPaneTo(e,s){const n=this.getPaneMaxScrollOffset(e,this.getState()),o=Math.max(0,Math.min(Number(s)||0,n));this.dispatch({type:"ui/scroll",pane:e,offset:o}),e==="chat"&&o>0&&this.maybeAutoExpandActiveHistory(o).catch(()=>{})}getScrollablePaneForFocus(){const e=this.getState().ui.focusRegion;return e===S.CHAT?"chat":e===S.ACTIVITY?"activity":e===S.INSPECTOR?this.getState().ui.inspectorTab==="files"?"filePreview":"inspector":null}scrollCurrentPane(e){const s=this.getScrollablePaneForFocus();if(!s)return;const n=s==="inspector"&&this.inspectorUsesBottomScroll(),o=s==="inspector"||s==="filePreview";this.scrollPane(s,o&&!n?-e:e)}scrollCurrentPaneToTop(){const e=this.getScrollablePaneForFocus();if(!e)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;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),o=Math.max(1,s.chatPaneHeight-2),i=Kt(e,n),r=Fe(i,n);return{contentWidth:n,contentHeight:o,totalLines:r}}getActivityRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.rightWidth-4),o=Math.max(1,s.activityPaneHeight-2),i=e.sessions.activeSessionId,r={sessions:{activeSessionId:i,byId:i?{[i]:e.sessions.byId[i]||null}:{}},history:{bySessionId:i?new Map([[i,e.history.bySessionId.get(i)||null]]):new Map}},a=Yt(r);return{contentWidth:n,contentHeight:o,totalLines:Fe(a.lines,n)}}getInspectorRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden)return{contentWidth:20,contentHeight:1,stickyLineCount:0,totalLines:0};const n=Math.max(20,s.rightWidth-4),o=e.sessions.activeSessionId,i=o&&e.orchestration.bySessionId?.[o]||null,r={branding:e.branding,sessions:{activeSessionId:o,byId:e.sessions.byId,flat:e.sessions.flat},history:{bySessionId:e.history.bySessionId},orchestration:{bySessionId:o&&i?{[o]:i}:{}},logs:e.logs,ui:{inspectorTab:e.ui.inspectorTab},executionHistory:e.executionHistory},a=Me(r,{width:n}),l=a.tabs.map(h=>({text:h===a.activeTab?`[${h}] `:`${h} `,color:h===a.activeTab?"magenta":"gray",bold:h===a.activeTab})),c=(a.lines||[]).map(h=>typeof h=="string"?{text:h,color:"white"}:h),f=a.activeTab==="sequence"?[l,...(a.stickyLines||[]).map(h=>typeof h=="string"?{text:h,color:"white"}:h)]:[],d=a.activeTab==="sequence"?c:[l,...c];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:Fe(f,n),totalLines:Fe(d,n)}}getFilePreviewRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden&&!e.files?.fullscreen)return{contentWidth:20,contentHeight:1,totalLines:0};const n=e.ui.inspectorTab==="files"&&!!e.files?.fullscreen,o=n?s.totalWidth:s.rightWidth,i=n?Math.max(10,s.bodyHeight):s.inspectorPaneHeight,r=Math.max(20,o-4),a=Math.max(8,r-4),l=e.sessions.activeSessionId,c=l&&e.sessions.byId[l]||null,f={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}}},d=Xt(f,{listWidth:a,previewWidth:a}),h=Math.max(9,i-4),m=Math.max(5,Math.min(10,Math.floor(h*.35)));let g=Math.max(5,Math.min(m,(d.listBodyLines||[]).length+2)),w=Math.max(5,h-g-1);const x=8;if(w<x){const b=x-w;g=Math.max(5,g-b),w=Math.max(5,h-g-1)}return{contentWidth:a,contentHeight:Math.max(1,w-2),totalLines:Fe(d.previewLines,a)}}getPaneMaxScrollOffset(e,s=this.getState()){if(!e)return 0;if(e==="chat"){const n=this.getActiveChatRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="activity"){const n=this.getActivityRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="inspector"){const n=this.getInspectorRenderMetrics(s),o=Math.min(n.contentHeight,n.stickyLineCount||0),i=Math.max(0,n.contentHeight-o);return Math.max(0,n.totalLines-i)}if(e==="filePreview"){const n=this.getFilePreviewRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}return 0}async maybeAutoExpandActiveHistory(e){const s=this.getState(),n=s.sessions.activeSessionId;if(!n)return;const o=s.history.bySessionId.get(n);if(!o?.hasOlderEvents||this.sessionHistoryExpansionLoads.has(n))return;if(Number(o.loadedEventCount||0)>=Jr){this.dispatch({type:"ui/status",text:"Reached automatic history limit. Press e to load more older CMS events."});return}const{contentHeight:i,totalLines:r}=this.getActiveChatRenderMetrics(s),a=Math.max(0,r-i);e<a||await this.expandSessionHistory(n,{requestedScrollOffset:e,autoTriggered:!0})}async expandSessionHistory(e,s={}){if(!e)return;if(this.sessionHistoryExpansionLoads.has(e))return this.sessionHistoryExpansionLoads.get(e);const n=this.getState(),o=n.history.bySessionId.get(e),i=Math.max($,Number(o?.loadedEventLimit??$)||$),r=$,a=Array.isArray(o?.events)&&o.events.length>0?Number(o.events[0]?.seq||0):0;if(!o?.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),f=l?this.getActiveChatRenderMetrics(n).totalLines:0,d=(async()=>{let h;if(typeof this.transport.getSessionEventsBefore=="function"&&a>0){const g=await this.transport.getSessionEventsBefore(e,a,r);if(!Array.isArray(g)||g.length===0)h={...o||qe([],{requestedLimit:i}),hasOlderEvents:!1};else{const w=qe(g,{requestedLimit:r}),x=[...w.events||[],...o?.events||[]];h={chat:Ee([...w.chat||[],...o?.chat||[]]),activity:[...w.activity||[],...o?.activity||[]],events:x,lastSeq:o?.lastSeq||o?.events?.[o?.events?.length-1]?.seq||g[g.length-1]?.seq||0,loadedEventLimit:x.length,loadedEventCount:x.length,hasOlderEvents:g.length>=r&&Number(g[0]?.seq||0)>1}}}else{const g=Ho(i);if(g<=i){this.dispatch({type:"ui/status",text:o?.hasOlderEvents?`Already showing a large recent history window (${i} events)`:"Already showing the oldest loaded history"});return}const w=await this.transport.getSessionEvents(e,void 0,g);h={...qe(w,{requestedLimit:g}),lastSeq:w[w.length-1]?.seq||0}}if(this.dispatch({type:"history/set",sessionId:e,history:h}),l&&c>0){const g=this.getState(),w=this.getActiveChatRenderMetrics(g).totalLines,x=Math.max(0,w-f);x>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:c+x})}const m=h.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${h.loadedEventCount} events loaded)`:`Loaded older history page (${h.loadedEventCount} events loaded)`:`Loaded full available history (${h.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:m})})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,d),d}async cancelActiveSession(){const e=this.getState().sessions.activeSessionId;e&&(await this.transport.cancelSession(e),this.dispatch({type:"ui/status",text:`Cancelled ${e.slice(0,8)}`}),await this.refreshSessions())}async completeActiveSession(e="Completed by user"){const s=this.getState().sessions.activeSessionId;if(!s)return;if(typeof this.transport.completeSession!="function"){this.dispatch({type:"ui/status",text:"Session completion is not supported by this transport"});return}const n=this.getState().sessions.byId[s];if(n?.status==="completed"&&!n?.cronActive&&!n?.cronInterval){this.dispatch({type:"ui/status",text:`${s.slice(0,8)} is already completed`});return}this.dispatch({type:"ui/status",text:`Completing ${s.slice(0,8)} (cascading to sub-agents)...`});try{await this.transport.completeSession(s,e),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.scheduleSessionsRefresh(900)}catch(o){await this.loadSession(s).catch(()=>{}),this.dispatch({type:"ui/status",text:`Failed to send /done: ${o?.message||String(o)}`})}}async deleteActiveSession(){const e=this.getState().sessions.activeSessionId;e&&(await this.transport.deleteSession(e),this.dispatch({type:"ui/status",text:`Deleted ${e.slice(0,8)}`}),await this.refreshSessions())}async handleCommand(e){switch(e){case y.REFRESH:await this.refreshSessions();return;case y.NEW_SESSION:await this.openNewSessionFlow();return;case y.OPEN_MODEL_PICKER:await this.openModelPicker();return;case y.OPEN_THEME_PICKER:this.openThemePicker();return;case y.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case y.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case y.CLOSE_MODAL:this.closeModal();return;case y.MODAL_PREV:this.moveModalSelection(-1);return;case y.MODAL_NEXT:this.moveModalSelection(1);return;case y.MODAL_PANE_PREV:this.moveModalPane(-1);return;case y.MODAL_PANE_NEXT:this.moveModalPane(1);return;case y.MODAL_CONFIRM:await this.confirmModal();return;case y.SEND_PROMPT:await this.sendPrompt();return;case y.FOCUS_NEXT:this.focusNext();return;case y.FOCUS_PREV:this.focusPrev();return;case y.FOCUS_LEFT:this.focusLeft();return;case y.FOCUS_RIGHT:this.focusRight();return;case y.FOCUS_PROMPT:this.setFocus(S.PROMPT);return;case y.FOCUS_SESSIONS:this.setFocus(S.SESSIONS);return;case y.MOVE_SESSION_UP:await this.moveSession(-1);return;case y.MOVE_SESSION_DOWN:await this.moveSession(1);return;case y.EXPAND_SESSION:this.expandActiveSession();return;case y.COLLAPSE_SESSION:this.collapseActiveSession();return;case y.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case y.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case y.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case y.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case y.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case y.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case y.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case y.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case y.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case y.OPEN_LOG_FILTER:this.openLogFilter();return;case y.OPEN_FILES_FILTER:this.openFilesFilter();return;case y.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case y.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case y.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case y.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case y.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case y.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case y.SCROLL_UP:this.scrollCurrentPane(1);return;case y.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case y.PAGE_UP:if(this.getState().ui.focusRegion===S.SESSIONS){await this.moveSessionPage(-1);return}this.scrollCurrentPane(10);return;case y.PAGE_DOWN:if(this.getState().ui.focusRegion===S.SESSIONS){await this.moveSessionPage(1);return}this.scrollCurrentPane(-10);return;case y.EXPAND_HISTORY:await this.expandActiveHistory();return;case y.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case y.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case y.CANCEL_SESSION:await this.cancelActiveSession();return;case y.DONE_SESSION:await this.completeActiveSession();return;case y.DELETE_SESSION:await this.deleteActiveSession();return;case y.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case y.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case y.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();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 Rn=0;function G(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 o of s)if(!Object.prototype.hasOwnProperty.call(e,o)||!Object.is(t[o],e[o]))return!1;return!0}function ia(t,e,s=Object.is){if(Object.is(t,e))return!0;if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(!s(t[n],e[n]))return!1;return!0}function ra(t,e){return Object.is(t,e)?!0:!t||!e?!1:Object.is(t.color,e.color)&&ia(t.title,e.title,G)}function vt(){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 aa(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 ca(t=2e3){const[e,s]=u.useState(()=>vt());return u.useEffect(()=>{if(vt()==null)return;const n=()=>{const i=vt();i!=null&&s(r=>r===i?r:i)};n();const o=setInterval(n,t);return()=>clearInterval(o)},[t]),u.useMemo(()=>aa(e),[e])}function ot(t,e){return t&&e?{[t]:e}:{}}function Ds(t){return typeof t=="string"?{text:t,color:"white"}:t}function it(t,e,s,n,o,i){const r=(e.tabs||ee).map(d=>({text:d===e.activeTab?`[${d}] `:`${d} `,color:d===e.activeTab?"magenta":"gray",bold:d===e.activeTab})),a=(e.lines||[]).map(Ds),l=(e.stickyLines||[]).map(Ds),c=e.activeTab==="sequence"?[r,...l]:[],f=e.activeTab==="sequence"?a:[r,...a];return u.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:o,stickyLines:c,marginBottom:Rn,lines:f,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="logs"||e.activeTab==="sequence"?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:i})}function Ws(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:o,frame:i}){const r=te(),a=ca(),l=R(e,h=>({sessions:h.sessions,mode:h.connection?.mode||"local",brandingTitle:h.branding?.title||"PilotSwarm",focused:h.ui.focusRegion==="sessions"}),G),c=u.useMemo(()=>({sessions:l.sessions,connection:{mode:l.mode},branding:{title:l.brandingTitle}}),[l.brandingTitle,l.mode,l.sessions]),f=u.useMemo(()=>Nt(c,s),[c,s]),d=u.useMemo(()=>f.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:f.map(h=>h.active?Ii(h.runs,{preserveColors:!0}):h.runs),[f]);return u.createElement(r.Panel,{title:"Sessions",titleRight:a,color:"yellow",focused:l.focused,width:n,height:o,marginBottom:Rn,lines:d,paneId:"sessions",paneLabel:"Sessions",frame:i})});u.memo(function({controller:e,width:s,height:n,frame:o}){const i=te(),r=R(e,gn,ra),a=R(e,h=>{const m=h.sessions.activeSessionId;return{activeSessionId:m,activeSession:m&&h.sessions.byId[m]||null,activeHistory:m&&h.history.bySessionId.get(m)||null,branding:h.branding,connectionError:h.connection.error,connectionMode:h.connection.mode,chatScroll:h.ui.scroll.chat,focused:h.ui.focusRegion==="chat"}},G),l=Math.max(20,s-4),c=u.useMemo(()=>{const h=new Map;return a.activeSessionId&&a.activeHistory&&h.set(a.activeSessionId,a.activeHistory),{branding:a.branding,connection:{error:a.connectionError,mode:a.connectionMode},sessions:{activeSessionId:a.activeSessionId,byId:ot(a.activeSessionId,a.activeSession)},history:{bySessionId:h}}},[a.activeHistory,a.activeSessionId,a.activeSession,a.branding,a.connectionError,a.connectionMode]),f=!a.activeSessionId&&a.connectionError,d=u.useMemo(()=>f?[{kind:"markup",value:a.branding.splash},{text:"",color:"gray"},{text:"Startup failed",color:"red",bold:!0},{text:a.connectionError,color:"white"},{text:"",color:"gray"},{text:"Check env credentials and model provider config, then relaunch.",color:"yellow"}]:Kt(c,l),[a.branding.splash,a.connectionError,l,c,f]);return u.createElement(i.Panel,{title:r.title,color:r.color,focused:a.focused,width:s,height:n,lines:d,scrollOffset:a.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:o})});const la=u.memo(function({controller:e,width:s,height:n,shellTitle:o,focused:i=!1,frame:r,showFullscreenTitle:a=!1}){const l=te(),c=R(e,T=>({activeSessionId:T.sessions.activeSessionId,activeSession:T.sessions.activeSessionId&&T.sessions.byId[T.sessions.activeSessionId]||null,sessionsFlat:T.sessions.flat,filesBySessionId:T.files.bySessionId,filesFullscreen:!!T.files.fullscreen,selectedArtifactId:T.files.selectedArtifactId,filesFilter:T.files.filter,filePreviewScroll:T.ui.scroll.filePreview}),G),f=Math.max(20,s-4),d=u.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:c.activeSessionId&&c.activeSession?{[c.activeSessionId]:c.activeSession}:{},flat:c.sessionsFlat},files:{bySessionId:c.filesBySessionId,fullscreen:c.filesFullscreen,selectedArtifactId:c.selectedArtifactId,filter:c.filesFilter},ui:{scroll:{filePreview:c.filePreviewScroll}}}),[c]),h=u.useMemo(()=>Xt(d,{listWidth:Math.max(8,f-4),previewWidth:Math.max(8,f-4)}),[f,d]),m=o||(a?h.fullscreenTitle:h.panelTitle||h.listTitle)||[{text:"Files",color:"magenta",bold:!0}],g=Math.max(9,n-4),w=Math.max(5,Math.min(10,Math.floor(g*.35)));let x=Math.max(5,Math.min(w,(h.listBodyLines||[]).length+2)),b=Math.max(5,g-x-1);const v=8;if(b<v){const T=v-b;x=Math.max(5,x-T),b=Math.max(5,g-x-1)}const M=Math.max(1,x-2),E=Math.max(0,h.selectedIndex-Math.floor(M/2)),O=r?{x:r.x+2,y:r.y+2,width:f,height:x}:null,H=r?{x:r.x+2,y:r.y+2+x+1,width:f,height:b}:null,P=ee.map(T=>({text:T==="files"?`[${T}] `:`${T} `,color:T==="files"?"magenta":"gray",bold:T==="files"}));return u.createElement(l.Panel,{title:m,color:"magenta",focused:i,width:s,height:n},u.createElement(l.Column,{width:f},u.createElement(l.Lines,{lines:[P]}),u.createElement(l.Panel,{title:h.listTitle,color:"gray",focused:!1,width:f,height:x,lines:h.listBodyLines||h.listLines.slice(1),scrollOffset:E,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:O}),u.createElement(l.Panel,{title:h.previewTitle,color:"gray",focused:!1,width:f,height:b,lines:h.previewLines,scrollOffset:h.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:H})))}),ua=u.memo(function({controller:e,width:s,height:n,frame:o,meta:i}){const r=te(),a=Math.max(20,s-4),l=R(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,activeOrchestration:d.sessions.activeSessionId&&d.orchestration.bySessionId?.[d.sessions.activeSessionId]||null,histories:d.history.bySessionId}),G),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:ot(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]),f=u.useMemo(()=>Me(c,{width:a}),[a,c]);return it(r,f,i,s,n,o)}),da=u.memo(function({controller:e,width:s,height:n,frame:o,meta:i}){const r=te(),a=Math.max(20,s-4),l=R(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,logs:d.logs}),G),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:ot(l.activeSessionId,l.activeSession)},logs:l.logs,ui:{inspectorTab:"logs"}}),[l.activeSession,l.activeSessionId,l.logs]),f=u.useMemo(()=>Me(c,{width:a}),[a,c]);return it(r,f,i,s,n,o)}),fa=u.memo(function({controller:e,width:s,height:n,frame:o,meta:i}){const r=te(),a=Math.max(20,s-4),l=R(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,executionHistory:d.executionHistory}),G),c=u.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:ot(l.activeSessionId,l.activeSession)},executionHistory:l.executionHistory,ui:{inspectorTab:"history"}}),[l.activeSession,l.activeSessionId,l.executionHistory]),f=u.useMemo(()=>Me(c,{width:a}),[a,c]);return it(r,f,i,s,n,o)}),ha=u.memo(function({controller:e,width:s,height:n,frame:o,meta:i}){const r=te(),a=Math.max(20,s-4),l=R(e,d=>({activeSessionId:d.sessions.activeSessionId,sessionsById:d.sessions.byId,sessionsFlat:d.sessions.flat,histories:d.history.bySessionId}),G),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]),f=u.useMemo(()=>Me(c,{width:a}),[a,c]);return it(r,f,i,s,n,o)});u.memo(function({controller:e,width:s,height:n,frame:o}){const i=R(e,r=>({inspectorTab:r.ui.inspectorTab,inspectorScroll:r.ui.scroll.inspector,focused:r.ui.focusRegion==="inspector"}),G);return i.inspectorTab==="files"?u.createElement(la,{controller:e,width:s,height:n,focused:i.focused,frame:o}):i.inspectorTab==="sequence"?u.createElement(ua,{controller:e,width:s,height:n,frame:o,meta:i}):i.inspectorTab==="logs"?u.createElement(da,{controller:e,width:s,height:n,frame:o,meta:i}):i.inspectorTab==="history"?u.createElement(fa,{controller:e,width:s,height:n,frame:o,meta:i}):u.createElement(ha,{controller:e,width:s,height:n,frame:o,meta:i})});u.memo(function({controller:e,width:s,height:n,maxLines:o,frame:i}){const r=te(),a=R(e,f=>{const d=f.sessions.activeSessionId;return{sessionsById:f.sessions.byId,activeSessionId:d,activeSession:d&&f.sessions.byId[d]||null,activeHistory:d&&f.history.bySessionId.get(d)||null,scroll:f.ui.scroll.activity,focused:f.ui.focusRegion==="activity"}},G),l=u.useMemo(()=>{const f=new Map;return a.activeSessionId&&a.activeHistory&&f.set(a.activeSessionId,a.activeHistory),{sessions:{activeSessionId:a.activeSessionId,byId:a.sessionsById},history:{bySessionId:f}}},[a.activeHistory,a.activeSessionId,a.sessionsById]),c=u.useMemo(()=>Yt(l,o),[o,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:"bottom",paneId:"activity",paneLabel:"Activity",frame:i})});u.memo(function({controller:e,rows:s}){const n=te(),o=R(e,i=>{const r=i.sessions.activeSessionId,a=r&&i.sessions.byId[r]||null;return{prompt:i.ui.prompt,promptCursor:i.ui.promptCursor,focused:i.ui.focusRegion==="prompt",answeringQuestion:!!a?.pendingQuestion?.question}},G);return u.createElement(n.Input,{label:o.answeringQuestion?"answer":"you",value:o.prompt,cursorIndex:o.promptCursor,focused:o.focused,placeholder:o.answeringQuestion?"Type an answer and press Enter":"Type a message and press Enter",rows:s})});u.memo(function({controller:e}){const s=te(),n=R(e,f=>({connected:f.connection.connected,workersOnline:f.connection.workersOnline,focusRegion:f.ui.focusRegion,inspectorTab:f.ui.inspectorTab,fullscreenPane:f.ui.fullscreenPane||null,logsAvailable:f.logs.available,logsTailing:f.logs.tailing,filesFullscreen:!!f.files.fullscreen,mode:f.connection.mode,statusText:f.ui.statusText,modal:f.ui.modal,activeSessionId:f.sessions.activeSessionId,activeSession:f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]||null}),G),o=u.useMemo(()=>({connection:{connected:n.connected,workersOnline:n.workersOnline,mode:n.mode},ui:{focusRegion:n.focusRegion,inspectorTab:n.inspectorTab,fullscreenPane:n.fullscreenPane,statusText:n.statusText,modal:n.modal},logs:{available:n.logsAvailable,tailing:n.logsTailing},files:{fullscreen:n.filesFullscreen},sessions:{activeSessionId:n.activeSessionId,byId:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{}}}),[n]),i=u.useMemo(()=>bn(o),[o]),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:Ws(i.left,c),right:Ws(i.right,l)})});const pa=920,Ln=7,Fn=19,st=16,On="pilotswarm.theme",_n="pilotswarm_theme",$n="pilotswarm.chatFocus",Us={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"History",files:"Files"};function ma(t,e,s){const n=Array.isArray(t)?t.filter(Boolean):[];if(n.length===0)return e;const o=n.indexOf(e),r=((o===-1?0:o)+s+n.length)%n.length;return n[r]}function Hn(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function Bn(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function ga(t){return typeof t?.transport?.listArtifacts=="function"}function Dn(t){return typeof t?.transport?.openPathInDefaultApp=="function"}function ya(){if(typeof window>"u")return!1;try{return window.localStorage.getItem($n)==="1"}catch{return!1}}function Sa(t){if(!(typeof window>"u"))try{window.localStorage.setItem($n,t?"1":"0")}catch{}}function ts(t){return ga(t)?ee:ee.filter(e=>e!=="files")}function ie(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const o of s)if(!Object.prototype.hasOwnProperty.call(e,o)||!Object.is(t[o],e[o]))return!1;return!0}function Wn(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:ke(t?.ui?.prompt||"")}function rt(t){return He({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,Wn(t),t.ui.layout?.sessionPaneAdjust??0)}function le(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){for(const n of Xs(s.value||""))e.push({kind:"runs",runs:n});continue}if(Array.isArray(s)){e.push({kind:"runs",runs:s});continue}e.push({kind:"text",...s})}return e}function he(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function Un(t=[]){return t.map(e=>String(e?.text||"")).join("")}function ba(t){return Array.isArray(t)?Un(t):String(t||"")}function wa(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=[];let n=Math.max(8,e);for(const o of t){if(n<=0)break;if(o?.color==="gray"&&s.length>0)continue;const r=String(o?.text||"");if(!r)continue;const a=r.length>n&&n>1?`${r.slice(0,n-1)}…`:r.slice(0,n);a&&(s.push({...o,text:a}),n-=a.length)}return s.length>0?s:t}function Ia(t){const e=pe(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.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 xa(){try{const t=document.cookie.match(new RegExp(`(?:^|; )${_n}=([^;]+)`));if(t?.[1])return decodeURIComponent(t[1])}catch{}try{return window.localStorage.getItem(On)}catch{return null}}function va(t){try{document.cookie=`${_n}=${encodeURIComponent(t)}; Path=/; Max-Age=31536000; SameSite=Lax`}catch{}try{window.localStorage.setItem(On,t)}catch{}}function Ea(t){const[e,s]=u.useState({width:0,height:0});return u.useLayoutEffect(()=>{const n=t.current;if(!n)return;const o=()=>{s({width:n.clientWidth,height:n.clientHeight})};o();const i=new ResizeObserver(o);return i.observe(n),window.addEventListener("resize",o),()=>{i.disconnect(),window.removeEventListener("resize",o)}},[t]),e}function Ta(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/Ln)),height:Math.max(18,Math.floor(s/Fn))}}function ka(t,e,s,n,o,i){const r=u.useMemo(()=>le(e),[e]);u.useLayoutEffect(()=>{const l=t.current;if(!l)return;const c=Math.max(0,l.scrollHeight-l.clientHeight),f=Math.max(0,Number(s)||0)*st,d=n==="bottom"?Math.max(0,c-f):Math.min(c,f);Math.abs(l.scrollTop-d)>2&&(l.scrollTop=d)},[r,t,n,s]);const a=u.useCallback(()=>{const l=t.current;if(!l||!o)return;const c=Math.max(0,l.scrollHeight-l.clientHeight),f=n==="bottom"?Math.max(0,c-l.scrollTop):Math.max(0,l.scrollTop);i.dispatch({type:"ui/scroll",pane:o,offset:f/st})},[i,o,t,n]);return{normalizedLines:r,onScroll:a}}function Ce({runs:t,theme:e}){return u.createElement(u.Fragment,null,(t||[]).map((s,n)=>u.createElement("span",{key:`${n}:${s.text||""}`,style:{color:he(e,s.color),backgroundColor:he(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"}},s.text||"")))}function Aa({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:he(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(jn,{content:s,theme:e})):null)}function ue({line:t,theme:e}){return t?t.kind==="systemNotice"?u.createElement(Aa,{line:t,theme:e}):t.kind==="runs"?u.createElement("div",{className:"ps-line"},u.createElement(Ce,{runs:t.runs,theme:e})):u.createElement("div",{className:"ps-line",style:{color:he(e,t.color),backgroundColor:he(e,t.backgroundColor),fontWeight:t.bold?700:400,textDecoration:t.underline?"underline":"none"}},t.text||" "):u.createElement("div",{className:"ps-line"}," ")}function Q(t){return t?t.kind==="runs"?Un(t.runs):String(t.text||""):""}function Ca(t,e,s,n){return u.useLayoutEffect(()=>{const o=t.current;if(!o)return;const i=Math.max(0,o.scrollHeight-o.clientHeight),r=Math.min(i,Math.max(0,Number(e)||0)*st);Math.abs(o.scrollTop-r)>2&&(o.scrollTop=r)},[t,e]),u.useCallback(()=>{const o=t.current;!o||!s||n.dispatch({type:"ui/scroll",pane:s,offset:Math.max(0,o.scrollTop)/st})},[n,s,t])}function Pa(t=""){const e=[],s=String(t||""),n=/(`[^`]+`)|(\[([^\]]+)\]\(([^)]+)\))|(\*\*([^*]+)\*\*)|(__(.+?)__)|(\*([^*]+)\*)|(_([^_]+)_)/g;let o=0,i;for(;(i=n.exec(s))!==null;)i.index>o&&e.push({type:"text",text:s.slice(o,i.index)}),i[1]?e.push({type:"code",text:i[1].slice(1,-1)}):i[2]?e.push({type:"link",text:i[3],href:i[4]}):i[5]?e.push({type:"strong",text:i[6]}):i[7]?e.push({type:"strong",text:i[8]}):i[9]?e.push({type:"em",text:i[10]}):i[11]&&e.push({type:"em",text:i[12]}),o=n.lastIndex;return o<s.length&&e.push({type:"text",text:s.slice(o)}),e}function ce(t,e,s="md"){return Pa(t).map((n,o)=>{const i=`${s}:${o}`;return n.type==="code"?u.createElement("code",{key:i,className:"ps-md-inline-code"},n.text):n.type==="strong"?u.createElement("strong",{key:i,className:"ps-md-strong"},ce(n.text,e,`${i}:strong`)):n.type==="em"?u.createElement("em",{key:i,className:"ps-md-em"},ce(n.text,e,`${i}:em`)):n.type==="link"?u.createElement("a",{key:i,className:"ps-md-link",href:n.href,target:"_blank",rel:"noreferrer",style:{color:he(e,"cyan")}},n.text):u.createElement(u.Fragment,{key:i},n.text)})}function js(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 qs(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Ma(t=""){const s=String(t||"").replace(/\r\n?/g,`
36
+ `).split(`
37
+ `),n=[];for(let o=0;o<s.length;){const i=s[o],r=i.trim();if(!r){o+=1;continue}const a=/^```(\S*)\s*$/.exec(r);if(a){const d=a[1]||"",h=[];for(o+=1;o<s.length&&!/^```/.test(s[o].trim());)h.push(s[o]),o+=1;o<s.length&&(o+=1),n.push({type:"code",language:d,content:h.join(`
38
+ `)});continue}const l=/^(#{1,6})\s+(.*)$/.exec(i);if(l){n.push({type:"heading",level:l[1].length,text:l[2].trim()}),o+=1;continue}if(i.includes("|")&&o+1<s.length&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(s[o+1].trim())){const d=qs(i);o+=2;const h=[];for(;o<s.length&&s[o].includes("|")&&s[o].trim();)h.push(qs(s[o])),o+=1;n.push({type:"table",header:d,rows:h});continue}if(/^\s*>/.test(i)){const d=[];for(;o<s.length&&/^\s*>/.test(s[o]);)d.push(s[o].replace(/^\s*>\s?/,"")),o+=1;n.push({type:"blockquote",text:d.join(`
39
+ `).trim()});continue}const c=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(i);if(c){const d=/\d+\./.test(c[2]),h=[];for(;o<s.length;){const m=s[o],g=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(m);if(!g||/\d+\./.test(g[2])!==d)break;const w=[g[3].trim()];for(o+=1;o<s.length&&s[o].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[o])&&!js(s[o],s[o+1]||"");)w.push(s[o].trim()),o+=1;if(h.push(w.join(" ")),!s[o]?.trim())break}n.push({type:"list",ordered:d,items:h});continue}const f=[i.trim()];for(o+=1;o<s.length&&s[o].trim()&&!js(s[o],s[o+1]||"");)f.push(s[o].trim()),o+=1;n.push({type:"paragraph",text:f.join(" ")})}return n}function jn({content:t,theme:e}){const s=u.useMemo(()=>Ma(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,o)=>{if(n.type==="heading")return u.createElement("div",{key:`block:${o}`,className:`ps-md-heading is-h${n.level}`},ce(n.text,e,`heading:${o}`));if(n.type==="code")return u.createElement("section",{key:`block:${o}`,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:${o}`,className:"ps-md-quote"},ce(n.text,e,`quote:${o}`));if(n.type==="list"){const i=n.ordered?"ol":"ul";return u.createElement(i,{key:`block:${o}`,className:`ps-md-list${n.ordered?" is-ordered":""}`},n.items.map((r,a)=>u.createElement("li",{key:`item:${a}`,className:"ps-md-list-item"},ce(r,e,`list:${o}:${a}`))))}return n.type==="table"?u.createElement("div",{key:`block:${o}`,className:"ps-md-table-wrap"},u.createElement("table",{className:"ps-md-table"},u.createElement("thead",null,u.createElement("tr",null,n.header.map((i,r)=>u.createElement("th",{key:`head:${r}`},ce(i,e,`table:${o}:head:${r}`))))),u.createElement("tbody",null,n.rows.map((i,r)=>u.createElement("tr",{key:`row:${r}`},i.map((a,l)=>u.createElement("td",{key:`cell:${r}:${l}`},ce(a,e,`table:${o}:${r}:${l}`)))))))):u.createElement("p",{key:`block:${o}`,className:"ps-md-paragraph"},ce(n.text,e,`para:${o}`))}))}function Na({controller:t,title:e,color:s,focused:n,scrollOffset:o=0,paneKey:i,theme:r,content:a}){const l=u.useRef(null),c=Ca(l,o,i,t);return u.createElement(Pe,{title:e,color:s,focused:n,theme:r},u.createElement("div",{ref:l,className:"ps-scroll-panel ps-markdown-scroll",onScroll:c},u.createElement(jn,{content:a,theme:r})))}function Je(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function Et(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function Ra(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function Be(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function La(t){const e=String(Q(t)||"").trim();return Je(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function Fa(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=Q(t);return Be(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function Oa(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 Vs(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?Oa(t.runs.slice(1,-1)):[{text:Q(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function _a(t){const e=String(t||"").trim();return Be(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function zs(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>t.map(o=>String(o[n]||"").trim()).filter(Boolean).join(" "))}function $a(t=[]){const e=[];for(let s=0;s<t.length;){const n=t[s],o=Q(n);if(Je(o)&&o.includes("┬")){const i=[],r=[];let a=[],l=!0;for(s+=1;s<t.length;){const c=t[s],f=Q(c);if(Et(f)){if(a.length>0){const d=zs(a);d.length>0&&(l?i.push(d):r.push(d))}s+=1;break}if(Ra(f)){if(a.length>0){const d=zs(a);d.length>0&&(l?i.push(d):r.push(d))}a=[],l=!1,s+=1;continue}if(Be(f)){const d=_a(f);d.length>0&&a.push(d)}s+=1}e.push({type:"table",headerRows:i,bodyRows:r});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&Je(o)){const i=La(n),r=[];for(s+=1;s<t.length;){const a=t[s],l=Q(a);if(Et(l)){s+=1;break}Be(l)?r.push(Fa(a)):r.push(Q(a)),s+=1}s<t.length&&Q(t[s]).trim().length===0&&(s+=1),e.push({type:"code",language:i||"text",content:r.join(`
40
+ `)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&Je(o)){const i=Vs(n),r=n.runs[0]?.color||"gray",a=[];for(s+=1;s<t.length;){const l=t[s],c=Q(l);if(Et(c)){s+=1;break}Be(c)?a.push(Vs(l)):a.push(l?.kind==="runs"?l.runs:[{text:Q(l),color:l?.color||null}]),s+=1}s<t.length&&Q(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:i,bodyLines:a,borderColor:r});continue}e.push({type:"line",line:n}),s+=1}return e}function Ha({lines:t,theme:e}){const s=u.useMemo(()=>$a(t),[t]);return u.createElement(u.Fragment,null,s.map((n,o)=>{if(n.type==="code")return u.createElement("section",{key:`code:${o}`,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:${o}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":he(e,n.borderColor)||"var(--ps-border)"}},u.createElement("header",{className:"ps-chat-card-header"},u.createElement(Ce,{runs:n.headerRuns,theme:e})),u.createElement("div",{className:"ps-chat-card-body"},(n.bodyLines||[]).map((i,r)=>u.createElement("div",{key:`card:${o}:line:${r}`,className:"ps-chat-card-line"},u.createElement(Ce,{runs:i,theme:e})))));if(n.type==="table"){const i=n.headerRows||[],r=n.bodyRows||[],a=Math.max(1,...i.map(l=>l.length),...r.map(l=>l.length));return u.createElement("div",{key:`table:${o}`,className:"ps-chat-table-wrap"},u.createElement("table",{className:"ps-chat-table"},i.length>0?u.createElement("thead",null,i.map((l,c)=>u.createElement("tr",{key:`thead:${c}`},Array.from({length:a},(f,d)=>u.createElement("th",{key:`th:${c}:${d}`},l[d]||""))))):null,u.createElement("tbody",null,r.map((l,c)=>u.createElement("tr",{key:`tbody:${c}`},Array.from({length:a},(f,d)=>u.createElement("td",{key:`td:${c}:${d}`},l[d]||"")))))))}return u.createElement(ue,{key:`line:${o}`,line:n.line,theme:e})}))}function Pe({title:t,color:e="gray",focused:s=!1,actions:n=null,children:o,theme:i,className:r=""}){const a=he(i,e);return u.createElement("section",{className:`ps-panel${s?" is-focused":""}${r?` ${r}`:""}`,style:{"--ps-panel-accent":a||"var(--ps-border)"}},u.createElement("header",{className:"ps-panel-header"},u.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?u.createElement(Ce,{runs:t,theme:i}):ba(t)),n?u.createElement("div",{className:"ps-panel-actions"},n):null),u.createElement("div",{className:"ps-panel-body"},o))}function at({title:t,color:e,focused:s,actions:n,lines:o,stickyLines:i=[],scrollOffset:r=0,scrollMode:a="top",paneKey:l,controller:c,className:f="",panelClassName:d="",topContent:h=null,structuredBlocks:m=!1}){const g=R(c,B=>B.ui.themeId),w=pe(g),x=u.useRef(null),b=u.useRef(null),v=u.useRef(!1),{normalizedLines:M,onScroll:E}=ka(x,o,r,a,l,c),O=u.useMemo(()=>le(i),[i]),H=f.includes("is-preserve")&&d.includes("has-preserved-sticky"),P=u.useCallback((B,W)=>{!B||!W||Math.abs((W.scrollLeft||0)-(B.scrollLeft||0))<=1||(v.current=!0,W.scrollLeft=B.scrollLeft,window.requestAnimationFrame(()=>{v.current=!1}))},[]),T=u.useCallback(B=>{E(),!(!H||v.current)&&P(B.currentTarget,b.current)},[E,H,P]),K=u.useCallback(B=>{!H||v.current||P(B.currentTarget,x.current)},[H,P]);return u.createElement(Pe,{title:t,color:e,focused:s,actions:n,theme:w,className:d},h,O.length>0?u.createElement("div",{ref:b,className:`ps-panel-sticky${H?" is-scroll-sync":""}`,onScroll:K},O.map((B,W)=>u.createElement(ue,{key:`sticky:${W}`,line:B,theme:w}))):null,u.createElement("div",{ref:x,className:`ps-scroll-panel ${f}`.trim(),onScroll:T},m?u.createElement(Ha,{lines:M,theme:w}):M.map((B,W)=>u.createElement(ue,{key:`line:${W}`,line:B,theme:w}))))}function ss({controller:t,actions:e=null,panelClassName:s=""}){const n=R(t,m=>m.ui.themeId),o=pe(n),i=u.useRef(new Map),r=R(t,m=>({activeSessionId:m.sessions.activeSessionId,sessionsById:m.sessions.byId,sessionsFlat:m.sessions.flat,filterQuery:m.sessions.filterQuery||"",connectionMode:m.connection?.mode||"local",focused:m.ui.focusRegion==="sessions"}),ie),a=u.useMemo(()=>Gt({sessions:{activeSessionId:r.activeSessionId,byId:r.sessionsById,flat:r.sessionsFlat,filterQuery:r.filterQuery},connection:{mode:r.connectionMode}}),[r.activeSessionId,r.connectionMode,r.filterQuery,r.sessionsById,r.sessionsFlat]),l=r.activeSessionId&&r.sessionsById[r.activeSessionId]||null,c=!!(l&&!l.isSystem),f=`ps-session-pane${s?` ${s}`:""}`,d=u.useCallback((m,g)=>{m&&(g?i.current.set(m,g):i.current.delete(m))},[]);u.useEffect(()=>{if(!r.focused||!r.activeSessionId)return;const m=i.current.get(r.activeSessionId);m&&(document.activeElement!==m&&m.focus({preventScroll:!0}),m.scrollIntoView({block:"nearest"}))},[a,r.activeSessionId,r.focused]);const h=u.createElement(u.Fragment,null,u.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(y.OPEN_RENAME_SESSION).catch(()=>{}),disabled:!c},"Rename"),e);return u.createElement(Pe,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:r.focused,theme:o,actions:h,className:f},u.createElement("div",{className:"ps-action-list ps-session-list"},a.length===0?u.createElement("div",{className:"ps-empty-state"},r.filterQuery?`No sessions matched "@@${r.filterQuery}".`:"No sessions yet."):a.map(m=>u.createElement("button",{key:m.sessionId,type:"button",ref:g=>d(m.sessionId,g),className:`ps-list-button ps-session-list-button${m.active?" is-selected":""}`,tabIndex:m.active?0:-1,"aria-selected":m.active?"true":"false",onClick:g=>{if(m.hasChildren&&m.active&&!g.metaKey&&!g.ctrlKey){t.dispatch({type:m.collapsed?"sessions/expand":"sessions/collapse",sessionId:m.sessionId}),t.setFocus("sessions");return}t.setFocus("sessions"),m.active||t.loadSession(m.sessionId).catch(()=>{})}},u.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:`${Math.max(0,m.depth)*18}px`}},Array.isArray(m.runs)?u.createElement(Ce,{runs:m.runs,theme:o}):m.text)))))}function ns({controller:t,mobile:e=!1,fullWidth:s=!1}){const n=R(t,l=>l.ui.themeId);pe(n);const o=R(t,l=>{const c=l.sessions.activeSessionId,f=rt(l),d=s||e?f.totalWidth:f.leftWidth,h=Math.max(20,d-4);return{activeSessionId:c,activeHistory:c&&l.history.bySessionId.get(c)||null,branding:l.branding,connection:l.connection,sessionsById:l.sessions.byId,sessionsFlat:l.sessions.flat,inspectorTab:l.ui.inspectorTab,focused:l.ui.focusRegion==="chat",scroll:l.ui.scroll.chat,contentWidth:h}},ie),i=u.useMemo(()=>({branding:o.branding,connection:o.connection,sessions:{activeSessionId:o.activeSessionId,byId:o.sessionsById,flat:o.sessionsFlat},history:{bySessionId:o.activeSessionId&&o.activeHistory?new Map([[o.activeSessionId,o.activeHistory]]):new Map},ui:{inspectorTab:o.inspectorTab}}),[o.activeHistory,o.activeSessionId,o.branding,o.connection,o.inspectorTab,o.sessionsById,o.sessionsFlat]),r=u.useMemo(()=>gn(i),[i]),a=u.useMemo(()=>Kt(i,o.contentWidth),[i,o.contentWidth]);return u.createElement(at,{controller:t,title:e?wa(r.title,28):r.title,color:r.color,focused:o.focused,lines:a,scrollOffset:o.scroll,scrollMode:"bottom",paneKey:"chat",className:"is-wrapped",panelClassName:"ps-chat-panel",structuredBlocks:!0})}function Ba({controller:t,sessionsCollapsed:e,setSessionsCollapsed:s}){const n=R(t,r=>r.ui.themeId),o=pe(n),i=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(Pe,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:!1,theme:o,actions:i,className:"ps-mobile-session-collapsed"},u.createElement("div",{className:"ps-mobile-session-summary"},"Session list collapsed.")):u.createElement(ss,{controller:t,actions:i,panelClassName:"ps-mobile-session-pane"}),u.createElement("div",{className:"ps-mobile-chat-pane"},u.createElement(ns,{controller:t,mobile:!0,fullWidth:!0})))}function qn({activeTab:t,controller:e}){const s=u.useMemo(()=>ts(e),[e]);return u.createElement("div",{className:"ps-tab-row"},s.map(n=>u.createElement("button",{key:n,type:"button",className:`ps-tab${t===n?" is-active":""}`,title:`Switch to ${Us[n]||n}`,"aria-pressed":t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}},Us[n]||n)))}function Da({controller:t,focused:e,mobile:s=!1}){const n=R(t,b=>b.ui.themeId),o=pe(n),i=u.useRef(null),r=R(t,b=>{const v=b.sessions.activeSessionId,M=rt(b),E=s||b.files.fullscreen?b.ui.layout?.viewportWidth??120:M.rightWidth;return{activeSessionId:v,sessionsById:b.sessions.byId,sessionsFlat:b.sessions.flat,filesBySessionId:b.files.bySessionId,filesFilter:b.files.filter,selectedArtifactId:b.files.selectedArtifactId,focused:e,previewScroll:b.ui.scroll.filePreview,fullscreen:!!b.files.fullscreen,contentWidth:Math.max(20,E-4),canBrowserUpload:Hn(t),canPathUpload:Bn(t),canOpenLocally:Dn(t)}},ie),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(()=>Xt(a,{listWidth:Math.max(18,r.contentWidth-4),previewWidth:Math.max(18,r.contentWidth-4),showHints:!1}),[a,r.contentWidth]),c=u.useMemo(()=>De(a),[a]),f=c.length>0,d=u.useCallback(b=>{const v=Array.isArray(b)?b.filter(Boolean):[];v.length!==0&&t.uploadArtifactFiles(v).catch(()=>{})},[t]),h=u.useCallback(()=>{if(r.canBrowserUpload&&i.current){i.current.click();return}r.canPathUpload&&t.handleCommand(y.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,r.canBrowserUpload,r.canPathUpload]),m=u.createElement(u.Fragment,null,u.createElement("input",{ref:i,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:b=>{d(Array.from(b.currentTarget.files||[])),b.currentTarget.value=""}}),u.createElement("button",{type:"button",className:"ps-mini-button",onClick:h,disabled:!r.canBrowserUpload&&!r.canPathUpload},"Upload"),u.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(y.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!f},"Download"),r.canOpenLocally?u.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(y.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!f},"Open"):null,u.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(y.OPEN_FILES_FILTER).catch(()=>{})},"Filter"),u.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(y.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})},r.fullscreen?"Close":"Fullscreen")),g=c.length===0?le(l.listBodyLines||[]).map((b,v)=>u.createElement(ue,{key:`empty:${v}`,line:b,theme:o})):c.map((b,v)=>u.createElement("button",{key:b.id,type:"button",className:`ps-list-button${v===l.selectedIndex?" is-selected":""}`,onClick:()=>{t.setFocus("inspector"),t.selectFileBrowserItem(b).catch(()=>{})}},u.createElement(ue,{line:le([l.listBodyLines?.[v]])[0],theme:o}))),w=l.previewRenderMode==="markdown"&&!l.previewLoading&&!l.previewError?u.createElement(Na,{controller:t,title:l.previewTitle,color:"cyan",focused:!1,scrollOffset:r.previewScroll,paneKey:"filePreview",theme:o,content:l.previewContent||""}):u.createElement(at,{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(Pe,{title:x.fullscreen?l.fullscreenTitle:l.panelTitle,color:"magenta",focused:x.focused,actions:m,theme:o},u.createElement(qn,{activeTab:"files",controller:t}),x.fullscreen?w:u.createElement("div",{className:"ps-files-grid"},u.createElement(Pe,{title:l.listTitle,color:"cyan",theme:o},u.createElement("div",{className:"ps-action-list"},g)),w))}function $e({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const o=R(t,c=>{const f=rt(c),d=e?c.ui.layout?.viewportWidth??120:f.rightWidth;return{inspectorTab:c.ui.inspectorTab,activeSessionId:c.sessions.activeSessionId,sessionsById:c.sessions.byId,sessionsFlat:c.sessions.flat,historyBySessionId:c.history.bySessionId,connection:c.connection,orchestrationBySessionId:c.orchestration.bySessionId,executionHistoryBySessionId:c.executionHistory?.bySessionId||{},executionHistoryFormat:c.executionHistory?.format||"pretty",logs:c.logs,files:c.files,focused:c.ui.focusRegion==="inspector",scroll:c.ui.scroll.inspector,logsTailing:c.logs.tailing,filesFullscreen:!!c.files.fullscreen,contentWidth:Math.max(20,d-4)}},ie),i=u.useMemo(()=>({sessions:{activeSessionId:o.activeSessionId,byId:o.sessionsById,flat:o.sessionsFlat},history:{bySessionId:o.historyBySessionId},connection:o.connection,ui:{inspectorTab:o.inspectorTab,scroll:{inspector:o.scroll}},logs:o.logs,files:o.files,orchestration:{bySessionId:o.orchestrationBySessionId},executionHistory:{bySessionId:o.executionHistoryBySessionId,format:o.executionHistoryFormat}}),[o.activeSessionId,o.connection,o.executionHistoryBySessionId,o.executionHistoryFormat,o.files,o.historyBySessionId,o.inspectorTab,o.logs,o.orchestrationBySessionId,o.scroll,o.sessionsById,o.sessionsFlat]),r=u.useMemo(()=>Me(i,{width:o.contentWidth,allowWideColumns:e}),[e,i,o.contentWidth]);if(o.inspectorTab==="files")return u.createElement(Da,{controller:t,focused:o.focused,mobile:e});const a=[];o.inspectorTab==="logs"?(a.push(u.createElement("button",{key:"tail",type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(y.TOGGLE_LOG_TAIL).catch(()=>{})},o.logsTailing?"Stop Tail":"Tail")),a.push(u.createElement("button",{key:"filter",type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(y.OPEN_LOG_FILTER).catch(()=>{})},"Filter"))):o.inspectorTab==="history"&&(a.push(u.createElement("button",{key:"refresh",type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(y.REFRESH_EXECUTION_HISTORY).catch(()=>{})},"Refresh")),a.push(u.createElement("button",{key:"save",type:"button",className:"ps-mini-button",onClick:()=>t.handleCommand(y.EXPORT_EXECUTION_HISTORY).catch(()=>{})},"Artifact")));const l=n?a.concat(n):a;return u.createElement(at,{controller:t,title:r.title,color:"magenta",focused:o.focused,actions:l,topContent:u.createElement(qn,{activeTab:r.activeTab,controller:t}),stickyLines:r.stickyLines||[],lines:r.lines,scrollOffset:o.scroll,scrollMode:r.activeTab==="logs"||r.activeTab==="sequence"?"bottom":"top",paneKey:"inspector",className:r.activeTab==="history"?"is-wrapped":"is-preserve",panelClassName:`${r.activeTab==="sequence"?"has-preserved-sticky":""}${s?` ${s}`:""}`.trim()})}function Ot({controller:t,panelClassName:e="",extraActions:s=null}){const n=R(t,r=>{const a=r.sessions.activeSessionId,l=rt(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,maxLines:c}},ie),o=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]),i=u.useMemo(()=>Yt(o,n.maxLines),[o,n.maxLines]);return u.createElement(at,{controller:t,title:i.title,color:"gray",focused:n.focused,actions:s,lines:i.lines,scrollOffset:n.scroll,scrollMode:"bottom",paneKey:"activity",className:"is-preserve",panelClassName:e})}const _t=[{id:"sessions",label:"Sessions",side:"left"},{id:"inspector",label:"Inspector",side:"right"},{id:"activity",label:"Activity",side:"right"}];function Wa({controller:t,pane:e,onClose:s}){if(!e)return null;let n=null;e==="sessions"?n=u.createElement(ss,{controller:t,panelClassName:"ps-chat-focus-pane",actions:u.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}):e==="inspector"?n=u.createElement($e,{controller:t,mobile:!1,panelClassName:"ps-chat-focus-pane",extraActions:u.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}):e==="activity"&&(n=u.createElement(Ot,{controller:t,panelClassName:"ps-chat-focus-pane",extraActions:u.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}));const o=_t.find(i=>i.id===e);return u.createElement("div",{className:`ps-chat-focus-overlay${o?.side==="left"?" is-left":" is-right"}`},n)}function Ua({controller:t,openPane:e,onTogglePane:s,mobile:n=!1}){const o=R(t,i=>i.ui.focusRegion);return u.createElement("div",{className:"ps-chat-focus-shell"},u.createElement("div",{className:"ps-chat-focus-rail"},_t.map(i=>u.createElement("button",{key:i.id,type:"button",className:`ps-mini-button ps-chat-focus-button${e===i.id?" is-active":""}`,"aria-pressed":e===i.id?"true":"false",onClick:()=>s(i.id)},i.label)),u.createElement("div",{className:"ps-chat-focus-status"},e?`Focused: ${_t.find(i=>i.id===e)?.label||e}`:`Focused: ${o==="prompt"?"Prompt":"Chat"}`)),u.createElement("div",{className:"ps-chat-focus-body"},u.createElement(ns,{controller:t,mobile:n,fullWidth:!0}),u.createElement(Wa,{controller:t,pane:e,onClose:()=>s(e)})))}function Vn({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const o=R(t,a=>{const l=a.sessions.activeSessionId,c=l&&a.sessions.byId[l]||null;return{value:a.ui.prompt,cursor:a.ui.promptCursor,focused:a.ui.focusRegion==="prompt",answerMode:!!c?.pendingQuestion?.question}},ie),i=u.useRef(null);u.useEffect(()=>{const a=i.current;if(!(!s||!o.focused||!a)){if(document.activeElement!==a)try{a.focus({preventScroll:!0})}catch{a.focus()}a.setSelectionRange(o.cursor,o.cursor)}},[s,o.cursor,o.focused]);const r=u.useCallback(()=>{t.handleCommand(y.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]);return u.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}`},u.createElement("label",{className:"ps-prompt-label"},o.answerMode?"answer":"you"),u.createElement("textarea",{ref:i,className:"ps-prompt-input",rows:e?2:Math.max(2,ke(o.value)),value:o.value,placeholder:o.answerMode?"Type an answer and press Enter":"Type a message and press Enter",enterKeyHint:"send",onFocus:()=>t.setFocus("prompt"),onSelect:a=>t.setPrompt(a.currentTarget.value,a.currentTarget.selectionStart||0),onChange:a=>t.setPrompt(a.currentTarget.value,a.currentTarget.selectionStart||a.currentTarget.value.length),onKeyDown:a=>{if(a.key==="Tab"&&!a.shiftKey&&t.acceptPromptReferenceAutocomplete()){a.preventDefault();return}a.key==="Enter"&&!a.shiftKey&&!a.metaKey&&!e&&(a.preventDefault(),r())}}),u.createElement("button",{type:"button",className:`ps-send-button${e?" is-inline":""}`,title:"Send prompt","aria-label":"Send prompt",onClick:r},e?"↩":"Send"))}function ja({canUpload:t,canOpenLocally:e}){return[{title:"Global",items:[["n","New session"],["Shift+N","New session with model"],["T","Theme picker"],["Tab / Shift+Tab","Cycle focus"],["[ / ]","Resize side panes"],["{ / }","Resize session list vertically"],["?","Toggle this legend"]]},{title:"Navigation",items:[["j / k","Move or scroll the focused pane"],["Ctrl+U / Ctrl+D","Page up/down"],["g / G","Jump top/bottom"],["m","Cycle inspector tabs"],["p","Focus prompt"],["Esc","Focus sessions"]]},{title:"Prompt",items:[["Enter","Send prompt"],["Tab","Accept @ / @@ autocomplete"],["@","Browse this session's artifacts and attach the selection"],["@@","Filter sessions and insert a durable session reference"]]},{title:"Files",items:[[t?"u / Ctrl+A":"u","Upload artifact to the active session"],["a","Download selected artifact"],...e?[["o","Open downloaded file locally"]]:[],["f","Filter the artifact browser"],["v","Toggle fullscreen preview"]]}]}function qa({open:t,onClose:e,canUpload:s,canOpenLocally:n}){if(!t)return null;const o=ja({canUpload:s,canOpenLocally:n});return u.createElement("div",{className:"ps-modal-backdrop",onClick:e},u.createElement("div",{className:"ps-modal is-wide ps-keybinding-modal",role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:i=>i.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},"Keyboard Shortcuts"),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:e},"Close")),u.createElement("div",{className:"ps-keybinding-grid"},o.map(i=>u.createElement("section",{key:i.title,className:"ps-keybinding-section"},u.createElement("h3",{className:"ps-keybinding-title"},i.title),u.createElement("div",{className:"ps-keybinding-list"},i.items.map(([r,a])=>u.createElement("div",{key:`${i.title}:${r}`,className:"ps-keybinding-row"},u.createElement("kbd",{className:"ps-keybinding-kbd"},r),u.createElement("span",{className:"ps-keybinding-description"},a))))))),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:e},"Done"))))}function Va({controller:t,open:e,onClose:s}){return e?u.createElement("div",{className:"ps-modal-backdrop ps-compose-backdrop",onClick:s},u.createElement("div",{className:"ps-compose-card",role:"dialog","aria-modal":"true","aria-label":"Compose prompt",onClick:n=>n.stopPropagation()},u.createElement("div",{className:"ps-compose-header"},u.createElement("div",{className:"ps-modal-title"},"Prompt"),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:s},"Close")),u.createElement(Vn,{controller:t,mobile:!1,active:e,onAfterSend:s}))):null}function za({controller:t,mobile:e,onToggleLegend:s,onOpenPrompt:n,chatFocusMode:o=!1,onToggleChatFocus:i=null,chatFocusDisabled:r=!1}){const a=R(t,c=>bn(c),ie),l=R(t,c=>!!(c.sessions.activeSessionId&&!c.sessions.byId[c.sessions.activeSessionId]?.isSystem));return u.createElement("div",{className:`ps-toolbar${e?" is-mobile":""}`},u.createElement("div",{className:"ps-toolbar-actions"},u.createElement("button",{type:"button",className:"ps-toolbar-button",onClick:()=>t.handleCommand(y.NEW_SESSION).catch(()=>{})},"New"),u.createElement("button",{type:"button",className:"ps-toolbar-button",onClick:()=>t.handleCommand(y.OPEN_MODEL_PICKER).catch(()=>{})},e?"Model":"New + Model"),u.createElement("button",{type:"button",className:"ps-toolbar-button",onClick:n},"Prompt"),u.createElement("button",{type:"button",className:"ps-toolbar-button",onClick:()=>t.handleCommand(y.OPEN_RENAME_SESSION).catch(()=>{}),disabled:!l},e?"Title":"Rename"),u.createElement("button",{type:"button",className:"ps-toolbar-button",onClick:()=>t.handleCommand(y.REFRESH).catch(()=>{})},"Refresh"),u.createElement("button",{type:"button",className:"ps-toolbar-button",onClick:()=>t.handleCommand(y.OPEN_THEME_PICKER).catch(()=>{})},"Theme"),i?u.createElement("button",{type:"button",className:`ps-toolbar-button${o?" is-active":""}`,onClick:i,disabled:r},e?o?"Exit Focus":"Focus":o?"Exit Focus":"Chat Focus"):null,u.createElement("button",{type:"button",className:"ps-toolbar-button",onClick:s},"Keys")),a.left?u.createElement("div",{className:"ps-toolbar-status"},a.left):null)}function Ga({controller:t,paneAdjust:e=0}){const s=u.useRef(null),[n,o]=u.useState(!1);return u.useEffect(()=>{if(!n)return;const i=()=>{s.current=null,o(!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)/Ln),f=c-l.appliedCells;f&&(t.adjustPaneSplit(f),l.appliedCells=c)};return window.addEventListener("pointermove",r),window.addEventListener("pointerup",i),window.addEventListener("pointercancel",i),()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",i),window.removeEventListener("pointercancel",i),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:i=>{i.button===0&&(i.preventDefault(),s.current={startX:i.clientX,appliedCells:0},o(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{e&&t.adjustPaneSplit(-e)},onKeyDown:i=>{if(i.key==="ArrowLeft"){i.preventDefault(),t.handleCommand(y.GROW_RIGHT_PANE).catch(()=>{});return}i.key==="ArrowRight"&&(i.preventDefault(),t.handleCommand(y.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 Ka({controller:t,sessionPaneAdjust:e=0}){const s=u.useRef(null),[n,o]=u.useState(!1);return u.useEffect(()=>{if(!n)return;const i=()=>{s.current=null,o(!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)/Fn),f=c-l.appliedCells;f&&(t.adjustSessionPaneSplit(f),l.appliedCells=c)};return window.addEventListener("pointermove",r),window.addEventListener("pointerup",i),window.addEventListener("pointercancel",i),()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",i),window.removeEventListener("pointercancel",i),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 session list. Double-click to reset.","aria-label":"Resize session list",onPointerDown:i=>{i.button===0&&(i.preventDefault(),s.current={startY:i.clientY,appliedCells:0},o(!0),document.body.classList.add("is-resizing-pane-y"))},onDoubleClick:()=>{e&&t.adjustSessionPaneSplit(-e)},onKeyDown:i=>{if(i.key==="ArrowUp"){i.preventDefault(),t.adjustSessionPaneSplit(-1);return}i.key==="ArrowDown"&&(i.preventDefault(),t.adjustSessionPaneSplit(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 Ya({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(o=>u.createElement("button",{key:o.id,type:"button",className:`ps-mobile-nav-button${t===o.id?" is-active":""}`,onClick:()=>{e(o.id),s.setFocus(o.focus)}},o.label)))}function Xa({controller:t}){const e=R(t,l=>l.ui.themeId),s=pe(e),n=R(t,l=>({rawModal:l.ui.modal,themePicker:Pr(l),modelPicker:yr(l),sessionAgentPicker:Sr(l),artifactPicker:vr(l),logFilter:Ir(l),filesFilter:xr(l),historyFormat:Cr(l),renameSession:br(l),artifactUpload:wr(l),logsFilter:l.logs.filter,filesFilterState:l.files.filter,historyFormatState:l.executionHistory?.format||"pretty"}),ie),o=n.rawModal;if(!o)return null;const i=()=>t.handleCommand(y.CLOSE_MODAL).catch(()=>{}),r=(l,c="Apply")=>u.createElement("div",{className:"ps-modal-backdrop",onClick:i},u.createElement("div",{className:"ps-modal",onClick:f=>f.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},l.title),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:i},"Close")),u.createElement("div",{className:"ps-modal-grid"},u.createElement("div",{className:"ps-modal-list"},(o.items||[]).map((f,d)=>u.createElement("button",{key:f.id||d,type:"button",className:`ps-list-button${d===o.selectedIndex?" is-selected":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:d})},u.createElement("div",{className:"ps-line"},u.createElement(Ce,{runs:Array.isArray(l.rows?.[d])?l.rows[d]:le([l.rows?.[d]])[0]?.runs||[{text:l.rows?.[d]?.text||"",color:l.rows?.[d]?.color}],theme:s}))))),u.createElement("div",{className:"ps-modal-details"},u.createElement("div",{className:"ps-modal-details-title"},l.detailsTitle||"Details"),le(l.detailsLines||[]).map((f,d)=>u.createElement(ue,{key:`detail:${d}`,line:f,theme:s})))),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button",onClick:i},"Cancel"),u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(y.MODAL_CONFIRM).catch(()=>{})},c))));if(o.type==="themePicker"&&n.themePicker)return r(n.themePicker,"Apply Theme");if(o.type==="modelPicker"&&n.modelPicker)return r(n.modelPicker,"Create Session");if(o.type==="sessionAgentPicker"&&n.sessionAgentPicker)return r(n.sessionAgentPicker,"Create Session");if(o.type==="artifactPicker"&&n.artifactPicker)return r(n.artifactPicker,"Download");if(o.type==="renameSession"&&n.renameSession)return u.createElement("div",{className:"ps-modal-backdrop",onClick:i},u.createElement("div",{className:"ps-modal is-narrow",onClick:l=>l.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:i},"Close")),u.createElement("input",{className:"ps-modal-input",value:n.renameSession.value,placeholder:n.renameSession.placeholder,onChange:l=>t.setRenameSessionValue(l.currentTarget.value,l.currentTarget.selectionStart||l.currentTarget.value.length),onKeyDown:l=>{l.key==="Enter"&&(l.preventDefault(),t.handleCommand(y.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),u.createElement("div",{className:"ps-modal-details"},le(n.renameSession.helpLines||[]).map((l,c)=>u.createElement(ue,{key:`help:${c}`,line:l,theme:s}))),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button",onClick:i},"Cancel"),u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(y.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(o.type==="artifactUpload"&&n.artifactUpload)return u.createElement("div",{className:"ps-modal-backdrop",onClick:i},u.createElement("div",{className:"ps-modal is-narrow",onClick:l=>l.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:i},"Close")),u.createElement("input",{className:"ps-modal-input",value:n.artifactUpload.value,placeholder:n.artifactUpload.placeholder,onChange:l=>t.setArtifactUploadValue(l.currentTarget.value,l.currentTarget.selectionStart||l.currentTarget.value.length),autoFocus:!0}),u.createElement("div",{className:"ps-modal-details"},le(n.artifactUpload.helpLines||[]).map((l,c)=>u.createElement(ue,{key:`help:${c}`,line:l,theme:s}))),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button",onClick:i},"Cancel"),u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(y.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const a=o.type==="logFilter"?n.logFilter:o.type==="filesFilter"?n.filesFilter:o.type==="historyFormat"?n.historyFormat:null;return a?u.createElement("div",{className:"ps-modal-backdrop",onClick:i},u.createElement("div",{className:"ps-modal is-wide",onClick:l=>l.stopPropagation()},u.createElement("div",{className:"ps-modal-header"},u.createElement("div",{className:"ps-modal-title"},a.title),u.createElement("button",{type:"button",className:"ps-modal-close",onClick:i},"Close")),u.createElement("div",{className:"ps-filter-grid"},(o.items||[]).map((l,c)=>{const f=o.type==="filesFilter"?n.filesFilterState?.[l.id]||l.options?.[0]?.id:o.type==="historyFormat"?n.historyFormatState:n.logsFilter?.[l.id]||l.options?.[0]?.id;return u.createElement("div",{key:l.id||c,className:"ps-filter-column"},u.createElement("div",{className:"ps-filter-title"},l.label),(l.options||[]).map(d=>u.createElement("button",{key:d.id,type:"button",className:`ps-filter-option${d.id===f?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:c}),o.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:d.id}):o.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[l.id]:d.id}}),t.ensureFilesForScope(d.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[l.id]:d.id}})}},d.label)))})),u.createElement("div",{className:"ps-modal-footer"},u.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:i},"Done")))):null}function Qa(t,e,{legendOpen:s=!1,onToggleLegend:n=null,onCloseLegend:o=null,promptOverlayOpen:i=!1,onOpenPromptOverlay:r=null,onClosePromptOverlay:a=null}={}){u.useEffect(()=>{const l=c=>{const f=c.target,d=f instanceof HTMLElement&&(f.tagName==="TEXTAREA"||f.tagName==="INPUT"||f.isContentEditable),h=t.getState().ui.modal,m=ts(t),g=t.getState().ui.inspectorTab,w=t.getState().ui.focusRegion,x=!c.metaKey&&!c.ctrlKey&&!c.altKey,b=!c.metaKey&&!c.ctrlKey&&!c.altKey&&c.key==="T"&&c.shiftKey,v=!c.metaKey&&!c.ctrlKey&&!c.altKey&&c.key==="N"&&c.shiftKey,M=E=>{const O=ma(m,g,E);t.selectInspectorTab(O).catch(()=>{})};if(!d&&(c.key==="?"||c.shiftKey&&c.key==="/")&&!c.metaKey&&!c.ctrlKey&&!c.altKey){c.preventDefault(),s?o?.():n?.();return}if(s){c.key==="Escape"&&(c.preventDefault(),o?.());return}if(i&&!h&&c.key==="Escape"){c.preventDefault(),a?.();return}if(!d&&b){c.preventDefault(),t.handleCommand(y.OPEN_THEME_PICKER).catch(()=>{});return}if(!d&&v){c.preventDefault(),t.handleCommand(y.OPEN_MODEL_PICKER).catch(()=>{});return}if(h&&!d){if(c.key==="Escape"){c.preventDefault(),t.handleCommand(y.CLOSE_MODAL).catch(()=>{});return}if(c.key==="Enter"){c.preventDefault(),t.handleCommand(y.MODAL_CONFIRM).catch(()=>{});return}if(c.key==="Tab"&&c.shiftKey){c.preventDefault(),t.handleCommand(y.MODAL_PANE_PREV).catch(()=>{});return}if(c.key==="Tab"){c.preventDefault(),t.handleCommand(y.MODAL_PANE_NEXT).catch(()=>{});return}if(c.key==="ArrowUp"||c.key==="k"){c.preventDefault(),t.handleCommand(y.MODAL_PREV).catch(()=>{});return}(c.key==="ArrowDown"||c.key==="j")&&(c.preventDefault(),t.handleCommand(y.MODAL_NEXT).catch(()=>{}));return}if(d){if(i&&c.key==="Escape"){c.preventDefault(),a?.();return}return}if(c.key==="r"&&x&&w!=="prompt"){c.preventDefault(),t.handleCommand(y.REFRESH).catch(()=>{});return}if(c.key==="n"&&x){c.preventDefault(),t.handleCommand(y.NEW_SESSION).catch(()=>{});return}if(w==="inspector"&&g==="files"&&(c.key==="u"&&x||(c.ctrlKey||c.metaKey)&&c.key.toLowerCase()==="a")){c.preventDefault(),t.handleCommand(y.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(w==="inspector"&&g==="files"&&c.key==="a"&&x){c.preventDefault(),t.handleCommand(y.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(w==="inspector"&&g==="files"&&c.key==="o"&&x){c.preventDefault(),t.handleCommand(y.OPEN_SELECTED_FILE).catch(()=>{});return}if(w==="inspector"&&g==="files"&&c.key==="f"&&x){c.preventDefault(),t.handleCommand(y.OPEN_FILES_FILTER).catch(()=>{});return}if(w==="inspector"&&g==="files"&&c.key==="v"&&x){c.preventDefault(),t.handleCommand(y.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(w==="inspector"&&g==="logs"&&c.key==="t"&&x){c.preventDefault(),t.handleCommand(y.TOGGLE_LOG_TAIL).catch(()=>{});return}if(w==="inspector"&&g==="logs"&&c.key==="f"&&x){c.preventDefault(),t.handleCommand(y.OPEN_LOG_FILTER).catch(()=>{});return}if(w==="inspector"&&g==="history"&&c.key==="f"&&x){c.preventDefault(),t.handleCommand(y.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(w==="inspector"&&g==="history"&&c.key==="r"&&x){c.preventDefault(),t.handleCommand(y.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(w==="inspector"&&g==="history"&&c.key==="a"&&x){c.preventDefault(),t.handleCommand(y.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(c.key==="a"&&x){c.preventDefault(),t.handleCommand(y.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(c.key==="p"&&x){c.preventDefault(),r?r():t.handleCommand(y.FOCUS_PROMPT).catch(()=>{});return}if(c.key==="c"&&x){c.preventDefault(),t.handleCommand(y.CANCEL_SESSION).catch(()=>{});return}if(c.key==="d"&&x){c.preventDefault(),t.handleCommand(y.DONE_SESSION).catch(()=>{});return}if(c.key==="D"&&c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey){c.preventDefault(),t.handleCommand(y.DELETE_SESSION).catch(()=>{});return}if(c.key==="m"&&x&&w==="inspector"){c.preventDefault(),M(1);return}if(c.key==="["&&x){c.preventDefault(),t.handleCommand(y.GROW_LEFT_PANE).catch(()=>{});return}if(c.key==="]"&&x){c.preventDefault(),t.handleCommand(y.GROW_RIGHT_PANE).catch(()=>{});return}if(c.key==="{"&&x){c.preventDefault(),t.handleCommand(y.SHRINK_SESSION_PANE).catch(()=>{});return}if(c.key==="}"&&x){c.preventDefault(),t.handleCommand(y.GROW_SESSION_PANE).catch(()=>{});return}if(w==="inspector"&&c.key==="ArrowLeft"){c.preventDefault(),M(-1);return}if(w==="inspector"&&c.key==="ArrowRight"){c.preventDefault(),M(1);return}if(w==="sessions"&&(c.key==="ArrowUp"||c.key==="k")){c.preventDefault(),t.handleCommand(y.MOVE_SESSION_UP).catch(()=>{});return}if(w==="sessions"&&(c.key==="ArrowDown"||c.key==="j")){c.preventDefault(),t.handleCommand(y.MOVE_SESSION_DOWN).catch(()=>{});return}if(w==="sessions"&&(c.key==="PageUp"||c.ctrlKey&&c.key.toLowerCase()==="u")){c.preventDefault(),t.handleCommand(y.PAGE_UP).catch(()=>{});return}if(w==="sessions"&&(c.key==="PageDown"||c.ctrlKey&&c.key.toLowerCase()==="d")){c.preventDefault(),t.handleCommand(y.PAGE_DOWN).catch(()=>{});return}if(w==="sessions"&&c.key==="t"&&x){c.preventDefault(),t.handleCommand(y.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(c.key==="PageUp"||c.ctrlKey&&c.key.toLowerCase()==="u")){c.preventDefault(),t.handleCommand(y.PAGE_UP).catch(()=>{});return}if(!e&&(c.key==="PageDown"||c.ctrlKey&&c.key.toLowerCase()==="d")){c.preventDefault(),t.handleCommand(y.PAGE_DOWN).catch(()=>{});return}if(!e&&c.key==="g"&&x){c.preventDefault(),t.handleCommand(y.SCROLL_TOP).catch(()=>{});return}if(!e&&c.key==="G"&&c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey){c.preventDefault(),t.handleCommand(y.SCROLL_BOTTOM).catch(()=>{});return}if(w!=="prompt"&&c.key==="h"&&x){c.preventDefault(),t.handleCommand(y.FOCUS_LEFT).catch(()=>{});return}if(w!=="prompt"&&c.key==="l"&&x){c.preventDefault(),t.handleCommand(y.FOCUS_RIGHT).catch(()=>{});return}if(!e&&(c.key==="ArrowUp"||c.key==="k")){c.preventDefault(),t.handleCommand(y.SCROLL_UP).catch(()=>{});return}if(!e&&(c.key==="ArrowDown"||c.key==="j")){c.preventDefault(),t.handleCommand(y.SCROLL_DOWN).catch(()=>{});return}!e&&c.key==="Escape"&&(c.preventDefault(),t.handleCommand(y.FOCUS_SESSIONS).catch(()=>{}))};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[t,s,e,o,n,a,r,i])}function Ja({transport:t,mode:e="remote",branding:s=null}={}){const n=xa(),o=Si(yi,di({mode:e,branding:s,themeId:n}));return new oa({store:o,transport:t})}function Za({controller:t}){const e=u.useRef(null),s=Ea(e),n=Ta(s),[o,i]=u.useState(!1),[r,a]=u.useState(!1),[l,c]=u.useState(()=>ya()),[f,d]=u.useState(null),h=R(t,_=>({themeId:_.ui.themeId,promptRows:Wn(_),paneAdjust:_.ui.layout?.paneAdjust??0,sessionPaneAdjust:_.ui.layout?.sessionPaneAdjust??0,focusRegion:_.ui.focusRegion,inspectorTab:_.ui.inspectorTab,filesFullscreen:!!_.files.fullscreen}),ie),[m,g]=u.useState("workspace"),[w,x]=u.useState(!1),b=(s.width||window.innerWidth||0)<pa,v=Hn(t)||Bn(t),M=Dn(t),E=u.useCallback(()=>{t.handleCommand(y.FOCUS_PROMPT).catch(()=>{}),a(!0)},[t]),O=u.useCallback(()=>{a(!1)},[]);Qa(t,b,{legendOpen:o,onToggleLegend:()=>i(_=>!_),onCloseLegend:()=>i(!1),promptOverlayOpen:r,onOpenPromptOverlay:E,onClosePromptOverlay:O}),u.useEffect(()=>{t.setViewport(n)},[t,n.height,n.width]),u.useEffect(()=>{Ia(h.themeId),va(h.themeId)},[h.themeId]),u.useEffect(()=>{Sa(l)},[l]),u.useEffect(()=>{b&&h.focusRegion!=="prompt"&&g(h.focusRegion==="activity"?"activity":h.focusRegion==="inspector"?"inspector":"workspace")},[b,h.focusRegion]),u.useEffect(()=>{const _=ts(t);!_.includes(h.inspectorTab)&&_.length>0&&t.selectInspectorTab(_[0]).catch(()=>{})},[t,h.inspectorTab]);const H=u.useMemo(()=>He(n,h.paneAdjust,h.promptRows,h.sessionPaneAdjust),[n,h.paneAdjust,h.promptRows,h.sessionPaneAdjust]),P=h.filesFullscreen&&h.inspectorTab==="files";u.useEffect(()=>{!P||!l||(c(!1),d(null))},[l,P]);const T=u.useCallback(()=>{c(_=>{const Ie=!_;return Ie?t.setFocus("chat"):d(null),Ie})},[t]),K=u.useCallback(_=>{d(Ie=>{const se=Ie===_?null:_;return t.setFocus(se||"chat"),se})},[t]),B=u.createElement("div",{className:"ps-workspace-grid",style:{gridTemplateColumns:`minmax(0, ${H.leftWidth}fr) 16px minmax(0, ${H.rightWidth}fr)`}},u.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`${H.sessionPaneHeight}fr 16px ${H.chatPaneHeight}fr`}},u.createElement(ss,{controller:t}),u.createElement(Ka,{controller:t,sessionPaneAdjust:h.sessionPaneAdjust}),u.createElement(ns,{controller:t})),u.createElement(Ga,{controller:t,paneAdjust:h.paneAdjust}),u.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`${H.inspectorPaneHeight}fr ${H.activityPaneHeight}fr`}},u.createElement($e,{controller:t,mobile:!1}),u.createElement(Ot,{controller:t}))),W=u.createElement(Ua,{controller:t,openPane:f,onTogglePane:K,mobile:b}),Ne=u.createElement("div",{className:"ps-workspace-full"},u.createElement($e,{controller:t,mobile:!1}));let re=null;return P?re=u.createElement("div",{className:"ps-mobile-pane-fill"},u.createElement($e,{controller:t,mobile:!0})):m==="inspector"?re=u.createElement("div",{className:"ps-mobile-pane-fill"},u.createElement($e,{controller:t,mobile:!0})):m==="activity"?re=u.createElement("div",{className:"ps-mobile-pane-fill"},u.createElement(Ot,{controller:t})):re=u.createElement(Ba,{controller:t,sessionsCollapsed:w,setSessionsCollapsed:x}),u.createElement("div",{ref:e,className:"ps-web-shell"},u.createElement(za,{controller:t,mobile:b,onToggleLegend:()=>i(_=>!_),onOpenPrompt:E,chatFocusMode:l,onToggleChatFocus:T,chatFocusDisabled:P}),u.createElement("div",{className:"ps-workspace"},P?Ne:l?W:b?re:B),u.createElement("div",{className:"ps-footer-shell"},u.createElement(Vn,{controller:t,mobile:b,active:!r})),b&&!l?u.createElement(Ya,{activePane:m,setActivePane:g,controller:t}):null,u.createElement(Xa,{controller:t}),u.createElement(qa,{open:o,onClose:()=>i(!1),canUpload:v,canOpenLocally:M}),u.createElement(Va,{controller:t,open:r,onClose:O}))}export{Za as P,u as R,Ja as c,Qn as r};