pilotswarm 0.5.21 → 0.5.23

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 (75) hide show
  1. package/package.json +2 -1
  2. package/tui/src/node-sdk-transport.js +22 -5
  3. package/ui/core/src/controller.js +1 -1
  4. package/ui/core/src/reducer.js +3 -2
  5. package/ui/core/src/selectors.js +142 -2
  6. package/ui/core/src/state.js +1 -1
  7. package/ui/react/src/web-app.js +541 -22
  8. package/web/dist/assets/abnfDiagram-VRR7QNED-BHkTpRkx.js +1 -0
  9. package/web/dist/assets/arc-BOgZyEWA.js +1 -0
  10. package/web/dist/assets/architectureDiagram-ZJ3FMSHR-DeE8fDMy.js +36 -0
  11. package/web/dist/assets/blockDiagram-677ZJIJ3-CzhdxVEu.js +132 -0
  12. package/web/dist/assets/c4Diagram-LMCZKHZV-Cc6p_IKP.js +10 -0
  13. package/web/dist/assets/channel-DhhWyKRW.js +1 -0
  14. package/web/dist/assets/chunk-2Q5K7J3B-BCo94LTM.js +1 -0
  15. package/web/dist/assets/chunk-32BRIVSS-DaklJ-6i.js +1 -0
  16. package/web/dist/assets/chunk-5VM5RSS4-BN_wg2pr.js +15 -0
  17. package/web/dist/assets/chunk-EX3LRPZG-DSFFLUoL.js +231 -0
  18. package/web/dist/assets/chunk-JWPE2WC7-DB4dAjza.js +1 -0
  19. package/web/dist/assets/chunk-MOJQB5TN-CRM5eGQS.js +88 -0
  20. package/web/dist/assets/chunk-RYQCIY6F-BFlkjazU.js +1 -0
  21. package/web/dist/assets/chunk-V7JOEXUC-Bnfh4AAv.js +206 -0
  22. package/web/dist/assets/chunk-VR4S4FIN-CQc4_qVM.js +1 -0
  23. package/web/dist/assets/chunk-XXDRQBXY-CZivyoDm.js +1 -0
  24. package/web/dist/assets/classDiagram-OUVF2IWQ-CQBxGpio.js +1 -0
  25. package/web/dist/assets/classDiagram-v2-EOCWNBFH-CQBxGpio.js +1 -0
  26. package/web/dist/assets/cose-bilkent-JH36ORCC-BUibhTD-.js +1 -0
  27. package/web/dist/assets/cynefin-VYW2F7L2-CRkjg5zF.js +166 -0
  28. package/web/dist/assets/cynefinDiagram-TSTJHNR4-BoeQn4Um.js +62 -0
  29. package/web/dist/assets/cytoscape.esm-D3_iZ_3b.js +321 -0
  30. package/web/dist/assets/dagre-VKFMJZFB-DGo7-PY5.js +4 -0
  31. package/web/dist/assets/defaultLocale-DX6XiGOO.js +1 -0
  32. package/web/dist/assets/diagram-FQU43EPY-DMXd2bdO.js +3 -0
  33. package/web/dist/assets/diagram-G47NLZAW-CkYHblMZ.js +24 -0
  34. package/web/dist/assets/diagram-NH7WQ7WH-C9iwEe4T.js +24 -0
  35. package/web/dist/assets/diagram-OA4YK3LP-DpYLrfwb.js +30 -0
  36. package/web/dist/assets/diagram-WEI45ONY-BvrBukHb.js +41 -0
  37. package/web/dist/assets/ebnfDiagram-CCIWWBDH-DGl1r3zR.js +1 -0
  38. package/web/dist/assets/erDiagram-Q63AITRT-CoP5DBSb.js +85 -0
  39. package/web/dist/assets/flowDiagram-23GEKE2U-DVHtyYyr.js +156 -0
  40. package/web/dist/assets/ganttDiagram-NO4QXBWP-_JyR78yC.js +292 -0
  41. package/web/dist/assets/gitGraphDiagram-IHSO6WYX-Bj7sh0Db.js +106 -0
  42. package/web/dist/assets/graph-DOmOIIwC.js +1 -0
  43. package/web/dist/assets/{index-BDMVG8w6.js → index-CB6NfSZb.js} +3 -3
  44. package/web/dist/assets/{index-CxkLM8_a.css → index-SmXlZ1eu.css} +1 -1
  45. package/web/dist/assets/infoDiagram-FWYZ7A6U-BrvMeRmA.js +2 -0
  46. package/web/dist/assets/init-Gi6I4Gst.js +1 -0
  47. package/web/dist/assets/ishikawaDiagram-FXEZZL3T-lNDujpEC.js +70 -0
  48. package/web/dist/assets/journeyDiagram-5HDEW3XC-yoD2QRni.js +139 -0
  49. package/web/dist/assets/kanban-definition-HUTT4EX6-DtyMlypg.js +89 -0
  50. package/web/dist/assets/katex-HP8lGamR.js +257 -0
  51. package/web/dist/assets/layout-D-LzfAck.js +1 -0
  52. package/web/dist/assets/linear-DXPbXF9v.js +1 -0
  53. package/web/dist/assets/map-DxJ2ADlA.js +1 -0
  54. package/web/dist/assets/mermaid.core-DCEXqVUL.js +308 -0
  55. package/web/dist/assets/mindmap-definition-LN4V7U3C-DpKHDJFg.js +96 -0
  56. package/web/dist/assets/ordinal-Cboi1Yqb.js +1 -0
  57. package/web/dist/assets/pegDiagram-2B236MQR-mxFI_8qh.js +1 -0
  58. package/web/dist/assets/pieDiagram-ENE6RG2P-sUWLrwMG.js +39 -0
  59. package/web/dist/assets/pilotswarm-CdEkcq2V.js +91 -0
  60. package/web/dist/assets/quadrantDiagram-ABIIQ3AL-Cph1z7ye.js +7 -0
  61. package/web/dist/assets/railroadDiagram-RFXS5EU6-BPKkt2va.js +1 -0
  62. package/web/dist/assets/requirementDiagram-TGXJPOKE-BB6DNHCy.js +84 -0
  63. package/web/dist/assets/sankeyDiagram-HTMAVEWB-BASvPQk2.js +40 -0
  64. package/web/dist/assets/sequenceDiagram-DBY2YBRQ-DMrNas01.js +162 -0
  65. package/web/dist/assets/sizeCapture-X5ZJPWSS-Ddq5yeZZ.js +1 -0
  66. package/web/dist/assets/stateDiagram-2N3HPSRC-DUb_IFST.js +1 -0
  67. package/web/dist/assets/stateDiagram-v2-6OUMAXLB-C3nsHf5u.js +1 -0
  68. package/web/dist/assets/swimlanes-5IMT3BWC-Cs9JsGaf.js +2 -0
  69. package/web/dist/assets/swimlanesDiagram-G3AALYLV-C2xZA5V6.js +8 -0
  70. package/web/dist/assets/timeline-definition-FHXFAJF6-xuNF5fTm.js +120 -0
  71. package/web/dist/assets/vennDiagram-L72KCM5P-fsI1GFLy.js +34 -0
  72. package/web/dist/assets/wardleyDiagram-EHGQE667-DEc-kumC.js +78 -0
  73. package/web/dist/assets/xychartDiagram-FW5EYKEG-BCo6Qrfu.js +7 -0
  74. package/web/dist/index.html +3 -3
  75. package/web/dist/assets/pilotswarm-CjMx44so.js +0 -90
@@ -0,0 +1,91 @@
1
+ function ya(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Is={exports:{}},H={};var qn;function Sa(){if(qn)return H;qn=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),r=Symbol.for("react.context"),a=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),p=Symbol.iterator;function h(b){return b===null||typeof b!="object"?null:(b=p&&b[p]||b["@@iterator"],typeof b=="function"?b:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,S={};function y(b,T,_){this.props=b,this.context=T,this.refs=S,this.updater=_||m}y.prototype.isReactComponent={},y.prototype.setState=function(b,T){if(typeof b!="object"&&typeof b!="function"&&b!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,b,T,"setState")},y.prototype.forceUpdate=function(b){this.updater.enqueueForceUpdate(this,b,"forceUpdate")};function w(){}w.prototype=y.prototype;function I(b,T,_){this.props=b,this.context=T,this.refs=S,this.updater=_||m}var x=I.prototype=new w;x.constructor=I,g(x,y.prototype),x.isPureReactComponent=!0;var C=Array.isArray;function v(){}var k={H:null,A:null,T:null,S:null},P=Object.prototype.hasOwnProperty;function O(b,T,_){var L=_.ref;return{$$typeof:t,type:b,key:T,ref:L!==void 0?L:null,props:_}}function M(b,T){return O(b.type,T,b.props)}function $(b){return typeof b=="object"&&b!==null&&b.$$typeof===t}function F(b){var T={"=":"=0",":":"=2"};return"$"+b.replace(/[=:]/g,function(_){return T[_]})}var Y=/\/+/g;function U(b,T){return typeof b=="object"&&b!==null&&b.key!=null?F(""+b.key):T.toString(36)}function V(b){switch(b.status){case"fulfilled":return b.value;case"rejected":throw b.reason;default:switch(typeof b.status=="string"?b.then(v,v):(b.status="pending",b.then(function(T){b.status==="pending"&&(b.status="fulfilled",b.value=T)},function(T){b.status==="pending"&&(b.status="rejected",b.reason=T)})),b.status){case"fulfilled":return b.value;case"rejected":throw b.reason}}throw b}function q(b,T,_,L,B){var D=typeof b;(D==="undefined"||D==="boolean")&&(b=null);var W=!1;if(b===null)W=!0;else switch(D){case"bigint":case"string":case"number":W=!0;break;case"object":switch(b.$$typeof){case t:case e:W=!0;break;case f:return W=b._init,q(W(b._payload),T,_,L,B)}}if(W)return B=B(b),W=L===""?"."+U(b,0):L,C(B)?(_="",W!=null&&(_=W.replace(Y,"$&/")+"/"),q(B,T,_,"",function(nt){return nt})):B!=null&&($(B)&&(B=M(B,_+(B.key==null||b&&b.key===B.key?"":(""+B.key).replace(Y,"$&/")+"/")+W)),T.push(B)),1;W=0;var ae=L===""?".":L+":";if(C(b))for(var ie=0;ie<b.length;ie++)L=b[ie],D=ae+U(L,ie),W+=q(L,T,_,D,B);else if(ie=h(b),typeof ie=="function")for(b=ie.call(b),ie=0;!(L=b.next()).done;)L=L.value,D=ae+U(L,ie++),W+=q(L,T,_,D,B);else if(D==="object"){if(typeof b.then=="function")return q(V(b),T,_,L,B);throw T=String(b),Error("Objects are not valid as a React child (found: "+(T==="[object Object]"?"object with keys {"+Object.keys(b).join(", ")+"}":T)+"). If you meant to render a collection of children, use an array instead.")}return W}function ee(b,T,_){if(b==null)return b;var L=[],B=0;return q(b,L,"","",function(D){return T.call(_,D,B++)}),L}function we(b){if(b._status===-1){var T=b._result;T=T(),T.then(function(_){(b._status===0||b._status===-1)&&(b._status=1,b._result=_)},function(_){(b._status===0||b._status===-1)&&(b._status=2,b._result=_)}),b._status===-1&&(b._status=0,b._result=T)}if(b._status===1)return b._result.default;throw b._result}var R=typeof reportError=="function"?reportError:function(b){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var T=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof b=="object"&&b!==null&&typeof b.message=="string"?String(b.message):String(b),error:b});if(!window.dispatchEvent(T))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",b);return}console.error(b)},K={map:ee,forEach:function(b,T,_){ee(b,function(){T.apply(this,arguments)},_)},count:function(b){var T=0;return ee(b,function(){T++}),T},toArray:function(b){return ee(b,function(T){return T})||[]},only:function(b){if(!$(b))throw Error("React.Children.only expected to receive a single React element child.");return b}};return H.Activity=d,H.Children=K,H.Component=y,H.Fragment=s,H.Profiler=i,H.PureComponent=I,H.StrictMode=n,H.Suspense=l,H.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=k,H.__COMPILER_RUNTIME={__proto__:null,c:function(b){return k.H.useMemoCache(b)}},H.cache=function(b){return function(){return b.apply(null,arguments)}},H.cacheSignal=function(){return null},H.cloneElement=function(b,T,_){if(b==null)throw Error("The argument must be a React element, but you passed "+b+".");var L=g({},b.props),B=b.key;if(T!=null)for(D in T.key!==void 0&&(B=""+T.key),T)!P.call(T,D)||D==="key"||D==="__self"||D==="__source"||D==="ref"&&T.ref===void 0||(L[D]=T[D]);var D=arguments.length-2;if(D===1)L.children=_;else if(1<D){for(var W=Array(D),ae=0;ae<D;ae++)W[ae]=arguments[ae+2];L.children=W}return O(b.type,B,L)},H.createContext=function(b){return b={$$typeof:r,_currentValue:b,_currentValue2:b,_threadCount:0,Provider:null,Consumer:null},b.Provider=b,b.Consumer={$$typeof:o,_context:b},b},H.createElement=function(b,T,_){var L,B={},D=null;if(T!=null)for(L in T.key!==void 0&&(D=""+T.key),T)P.call(T,L)&&L!=="key"&&L!=="__self"&&L!=="__source"&&(B[L]=T[L]);var W=arguments.length-2;if(W===1)B.children=_;else if(1<W){for(var ae=Array(W),ie=0;ie<W;ie++)ae[ie]=arguments[ie+2];B.children=ae}if(b&&b.defaultProps)for(L in W=b.defaultProps,W)B[L]===void 0&&(B[L]=W[L]);return O(b,D,B)},H.createRef=function(){return{current:null}},H.forwardRef=function(b){return{$$typeof:a,render:b}},H.isValidElement=$,H.lazy=function(b){return{$$typeof:f,_payload:{_status:-1,_result:b},_init:we}},H.memo=function(b,T){return{$$typeof:u,type:b,compare:T===void 0?null:T}},H.startTransition=function(b){var T=k.T,_={};k.T=_;try{var L=b(),B=k.S;B!==null&&B(_,L),typeof L=="object"&&L!==null&&typeof L.then=="function"&&L.then(v,R)}catch(D){R(D)}finally{T!==null&&_.types!==null&&(T.types=_.types),k.T=T}},H.unstable_useCacheRefresh=function(){return k.H.useCacheRefresh()},H.use=function(b){return k.H.use(b)},H.useActionState=function(b,T,_){return k.H.useActionState(b,T,_)},H.useCallback=function(b,T){return k.H.useCallback(b,T)},H.useContext=function(b){return k.H.useContext(b)},H.useDebugValue=function(){},H.useDeferredValue=function(b,T){return k.H.useDeferredValue(b,T)},H.useEffect=function(b,T){return k.H.useEffect(b,T)},H.useEffectEvent=function(b){return k.H.useEffectEvent(b)},H.useId=function(){return k.H.useId()},H.useImperativeHandle=function(b,T,_){return k.H.useImperativeHandle(b,T,_)},H.useInsertionEffect=function(b,T){return k.H.useInsertionEffect(b,T)},H.useLayoutEffect=function(b,T){return k.H.useLayoutEffect(b,T)},H.useMemo=function(b,T){return k.H.useMemo(b,T)},H.useOptimistic=function(b,T){return k.H.useOptimistic(b,T)},H.useReducer=function(b,T,_){return k.H.useReducer(b,T,_)},H.useRef=function(b){return k.H.useRef(b)},H.useState=function(b){return k.H.useState(b)},H.useSyncExternalStore=function(b,T,_){return k.H.useSyncExternalStore(b,T,_)},H.useTransition=function(){return k.H.useTransition()},H.version="19.2.4",H}var zn;function Mo(){return zn||(zn=1,Is.exports=Sa()),Is.exports}var ba=Mo();const c=ya(ba);var xs={exports:{}},ce={};var Yn;function wa(){if(Yn)return ce;Yn=1;var t=Mo();function e(l){var u="https://react.dev/errors/"+l;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var f=2;f<arguments.length;f++)u+="&args[]="+encodeURIComponent(arguments[f])}return"Minified React error #"+l+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(){}var n={d:{f:s,r:function(){throw Error(e(522))},D:s,C:s,L:s,m:s,X:s,S:s,M:s},p:0,findDOMNode:null},i=Symbol.for("react.portal");function o(l,u,f){var d=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:d==null?null:""+d,children:l,containerInfo:u,implementation:f}}var r=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function a(l,u){if(l==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return ce.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,ce.createPortal=function(l,u){var f=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(e(299));return o(l,u,null,f)},ce.flushSync=function(l){var u=r.T,f=n.p;try{if(r.T=null,n.p=2,l)return l()}finally{r.T=u,n.p=f,n.d.f()}},ce.preconnect=function(l,u){typeof l=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,n.d.C(l,u))},ce.prefetchDNS=function(l){typeof l=="string"&&n.d.D(l)},ce.preinit=function(l,u){if(typeof l=="string"&&u&&typeof u.as=="string"){var f=u.as,d=a(f,u.crossOrigin),p=typeof u.integrity=="string"?u.integrity:void 0,h=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;f==="style"?n.d.S(l,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:d,integrity:p,fetchPriority:h}):f==="script"&&n.d.X(l,{crossOrigin:d,integrity:p,fetchPriority:h,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},ce.preinitModule=function(l,u){if(typeof l=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var f=a(u.as,u.crossOrigin);n.d.M(l,{crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&n.d.M(l)},ce.preload=function(l,u){if(typeof l=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var f=u.as,d=a(f,u.crossOrigin);n.d.L(l,f,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},ce.preloadModule=function(l,u){if(typeof l=="string")if(u){var f=a(u.as,u.crossOrigin);n.d.m(l,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else n.d.m(l)},ce.requestFormReset=function(l){n.d.r(l)},ce.unstable_batchedUpdates=function(l,u){return l(u)},ce.useFormState=function(l,u,f){return r.H.useFormState(l,u,f)},ce.useFormStatus=function(){return r.H.useHostTransitionStatus()},ce.version="19.2.4",ce}var Qn;function Ia(){if(Qn)return xs.exports;Qn=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),xs.exports=wa(),xs.exports}const xa=c.createContext(null);function Ee(){const t=c.useContext(xa);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function z(t,e,s=Object.is){const n=c.useRef(e),i=c.useRef(s);n.current=e,i.current=s;const[o,r]=c.useState(()=>e(t.getState())),a=c.useRef(o);return c.useEffect(()=>{a.current=o},[o]),c.useEffect(()=>t.subscribe(l=>{const u=n.current(l);i.current(a.current,u)||(a.current=u,r(u))}),[t]),o}const Xn=[".  ",".. ","..."],Jn=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function No(t,e=120){const[s,n]=c.useState(0);return c.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(o=>(o+1)%Jn.length)},e);return()=>clearInterval(i)},[t,e]),t?Jn[s]:""}function Po(t,e=360){const[s,n]=c.useState(0);return c.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(o=>(o+1)%Xn.length)},e);return()=>clearInterval(i)},[t,e]),t?Xn[s]:""}function _o(t,e=""){if(!Array.isArray(t)||t.length===0)return null;if(!e)return t;const s=t[t.length-1]||{};return[...t,{text:e,color:s.color||"gray",bold:!!s.bold,underline:!!s.underline,backgroundColor:s.backgroundColor}]}const A={SESSIONS:"sessions",CHAT:"chat",INSPECTOR:"inspector",ACTIVITY:"activity",PROMPT:"prompt",ADMIN:"admin"},Te=["sequence","logs","nodes","history","files","stats"],E={REFRESH:"refresh",NEW_SESSION:"newSession",OPEN_MODEL_PICKER:"openModelPicker",OPEN_SWITCH_MODEL_PICKER:"openSwitchModelPicker",OPEN_THEME_PICKER:"openThemePicker",OPEN_RENAME_SESSION:"openRenameSession",OPEN_SESSION_FILTER:"openSessionFilter",OPEN_TERMINATE_PICKER:"openTerminatePicker",OPEN_MOVE_TO_GROUP:"openMoveToGroup",CREATE_SESSION_GROUP:"createSessionGroup",OPEN_ARTIFACT_UPLOAD:"openArtifactUpload",TOGGLE_CHAT_VIEW:"toggleChatView",CLOSE_MODAL:"closeModal",MODAL_PREV:"modalPrev",MODAL_NEXT:"modalNext",MODAL_PANE_PREV:"modalPanePrev",MODAL_PANE_NEXT:"modalPaneNext",MODAL_CONFIRM:"modalConfirm",SEND_PROMPT:"sendPrompt",FOCUS_NEXT:"focusNext",FOCUS_PREV:"focusPrev",FOCUS_LEFT:"focusLeft",FOCUS_RIGHT:"focusRight",FOCUS_PROMPT:"focusPrompt",FOCUS_SESSIONS:"focusSessions",MOVE_SESSION_UP:"moveSessionUp",MOVE_SESSION_DOWN:"moveSessionDown",EXPAND_SESSION:"expandSession",COLLAPSE_SESSION:"collapseSession",NEXT_INSPECTOR_TAB:"nextInspectorTab",PREV_INSPECTOR_TAB:"prevInspectorTab",CYCLE_INSPECTOR_TAB:"cycleInspectorTab",GROW_LEFT_PANE:"growLeftPane",GROW_RIGHT_PANE:"growRightPane",GROW_SESSION_PANE:"growSessionPane",SHRINK_SESSION_PANE:"shrinkSessionPane",GROW_FOCUSED_PANE:"growFocusedPane",SHRINK_FOCUSED_PANE:"shrinkFocusedPane",OPEN_ARTIFACT_PICKER:"openArtifactPicker",OPEN_HELP:"openHelp",SEQUENCE_SELECT_PREV:"sequenceSelectPrev",SEQUENCE_SELECT_NEXT:"sequenceSelectNext",TOGGLE_SEQUENCE_TURN:"toggleSequenceTurn",TOGGLE_LOG_TAIL:"toggleLogTail",TOGGLE_STATS_VIEW:"toggleStatsView",OPEN_LOG_FILTER:"openLogFilter",OPEN_FILES_FILTER:"openFilesFilter",MOVE_FILE_UP:"moveFileUp",MOVE_FILE_DOWN:"moveFileDown",DOWNLOAD_SELECTED_FILE:"downloadSelectedFile",DELETE_SELECTED_FILE:"deleteSelectedFile",OPEN_SELECTED_FILE:"openSelectedFile",TOGGLE_FILE_PREVIEW_FULLSCREEN:"toggleFilePreviewFullscreen",TOGGLE_PANE_FULLSCREEN:"togglePaneFullscreen",SCROLL_UP:"scrollUp",SCROLL_DOWN:"scrollDown",PAGE_UP:"pageUp",PAGE_DOWN:"pageDown",EXPAND_HISTORY:"expandHistory",SCROLL_TOP:"scrollTop",SCROLL_BOTTOM:"scrollBottom",DONE_SESSION:"doneSession",CANCEL_SESSION:"cancelSession",STOP_TURN:"stopTurn",DELETE_SESSION:"deleteSession",REGENERATE_SESSION:"regenerateSession",PIN_SESSION:"pinSession",CYCLE_SESSION_VISIBILITY:"cycleSessionVisibility",OPEN_SHARE_SESSION:"openShareSession",TOGGLE_SELECT_MODE:"toggleSelectMode",TOGGLE_SESSION_SELECTION:"toggleSessionSelection",CLEAR_SESSION_SELECTION:"clearSessionSelection",OPEN_HISTORY_FORMAT:"openHistoryFormat",REFRESH_EXECUTION_HISTORY:"refreshExecutionHistory",EXPORT_EXECUTION_HISTORY:"exportExecutionHistory",OPEN_ADMIN_CONSOLE:"openAdminConsole",CLOSE_ADMIN_CONSOLE:"closeAdminConsole",ADMIN_REFRESH_PROFILE:"adminRefreshProfile",ADMIN_BEGIN_EDIT_GHCP_KEY:"adminBeginEditGhcpKey",ADMIN_CANCEL_EDIT_GHCP_KEY:"adminCancelEditGhcpKey",ADMIN_SAVE_GHCP_KEY:"adminSaveGhcpKey",ADMIN_CLEAR_GHCP_KEY:"adminClearGhcpKey"};function it(t,e,s){const n=t.indexOf(e),o=((n===-1?0:n)+s+t.length)%t.length;return t[o]}function fn(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 zs(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 va(t){const e=fn(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function Ea(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=fn(t);return e==null?null:{text:`ctx ${zs(t.currentTokens)}/${zs(t.tokenLimit)} ${e}%`,color:va(t)}}function Aa(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 Oo(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function Ta(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function Ro(t,e,s={},n={}){if(!e)return null;const i=Oo(t)||{},o=Ta(n.timestamp);return e==="session.usage_info"?typeof s.tokenLimit!="number"||typeof s.currentTokens!="number"||typeof s.messagesLength!="number"?null:(i.tokenLimit=s.tokenLimit,i.currentTokens=s.currentTokens,i.messagesLength=s.messagesLength,i.utilization=s.tokenLimit>0?s.currentTokens/s.tokenLimit:0,typeof s.systemTokens=="number"&&(i.systemTokens=s.systemTokens),typeof s.conversationTokens=="number"&&(i.conversationTokens=s.conversationTokens),typeof s.toolDefinitionsTokens=="number"&&(i.toolDefinitionsTokens=s.toolDefinitionsTokens),typeof s.isInitial=="boolean"&&(i.isInitial=s.isInitial),i):e==="assistant.usage"?(typeof s.inputTokens=="number"&&(i.lastInputTokens=s.inputTokens),typeof s.outputTokens=="number"&&(i.lastOutputTokens=s.outputTokens),typeof s.cacheReadTokens=="number"&&(i.lastCacheReadTokens=s.cacheReadTokens),typeof s.cacheWriteTokens=="number"&&(i.lastCacheWriteTokens=s.cacheWriteTokens),i):e==="session.compaction_start"?(i.compaction={...i.compaction||{},state:"running",startedAt:o,completedAt:void 0,error:void 0},i):e==="session.compaction_complete"?(i.compaction={...i.compaction||{},state:s.success===!1?"failed":"succeeded",completedAt:o,error:typeof s.error=="string"?s.error:void 0,preCompactionTokens:typeof s.preCompactionTokens=="number"?s.preCompactionTokens:void 0,postCompactionTokens:typeof s.postCompactionTokens=="number"?s.postCompactionTokens:void 0,preCompactionMessagesLength:typeof s.preCompactionMessagesLength=="number"?s.preCompactionMessagesLength:void 0,messagesRemoved:typeof s.messagesRemoved=="number"?s.messagesRemoved:void 0,tokensRemoved:typeof s.tokensRemoved=="number"?s.tokensRemoved:void 0,systemTokens:typeof s.systemTokens=="number"?s.systemTokens:void 0,conversationTokens:typeof s.conversationTokens=="number"?s.conversationTokens:void 0,toolDefinitionsTokens:typeof s.toolDefinitionsTokens=="number"?s.toolDefinitionsTokens:void 0,inputTokens:typeof s.compactionTokensUsed?.input=="number"?s.compactionTokensUsed.input:void 0,outputTokens:typeof s.compactionTokensUsed?.output=="number"?s.compactionTokensUsed.output:void 0,cachedInputTokens:typeof s.compactionTokensUsed?.cachedInput=="number"?s.compactionTokensUsed.cachedInput:void 0},typeof s.postCompactionTokens=="number"&&typeof i.tokenLimit=="number"&&i.tokenLimit>0&&(i.currentTokens=s.postCompactionTokens,i.utilization=s.postCompactionTokens/i.tokenLimit),typeof s.preCompactionMessagesLength=="number"&&typeof s.messagesRemoved=="number"&&(i.messagesLength=Math.max(0,s.preCompactionMessagesLength-s.messagesRemoved)),typeof s.systemTokens=="number"&&(i.systemTokens=s.systemTokens),typeof s.conversationTokens=="number"&&(i.conversationTokens=s.conversationTokens),typeof s.toolDefinitionsTokens=="number"&&(i.toolDefinitionsTokens=s.toolDefinitionsTokens),i):null}function Ca(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 ${zs(s.tokensRemoved)}`,color:"gray"}]:[]]}const Ys=/\{(\/?)([a-z-]+)\}/g,ka={color:null,bold:!1,underline:!1},Xt=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,Zn=/session:\/\/([A-Za-z0-9-]+)/g,Ma={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function zt(t){return{color:t.color,bold:t.bold,underline:t.underline}}function Na(t,e,s){const n=zt(t);if(e==="bold")return n.bold=!s,n;if(e==="underline")return n.underline=!s,n;if(e.endsWith("-fg")){const i=e.slice(0,-3);return n.color=s?null:Ma[i]||null,n}return n}function pn(t){return String(t||"").replace(Ys,"")}function Lo(t){const e=[],n=String(t||"").split(`
2
+ `);for(const i of n){const o=[];let r=zt(ka),a=0,l;for(;(l=Ys.exec(i))!==null;){const[u,f,d]=l;l.index>a&&o.push({text:i.slice(a,l.index),...zt(r)}),r=Na(r,d,f==="/"),a=l.index+u.length}(a<i.length||o.length===0)&&o.push({text:i.slice(a),...zt(r)}),e.push(o),Ys.lastIndex=0}return e}function Z(t){return String(t||"").slice(0,8)}function $o(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}function pe(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t),n=s.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return n;const o=s.toLocaleDateString("en-GB",{month:"short",day:"numeric"}),r=s.getFullYear()===e.getFullYear()?"":` ${s.getFullYear()}`;return`${o}${r} ${n}`}catch{return""}}function Pt(t){if(typeof t!="number"||!Number.isFinite(t)||t<0)return"?";const e=Math.round(t),s=Math.floor(e/3600),n=Math.floor(e%3600/60),i=e%60;return s>0?`${s}h ${n}m`:n>0?`${n}m ${i}s`:`${i}s`}function Pa(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function _a(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function Jt(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function ei(t,e,s){const n=t[e+s.length]||"";if(!n||/\s/u.test(n))return!1;if(!s.includes("_"))return!0;const i=t[e-1]||"";return!(Jt(i)&&Jt(n))}function Oa(t,e,s){const n=t[e-1]||"";if(!n||/\s/u.test(n))return!1;if(!s.includes("_"))return!0;const i=t[e+s.length]||"";return!(Jt(n)&&Jt(i))}function ti(t,e,s){let n=s;for(;n<t.length;){const i=t.indexOf(e,n);if(i<0)return-1;if(Oa(t,i,e))return i;n=i+e.length}return-1}function Ra(t){let e=String(t||""),s="";for(;e&&/[.,!?;:]/u.test(e[e.length-1]||"");)s=`${e[e.length-1]}${s}`,e=e.slice(0,-1);return{url:e,trailing:s}}function La(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function Et(t,e,s={}){if(!e)return;const n=t[t.length-1];if(n&&n.color===(s.color||null)&&!!n.bold==!!s.bold&&!!n.underline==!!s.underline&&n.backgroundColor===s.backgroundColor&&n.href===s.href){n.text+=e;return}t.push({text:e,color:s.color||null,bold:!!s.bold,underline:!!s.underline,backgroundColor:s.backgroundColor||void 0,href:s.href||void 0})}function Ue(t,e){if(e){if(e.type==="text"){const s=t[t.length-1];if(s?.type==="text"){s.text+=e.text||"";return}}t.push(e)}}function Fo(t){return(t||[]).map(e=>e?.text||"").join("")}function Yt(t){return ve(Fo(t))}function $a(t,e){const s=Math.max(0,Number(e)||0);if(s<=0)return[];const n=[];let i=s;for(const o of t||[]){if(i<=0)break;const r=String(o?.text||"");if(!r)continue;const a=Ft(r,i);a&&(n.push({...o,text:a}),i-=ve(a))}return n}function Bo(t,e){const s=Math.max(0,Number(e)||0),n=$a(t,s),i=Yt(n),o=Math.max(0,s-i);return o>0&&n.push({text:" ".repeat(o),color:null,bold:!1,underline:!1}),n}function Do(t,e){const s=Math.max(1,Number(e)||1),n=[];let i=[],o=0;function r(){if(i.length===0){n.push([{text:"",color:null,bold:!1,underline:!1}]);return}n.push(i),i=[],o=0}for(const a of t||[]){let l=String(a?.text||"");if(l)for(;l.length>0;){const u=Math.max(1,s-o),f=Ft(l,u);if(!f)break;if(f.length===l.length||ve(f)<u){i.push({...a,text:f}),o+=ve(f),l=l.slice(f.length),o>=s&&r();continue}const d=f.lastIndexOf(" ");if(d>0&&(o>0||d>0)){const p=f.slice(0,d+1);i.push({...a,text:p}),o+=ve(p),l=l.slice(p.length),r()}else i.push({...a,text:f}),o+=ve(f),l=l.slice(f.length),o>=s&&r()}}return(i.length>0||n.length===0)&&r(),n}function si(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function Ho(t){if(!t)return t;let e=String(t);for(;;){const s=e.replace(/[*_`]+$/g,"").replace(/[)\]}>!,;:?]+$/g,"").replace(/(\.[A-Za-z0-9]{1,16})\.+$/g,"$1");if(s===e)return e;e=s}}function Fa(t){const e=String(t||"");return Xt.lastIndex=0,[...e.matchAll(Xt)].map(s=>{const n=s[1],i=Ho(s[2]);return!n||!i?null:{sessionId:n,filename:i,uri:`artifact://${n}/${i}`}}).filter(Boolean)}function Ze(t){const e=String(t||"");if(!e)return e;Xt.lastIndex=0;const s=e.replace(Xt,(n,i,o)=>{const r=Ho(o);return!i||!r?n:`[artifact: ${r}](artifact://${i}/${r}) (press a to download)`});return Zn.lastIndex=0,s.replace(Zn,(n,i)=>i?`[session: ${Z(i)}](session://${i})`:n)}function hn(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const o=La(e,"`",n),r="`".repeat(o),a=_a(e,r,n+o);if(a>n+o-1){Ue(s,{type:"code",text:e.slice(n+o,a)}),n=a+o;continue}}if(e.startsWith("**",n)||e.startsWith("__",n)){const o=e.slice(n,n+2),r=ei(e,n,o)?ti(e,o,n+2):-1;if(r>n+2){Ue(s,{type:"strong",text:e.slice(n+2,r)}),n=r+2;continue}}if(e[n]==="["){const o=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(o){Ue(s,{type:"link",text:o[1],href:o[2]}),n+=o[0].length;continue}}if(e.startsWith("<http://",n)||e.startsWith("<https://",n)){const o=e.indexOf(">",n+1);if(o>n+1){const r=e.slice(n+1,o);Ue(s,{type:"link",text:r,href:r}),n=o+1;continue}}if(e.startsWith("http://",n)||e.startsWith("https://",n)){let o=n;for(;o<e.length&&!/\s/u.test(e[o]||"");)o+=1;const{url:r,trailing:a}=Ra(e.slice(n,o));if(r){Ue(s,{type:"link",text:r,href:r}),a&&Ue(s,{type:"text",text:a}),n=o;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&ei(e,n,e[n])){const o=e[n],r=ti(e,o,n+1);if(r>n+1){Ue(s,{type:"em",text:e.slice(n+1,r)}),n=r+1;continue}}let i=e.length;for(const o of["<https://","<http://","https://","http://","**","__","`","[","*","_"]){const r=e.indexOf(o,n+1);r!==-1&&r<i&&(i=r)}Ue(s,{type:"text",text:e.slice(n,i)}),n=i}return s.length>0?s:[{type:"text",text:""}]}function Ba(t=""){return hn(t).filter(e=>e?.type==="link"&&/^https?:\/\//i.test(String(e?.href||""))).map(e=>({href:String(e.href||"").trim(),text:String(e.text||e.href||"").trim()})).filter(e=>e.href)}function Ct(t){const e=hn(t),s=[];for(const n of e){if(n.type==="code"){Et(s,n.text,{color:"cyan"});continue}if(n.type==="strong"){Et(s,n.text,{bold:!0});continue}if(n.type==="em"){Et(s,n.text,{underline:!0});continue}if(n.type==="link"){Et(s,n.text,{color:"cyan",underline:!0,href:n.href});continue}Et(s,n.text)}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function ut(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function dt(t){const e=String(t||"").trim().replace(/^\|/,"").replace(/\|$/,""),s=[];let n="",i=!1;for(const o of e){if(i){n+=o,i=!1;continue}if(o==="\\"){i=!0;continue}if(o==="|"){s.push(n.trim()),n="";continue}n+=o}return s.push(n.trim()),s}function Zt(t){return t.length>0&&t.every(e=>/^:?-+:?$/.test(String(e||"").replace(/\s+/g,"")))}function ve(t){return Array.from(String(t||"")).length}function Ft(t,e){if(e<=0)return"";let s="",n=0;for(const i of Array.from(String(t||""))){if(n+1>e)break;s+=i,n+=1}return s}function Go(t,e){const s=String(t||""),n=Math.max(0,e-ve(s));return s+" ".repeat(n)}function Uo(t){return Fo(Ct(t))}function Da(t,e){const s=Uo(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),i=[];let o="";const r=a=>{let l=a;for(;ve(l)>e;){const u=Ft(l,e);if(!u)break;o&&(i.push(o),o=""),i.push(u),l=l.slice(u.length)}return l};for(const a of n){const l=r(a);if(!l)continue;if(!o){o=l;continue}const u=`${o} ${l}`;ve(u)<=e?o=u:(i.push(o),o=l)}return o&&i.push(o),i.length>0?i:[""]}function Ha(t,e){const s=Math.max(1,...t.map(f=>f.length)),n=Math.max(s*3,e-(s*3+1)),i=Array.from({length:s},(f,d)=>Math.max(3,...t.map(p=>ve(p[d]||"")))),o=Array.from({length:s},(f,d)=>Math.max(3,...t.map(p=>Math.max(0,...String(p[d]||"").split(/\s+/).filter(Boolean).map(h=>ve(h)))))),r=Array.from({length:s},(f,d)=>Math.max(3,Math.min(Math.max(ve(t[0]?.[d]||"")||3,o[d]),24)));if(i.reduce((f,d)=>f+d,0)<=n)return i;const l=r.slice();let u=n-l.reduce((f,d)=>f+d,0);if(u<0){const f=Math.max(3,Math.floor(n/s));return l.map((d,p)=>p===s-1?Math.max(3,n-f*(s-1)):f)}for(;u>0;){let f=0,d=-1/0;for(let p=0;p<s;p++){const h=i[p]-l[p];h>d&&(d=h,f=p)}if(d<=0){l[s-1]+=u;break}l[f]+=1,u-=1}return l}function Ga(t,e){if(!t||t.length===0)return"";const s=Math.max(1,...t.map(p=>p.length)),i=t.map(p=>Array.from({length:s},(h,m)=>p[m]||"")).map(p=>p.map(h=>Uo(h))),o=Ha(i,e),r=[],a=`┌${o.map(p=>"─".repeat(p+2)).join("┬")}┐`,l=`├${o.map(p=>"─".repeat(p+2)).join("┼")}┤`,u=`└${o.map(p=>"─".repeat(p+2)).join("┴")}┘`,f=p=>{const h=p.map((g,S)=>Da(g,o[S])),m=Math.max(...h.map(g=>g.length));for(let g=0;g<m;g++){const S=h.map((y,w)=>Go(y[g]||"",o[w]));r.push(`│ ${S.join(" │ ")} │`)}};r.push(a),f(i[0]),r.push(l);const d=i.slice(1);for(const p of d)f(p);return r.push(u),r.join(`
3
+ `)}function Ua(t,e){const s=String(t||"").split(`
4
+ `),n=[];let i=!1;for(let o=0;o<s.length;o++){const r=s[o];if(r.trim().startsWith("```")){i=!i,n.push(r);continue}if(i){n.push(r);continue}const l=s[o+1];if(!ut(r)||!ut(l)){n.push(r);continue}const u=dt(r),f=dt(l);if(!Zt(f)||u.length!==f.length){n.push(r);continue}const d=[u];for(o+=1;o+1<s.length&&ut(s[o+1]);){o+=1;const p=dt(s[o]);Zt(p)||d.push(p)}n.push(Ga(d,e))}return n.join(`
5
+ `)}function ja(t,e){const s=String(t||"");if(!s)return[""];const n=[];let i=s;for(;i.length>0;){const o=Ft(i,e);if(!o)break;n.push(o),i=i.slice(o.length)}return n.length>0?n:[""]}function ni(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",i=Ft(n,Math.max(1,s-4)),o=Math.max(0,s-i.length-2);return[{text:`┌${i}${"─".repeat(o)}┐`,color:"gray"}]}function ii(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function oi(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),i=[];for(const o of t){const r=ja(o,n);for(const a of r)i.push([{text:"│",color:"gray"},{text:Go(a,n),color:"cyan"},{text:"│",color:"gray"}]);r.length===0&&i.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}])}return i.length===0&&i.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}]),i}function St(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),i=e.tableMode==="sentinel"?"sentinel":"boxArt",r=(i==="boxArt"?Ua(String(t||""),n):String(t||"")).split(`
6
+ `);let a=!1,l="",u=[];for(let f=0;f<r.length;f+=1){const d=r[f],p=d.trim();if(p.startsWith("```")){a?(s.push(ni(l,Math.max(8,n))),s.push(...oi(u,Math.max(8,n))),s.push(ii(Math.max(8,n))),a=!1,l="",u=[]):(a=!0,l=p.slice(3).trim(),u=[]);continue}if(a){u.push(d);continue}if(i==="sentinel"&&d&&ut(d)){const y=r[f+1]||"";if(ut(y)){const w=dt(d),I=dt(y);if(Zt(I)&&w.length===I.length){const x=[];let C=f+2;for(;C<r.length&&ut(r[C]);){const v=dt(r[C]);Zt(v)||x.push(v),C+=1}s.push({kind:"markdownTable",header:w,rows:x}),f=C-1;continue}}}if(!d){s.push([{text:"",color:null}]);continue}const h=/^(#{1,6})\s+(.*)$/.exec(d);if(h){s.push([{text:h[2],color:"white",bold:!0}]);continue}const m=/^>\s?(.*)$/.exec(d);if(m){s.push([{text:"> ",color:"gray"},...Ct(m[1]).map(y=>({...y,color:y.color||"gray"}))]);continue}const g=/^\s*[-*]\s+(.*)$/.exec(d);if(g){s.push([{text:"• ",color:"gray"},...Ct(g[1])]);continue}const S=/^\s*(\d+)\.\s+(.*)$/.exec(d);if(S){s.push([{text:`${S[1]}. `,color:"gray"},...Ct(S[2])]);continue}s.push(Ct(d))}return a&&(s.push(ni(l,Math.max(8,n))),s.push(...oi(u,Math.max(8,n))),s.push(ii(Math.max(8,n)))),s}function ne({title:t="SYSTEM",timestamp:e="",body:s="",width:n=80,titleColor:i="yellow",borderColor:o="gray",bodyColor:r=null,fitToContent:a=!1,tableMode:l=null}={}){const u=Math.max(a?12:20,Number(n)||(a?12:20)),f=Math.max(1,u-4),d=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:i,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]];if(l==="sentinel"){const I=St(String(s||""),{width:f,tableMode:l}),x=r?I.map(C=>Array.isArray(C)?si(C,r):C):I;return[{kind:"cardStart",runs:d,borderColor:o},...x,{kind:"cardEnd"},[{text:"",color:null}]]}const p=St(String(s||""),{width:f}),h=p.length>0?p.flatMap(I=>Do(I,f)):[[{text:"",color:null}]],m=r?h.map(I=>si(I,r)):h,g=m.reduce((I,x)=>Math.max(I,Yt(x)),0),S=a?Math.min(u,Math.max(12,Yt(d)+3,g+4)):u,y=Math.max(1,S-4),w=Math.max(0,S-Yt(d)-3);return[[{text:"┌─",color:o},...d,{text:`${"─".repeat(w)}┐`,color:o}],...m.map(I=>[{text:"│ ",color:o},...Bo(I,y),{text:" │",color:o}]),[{text:`└${"─".repeat(Math.max(1,S-2))}┘`,color:o}],[{text:"",color:null}]]}function It(t,e="PilotSwarm"){const s=e||"PilotSwarm",n=String(t?.agentId||"");if(n==="pilotswarm")return s;if(n==="sweeper")return"Sweeper Agent";if(n==="resourcemgr")return"Resource Manager Agent";if(n==="facts-manager")return"Facts Manager";const i=String(t?.title||"").trim();return/^pilotswarm(?: agent)?$/i.test(i)?s:/^sweeper agent$/i.test(i)||/^sweeper$/i.test(i)?"Sweeper Agent":/^resource manager agent$/i.test(i)||/^resourcemgr$/i.test(i)?"Resource Manager Agent":/^facts manager$/i.test(i)||/^facts-manager$/i.test(i)?"Facts Manager":i||"System Agent"}function jo(t){const e=It(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}const J=300,Wa=[J,1e3,3e3,1e4],Ka=["user.message","assistant.message","system.message","session.epoch_committed","session.regenerate_refused"];function Wo(t){const e=t?.data&&typeof t.data=="object"?t.data:{},s=Number.isFinite(e.toEpoch)?e.toEpoch:Number(e.epoch)||0,n=Number.isFinite(e.turnsArchived)?e.turnsArchived:null;return{id:`${t.sessionId}:${t.seq}:epoch`,kind:"epoch-divider",role:"epoch-divider",epoch:s,turnsArchived:n,time:pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Ko(t){const e=t?.data&&typeof t.data=="object"?t.data:{};return{id:`${t.sessionId}:${t.seq}:regen-refused`,kind:"regen-refused",role:"regen-refused",reason:typeof e.reason=="string"?e.reason:"unknown",time:pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Ae(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(J,Number(e)||J);return s.length>n?s.slice(-n):s}function Ge(t){return String(t||"").replace(/\r\n/g,`
7
+ `).trim()}function ri(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"";try{return e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short"}).replace(/,\s*/g," ").replace(/\s+/g," ").trim()}catch{return e.toISOString().replace(/\.000Z$/,"Z")}}const Vo=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,Va=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function mn(t){return Vo.test(Ge(t))}function Ke(t){const e=String(t||"").replace(/\r\n/g,`
8
+ `).trim();if(!e)return"";const s=e.replace(Va,"").trimStart();return s!==e?s.trim():mn(e)?e.replace(Vo,"").trim():e}function qo(t){const e=String(t||"").replace(/\r\n/g,`
9
+ `).split(`
10
+ `),s=[];let n=[];function i(){n.length!==0&&(s.push({kind:"text",text:n.join(`
11
+ `)}),n=[])}for(let o=0;o<e.length;){const r=e[o];if(!/^\s*\[SYSTEM:/i.test(r)){n.push(r),o+=1;continue}const a=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(r);if(a){i(),s.push({kind:"system",text:a[1].trim()}),o+=1;continue}const l=[r.replace(/^\s*\[SYSTEM:\s*/i,"")];let u=-1;for(let f=o+1;f<e.length;f+=1){const d=e[f];if(d.trim()==="]"){u=f;break}if(/\]\s*$/.test(d.trim())){const p=d.replace(/\]\s*$/,"");p.trim()&&l.push(p),u=f;break}l.push(d)}if(u===-1){n.push(r),o+=1;continue}i(),s.push({kind:"system",text:l.join(`
12
+ `).trim()}),o=u+1}return i(),s}function zo(t,e){const s=String(t||"").replace(/\r\n/g,`
13
+ `);return e==="user"||e==="assistant"?qo(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
14
+ `).trim():s.trim()}function qa(t,e){return e!=="user"&&e!=="assistant"?[]:qo(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function ai(t){const e=Ge(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=zo(e,t.role);if(s)return s}return Ke(e)}function ds(t){const e=String(t||"").replace(/\r\n/g,`
15
+ `).trim(),s='The user was asked: "',n=`"
16
+ The user responded: "`;if(!e.startsWith(s)||!e.endsWith('"'))return null;const i=e.indexOf(n,s.length);if(i===-1)return null;const o=e.slice(s.length,i),r=e.slice(i+n.length,-1);return!o.trim()||!r.trim()?null:{question:o,answer:r}}function za(t){return Ge(pn(t)).length>0}function Ya(t){const e=Ge(t);return e?/^\[SYSTEM:/i.test(e)||/^\[CHILD_UPDATE\b/i.test(e)||/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(e)||/^Buffered child updates arrived /i.test(e)||/^There is an active recurring schedule every /i.test(e)||/^It remains active automatically after this turn completes/i.test(e)||/^Sub-agent spawned successfully\./i.test(e)||/^Message sent to sub-agent /i.test(e)||/^No sub-agents have been spawned yet\./i.test(e)||/^Sub-agent status report \(/i.test(e)||/^Active sessions \(/i.test(e)||/^Sub-agents completed:/i.test(e)||/^Sub-agent .* has been (completed gracefully|cancelled|deleted)\./i.test(e)||/^The runtime recovered this session after the worker lost the live Copilot session\./i.test(e)||/^The runtime recovered this session after the live Copilot session was lost on a worker\./i.test(e)||/^The runtime is replaying this turn after a worker restart/i.test(e)||/^The runtime detected missing Copilot session state for /i.test(e)||/^(spawn_agent|message_agent|check_agents|wait_for_agents|complete_agent|cancel_agent|delete_agent) failed/i.test(e):!1}function Qa(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(Ge(t))}function ot(t,e){const s=String(t||""),n=`${e}=`,i=s.indexOf(n);if(i<0)return"";const o=s.slice(i+n.length),r=[" request_id="," from="," subject="," reason="," expects_response="," expires_at="," verdict="];let a=o.length;for(const l of r){const u=o.indexOf(l);u>=0&&(a=Math.min(a,u))}return o.slice(0,a).trim()}function Xa(t,e){const s=Ge(e);if(!s)return null;const n=/^\[SESSION_MESSAGE\s+([^\]]+)\]\n?/i.exec(s);if(n){const o=n[1],r=`
17
+ Request body:
18
+ `,a=s.indexOf(r),l=a>=0?s.slice(a+r.length).trim():s.slice(n[0].length).trim(),u=ot(o,"request_id"),f=ot(o,"from"),d=ot(o,"subject"),p=/\bexpects_response=true\b/i.test(o),h=[f?`From: session-${Z(f)}`:"",u?`Request ID: ${u}`:"",d?`Subject: ${d}`:"",p?"Response: required":"Response: not required","",l].filter((m,g)=>g===4||String(m||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:h.join(`
19
+ `),time:pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:p?"Session Request":"Session Message",cardTitleColor:"cyan",cardBorderColor:"cyan"}}const i=/^\[SESSION_MESSAGE_RESPONSE\s+([^\]]+)\]\n?/i.exec(s);if(i){const o=i[1],r=/^This is the requested cross-session response\.[^\n]*\n\n?/i,a=s.slice(i[0].length).trim().replace(r,"").trim(),l=ot(o,"request_id"),u=ot(o,"from"),f=ot(o,"verdict")||"answered",d=[u?`From: session-${Z(u)}`:"",l?`Request ID: ${l}`:"",`Verdict: ${f}`,"",a].filter((p,h)=>h===3||String(p||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:d.join(`
20
+ `),time:pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:"Session Reply",cardTitleColor:"green",cardBorderColor:"green"}}return null}function Ja(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&Ya(s)?"system":e}function Za(t,e){const s=Array.isArray(t?.clientMessageIds)?t.clientMessageIds:[],n=Array.isArray(e?.clientMessageIds)?e.clientMessageIds:[];return s.length===0||n.length===0?null:s.some(i=>n.includes(i))}function el(t,e){if(!t||!e||t.role!==e.role)return!1;const s=ai(t),n=ai(e);if(!s||!n||s!==n)return!1;const i=Za(t,e);if(i!=null)return i;const o=Number(t.createdAt||0),r=Number(e.createdAt||0);return t.optimistic||e.optimistic?!0:!o||!r?!1:Math.abs(o-r)<=1e4}function ft(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!el(n,s)){e.push(s);continue}if(n?.optimistic&&!s?.optimistic){e[e.length-1]=s;continue}if(!n?.optimistic&&s?.optimistic)continue;const i=Number(n?.createdAt||0),o=Number(s?.createdAt||0),r=o>=i?s:n;if(r.role==="user"&&!n?.optimistic&&!s?.optimistic){const a=Math.min(Number(n?.firstDeliveredAt||i||1/0),Number(s?.firstDeliveredAt||o||1/0));e[e.length-1]={...r,redelivered:!0,...Number.isFinite(a)?{firstDeliveredAt:a}:{}};continue}e[e.length-1]=r}return e}function tl(t){return typeof t=="string"?t.replace(/^\[FROM:[^\]\n]*\]\n?/,""):t}function pt(t,e){const s=xt(t),n=Xa(t,s);if(n)return n;const i=tl(zo(s,e));if(!za(i))return null;const o=Array.isArray(t?.data?.clientMessageIds)?t.data.clientMessageIds.filter(l=>typeof l=="string"&&l):[],r=t?.data?.sender&&typeof t.data.sender=="object"?t.data.sender:null,a=Array.isArray(t?.data?.attachments)?t.data.attachments.filter(l=>l&&typeof l.filename=="string"&&l.filename):[];return{id:`${t.sessionId}:${t.seq}`,role:Ja(t,e,i),text:i,time:pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...o.length>0?{clientMessageIds:o}:{},...r?{sender:r}:{},...a.length>0?{attachments:a}:{}}}function Yo(t){return t?.eventType!=="system.message"?!1:!Qa(xt(t))}function es(t,e){return qa(xt(t),e).map((s,n)=>Rt({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function sl(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=Ge(e.text),n=ds(e.text),i=n?Ge(n.answer):"";let o=!1;return t.filter(r=>{if(o||!r?.optimistic||r.role!==e.role)return!0;const a=Ge(r.text);return a!==s&&a!==i?!0:(o=!0,!1)})}function xt(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 Pa(e)}function nl(t){return(t||[]).map(e=>e?.text||"").join("")}function il(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function gn(t=[]){const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();if(!i)continue;const o=i.toLowerCase();e.has(o)||(e.add(o),s.push(i))}return s.join(" | ")}function ol(t,e=""){return gn([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function rl(t,e=""){return gn([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function al(t,e=""){const s=xt(t),n=Ke(e);return gn([Ke(s),n,t?.data?.detail,t?.data?.message])}function ll(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 cl(t,e){if(!e||typeof e!="object")return"";if(t==="wait"){const i=e.seconds!=null?`${e.seconds}s`:"?",o=e.preserveWorkerAffinity===!0?" preserve=true":"",r=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${i}${o}${r}`}if(t==="cron"){if(e.action==="cancel")return" cancel";const i=e.seconds!=null?`${e.seconds}s`:"?",o=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${i}${o}`}const s=Object.entries(e).slice(0,4).map(([i,o])=>`${i}=${ll(o)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function yn(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function te(t,e,s,n="",i="white"){return[...yn(t),{text:e,color:s},...n?[{text:` ${n}`,color:i}]:[]]}function ul(t,e=96){return il(pn(xt(t)),e)||""}function vs(t,e,s="start"){const n=typeof e?.data?.toolCallId=="string"?e.data.toolCallId:"",i=typeof e?.data?.requestId=="string"?e.data.requestId:"",o=e?.data?.toolName||e?.data?.name||(n?`tool call ${n.slice(0,8)}`:i?`tool request ${i.slice(0,8)}`:"tool"),r=e?.data?.arguments||e?.data?.args,a=e?.data?.durableSessionId,l=cl(o,r),u=s==="start"?"▶":s==="partial"?"…":"✓",f=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...yn(t),{text:`${u} ${o}${l}`,color:f},...a?[{text:` [sess ${Z(a)}]`,color:"gray"}]:[]]}function Rt(t){const e=pe(t.createdAt),s=ul(t);let n=null;switch(t.eventType){case"assistant.usage":case"session.info":case"session.idle":case"session.usage_info":case"pending_messages.modified":case"pending_messages.cancelled":case"abort":case"assistant.turn_end":case"assistant.streaming_progress":return null;case"tool.execution_start":n=vs(e,t,"start");break;case"tool.execution_complete":n=vs(e,t,"complete");break;case"tool.execution_partial_result":n=vs(e,t,"partial");break;case"tool.execution_progress":{const i=(t?.data??{})||{},o=i.toolName||i.name||"tool",r=typeof i.message=="string"&&i.message?i.message:typeof i.detail=="string"&&i.detail?i.detail:i.percent!=null?`${Math.round(Number(i.percent))}%`:"running…";n=te(e,"[tool]","cyan",`${o} ${r}`,"white");break}case"assistant.reasoning":n=te(e,"[reasoning]","gray",s||"…","white");break;case"assistant.intent":{const i=(t?.data??{})||{},o=typeof i.summary=="string"&&i.summary?i.summary:typeof i.intent=="string"&&i.intent?i.intent:s||"";n=te(e,"[intent]","gray",o||"…","white");break}case"assistant.turn_start":n=te(e,"[turn start]","gray",s);break;case"session.turn_completed":n=te(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=te(e,"[lossy handoff]","yellow",rl(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=te(e,"[dehydrated]","cyan",ol(t,s));break;case"session.hydrated":case"session.rehydrated":n=te(e,"[rehydrated]","green",s);break;case"session.wait_started":{const i=t?.data?.seconds!=null?`${t.data.seconds}s`:"?",o=typeof t?.data?.reason=="string"&&t.data.reason?` reason=${JSON.stringify(t.data.reason)}`:"",r=t?.data?.preserveAffinity?" preserve=true":"";n=te(e,"[wait]","yellow",`${i}${r}${o}`.trim());break}case"session.input_required_started":n=te(e,"[input]","yellow",s);break;case"session.agent_spawned":n=te(e,"[spawn]","cyan",t?.data?.agentId||Z(t?.data?.childSessionId),"white");break;case"session.cron_started":n=te(e,"[cron]","magenta",`started${t?.data?.seconds!=null?` ${t.data.seconds}s`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_scheduled":case"session.cron_at_started":n=te(e,"[cron]","magenta",`scheduled${t?.data?.nextFireAt?` ${ri(t.data.nextFireAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_fired":n=te(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=te(e,"[cron]","magenta",`fired${t?.data?.scheduledAt?` ${ri(t.data.scheduledAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_cancelled":case"session.cron_at_cancelled":n=te(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=te(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=te(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=te(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.compaction_start":case"session.compaction_complete":n=Ca(e,t.eventType,t.data||{});break;case"session.error":n=te(e,"[error]","red",s||"session error","white");break;case"system.message":mn(xt(t))?n=te(e,"[rehydrated]","green",al(t,s)||"conversation preserved"):n=te(e,"[system]","gray",s||"system message");break;default:n=[...yn(e),{text:`[${t.eventType}]`,color:"gray"},...s?[{text:` ${s}`,color:"white"}]:[]];break}return{id:`${t.sessionId}:${t.seq}`,eventType:t.eventType,time:e,seq:Number.isFinite(Number(t?.seq))?Number(t.seq):0,createdAt:t?.createdAt instanceof Date?t.createdAt.getTime():t?.createdAt?new Date(t.createdAt).getTime():0,text:nl(n),line:n}}function dl(t=J){const e=Math.max(J,Number(t)||J);return Wa.find(n=>n>e)||Math.min(1e5,e*2)}function Ut(t=[],e={}){const s=Math.max(J,Number(e.requestedLimit??e.eventLimit??J)||J),n=[],i=[],o=[];for(const r of t){if(o.push(r),r.eventType==="user.message"){i.push(...es(r,"user"));const l=pt(r,"user");l&&n.push(l);continue}if(r.eventType==="assistant.message"){i.push(...es(r,"assistant"));const l=pt(r,"assistant");l&&n.push(l);continue}if(r.eventType==="system.message"){if(Yo(r)){const l=Rt(r);l&&i.push(l)}else{const l=pt(r,"system");l&&n.push(l)}continue}if(r.eventType==="session.epoch_committed"){n.push(Wo(r));continue}if(r.eventType==="session.regenerate_refused"){n.push(Ko(r));continue}const a=Rt(r);a&&i.push(a)}return{chat:ft(n),activity:i,events:o.slice(-s),loadedEventLimit:s,loadedEventCount:o.length,hasOlderEvents:o.length>=s}}function li(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max(J,Number(t?.loadedEventLimit??J)||J),i=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),o={chat:Ae(t?.chat||[],n),activity:Ae(t?.activity||[],n),events:i,lastSeq:e.seq,loadedEventLimit:n,loadedEventCount:Math.max(Number(t?.loadedEventCount||0),i.length),hasOlderEvents:!!t?.hasOlderEvents,stoppedMessageIds:Array.isArray(t?.stoppedMessageIds)?t.stoppedMessageIds:[]};if(e.eventType==="session.turn_stopped"){const a=Array.isArray(e?.data?.clientMessageIds)?e.data.clientMessageIds.filter(l=>typeof l=="string"&&l):[];if(a.length>0){const l=new Set([...o.stoppedMessageIds,...a]);o.stoppedMessageIds=Array.from(l),o.chat=o.chat.map(u=>Array.isArray(u.clientMessageIds)&&u.clientMessageIds.some(f=>l.has(f))?{...u,stopped:!0}:u)}return o}if(e.eventType==="user.message"){o.activity.push(...es(e,"user")),o.activity=Ae(o.activity,n);const a=pt(e,"user");return a&&(Array.isArray(a.clientMessageIds)&&a.clientMessageIds.some(l=>o.stoppedMessageIds.includes(l))&&(a.stopped=!0),o.chat=sl(o.chat,a),o.chat.push(a),o.chat=Ae(ft(o.chat),n)),o}if(e.eventType==="assistant.message"){o.activity.push(...es(e,"assistant")),o.activity=Ae(o.activity,n);const a=pt(e,"assistant");return a&&(o.chat.push(a),o.chat=Ae(ft(o.chat),n)),o}if(e.eventType==="system.message"){if(Yo(e)){const a=Rt(e);a&&(o.activity.push(a),o.activity=Ae(o.activity,n))}else{const a=pt(e,"system");if(!a)return o;o.chat.push(a),o.chat=Ae(ft(o.chat),n)}return o}if(e.eventType==="session.epoch_committed")return o.chat.push(Wo(e)),o.chat=Ae(o.chat,n),o;if(e.eventType==="session.regenerate_refused")return o.chat.push(Ko(e)),o.chat=Ae(o.chat,n),o;const r=Rt(e);return r&&(o.activity.push(r),o.activity=Ae(o.activity,n)),o}function Es(t,e=null){const s=typeof e?.splash=="string"&&e.splash.trim()?e.splash:null,n=s||t?.splash;if(!n)return[];const i=s?e?.splashMobile:t?.splashMobile,o=typeof i=="string"&&i.trim()?i:null,r=e?.isSystem?It(e,t?.title||"PilotSwarm"):e?.title||t?.title||"PilotSwarm",a="{gray-fg}Start interacting with this session to replace the splash screen.{/gray-fg}";return[{id:`splash:${r}`,role:"system",text:`${n}
21
+
22
+ ${a}`,...o?{mobileText:`${o}
23
+
24
+ ${a}`}:{},time:"",splash:!0}]}const fl=.7,pl=30,ci=36,As=18,Ts=18,Cs=0,Qo=3,bt=6,fs=10,hl=.25,ml=.5,ht=6,ts=10,Xo=.336,ks=ht,Ms=ts,Ns=bt,Ps=fs;function kt(t,e,s){return Math.max(e,Math.min(s,t))}function gl(t){return[A.SESSIONS,A.CHAT,A.INSPECTOR,A.ACTIVITY].includes(t)?t:null}function yl(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function mt(t=""){const e=String(t||"").split(`
25
+ `).length;return kt(e,1,Qo)}function Jo(t){return Math.max(bt,Math.floor(t*hl))}function Zo(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*ml),n=Math.max(bt,e-fs);return Math.max(bt,Math.min(n,s))}function _t(t,e=0,s=1,n=0,i=0,o=null){const r=yl(t),a=r.width,l=r.height,u=kt(Number(s)||1,1,Qo),f=gl(o),d=5+u,p=Math.max(18,l-d),m=Math.floor(a*fl)+(Number(e)||0),g=a-m-Cs;let S=!1,y=!1;m<=As&&g>Ts?S=!0:g<=Ts&&m>As?y=!0:m<=As&&g<=Ts&&(y=e>=0,S=!y);let w,I;S?(w=0,I=a):y?(w=a,I=0):(w=kt(m,pl,a-ci-Cs),I=Math.max(ci,a-w-Cs));const C=Jo(p)+(Number(n)||0),v=p-C;let k=!1,P=!1;v<=Ps&&C>Ns?P=!0:C<=Ns&&v>Ps?k=!0:v<=Ps&&C<=Ns&&(P=(Number(n)||0)>=0,k=!P);let O,M;if(k)O=0,M=p;else if(P)O=p,M=0;else{const we=Zo(l,p);O=kt(C,bt,we),M=Math.max(fs,p-O)}const F=Math.max(ht,Math.floor(p*Xo))+(Number(i)||0),Y=p-F;let U=!1,V=!1;Y<=Ms&&F>ks?U=!0:F<=ks&&Y>Ms?V=!0:Y<=Ms&&F<=ks&&(U=(Number(i)||0)>=0,V=!U);let q,ee;return U?(q=p,ee=0):V?(ee=p,q=0):(q=kt(F,ht,Math.max(ht,p-ts)),ee=Math.max(ts,p-q)),{viewport:r,totalWidth:a,totalHeight:l,reservedRows:d,bodyHeight:p,promptRows:u,fullscreenPane:f,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(i)||0,leftHidden:S,rightHidden:y,inspectorHidden:U,activityHidden:V,sessionHidden:k,chatHidden:P,leftWidth:w,rightWidth:I,sessionPaneHeight:O,chatPaneHeight:M,activityPaneHeight:q,inspectorPaneHeight:ee}}function Qs(t){if(t?.fullscreenPane)return[t.fullscreenPane,A.PROMPT];if(t?.leftHidden)return[A.INSPECTOR,A.ACTIVITY,A.PROMPT];if(t?.rightHidden)return[...t?.sessionHidden?[A.CHAT]:t?.chatHidden?[A.SESSIONS]:[A.SESSIONS,A.CHAT],A.PROMPT];if(t?.sessionHidden){const e=t?.inspectorHidden?[A.ACTIVITY]:t?.activityHidden?[A.INSPECTOR]:[A.INSPECTOR,A.ACTIVITY];return[A.CHAT,...e,A.PROMPT]}if(t?.chatHidden){const e=t?.inspectorHidden?[A.ACTIVITY]:t?.activityHidden?[A.INSPECTOR]:[A.INSPECTOR,A.ACTIVITY];return[A.SESSIONS,...e,A.PROMPT]}return t?.inspectorHidden?[A.SESSIONS,A.CHAT,A.ACTIVITY,A.PROMPT]:t?.activityHidden?[A.SESSIONS,A.CHAT,A.INSPECTOR,A.PROMPT]:[A.SESSIONS,A.CHAT,A.INSPECTOR,A.ACTIVITY,A.PROMPT]}function Fe(t,e){const s=Qs(e);return s.includes(t)?t:s[0]||A.PROMPT}function Sl(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[A.PROMPT]:A.PROMPT,[A.ACTIVITY]:A.INSPECTOR,[A.INSPECTOR]:A.INSPECTOR}[t]||A.INSPECTOR:e?.rightHidden?{[A.PROMPT]:A.PROMPT,[A.CHAT]:e?.sessionHidden?A.CHAT:A.SESSIONS,[A.SESSIONS]:A.SESSIONS}[t]||(e?.sessionHidden?A.CHAT:A.SESSIONS):{[A.PROMPT]:e?.sessionHidden?A.CHAT:A.SESSIONS,[A.ACTIVITY]:e?.chatHidden?A.SESSIONS:A.CHAT,[A.INSPECTOR]:e?.chatHidden?A.SESSIONS:A.CHAT,[A.CHAT]:e?.sessionHidden?A.CHAT:A.SESSIONS,[A.SESSIONS]:A.SESSIONS}[t]||(e?.sessionHidden?A.CHAT:A.SESSIONS)}function bl(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[A.PROMPT]:A.PROMPT,[A.INSPECTOR]:A.ACTIVITY,[A.ACTIVITY]:A.ACTIVITY}[t]||A.INSPECTOR:e?.rightHidden?{[A.PROMPT]:A.PROMPT,[A.SESSIONS]:e?.chatHidden?A.SESSIONS:A.CHAT,[A.CHAT]:A.CHAT}[t]||(e?.chatHidden?A.SESSIONS:A.CHAT):e?.inspectorHidden?{[A.PROMPT]:A.PROMPT,[A.SESSIONS]:A.CHAT,[A.CHAT]:A.ACTIVITY,[A.ACTIVITY]:A.ACTIVITY}[t]||A.CHAT:e?.activityHidden?{[A.PROMPT]:A.PROMPT,[A.SESSIONS]:A.CHAT,[A.CHAT]:A.INSPECTOR,[A.INSPECTOR]:A.INSPECTOR}[t]||A.CHAT:{[A.PROMPT]:A.PROMPT,[A.SESSIONS]:A.CHAT,[A.CHAT]:A.INSPECTOR,[A.INSPECTOR]:A.ACTIVITY,[A.ACTIVITY]:A.ACTIVITY}[t]||A.CHAT}function ui(t){return t?.isSystem?jo(t):Number.MAX_SAFE_INTEGER}function wl(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 Il(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return wl(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 xl(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function di(t,e){return!!(xl(t)&&e&&e.has(t.sessionId))}function fi(t,e){return t.isSystem?0:t.isGroup&&di(t,e)?1:di(t,e)?2:t.isGroup?3:4}function pi(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function hi(t,e,s,n){const i=fi(t,n),o=fi(e,n);if(i!==o)return i-o;const r=ui(t),a=ui(e);if(r!==a)return r-a;const l=s.get(t.sessionId),u=s.get(e.sessionId);if(typeof l=="number"&&typeof u=="number"&&l!==u)return l-u;const f=pi(t),d=pi(e);if(f>0&&d>0&&f!==d)return d-f;const p=(e.createdAt||0)-(t.createdAt||0);if(p!==0)return p;const h=String(t.title||""),m=String(e.title||""),g=h.localeCompare(m);return g!==0?g:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function De(t=[],e=new Set,s=[],n=null){const i=new Map,o=new Map,r=Il(s),a=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const d of t)i.set(d.sessionId,d);for(const d of t){const p=!d.isGroup&&d.groupId&&!d.parentSessionId&&i.has(`group:${d.groupId}`)?`group:${d.groupId}`:null,h=d.parentSessionId||p;!h||!i.has(h)||(o.has(h)||o.set(h,[]),o.get(h).push(d))}for(const d of o.values())d.sort((p,h)=>hi(p,h,r,a));const l=t.filter(d=>!(d.parentSessionId&&i.has(d.parentSessionId)||!d.isGroup&&d.groupId&&!d.parentSessionId&&i.has(`group:${d.groupId}`))).sort((d,p)=>hi(d,p,r,a)),u=[];function f(d,p){const h=o.get(d.sessionId)||[];if(u.push({sessionId:d.sessionId,depth:p,hasChildren:h.length>0,collapsed:e.has(d.sessionId)}),!e.has(d.sessionId))for(const m of h)f(m,p+1)}for(const d of l)f(d,0);return u}function vl(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function _s(t){return Number.parseInt(t,16)/255}function El(t){const e=String(t||"").trim();return/^#[0-9a-f]{3}$/iu.test(e)?`#${e.slice(1).split("").map(s=>s+s).join("")}`:/^#[0-9a-f]{6}$/iu.test(e)?e:null}function Os(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Al(t){const e=El(t);if(!e)return 0;const s=Os(_s(e.slice(1,3))),n=Os(_s(e.slice(3,5))),i=Os(_s(e.slice(5,7)));return .2126*s+.7152*n+.0722*i}function Tl(t){const e=t?.page?.background||t?.tui?.background||t?.terminal?.background;return Al(e)>=.5}function re({id:t,label:e,description:s,page:n,terminal:i,tui:o={}}){const r={background:n?.background||i?.background||"#000000",surface:i?.background||n?.background||"#000000",foreground:i?.foreground||n?.foreground||"#ffffff",white:i?.foreground||n?.foreground||"#ffffff",gray:n?.hintColor||i?.brightBlack||i?.white||"#999999",black:i?.black||"#000000",red:i?.red||"#ff5555",green:i?.green||"#55ff55",yellow:i?.yellow||"#ffff55",blue:i?.blue||"#5555ff",magenta:i?.magenta||"#ff55ff",cyan:i?.cyan||"#55ffff",userChat:"#ffd866",userChatLabel:"#ffec99",otherUserChatLabel:i?.brightMagenta||i?.magenta||"#c9a3ff",activeHighlightBackground:i?.blue||"#5555ff",activeHighlightForeground:i?.background||"#000000",selectionBackground:i?.cursor||i?.blue||"#5555ff",selectionForeground:i?.cursorAccent||i?.background||"#000000",promptCursorBackground:i?.cursor||i?.green||"#55ff55",promptCursorForeground:i?.cursorAccent||i?.background||"#000000"};return vl({id:t,label:e,description:s,page:n,terminal:i,tui:{...r,...o}})}const Cl=re({id:"github-dark",label:"GitHub Dark",description:"GitHub dark palette with soft blue accents and cool neutrals.",page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#30363d",modalForeground:"#e6edf3",modalMuted:"#8b949e",modalSelectedBackground:"#1f6feb33",modalSelectedBorder:"#2f81f7",modalSelectedForeground:"#79c0ff"},terminal:{background:"#0d1117",foreground:"#e6edf3",cursor:"#2f81f7",cursorAccent:"#0d1117",selectionBackground:"rgba(56, 139, 253, 0.28)",black:"#484f58",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"},tui:{surface:"#0d1117",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),kl=re({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",page:{background:"#ffffff",foreground:"#1f2328",overlayBackground:"#ffffff",overlayForeground:"#1f2328",hintColor:"#57606a",modalBackdrop:"rgba(31, 35, 40, 0.34)",modalBackground:"#ffffff",modalBorder:"#d0d7de",modalForeground:"#1f2328",modalMuted:"#57606a",modalSelectedBackground:"#ddf4ff",modalSelectedBorder:"#0969da",modalSelectedForeground:"#0550ae"},terminal:{background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",cursorAccent:"#ffffff",selectionBackground:"#ddf4ff",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#116329",brightYellow:"#7d4e00",brightBlue:"#0550ae",brightMagenta:"#6639ba",brightCyan:"#0f6f78",brightWhite:"#1f2328"},tui:{surface:"#ffffff",border:"#d0d7de",userChat:"#0969da",userChatLabel:"#0550ae",activeHighlightBackground:"#ddf4ff",activeHighlightForeground:"#0550ae",selectionBackground:"#0969da",selectionForeground:"#ffffff",promptCursorBackground:"#0969da",promptCursorForeground:"#ffffff"}}),Ml=re({id:"daylight",label:"Daylight",description:"Crisp white workspace with near-black text and deep saturated accents — every color slot holds AA contrast.",page:{background:"#ffffff",foreground:"#111827",overlayBackground:"#ffffff",overlayForeground:"#111827",hintColor:"#4b5563",modalBackdrop:"rgba(17, 24, 39, 0.35)",modalBackground:"#ffffff",modalBorder:"#d1d5db",modalForeground:"#111827",modalMuted:"#4b5563",modalSelectedBackground:"#dbeafe",modalSelectedBorder:"#1d4ed8",modalSelectedForeground:"#1e3a8a"},terminal:{background:"#ffffff",foreground:"#111827",cursor:"#1d4ed8",cursorAccent:"#ffffff",selectionBackground:"#bfdbfe",black:"#111827",red:"#b91c1c",green:"#047857",yellow:"#92400e",blue:"#1d4ed8",magenta:"#6d28d9",cyan:"#0e7490",white:"#4b5563",brightBlack:"#374151",brightRed:"#991b1b",brightGreen:"#065f46",brightYellow:"#78350f",brightBlue:"#1e40af",brightMagenta:"#5b21b6",brightCyan:"#155e75",brightWhite:"#111827"},tui:{surface:"#ffffff",border:"#d1d5db",userChat:"#1e40af",userChatLabel:"#1e3a8a",activeHighlightBackground:"#dbeafe",activeHighlightForeground:"#1e3a8a",selectionBackground:"#1d4ed8",selectionForeground:"#ffffff",promptCursorBackground:"#1d4ed8",promptCursorForeground:"#ffffff"}}),Nl=re({id:"paper-ink",label:"Paper Ink",description:"Warm paper background with true-ink text and letterpress accents — warmth without washed-out output.",page:{background:"#faf6ef",foreground:"#1c1917",overlayBackground:"#fffdf8",overlayForeground:"#1c1917",hintColor:"#57534e",modalBackdrop:"rgba(28, 25, 23, 0.35)",modalBackground:"#fffdf8",modalBorder:"#d6cfc2",modalForeground:"#1c1917",modalMuted:"#57534e",modalSelectedBackground:"#f1e4c7",modalSelectedBorder:"#854d0e",modalSelectedForeground:"#713f12"},terminal:{background:"#faf6ef",foreground:"#1c1917",cursor:"#9f1239",cursorAccent:"#fffdf8",selectionBackground:"#f1e4c7",black:"#1c1917",red:"#9f1239",green:"#3f6212",yellow:"#854d0e",blue:"#1e40af",magenta:"#86198f",cyan:"#0f766e",white:"#57534e",brightBlack:"#44403c",brightRed:"#881337",brightGreen:"#365314",brightYellow:"#713f12",brightBlue:"#1e3a8a",brightMagenta:"#701a75",brightCyan:"#115e59",brightWhite:"#1c1917"},tui:{surface:"#fffdf8",border:"#d6cfc2",userChat:"#1e40af",userChatLabel:"#1e3a8a",activeHighlightBackground:"#f1e4c7",activeHighlightForeground:"#713f12",selectionBackground:"#854d0e",selectionForeground:"#fffdf8",promptCursorBackground:"#9f1239",promptCursorForeground:"#fffdf8"}}),Pl=re({id:"light-high-contrast",label:"Light High Contrast",description:"Pure black on white with maximum-contrast accents — nothing washes out, ever.",page:{background:"#ffffff",foreground:"#000000",overlayBackground:"#ffffff",overlayForeground:"#000000",hintColor:"#333333",modalBackdrop:"rgba(0, 0, 0, 0.4)",modalBackground:"#ffffff",modalBorder:"#767676",modalForeground:"#000000",modalMuted:"#333333",modalSelectedBackground:"#cce5ff",modalSelectedBorder:"#0000cc",modalSelectedForeground:"#00008b"},terminal:{background:"#ffffff",foreground:"#000000",cursor:"#0000cc",cursorAccent:"#ffffff",selectionBackground:"#b3d7ff",black:"#000000",red:"#a80000",green:"#006400",yellow:"#5c4500",blue:"#0000cc",magenta:"#77008c",cyan:"#005f6b",white:"#333333",brightBlack:"#1a1a1a",brightRed:"#8b0000",brightGreen:"#004b00",brightYellow:"#4a3700",brightBlue:"#0000a0",brightMagenta:"#5f0070",brightCyan:"#004a54",brightWhite:"#000000"},tui:{surface:"#ffffff",border:"#767676",userChat:"#0000cc",userChatLabel:"#00008b",activeHighlightBackground:"#cce5ff",activeHighlightForeground:"#00008b",selectionBackground:"#0000cc",selectionForeground:"#ffffff",promptCursorBackground:"#0000cc",promptCursorForeground:"#ffffff"}}),_l=re({id:"cobalt2",label:"Cobalt2",description:"Electric blue shell with bright yellow accents and saturated syntax colors.",page:{background:"#193549",foreground:"#ffffff",overlayBackground:"#193549",overlayForeground:"#ffffff",hintColor:"#a8c5e6",modalBackdrop:"rgba(7, 17, 28, 0.68)",modalBackground:"#224b68",modalBorder:"#2e6c99",modalForeground:"#ffffff",modalMuted:"#a8c5e6",modalSelectedBackground:"#ffc600",modalSelectedBorder:"#ffc600",modalSelectedForeground:"#193549"},terminal:{background:"#193549",foreground:"#ffffff",cursor:"#ffc600",cursorAccent:"#193549",selectionBackground:"rgba(255, 255, 255, 0.18)",black:"#000000",red:"#ff628c",green:"#3ad900",yellow:"#ff9d00",blue:"#0088ff",magenta:"#ff628c",cyan:"#80ffbb",white:"#ffffff",brightBlack:"#666666",brightRed:"#ff628c",brightGreen:"#3ad900",brightYellow:"#ff9d00",brightBlue:"#0088ff",brightMagenta:"#ff9d00",brightCyan:"#80ffbb",brightWhite:"#ffffff"},tui:{surface:"#193549",activeHighlightBackground:"#0f5f91",activeHighlightForeground:"#ffffff",selectionBackground:"#ffc600",selectionForeground:"#193549",promptCursorBackground:"#ffc600",promptCursorForeground:"#193549"}}),Ol=re({id:"dracula",label:"Dracula",description:"Classic Dracula contrast with neon green, pink, and violet accents.",page:{background:"#282a36",foreground:"#f8f8f2",overlayBackground:"#282a36",overlayForeground:"#f8f8f2",hintColor:"#bd93f9",modalBackdrop:"rgba(24, 25, 33, 0.72)",modalBackground:"#313442",modalBorder:"#6272a4",modalForeground:"#f8f8f2",modalMuted:"#bd93f9",modalSelectedBackground:"#44475a",modalSelectedBorder:"#bd93f9",modalSelectedForeground:"#f8f8f2"},terminal:{background:"#282a36",foreground:"#f8f8f2",cursor:"#f8f8f2",cursorAccent:"#282a36",selectionBackground:"rgba(189, 147, 249, 0.24)",black:"#21222c",red:"#ff5555",green:"#50fa7b",yellow:"#f1fa8c",blue:"#bd93f9",magenta:"#ff79c6",cyan:"#8be9fd",white:"#f8f8f2",brightBlack:"#6272a4",brightRed:"#ff6e6e",brightGreen:"#69ff94",brightYellow:"#ffffa5",brightBlue:"#d6acff",brightMagenta:"#ff92df",brightCyan:"#a4ffff",brightWhite:"#ffffff"},tui:{surface:"#282a36",activeHighlightBackground:"#44475a",activeHighlightForeground:"#f8f8f2",selectionBackground:"#bd93f9",selectionForeground:"#282a36",promptCursorBackground:"#f8f8f2",promptCursorForeground:"#282a36"}}),Rl=re({id:"catppuccin-mocha",label:"Catppuccin Mocha",description:"Creamy dark palette with soft pastels and high legibility.",page:{background:"#1e1e2e",foreground:"#cdd6f4",overlayBackground:"#1e1e2e",overlayForeground:"#cdd6f4",hintColor:"#bac2de",modalBackdrop:"rgba(17, 17, 27, 0.74)",modalBackground:"#313244",modalBorder:"#585b70",modalForeground:"#cdd6f4",modalMuted:"#bac2de",modalSelectedBackground:"#45475a",modalSelectedBorder:"#89b4fa",modalSelectedForeground:"#cdd6f4"},terminal:{background:"#1e1e2e",foreground:"#cdd6f4",cursor:"#f5e0dc",cursorAccent:"#1e1e2e",selectionBackground:"rgba(137, 180, 250, 0.22)",black:"#45475a",red:"#f38ba8",green:"#a6e3a1",yellow:"#f9e2af",blue:"#89b4fa",magenta:"#f5c2e7",cyan:"#94e2d5",white:"#bac2de",brightBlack:"#585b70",brightRed:"#f38ba8",brightGreen:"#a6e3a1",brightYellow:"#f9e2af",brightBlue:"#89b4fa",brightMagenta:"#f5c2e7",brightCyan:"#94e2d5",brightWhite:"#f5e0dc"},tui:{surface:"#1e1e2e",activeHighlightBackground:"#45475a",activeHighlightForeground:"#cdd6f4",selectionBackground:"#89b4fa",selectionForeground:"#1e1e2e",promptCursorBackground:"#f5e0dc",promptCursorForeground:"#1e1e2e"}}),Ll=re({id:"hacker-x-matrix",label:"Hacker X - Matrix",description:"Black-and-phosphor terminal palette with vivid green glow and CRT-style contrast.",page:{background:"#030603",foreground:"#c8ffc8",overlayBackground:"#030603",overlayForeground:"#c8ffc8",hintColor:"#59a659",modalBackdrop:"rgba(0, 6, 0, 0.82)",modalBackground:"#081208",modalBorder:"#1f5f1f",modalForeground:"#d6ffd6",modalMuted:"#6dbb6d",modalSelectedBackground:"#0f240f",modalSelectedBorder:"#39ff14",modalSelectedForeground:"#dfffdf"},terminal:{background:"#000000",foreground:"#c8ffc8",cursor:"#39ff14",cursorAccent:"#000000",selectionBackground:"rgba(57, 255, 20, 0.2)",black:"#031003",red:"#39ff14",green:"#2a7a22",yellow:"#4a8a30",blue:"#1a6a4a",magenta:"#2a7a3a",cyan:"#2a8a5a",white:"#b7f7b7",brightBlack:"#59a659",brightRed:"#9aff86",brightGreen:"#7dff66",brightYellow:"#e0ff8a",brightBlue:"#61ffc2",brightMagenta:"#b4ffb4",brightCyan:"#98ffe0",brightWhite:"#e8ffe8"},tui:{surface:"#030603",activeHighlightBackground:"#1a3a1a",activeHighlightForeground:"#e8ffe8",selectionBackground:"#39ff14",selectionForeground:"#000000",promptCursorBackground:"#39ff14",promptCursorForeground:"#000000"}}),$l=re({id:"hacker-x-orion-prime",label:"Hacker X - Orion Prime",description:"Deep-space navy palette with electric cyan, violet, and amber accents.",page:{background:"#0a0f1e",foreground:"#e8f2ff",overlayBackground:"#0a0f1e",overlayForeground:"#e8f2ff",hintColor:"#7e90b5",modalBackdrop:"rgba(6, 10, 24, 0.76)",modalBackground:"#121a30",modalBorder:"#2d4a73",modalForeground:"#edf5ff",modalMuted:"#93a7cc",modalSelectedBackground:"#19365f",modalSelectedBorder:"#55c2ff",modalSelectedForeground:"#f3fbff"},terminal:{background:"#0a0f1e",foreground:"#e8f2ff",cursor:"#55c2ff",cursorAccent:"#0a0f1e",selectionBackground:"rgba(85, 194, 255, 0.22)",black:"#10182b",red:"#ff6b88",green:"#67f5c2",yellow:"#ffd36b",blue:"#55c2ff",magenta:"#c79bff",cyan:"#7ceeff",white:"#c3d4ef",brightBlack:"#7e90b5",brightRed:"#ff8aa2",brightGreen:"#8cffd8",brightYellow:"#ffe28f",brightBlue:"#8fdcff",brightMagenta:"#d8b6ff",brightCyan:"#a2f5ff",brightWhite:"#ffffff"},tui:{surface:"#0c1325",activeHighlightBackground:"#173052",activeHighlightForeground:"#f3fbff",selectionBackground:"#55c2ff",selectionForeground:"#0a0f1e",promptCursorBackground:"#55c2ff",promptCursorForeground:"#0a0f1e"}}),Fl=re({id:"tokyo-night",label:"Tokyo Night",description:"Deep blue-gray canvas with vivid neon accents inspired by Tokyo city lights.",page:{background:"#1a1b26",foreground:"#a9b1d6",overlayBackground:"#1a1b26",overlayForeground:"#a9b1d6",hintColor:"#737aa2",modalBackdrop:"rgba(26, 27, 38, 0.74)",modalBackground:"#24283b",modalBorder:"#414868",modalForeground:"#a9b1d6",modalMuted:"#737aa2",modalSelectedBackground:"#33467c",modalSelectedBorder:"#7aa2f7",modalSelectedForeground:"#c0caf5"},terminal:{background:"#1a1b26",foreground:"#a9b1d6",cursor:"#c0caf5",cursorAccent:"#1a1b26",selectionBackground:"rgba(122, 162, 247, 0.22)",black:"#414868",red:"#f7768e",green:"#9ece6a",yellow:"#e0af68",blue:"#7aa2f7",magenta:"#bb9af7",cyan:"#7dcfff",white:"#a9b1d6",brightBlack:"#565f89",brightRed:"#f7768e",brightGreen:"#9ece6a",brightYellow:"#e0af68",brightBlue:"#7aa2f7",brightMagenta:"#bb9af7",brightCyan:"#7dcfff",brightWhite:"#c0caf5"},tui:{surface:"#1a1b26",activeHighlightBackground:"#33467c",activeHighlightForeground:"#c0caf5",selectionBackground:"#7aa2f7",selectionForeground:"#1a1b26",promptCursorBackground:"#c0caf5",promptCursorForeground:"#1a1b26"}}),Bl=re({id:"gruvbox-dark",label:"Gruvbox Dark",description:"Retro warm palette with earthy browns, oranges, and high readability.",page:{background:"#282828",foreground:"#ebdbb2",overlayBackground:"#282828",overlayForeground:"#ebdbb2",hintColor:"#a89984",modalBackdrop:"rgba(40, 40, 40, 0.74)",modalBackground:"#3c3836",modalBorder:"#504945",modalForeground:"#ebdbb2",modalMuted:"#a89984",modalSelectedBackground:"#504945",modalSelectedBorder:"#fabd2f",modalSelectedForeground:"#fbf1c7"},terminal:{background:"#282828",foreground:"#ebdbb2",cursor:"#ebdbb2",cursorAccent:"#282828",selectionBackground:"rgba(250, 189, 47, 0.22)",black:"#282828",red:"#cc241d",green:"#98971a",yellow:"#d79921",blue:"#458588",magenta:"#b16286",cyan:"#689d6a",white:"#a89984",brightBlack:"#928374",brightRed:"#fb4934",brightGreen:"#b8bb26",brightYellow:"#fabd2f",brightBlue:"#83a598",brightMagenta:"#d3869b",brightCyan:"#8ec07c",brightWhite:"#ebdbb2"},tui:{surface:"#282828",activeHighlightBackground:"#504945",activeHighlightForeground:"#fbf1c7",selectionBackground:"#fabd2f",selectionForeground:"#282828",promptCursorBackground:"#ebdbb2",promptCursorForeground:"#282828"}}),Dl=re({id:"noctis",label:"Noctis",description:"Dark cyan-tinted palette with warm and cold medium contrast accents.",page:{background:"#052529",foreground:"#b2cacd",overlayBackground:"#052529",overlayForeground:"#b2cacd",hintColor:"#40d4e7",modalBackdrop:"rgba(3, 25, 27, 0.72)",modalBackground:"#073940",modalBorder:"#0e6671",modalForeground:"#b2cacd",modalMuted:"#87a7ab",modalSelectedBackground:"#0b515b",modalSelectedBorder:"#40d4e7",modalSelectedForeground:"#ebfdff"},terminal:{background:"#03191b",foreground:"#b2cacd",cursor:"#85efff",cursorAccent:"#03191b",selectionBackground:"rgba(22, 159, 177, 0.27)",black:"#324a4d",red:"#e66533",green:"#49e9a6",yellow:"#e4b781",blue:"#49ace9",magenta:"#df769b",cyan:"#49d6e9",white:"#b2cacd",brightBlack:"#5e878c",brightRed:"#e97749",brightGreen:"#60ebb1",brightYellow:"#e69533",brightBlue:"#60b6eb",brightMagenta:"#e798b3",brightCyan:"#60dbeb",brightWhite:"#c1d4d7"},tui:{surface:"#03191b",activeHighlightBackground:"#083d44",activeHighlightForeground:"#ebfdff",selectionBackground:"#169fb1",selectionForeground:"#052529",promptCursorBackground:"#85efff",promptCursorForeground:"#03191b"}}),er=re({id:"noctis-obscuro",label:"Noctis Obscuro",description:"Deep obsidian palette with cool blue accents and restrained contrast for long sessions.",page:{background:"#0b1117",foreground:"#c7d1da",overlayBackground:"#0b1117",overlayForeground:"#c7d1da",hintColor:"#7cc6ff",modalBackdrop:"rgba(5, 9, 13, 0.74)",modalBackground:"#121a23",modalBorder:"#28455b",modalForeground:"#d7e2eb",modalMuted:"#8f9dab",modalSelectedBackground:"#173041",modalSelectedBorder:"#7cc6ff",modalSelectedForeground:"#eef6ff"},terminal:{background:"#060b10",foreground:"#c7d1da",cursor:"#9fd4ff",cursorAccent:"#060b10",selectionBackground:"rgba(72, 125, 170, 0.30)",black:"#2a3138",red:"#ef6b73",green:"#7ddc8f",yellow:"#d9b36c",blue:"#68aee8",magenta:"#b28cff",cyan:"#58c9d4",white:"#c7d1da",brightBlack:"#6e7a86",brightRed:"#f28a92",brightGreen:"#97e5a6",brightYellow:"#e4c28b",brightBlue:"#86c1f1",brightMagenta:"#c6a7ff",brightCyan:"#7ad7df",brightWhite:"#e5edf5"},tui:{surface:"#060b10",activeHighlightBackground:"#123142",activeHighlightForeground:"#eef6ff",selectionBackground:"#4a7baa",selectionForeground:"#0b1117",promptCursorBackground:"#9fd4ff",promptCursorForeground:"#060b10"}}),Hl=re({id:"dark-high-contrast",label:"Dark High Contrast",description:"Pure black background with maximum contrast ANSI colors for accessibility.",page:{background:"#000000",foreground:"#ffffff",overlayBackground:"#000000",overlayForeground:"#ffffff",hintColor:"#3794ff",modalBackdrop:"rgba(0, 0, 0, 0.85)",modalBackground:"#0c0c0c",modalBorder:"#6fc3df",modalForeground:"#ffffff",modalMuted:"#9d9d9d",modalSelectedBackground:"#0f4a85",modalSelectedBorder:"#f38518",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#ffffff",cursor:"#ffffff",cursorAccent:"#000000",selectionBackground:"rgba(255, 255, 255, 0.3)",black:"#000000",red:"#f44747",green:"#73c991",yellow:"#e5e510",blue:"#3794ff",magenta:"#bc3fbc",cyan:"#29b8db",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#89d185",brightYellow:"#f5f543",brightBlue:"#6fc3df",brightMagenta:"#d670d6",brightCyan:"#2ee2e2",brightWhite:"#ffffff"},tui:{surface:"#000000",activeHighlightBackground:"#0f4a85",activeHighlightForeground:"#ffffff",selectionBackground:"#f38518",selectionForeground:"#000000",promptCursorBackground:"#ffffff",promptCursorForeground:"#000000"}}),Gl=re({id:"terminal-green",label:"Terminal Green",description:"Classic black terminal with phosphor green text, amber warnings, and crisp operator contrast.",page:{background:"#020503",foreground:"#c9f7d3",overlayBackground:"#020503",overlayForeground:"#d9ffe0",hintColor:"#7ee787",modalBackdrop:"rgba(0, 6, 2, 0.82)",modalBackground:"#061109",modalBorder:"#245c33",modalForeground:"#d9ffe0",modalMuted:"#83a98c",modalSelectedBackground:"#0b2a14",modalSelectedBorder:"#63e27a",modalSelectedForeground:"#ecfff0"},terminal:{background:"#020503",foreground:"#c9f7d3",cursor:"#8cff9f",cursorAccent:"#020503",selectionBackground:"#174923",black:"#061109",red:"#ff5f5f",green:"#63e27a",yellow:"#d6b95f",blue:"#5aa7ff",magenta:"#c586ff",cyan:"#5ce1d8",white:"#c9f7d3",brightBlack:"#5b7a61",brightRed:"#ff7f7f",brightGreen:"#8cff9f",brightYellow:"#f0d982",brightBlue:"#82bdff",brightMagenta:"#d9a8ff",brightCyan:"#89f4ee",brightWhite:"#effff1"},tui:{surface:"#020503",border:"#245c33",userChat:"#f0d982",userChatLabel:"#fff0a8",activeHighlightBackground:"#0b2a14",activeHighlightForeground:"#ecfff0",selectionBackground:"#63e27a",selectionForeground:"#020503",promptCursorBackground:"#8cff9f",promptCursorForeground:"#020503"}}),Ul=re({id:"solarized-ops",label:"Solarized Ops",description:"Solarized-inspired operations palette with deep blue-green surfaces and balanced long-session contrast.",page:{background:"#002b36",foreground:"#d7e2d0",overlayBackground:"#073642",overlayForeground:"#e5efe4",hintColor:"#93a1a1",modalBackdrop:"rgba(0, 20, 25, 0.74)",modalBackground:"#073642",modalBorder:"#2f5d67",modalForeground:"#e5efe4",modalMuted:"#93a1a1",modalSelectedBackground:"#164b56",modalSelectedBorder:"#2aa198",modalSelectedForeground:"#fdf6e3"},terminal:{background:"#002b36",foreground:"#d7e2d0",cursor:"#2aa198",cursorAccent:"#002b36",selectionBackground:"#164b56",black:"#073642",red:"#dc322f",green:"#859900",yellow:"#b58900",blue:"#268bd2",magenta:"#6c71c4",cyan:"#2aa198",white:"#eee8d5",brightBlack:"#586e75",brightRed:"#cb4b16",brightGreen:"#93a100",brightYellow:"#c79b00",brightBlue:"#3aa0e6",brightMagenta:"#7b80d6",brightCyan:"#36b5ac",brightWhite:"#fdf6e3"},tui:{surface:"#073642",border:"#2f5d67",userChat:"#b58900",userChatLabel:"#f0d47a",activeHighlightBackground:"#164b56",activeHighlightForeground:"#fdf6e3",selectionBackground:"#268bd2",selectionForeground:"#002b36",promptCursorBackground:"#2aa198",promptCursorForeground:"#002b36"}}),jl=re({id:"high-contrast-mono",label:"High Contrast Mono",description:"Accessibility-first monochrome theme with cobalt selection and severity colors only where they matter.",page:{background:"#000000",foreground:"#f8f8f2",overlayBackground:"#050505",overlayForeground:"#ffffff",hintColor:"#b8b8b8",modalBackdrop:"rgba(0, 0, 0, 0.88)",modalBackground:"#050505",modalBorder:"#d8d8d8",modalForeground:"#ffffff",modalMuted:"#b8b8b8",modalSelectedBackground:"#003f88",modalSelectedBorder:"#ffffff",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#f8f8f2",cursor:"#ffffff",cursorAccent:"#000000",selectionBackground:"#003f88",black:"#000000",red:"#ff4d4d",green:"#00d084",yellow:"#ffd84d",blue:"#4da3ff",magenta:"#d8d8d8",cyan:"#ffffff",white:"#f8f8f2",brightBlack:"#8a8a8a",brightRed:"#ff6b6b",brightGreen:"#28e29a",brightYellow:"#ffe173",brightBlue:"#73b8ff",brightMagenta:"#ffffff",brightCyan:"#ffffff",brightWhite:"#ffffff"},tui:{surface:"#000000",border:"#d8d8d8",userChat:"#ffffff",userChatLabel:"#d8d8d8",activeHighlightBackground:"#003f88",activeHighlightForeground:"#ffffff",selectionBackground:"#ffffff",selectionForeground:"#000000",promptCursorBackground:"#ffffff",promptCursorForeground:"#000000"}}),tr=Object.freeze([Ol,Cl,kl,Ml,Nl,Pl,_l,$l,Ll,Rl,Fl,Bl,Dl,er,Hl,Gl,Ul,jl].sort((t,e)=>t.label.localeCompare(e.label,void 0,{sensitivity:"base"}))),Wl=new Map(tr.map(t=>[t.id,t])),Kl=er.id;function Vl(){return tr}function ze(t){return t?Wl.get(t)??null:null}const ql=new Set(["agent","user","system"]);function ss(t){const e=Array.isArray(t?.ownerKeys)?[...new Set(t.ownerKeys.map(n=>String(n||"").trim()).filter(Boolean))]:[];return{all:t&&typeof t=="object"?t?.all===!0:!0,includeSystem:t?.includeSystem===!0,includeUnowned:t?.includeUnowned===!0,includeMe:t?.includeMe===!0,includeShared:t?.includeShared===!0,ownerKeys:e}}function zl(t){if(typeof t=="string"){const i=t.trim();return i?{filename:i,sizeBytes:null,contentType:"",isBinary:!1,uploadedAt:"",source:"agent"}:null}if(!t||typeof t!="object")return null;const e=String(t.filename||"").trim();if(!e)return null;const s=Number(t.sizeBytes),n=typeof t.contentType=="string"?t.contentType:"";return{filename:e,sizeBytes:Number.isFinite(s)&&s>=0?s:null,contentType:n,isBinary:t.isBinary===!0,uploadedAt:typeof t.uploadedAt=="string"?t.uploadedAt:"",source:ql.has(t.source)?t.source:"agent"}}function ns(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const i of e){const o=zl(i);!o||n.has(o.filename)||(n.add(o.filename),s.push(o))}return s}function Yl(t,e){const s=String(e||"").trim();return s&&ns(t).find(n=>n.filename===s)||null}function Sn(t){const e=t&&typeof t=="object"?t:{},s=Number(e.paneAdjust),n=Number(e.sessionPaneAdjust),i=Number(e.portalSessionColumnAdjust),o=Number(e.activityPaneAdjust);return{paneAdjust:Number.isFinite(s)?Math.trunc(s):0,sessionPaneAdjust:Number.isFinite(n)?Math.trunc(n):0,portalSessionColumnAdjust:Number.isFinite(i)?Math.trunc(i):0,activityPaneAdjust:Number.isFinite(o)?Math.trunc(o):0}}function is(t){if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();!i||e.has(i)||(e.add(i),s.push(i))}return s}function Xs(t){if(!Array.isArray(t))return new Set;const e=new Set;for(const s of t){const n=String(s||"").trim();n&&e.add(n)}return e}function sr(t){if(t==null)return null;const e=String(t).trim();return e||null}function Ql({mode:t="local",branding:e=null,themeId:s=null,chatViewMode:n=null,sessionOwnerFilter:i=null,layoutAdjustments:o=null,pinnedSessionIds:r=null,collapsedSessionIds:a=null,activeSessionId:l=null}={}){const u=i!=null,f=a!=null,d=Sn(o);return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},auth:{principal:null,authorization:null},ui:{focusRegion:A.SESSIONS,inspectorTab:Te[0],sequenceExpandedTurns:[],sequenceSelectedTurn:null,chatViewMode:n==="summary"||n==="rich"?n:"transcript",statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:ze(s)?.id||Kl,modal:null,fullscreenPane:null,layout:{...d,viewportWidth:120,viewportHeight:40},scroll:{chat:0,inspector:0,activity:0,filePreview:0},chatScrollBySession:{},followBottom:{inspector:!0,activity:!0}},connection:{mode:t,connected:!1,workersOnline:null,error:null},sessions:{byId:{},flat:[],activeSessionId:sr(l),collapsedIds:Xs(a),collapsedIdsExplicit:f,pinnedIds:is(r),selectedIds:[],selectMode:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:u,ownerFilter:ss(i),navigationIntent:null,filterExceptionId:null},history:{bySessionId:new Map},outbox:{bySessionId:{}},orchestration:{bySessionId:{}},executionHistory:{bySessionId:{},format:"pretty"},files:{bySessionId:{},fullscreen:!1,selectedArtifactId:null,filter:{scope:"selectedSession",query:""}},logs:{available:!1,availabilityReason:"Log tailing disabled: no K8S_CONTEXT configured in the env file.",tailing:!1,entries:[],filter:{source:"allNodes",level:"all",format:"pretty"}},sessionStats:{bySessionId:{}},fleetStats:{loading:!1,data:null,userStats:null,fetchedAt:0},admin:{visible:!1,loading:!1,loadError:null,profile:null,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:0,storeAsSystem:!1},systemGhcpKey:{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null}}}}function nr(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function Xl(t,e){return!(!nr(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const ir="activeHighlightBackground",bn="activeHighlightForeground",Rs="userChat",Jl="userChatLabel",Zl="otherUserChatLabel",mi=new WeakMap,gi=new WeakMap;function ec(t){return t||bn}function or(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?ec(s?.color):bn,backgroundColor:ir,bold:s?.bold??!0}))}function Me(t,{color:e=bn,bold:s=!0}={}){return{text:t,color:e,backgroundColor:ir,bold:s}}function _e(t,e){return[{text:String(t||""),color:e,bold:!0}]}const tc=72;function rr(t){const e=Number(t)||0;return e>0&&e<=tc}function wn(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function sc(t){const e=wn(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function nc(t){const e=ar(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function ar(t){return t?.rowVisualStatus||wn(t)}function lr(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function In(t){const e=wn(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&nr(t?.error)&&!lr(t?.orchestrationStatus)?"warning":null}function cr(t,e="local"){const s=In(t);if(s)return s;const n=ar(t);if(e==="remote"&&lr(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 gt(t,e="local"){switch(cr(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 ur(t,e="local"){switch(cr(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 ue(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function xn(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const ic=ue({provider:"system",subject:"system"});function yi(t){const e=String(t||"").trim();if(!e)return"";const s=e.replace(/@.*/u,"").split(/[^A-Za-z0-9]+/u).map(i=>i.trim()).filter(Boolean);return s.length>=2?`${s[0][0]}${s[1][0]}`.toLowerCase():(s[0]||e).replace(/[^A-Za-z0-9]/gu,"").slice(0,2).toLowerCase()}function Si(t){return yi(t?.displayName)||yi(t?.email)||"?"}function bi(t){const e=t.sessions?.ownerFilter;if(Array.isArray(e?.ownerKeys)&&e.ownerKeys.length>0)return!0;const s=new Set;for(const n of Object.values(t.sessions?.byId||{})){if(!n||n.isSystem||n.isGroup)continue;const i=ue(n.owner);if(i&&(s.add(i),s.size>1))return!0}return!1}function dr(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function vn(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of dr(t,e)){const i=ue(n?.owner);i&&!s.has(i)&&s.set(i,n.owner)}return s.size===1?s.values().next().value:null}function wi(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Ii(t,e){const s=wi(t),n=wi(e?.agentId);return!!(s&&n&&s===n)}function oc(t){if(!t?.agentId||t?.isSystem)return null;const e=String(t?.title||"").trim();if(!e)return null;const s=" · ",n=e.lastIndexOf(s);if(n>0){const r=e.slice(0,n).trim(),a=e.slice(n+s.length).trim();if(r&&Ii(a,t))return{displayTitle:r,agentTitle:a}}const i=/^(.+?)\s+[–—-]\s+(.+)$/u.exec(e);if(i){const r=i[1].trim(),a=i[2].trim();if(r&&a)return{displayTitle:a,agentTitle:r}}const o=e.indexOf(": ");if(o>0){const r=e.slice(0,o).trim(),a=e.slice(o+2).trim();if(a&&Ii(r,t))return{displayTitle:a,agentTitle:r}}return null}function rc(t){const e=String(t||""),s=e.indexOf(": ");if(s<=0)return null;const n=e.slice(0,s).trim(),i=e.slice(s+2).trim();return!n||!i?null:{userTitle:i,typeTitle:n}}function ps(t){const e=String(t?.title||"").trim(),s=oc(t);if(!s)return e;const n=rc(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function fr(t,e){const s=Z(t?.sessionId);if(t?.isSystem)return`${It(t,e)} (${s})`;const n=ps(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function xi(t,e={},s={},n=void 0){if(!e||e.all===!0)return!0;if(t?.isSystem)return e.includeSystem===!0;const i=ue(n!==void 0?n:t?.owner);if(!i)return e.includeUnowned===!0;if(i===ic)return e.includeSystem===!0;const o=ue(s?.principal);return e.includeMe&&o&&i===o||e.includeShared===!0&&i!==o?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(i)}function pr(t,e={},s={},n=null){const i=vn(t,n||{});if(xi(t,e,s,i))return!0;if(!n)return!1;if(t?.isGroup)return dr(t,n).some(a=>pr(a,e,s,n));let o=t,r=0;for(;o?.parentSessionId&&r<16;){const a=n[o.parentSessionId];if(!a)return!1;if(xi(a,e,s))return!0;o=a,r+=1}return!1}function ac(t){return(t||[]).map(e=>e?.text||"").join("")}function En(t){const e=new Map,s=new Map;for(const n of Object.values(t||{})){const i=n?.parentSessionId;i&&(s.set(n.sessionId,i),e.has(i)||e.set(i,[]),e.get(i).push(n.sessionId))}return{childMap:e,parentMap:s}}function vi(t){const{childMap:e}=En(t),s=new Map;function n(i){if(s.has(i))return s.get(i);const r=(e.get(i)||[]).reduce((a,l)=>a+1+n(l),0);return s.set(i,r),r}for(const i of Object.keys(t||{}))n(i);return s}function Ei(t=[],e={}){const{parentMap:s}=En(e),n=new Map;for(const i of t){let o=s.get(i.sessionId);for(;o;)n.set(o,(n.get(o)||0)+1),o=s.get(o)}return n}function An(t={}){if(!t||typeof t!="object")return vi(t);const e=mi.get(t);if(e)return e;const s=vi(t);return mi.set(t,s),s}function Tn(t=[],e={}){if(!Array.isArray(t))return Ei(t,e);const s=gi.get(t);if(s)return s;const n=Ei(t,e);return gi.set(t,n),n}function hr(t,e,s,n){const i=s.get(t)||0,o=n.get(t)||0,r=Math.max(0,i-o),a=e?.collapsed?i:r;return a?{text:`[+${a}]`,color:"cyan"}:null}function Js(t){if(!t)return"scheduled";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"scheduled";try{return e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short"}).replace(/,\s*/g," ").replace(/\s+/g," ").trim()}catch{return e.toISOString().replace(/\.000Z$/,"Z")}}function lc(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${Js(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${Pt(t.cronInterval)}]`,color:"magenta"}:null}function mr(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function cc(t,e){const s=[];typeof t?.regenStage=="string"&&t.regenStage&&s.push({text:`↻ regen:${t.regenStage}`,color:"magenta"});const n=nc(t);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:gt(t,e)}));const i=Pn(t?.model,t?.reasoningEffort);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i,color:"cyan"}));const o=Ea(t?.contextUsage);o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color}));const r=Aa(t?.contextUsage);return r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r.text,color:r.color})),s}function uc(t,e,s,n,i){const o=[],r=s.connection?.mode||"local",a=t.depth>0?`${" ".repeat(Math.max(0,t.depth-1))}└ `:"";a&&o.push({text:a,color:"gray"});const l=new Set(Array.isArray(s.sessions?.pinnedIds)?s.sessions.pinnedIds:[]),u=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),f=!!s.sessions?.selectMode,d=u.has(t.sessionId),p=l.has(t.sessionId);if(f&&o.push({text:d?"[x] ":"[ ] ",color:d?"cyan":"gray",bold:d}),t.depth===0&&mr(e)&&l.size>0&&(p&&!e?.isSystem?o.push({text:"📌 ",color:"yellow"}):o.push({text:" ",color:"gray"})),e?.isGroup)o.push({text:"🗂 ",color:"cyan",bold:!0});else if(e?.isSystem)o.push({text:"⚙ ",color:"yellow",bold:!0});else if(e?.serviceKind)o.push({text:"⚗ ",color:"magenta",bold:!0});else{const V=ur(e,r);o.push({text:V?`${V} `:" ",color:gt(e,r)})}const h=e?.isGroup?"cyan":e?.isSystem?"yellow":gt(e,r),m=vn(e,s.sessions?.byId||{}),g=Z(e?.sessionId),S=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,y=S?qu(S):"",w=Pn(e?.model,e?.reasoningEffort),I=e?.isSystem?It(e,s.branding?.title||"PilotSwarm"):ps(e),x=!!(e?.isSystem||e?.isGroup||I&&I.trim()),C=[...o];if(bi(s)&&!e?.isSystem&&!e?.isGroup){const V=m?Si(m):"?",q=ue(s?.auth?.principal),ee=q&&ue(m)===q;C.push({text:`[${V}] `,color:ee?"green":"cyan",bold:!0})}x?C.push({text:I,color:h,bold:!!(e?.isSystem||e?.isGroup)}):(C.push({text:g,color:h}),y&&(C.push({text:" · ",color:"gray"}),C.push({text:y,color:"gray"})),w&&(C.push({text:" · ",color:"gray"}),C.push({text:w,color:"green"})));const v=hr(e?.sessionId,t,n,i);v&&C.push({text:` ${v.text}`,color:v.color,bold:v.bold});const k=lc(e);k&&C.push({text:" ⏱",color:"magenta"});const P=[],O=e?.contextUsage?.compaction?.state,M=fn(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&P.push({text:`${e.memberCount}`,color:"gray"}):O==="running"?P.push({text:"⇊",color:"magenta"}):O==="failed"?P.push({text:"!",color:"red"}):M!=null?P.push({text:`${M}%`,color:M>=85?"red":M>=70?"yellow":"green"}):P.push({text:"—",color:"gray"});const $=[];e?.isGroup&&e?.memberCount!=null&&($.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),y&&($.push({text:" · ",color:"gray"}),$.push({text:y,color:"gray"})));const F=[],Y=()=>{F.length&&F.push({text:" · ",color:"gray"})};if(e?.isGroup)F.push(...$);else{x&&(F.push({text:g,color:"cyan"}),y&&(Y(),F.push({text:y,color:"gray"})),w&&(Y(),F.push({text:w,color:"green"})));const V=e?.contextUsage;V&&Number.isFinite(V.currentTokens)&&Number.isFinite(V.tokenLimit)&&V.tokenLimit>0&&(Y(),F.push({text:`ctx ${j(V.currentTokens)}/${j(V.tokenLimit)}`,color:"gray"}));const q=n?.[e?.sessionId];q&&(Y(),F.push({text:`${q} child${q===1?"":"ren"}`,color:"gray"})),k&&(Y(),F.push({text:k.text,color:k.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(Y(),F.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...C,...x&&y&&!e?.isGroup?[{text:" ",color:"gray"},{text:y,color:"gray"}]:[],...P.length&&!e?.isGroup?[{text:" · ",color:"gray"},...P]:[],...e?.isGroup&&$.length?[{text:" ",color:"gray"},...$]:[]],titleRuns:C,ctxRuns:P,metaRuns:$,badgeRuns:[],selectedMetaRuns:F,detailRuns:F,chrome:{kind:e?.isGroup?"group":e?.isSystem?"system":e?.serviceKind?"service":"session",title:x?I:g,untitled:!x,statusColor:gt(e,r),accentColor:h,pinned:p,selectMode:f,checked:d,owner:bi(s)&&!e?.isSystem&&!e?.isGroup?{initials:m?Si(m):"?",isMine:!!(ue(s?.auth?.principal)&&ue(m)===ue(s?.auth?.principal))}:null,childBadge:v?{text:v.text,color:v.color}:null,cron:!!k,age:y||null,model:w||null,shortId:g,ctx:P.length>0?{text:P[0].text,color:P[0].color}:null}}}function gr(t){return String(t||"").trim().toLowerCase()}function Je(t,e){const s=gr(e);return s?String(t||"").toLowerCase().includes(s):!0}function dc(t){const e=t?.filterExceptionId||null,s=t?.byId||{};if(!e||!s[e])return null;const n=new Set([e]);let i=s[e],o=0;for(;i&&o<16;){let r=null;if(i.parentSessionId&&s[i.parentSessionId]?r=i.parentSessionId:!i.isGroup&&i.groupId&&s[`group:${i.groupId}`]&&(r=`group:${i.groupId}`),!r||n.has(r))break;n.add(r),i=s[r],o+=1}return n}function wt(t){const e=An(t.sessions.byId),s=Tn(t.sessions.flat,t.sessions.byId),n=gr(t.sessions?.filterQuery||""),i=t.sessions?.ownerFilter||{all:!0},o=t.auth||{},r=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),a=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]),l=dc(t.sessions);return t.sessions.flat.map(u=>{const f=t.sessions.byId[u.sessionId],d=uc(u,f,t,e,s);return{sessionId:u.sessionId,text:ac(d.runs),...d,depth:u.depth,status:f?.status,statusColor:gt(f,t.connection?.mode||"local"),active:u.sessionId===t.sessions.activeSessionId,isSystem:!!f?.isSystem,isGroup:!!f?.isGroup,hasChildren:u.hasChildren,collapsed:u.collapsed,pinned:r.has(u.sessionId),selected:a.has(u.sessionId),canPin:mr(f)}}).filter(u=>{if(l?.has(u.sessionId))return!0;const f=t.sessions.byId[u.sessionId];if(!pr(f,i,o,t.sessions.byId))return!1;const d=vn(f,t.sessions.byId),p=d?`${xn(d,"")} ${d.email||""}`:"",h=`${f?.shortSummary||""} ${f?.summaryState?.intent||""} ${f?.summaryState?.summary||""}`;return Je(u.text,n)||Je(u.sessionId,n)||Je(p,n)||Je(h,n)})}function Zs(t,e=8){const s=wt(t);if(s.length===0)return[];const n=new Set(s.map(d=>d.sessionId)),i=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(d=>n.has(d.sessionId)),o=i.findIndex(d=>d.sessionId===t.sessions.activeSessionId),r=Math.max(0,o);if(i.length<=e)return s;const a=Math.floor(e/2);let l=Math.max(0,r-a),u=Math.min(i.length,l+e);u>i.length&&(u=i.length,l=Math.max(0,u-e));const f=i.slice(l,u);return An(t.sessions.byId),Tn(i,t.sessions.byId),s.filter(d=>f.some(p=>p.sessionId===d.sessionId))}function Ce(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function fc(t){const e=t.sessions?.navigationIntent;if(!e||e.status!=="failed")return null;const s=e.errorKind==="not_found"?"not_found":"network";return{sessionId:e.sessionId,errorKind:s,retryable:s==="network",message:s==="not_found"?"This session was not found or has not been shared with you.":"Could not load the linked session. Check your connection and try again."}}function wh(t){const e=t.sessions?.filterExceptionId||null;return!e||!t.sessions?.byId?.[e]?null:"Showing linked session outside your current filters."}function yr(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function pc(t){const e=t?.pendingQuestion;if(!e?.question)return null;const s=[String(e.question).trim()],n=Array.isArray(e.choices)?e.choices.filter(i=>typeof i=="string"&&i.trim()):[];if(n.length>0){s.push("","Choices:");for(const i of n)s.push(`- ${i}`)}return n.length>0&&e.allowFreeform===!1?s.push("","Reply with one of the choices above in the prompt below."):n.length>0?s.push("","Reply with one of the choices above, or type a free-form answer below."):s.push("","Type your answer in the prompt below and press Enter."),{id:`pending-question:${t.sessionId}:${e.question}`,role:"system",text:s.join(`
26
+ `),time:"",createdAt:t.updatedAt||Date.now(),cardTitle:"Question",cardTitleColor:"cyan",cardBorderColor:"cyan"}}function hc(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),i=String(s?.answer||"").trim();if(!n||!i||Sr(e,n))return null;const o=s.pendingPhase==="queued"?"queued":"pending",r=Number(s.answeredAt||0)||t.updatedAt||Date.now();return{id:`answered-question:${t.sessionId}:${n}:${r}`,role:"user",text:`The user was asked: "${n}"
27
+ The user responded: "${i}"`,time:"",createdAt:r,optimistic:!0,pendingPhase:o}}function mc(t,e){if(!t||!e?.id)return null;const s=String(e.text||"").trim();return s?{id:`pending-outbox:${t}:${e.id}`,role:"user",text:s,time:"",createdAt:Number(e.createdAt)||Date.now(),pendingPhase:e.phase==="cancelling"?"cancelling":e.phase==="rejected"?"rejected":e.phase==="queued"?"queued":"pending"}:null}function Sr(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>ds(n?.text||"")?.question?.trim()===s):!1}function gc(t){const e=String(t?.error||"").trim();if(!e)return null;const s=In(t);if(!s)return null;const n=s==="failed",i=n?e:`${e}
28
+
29
+ The orchestration is still running, so this may be transient.`;return{id:`session-error:${t.sessionId}:${s}:${e}`,role:"system",text:i,time:"",createdAt:t.updatedAt||Date.now(),cardTitle:n?"Error":"Warning",cardTitleColor:n?"red":"yellow",cardBorderColor:n?"red":"yellow"}}function Ai(t=[],e){for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n?.eventType===e)return Number(n?.seq||0)}return 0}function yc(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function Sc(t,e=0){const s=Array.isArray(t?.activity)?t.activity:[],n=new Set(["assistant.reasoning","assistant.turn_start","session.turn_started","session.turn_completed"]);for(let i=s.length-1;i>=0;i-=1){const o=s[i];if(!o||n.has(o.eventType)||Number(o?.seq||0)<=e)continue;const r=yc(o.text);if(r)return{...o,summaryText:r}}return null}function bc(t,e,s=[],n=[]){if(!t||t?.pendingQuestion?.question)return null;const i=String(t?.status||"").toLowerCase();if(i==="completed"||i==="failed"||i==="cancelled")return null;const o=(s||[]).filter(C=>C?.role==="user"||C?.role==="assistant"),r=o[o.length-1]||null,a=r?.role==="user",l=a&&r?.optimistic===!0,u=(n||[]).filter(C=>C?.phase==="pending").length,f=(n||[]).filter(C=>C?.phase==="queued").length,d=(n||[]).filter(C=>C?.phase==="cancelling").length,p=Array.isArray(e?.events)?e.events:[],h=Ai(p,"user.message"),m=Ai(p,"assistant.message"),g=h>m;if(i==="waiting"||i==="input_required"||!a&&!g&&i!=="running"&&!l)return null;const S=Math.max(h,m),y=p.filter(C=>C?.eventType==="assistant.reasoning"&&Number(C?.seq||0)>S),w=y[y.length-1]||null,I=String(w?.data?.content||w?.data?.text||w?.data?.message||"").trim();if(I)return{kind:"thinking",label:"Thinking",text:I,createdAt:w?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:w?.seq||0};const x=Sc(e,S);return x?.summaryText?{kind:i==="running"?"working":"sending",label:i==="running"?"Working":"Sending",text:x.summaryText,createdAt:x.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:x.seq||0}:u>0?{kind:"pending",label:u===1?"Pending":`Pending ${u}`,text:u===1?"One prompt is waiting to be sent.":`${u} prompts are waiting to be sent.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:f>0?{kind:"queued",label:f===1?"Queued":`Queued ${f}`,text:f===1?"One prompt is durably queued, waiting for the LLM to receive it.":`${f} prompts are durably queued, waiting for the LLM to receive them.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:d>0?{kind:"cancelling",label:d===1?"Cancelling":`Cancelling ${d}`,text:d===1?"One queued prompt is waiting for cancellation confirmation.":`${d} queued prompts are waiting for cancellation confirmation.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:l?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:r?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:i==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:null}function hs(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return Es(t.branding);if(s?.isGroup){const u=Object.values(t.sessions.byId||{}).filter(h=>h&&!h.isGroup&&h.groupId===s.groupId&&!h.parentSessionId),f=h=>String(h??"").replace(/\|/g,"\\|").replace(/[\r\n]+/g," ").trim()||" ",d=u.map(h=>`| ${f(h.title||h.sessionId)} | ${f(h.status||"unknown")} | ${f(h.shortSummary||"")} |`),p=[`# ${s.title||s.groupId}`,s.shortSummary||"","","| Metric | Count |","|---|---:|",`| Members | ${s.memberCount??u.length} |`,`| Running | ${s.runningCount??0} |`,`| Waiting | ${s.waitingCount??0} |`,`| Completed | ${s.completedCount??0} |`,`| Failed | ${s.failedCount??0} |`,`| Cancelled | ${s.cancelledCount??0} |`,"","## Members",...d.length>0?["| Session | Status | Summary |","|---|---|---|",...d]:["_No top-level members._"]];return[{id:`group-details:${s.sessionId}`,role:"system",noChrome:!0,text:p.filter((h,m)=>m===1||String(h||"").length>0).join(`
30
+ `),createdAt:s.updatedAt||Date.now()}]}if(t.ui?.chatViewMode==="summary")return wc(s);const n=t.history.bySessionId.get(e),i=n?.chat||[],o=s?.pendingQuestion?.question&&!Sr(i,s.pendingQuestion.question)?pc(s):null,r=hc(s,i),a=gc(s);if((!n||i.length===0)&&!o&&!r&&!a)return Es(t.branding,s);const l=i.length>0?[...i]:Es(t.branding,s);return o&&l.push(o),r&&l.push(r),a&&l.push(a),l}function wc(t){const e=u=>{const f=String(u||"");return f.includes("\\n")?f.replace(/\\\\n/g,`
31
+ `).replace(/\\n/g,`
32
+ `):f},s=t?.summaryState&&typeof t.summaryState=="object"&&!Array.isArray(t.summaryState)?t.summaryState:null,n=s?.state&&typeof s.state=="object"&&!Array.isArray(s.state)?s.state:null,i=ps(t)||t?.title||t?.sessionId||"Session",o=[];o.push(`# ${i}`),o.push("");const r=[],a=sc(t);if(a&&r.push(["Status",a]),s?.intent&&r.push(["Intent",String(s.intent)]),t?.summaryUpdatedAt){const u=pe(t.summaryUpdatedAt);u&&r.push(["Updated",u])}for(const[u,f]of r)o.push(`**${u}:** ${f}`);r.length>0&&o.push("");const l=e(s?.summary||t?.shortSummary||"").trim();if(l&&(o.push(l),o.push("")),n){const u=Object.entries(n).filter(([,f])=>f!=null&&!(typeof f=="string"&&!f.trim()));if(u.length>0){o.push("## State");for(const[f,d]of u)if(Array.isArray(d))if(d.length===0)o.push(`- **${f}:** _(empty)_`);else{o.push(`- **${f}:**`);for(const p of d.slice(0,16)){const h=typeof p=="string"?e(p):JSON.stringify(p);o.push(` - ${h}`)}}else if(d&&typeof d=="object"){o.push(`- **${f}:**`);for(const[p,h]of Object.entries(d).slice(0,16)){const m=typeof h=="string"?e(h):JSON.stringify(h);o.push(` - **${p}:** ${m}`)}}else o.push(`- **${f}:** ${e(String(d))}`);o.push("")}}for(const[u,f]of[["Blockers","blockers"],["Open Questions","openQuestions"],["Next Actions","nextActions"]]){const d=Array.isArray(s?.[f])?s[f].filter(Boolean).slice(0,12):[];if(d.length!==0){o.push(`## ${u}`);for(const p of d)o.push(`- ${typeof p=="string"?e(p):JSON.stringify(p)}`);o.push("")}}for(!s&&!l&&o.push("_No summary has been written yet for this session._");o.length>0&&o[o.length-1]==="";)o.pop();return[{id:`summary:${t?.sessionId||"none"}`,role:"system",noChrome:!0,text:o.join(`
33
+ `),createdAt:t?.summaryUpdatedAt||t?.updatedAt||Date.now()}]}function Ic(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>mc(e,s)).filter(Boolean):[]:[]}function Ls(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function br(t,e={}){const s=pe(t?.createdAt||t?.time),n=t?.sender,i=n?.kind==="user"?ue(n):null,o=e?.viewerKey||null,r=e?.ownerKey||null,a=e?.sharedContext===!0,l=t?.role==="user",f=a&&l&&i&&!(l&&i&&o&&i===o),p=a&&l&&r&&(i&&i===r||!i&&o&&o===r)?" (owner)":"",h=l?(f?n.display||n.subject||"User":"You")+p:t?.role==="assistant"?"Agent":t?.role==="system"?"System":"PilotSwarm";let m=null,g=null;t?.pendingPhase==="pending"?(m="○",g="yellow"):t?.pendingPhase==="queued"?(m="✓",g="cyan"):t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?(m="x",g="red"):t?.role==="user"&&!t?.optimistic&&!t?.pendingPhase&&(t?.stopped?(m="⊘",g="yellow"):t?.redelivered?(m="✓✓↻",g="yellow"):(m="✓✓",g="green"));const S=t?.pendingPhase==="pending"?"yellow":t?.pendingPhase==="queued"?"cyan":t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?"red":f?Zl:t?.role==="user"?Jl:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white";return{time:s,glyph:m,glyphColor:g,roleLabel:h,roleColor:S,fromOtherPerson:f}}function xc(t,e={}){const{time:s,glyph:n,glyphColor:i,roleLabel:o,roleColor:r}=br(t,e),a=s?`[${s}] `:"",l=[...Ls(a,"gray")];return n&&l.push(...Ls(`${n} `,i)),l.push(...Ls(`${o}: `,r,{bold:!0})),l}function qe(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function wr(){return[{text:"",color:null}]}function vc(t){const e=(t||[]).find(n=>qe(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=qe(e).trimStart();return/^[┌│└]/.test(s)}function os(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(qe(s).trim().length>0)break;e.shift()}return e}function Ec(t){const e=String(t||"").replace(/\r\n/g,`
34
+ `),s=e.trim();if(!s)return null;if(s.startsWith("[SYSTEM:")&&s.endsWith("]"))return{leadingText:"",systemText:s.slice(8,-1).trim()};const n=e.lastIndexOf(`
35
+
36
+ [SYSTEM:`);if(n>=0&&e.trimEnd().endsWith("]")){const i=e.slice(0,n).trimEnd(),o=e.slice(n+2).trim();if(o.startsWith("[SYSTEM:"))return{leadingText:i,systemText:o.slice(8,-1).trim()}}return Ac.test(s)?{leadingText:"",systemText:s}:null}const Ac=/^(?:Sub-agents?\s+completed\b|Sub-agent\s+status\s+report\b|Active\s+sessions\b|No\s+(?:tracked\s+sub-agents|running\s+sub-agents|sub-agents\s+have\s+been\s+spawned)\b|spawn_agent\s+failed\b|message_agent\s+failed\b|complete_agent\s+failed\b)/i;function Cn(t){const e=Ec(t);if(e){const r=[];e.leadingText&&r.push({kind:"text",text:e.leadingText});const a=Ke(e.systemText);return a&&r.push({kind:"system",text:a}),r}const s=String(t||"").replace(/\r\n/g,`
37
+ `).split(`
38
+ `),n=[];let i=[];function o(){i.length!==0&&(n.push({kind:"text",text:i.join(`
39
+ `)}),i=[])}for(let r=0;r<s.length;){const a=s[r];if(!/^\s*\[SYSTEM:/i.test(a)){i.push(a),r+=1;continue}const l=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(a);if(l){o();const p=Ke(l[1].trim());if(!p){r+=1;continue}n.push({kind:"system",text:p}),r+=1;continue}const u=[a.replace(/^\s*\[SYSTEM:\s*/i,"")];let f=-1;for(let p=r+1;p<s.length;p+=1){const h=s[p];if(h.trim()==="]"){f=p;break}if(/\]\s*$/.test(h.trim())){const m=h.replace(/\]\s*$/,"");m.trim()&&u.push(m),f=p;break}u.push(h)}if(f===-1){i.push(a),r+=1;continue}o();const d=Ke(u.join(`
40
+ `).trim());if(!d){r=f+1;continue}n.push({kind:"system",text:d}),r=f+1}return o(),n}function Tc(t){return t?t?.role==="system"?!mn(t?.text||"")||!!Ke(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:Cn(t?.text||"").some(e=>e.kind==="system"):!1}function Ti(t){return Tc(t)?"system":t?.role||"other"}function Ir(t,e){return!t||!e?!1:Ti(t)!==Ti(e)}function Cc(t){const e=String(t||"").replace(/\s+/g," ").trim();if(!e)return"System notice.";const s=/^The session was dehydrated and has been rehydrated on a new worker(?: \(([^)]+)\))?\./.exec(e);if(s)return s[1]?`Session rehydrated on a new worker (${s[1]}).`:"Session rehydrated on a new worker.";const i=/^(.{1,160}?[.!?])(?:\s|$)/.exec(e)?.[1]?.trim()||e;return i.length>=e.length?i.length>160?`${i.slice(0,159).trimEnd()}…`:i:`${i}…`}function kc(t,e=""){const s=Cc(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:Ze(t),color:"gray"}}function Ci({title:t,summary:e,body:s,timestamp:n="",color:i="gray"}){const o=String(t||"System").trim()||"System",r=String(e||"").replace(/\s+/g," ").trim();return{kind:"systemNotice",text:`${n?`[${n}] `:""}${o}${r?`: ${r}`:""}`,summary:r,body:Ze(s||r),color:i}}function Mc(t){return t?.label?[{text:t.label,color:t.kind==="working"?"yellow":"cyan",bold:!0}]:null}function Nc(t,e){return e?(t||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||e})):s):t}function Pc(t){const e=(t||[]).find(s=>qe(s).trim().length>0);return e?qe(e).trimStart().startsWith("┌"):!1}function rs(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&Pc(e)&&qe(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function _c(t){const e=String(t||""),s=/^\s*Sub-agent\s+completed\b/i.test(e),n=/^\s*Sub-agents\s+completed/i.test(e);if(!s&&!n)return null;const i=[],o=/(?:^|\n)\s*-\s*Agent\s+(\S+)\s*\n\s*Task:\s*"([^"]*)"\s*\n\s*Status:\s*(\S+)\s*\n\s*Result:\s*([\s\S]*?)(?=(?:\n\s*-\s*Agent\s+\S+)|$)/g;let r;for(;(r=o.exec(e))!==null;)i.push({agentId:r[1],task:r[2],status:r[3],result:r[4].trim()});return i.length===0?null:s||i.length===1?{kind:"subAgentSingle",...i[0]}:{kind:"subAgentMulti",agents:i}}function Oc(t,e,s){const n=Math.max(20,Number(s)||20),i=pe(e?.createdAt||e?.time),o=_c(t),r=a=>{const l=String(a||"").replace(/^session-/i,"");return Z(l)||l||String(a||"")};if(o?.kind==="subAgentSingle"){const a=r(o.agentId),l=[o.task?`**Task:** ${o.task}`:"",o.status?`**Status:** ${o.status}`:"","",o.result||"_(no result)_"].filter((u,f)=>f===2||u).join(`
41
+ `);return[Ci({title:`Sub-agent Response — ${a}`,summary:o.status||"completed",timestamp:i,body:l,color:"cyan"})]}if(o?.kind==="subAgentMulti"){const a=o.agents.map(u=>{const f=r(u.agentId),d=u.task?`**Task:** ${u.task}`:"",p=u.status?`**Status:** ${u.status}`:"";return`${[`### ${f}`,d,p].filter(Boolean).join(`
42
+ `)}
43
+
44
+ ${u.result||"_(no result)_"}`}),l=o.agents.map(u=>`${r(u.agentId)} ${u.status||"completed"}`).join(" · ");return[Ci({title:`Sub-agent Responses (${o.agents.length})`,summary:l,timestamp:i,body:a.join(`
45
+
46
+ ---
47
+
48
+ `),color:"cyan"})]}return ne({title:"System",timestamp:i,body:t,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function Rc(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),i=pe(t?.createdAt||t?.time),o=String(t?.thinkingLabel||"Thinking…").trim()||"Thinking…",r=t?.progressKind==="working"?"yellow":(t?.progressKind==="sending","cyan"),a=X([{text:` ⠋ ${o} `,color:r,bold:!0},...i?[{text:` ${i} `,color:"gray"}]:[]],Math.max(1,s-3)),l=a.reduce((p,h)=>p+String(h?.text||"").length,0),u=Math.max(0,s-l-3),f=String(t?.text||"").trim()?os(St(Ze(t.text),{width:n})).flatMap(p=>Do(p,n)):[],d=[[{text:"┌─",color:"gray"},...a,{text:`${"─".repeat(u)}┐`,color:"gray"}]];for(const p of f)d.push([{text:"│ ",color:"gray"},...Bo(p.map(h=>({...h,color:h?.color&&h.color!=="white"?h.color:"gray"})),n),{text:" │",color:"gray"}]);return d.push([{text:`└${"─".repeat(Math.max(1,s-2))}┘`,color:"gray"}]),d.push([{text:"",color:null}]),d}function Lc(t){return String(t||"").split(`
49
+ `).reduce((e,s)=>Math.max(e,pn(s).length),0)}function Lt(t,e,s={}){if(t?.splash){const u=t.mobileText&&Lc(t.text)>e;return[{kind:"markup",value:u?t.mobileText:t.text,splashAlt:!u&&t.mobileText?t.mobileText:null}]}if(t?.thinking)return Rc(t,e);if(t?.noChrome)return os(St(Ze(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const u=ds(t?.text||"");if(u)return[...ne({title:"Question",timestamp:pe(t?.createdAt||t?.time),body:u.question,width:Math.max(20,e),titleColor:Rs,borderColor:Rs,tableMode:s.tableMode}),...Lt({...t,text:u.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const u=Cn(t?.text||"");if(u.some(f=>f.kind==="system")){const f=[];let d=!1;for(const h of u)h.kind!=="system"&&h.text.trim()&&(rs(f,Lt({...t,text:h.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:d})),d=!0);if(f.length>0)return f;const p=[];for(const h of u)h.kind!=="system"||!h.text.trim()||rs(p,Oc(h.text,t,e));if(p.length>0)return p}}if(t?.role!=="user"&&t?.role!=="assistant"){const u=Ke(t?.text||"");if(t?.role==="system"&&!u)return[];const f=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!f)return[kc(u||t?.text||"",pe(t?.createdAt||t?.time))];const d=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return ne({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:pe(t?.createdAt||t?.time),body:Ze(t?.text||""),width:Math.max(20,e),titleColor:t?.cardTitleColor||(t?.role==="system"?"yellow":"cyan"),borderColor:t?.cardBorderColor||"gray",tableMode:s.tableMode,...d?{bodyColor:"gray",fitToContent:!0}:{}})}const n=os(St(Ze(t?.text||""),{width:e,tableMode:s.tableMode})),i=Nc(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?Rs:null),o=s.skipPrefix?[]:xc(t,s),r=xr(t,s);if(i.length===0){const u=o.length>0?[o]:[];return r.length>0?[...u,...r]:u}if(vc(i)){const u=o.length>0?[o,...i]:i;return r.length>0?[...u,...r]:u}const a=[];let l=o.length===0;for(const u of i){if(!Array.isArray(u)){l||(a.push(o),l=!0),a.push(u);continue}l?a.push(u):(a.push([...o,...u]),l=!0)}return a.push(...r),a}function xr(t,e={}){const s=Array.isArray(t?.attachments)?t.attachments:[];return s.length===0?[]:e.tableMode==="sentinel"?[{kind:"imageAttachments",sessionId:String(t?.id||"").split(":")[0]||null,attachments:s}]:s.map(n=>{const i=Number(n?.sizeBytes)||0,o=i>=1024*1024?`${(i/(1024*1024)).toFixed(1)} MB`:i>=1024?`${Math.round(i/1024)} KB`:`${i} B`;return[{text:" ",color:null},{text:`[image: ${n.filename}${i>0?` · ${o}`:""}]`,color:"cyan"}]})}const $c=new Set(["assistant.usage","session.info","session.idle","session.usage_info","pending_messages.modified","pending_messages.cancelled","abort","assistant.turn_start","assistant.turn_end","assistant.streaming_progress","session.turn_completed","tool.execution_partial_result","tool.execution_progress"]);function Fc(t){const e=Math.max(0,Math.floor((Number(t)||0)/1e3));if(e<60)return`${e}s`;const s=Math.floor(e/60),n=e%60;if(s<60)return`${s}m ${String(n).padStart(2,"0")}s`;const i=Math.floor(s/60),o=s%60;return`${i}h ${String(o).padStart(2,"0")}m`}const Bc=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),Dc=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function Hc(t,e){const s=String(t||"").toLowerCase();return s==="search_skills"||s.includes("skill")?e?"loading skills…":"loaded skills":Bc.has(s)?e?"reading facts…":"read facts":Dc.has(s)?e?"writing facts…":"wrote facts":s.startsWith("graph_")?/upsert|delete|archive|merge|remove|set_/.test(s)?e?"writing to the graph…":"wrote to the graph":e?"reading the graph…":"read the graph":s.startsWith("facts_")||s.endsWith("_fact")||s.endsWith("_facts")?/store|write|set|delete|purge|update/.test(s)?e?"writing facts…":"wrote facts":e?"reading facts…":"read facts":""}function Gc(t){const e=String(t?.eventType||"");if(e==="tool.execution_start"||e==="tool.execution_complete"){const n=(String(t?.text||"").replace(/^\s*\d{1,2}:\d{2}(?::\d{2})?\s*/,"").replace(/^\[[^\]]+\]\s*/,"").replace(/^[^A-Za-z0-9_]+/,"").trim().match(/^[A-Za-z0-9_.:-]+/)||[""])[0];if(!n)return"running tools…";const i=Hc(n,e==="tool.execution_start");if(i)return i;const o=n.length>28?`${n.slice(0,27)}…`:n;return e==="tool.execution_start"?`running tool: ${o}…`:`finished tool: ${o}`}switch(e){case"skill.invoked":return"loading skills…";case"learned_skill.read":return"loading skills…";case"skills.searched":return"loading skills…";case"facts.searched":case"facts.similar":return"reading facts…";case"graph.searched":case"graph.node_searched":case"graph.node_loaded":return"reading the graph…";case"graph.namespace_mutated":return"writing to the graph…";case"assistant.reasoning":return"thinking…";case"assistant.intent":return"planning…";case"assistant.message_start":case"assistant.message":return"writing reply…";case"session.compaction_start":return"compacting context…";case"session.compaction_complete":return"context compacted";case"session.dehydrated":return"dehydrating…";case"session.hydrated":case"session.rehydrated":return"rehydrating…";case"session.agent_spawned":return"coordinating agents…";case"session.wait_started":return"waiting…";case"session.input_required_started":return"awaiting input…";case"session.lossy_handoff":return"moving to a new worker…";case"session.error":return"recovering from an error…";default:return""}}function kn(t,e={}){if(t?.ui?.chatViewMode==="summary")return[];const s=Ce(t);if(!s||s.isGroup)return[];if(String(s?.status||"").toLowerCase()!=="running")return[];const i=t.history?.bySessionId?.get(s.sessionId)||null,o=Array.isArray(i?.chat)?i.chat:[];let r=0;for(let w=o.length-1;w>=0;w-=1)if(o[w]?.role==="user"){r=Number(o[w]?.createdAt||0);break}const a=Array.isArray(i?.activity)?i.activity:[];let l=0,u=0;for(let w=a.length-1;w>=0;w-=1){const I=a[w],x=I?.eventType,C=Number(I?.createdAt||0);if(!l&&x==="assistant.turn_start"&&(l=C),!u&&(x==="assistant.turn_end"||x==="session.turn_completed")&&(u=C),l&&u)break}let f=0;r>u?f=r:l>u&&(f=l);let d=null;for(let w=a.length-1;w>=0;w-=1){const I=a[w];if(!(!I||$c.has(I.eventType))){if(Number(I.createdAt||0)<=u)break;d=I;break}}const p=Number.isFinite(e.now)?e.now:Date.now(),h=f>0?Fc(p-f):"",m=String(e.spinnerFrame||"").trim()||"●",g=d?Gc(d):"",S=[{text:`${m} `,color:"cyan"},{text:"Working",color:"cyan"},...h?[{text:` · ${h}`,color:"gray"}]:[],...g?[{text:` — ${g}`,color:"gray"}]:[]],y=Math.max(24,Math.min(120,Math.floor(Number(e.maxWidth)||80)));return[X(S,y)]}function Mn(t,e=80,s={}){const n=hs(t);if(!n||n.length===0)return[{text:"No messages yet.",color:"gray"}];const i=ue(t?.auth?.principal),o=t?.sessions?.activeSessionId,r=o?t?.sessions?.byId?.[o]:null,a=ue(r?.owner),l=!!(r&&(r.visibility&&r.visibility!=="private"||a&&i&&a!==i)),u={...s?.tableMode?{tableMode:s.tableMode}:{},...i?{viewerKey:i}:{},...a?{ownerKey:a}:{},...l?{sharedContext:!0}:{}},f=[];for(const[d,p]of n.entries()){if(p?.kind==="epoch-divider")f.push(Er(p,e));else if(p?.kind==="regen-refused")f.push(Ar(p,e));else{const m=Lt(p,e,u);rs(f,m)}const h=n[d+1];h&&Ir(p,h)&&qe(f[f.length-1]).trim().length>0&&f.push(wr())}return f.length>0?f:[{text:"No messages yet.",color:"gray"}]}function Uc(t){return!(!t||t.kind==="epoch-divider"||t.kind==="regen-refused"||t.splash||t.thinking||t.noChrome||t.role!=="user"&&t.role!=="assistant"||t.role==="user"&&ds(t?.text||"")||Cn(t?.text||"").some(s=>s.kind==="system"))}function jc(t,e=80,s={}){const n=hs(t);if(!n||n.length===0)return[];const i=ue(t?.auth?.principal),o=t?.sessions?.activeSessionId,r=o?t?.sessions?.byId?.[o]:null,a=ue(r?.owner),l=!!(r&&(r.visibility&&r.visibility!=="private"||a&&i&&a!==i)),u={...s?.tableMode?{tableMode:s.tableMode}:{},...i?{viewerKey:i}:{},...a?{ownerKey:a}:{},...l?{sharedContext:!0}:{}},f=[];for(const d of n){if(d?.kind==="epoch-divider"){f.push({kind:"lines",variant:"divider",lines:[Er(d,e)]});continue}if(d?.kind==="regen-refused"){f.push({kind:"lines",variant:"divider",lines:[Ar(d,e)]});continue}if(Uc(d)){const m=xr(d,{tableMode:"sentinel"}).find(g=>g?.kind==="imageAttachments")||null;f.push({kind:"message",id:d?.id??null,role:d.role,header:br(d,u),text:Ze(d?.text||""),pendingPhase:d?.pendingPhase||null,attachments:m?{sessionId:m.sessionId,attachments:m.attachments}:null});continue}const p=Lt(d,e,u);p.length>0&&f.push({kind:"lines",variant:"event",lines:p})}return f}function vr(t,e,s){const i=Math.max(24,Number(s)||80)-t.length;if(i<2)return[{text:t.trim(),color:e,bold:!0}];const o=Math.min(6,Math.floor(i/2));return o<1?[{text:t.trim(),color:e,bold:!0}]:[{text:"─".repeat(o),color:e},{text:t,color:e,bold:!0},{text:"─".repeat(o),color:e}]}function Er(t,e){const s=Number.isFinite(t?.turnsArchived)?t.turnsArchived:null,n=` ↻ context regenerated · epoch ${t?.epoch??"?"}${s!=null?` · ${s} turn${s===1?"":"s"} archived`:""} `;return vr(n,"magenta",e)}const Wc={cooldown:"on cooldown (once per 6h)",too_young:"too soon (needs 5+ turns)",already_pending:"already in progress",is_system:"not allowed for system sessions",not_owner:"owner only",not_parent:"parent only"};function Ar(t,e){const s=String(t?.reason||"unknown"),i=` ↻ regeneration refused · ${Wc[s]||s.replace(/_/g," ")} `;return vr(i,"yellow",e)}function Nn(t,e=80,s={}){const n=Ic(t);if(!n||n.length===0)return[];const i=Math.max(20,Number(e)||80),o=n.filter(g=>g.pendingPhase==="queued").length,r=n.filter(g=>g.pendingPhase==="pending").length,a=n.filter(g=>g.pendingPhase==="cancelling").length,l=n.filter(g=>g.pendingPhase==="rejected").length,u=[];r>0&&u.push(`${r} pending`),o>0&&u.push(`${o} queued`),a>0&&u.push(`${a} cancelling`),l>0&&u.push(`${l} rejected`);const d=` queued prompts: ${u.length>0?u.join(" · "):"queued prompts"} `,p=Math.max(1,i-d.length),h=[[{text:d,color:"gray"},{text:"─".repeat(p),color:"gray"}]],m=s?.tableMode?{tableMode:s.tableMode}:{};for(const[g,S]of n.entries()){rs(h,Lt(S,i,m));const y=n[g+1];y&&Ir(S,y)&&qe(h[h.length-1]).trim().length>0&&h.push(wr())}return h}function Kc(t){const e=hs(t),s=[],n=new Set;for(const i of e||[])for(const o of Fa(i?.text||"")){const r=`${o.sessionId}/${o.filename}`;n.has(r)||(n.add(r),s.push(o))}return s}function Vc(t){const e=hs(t),s=[],n=new Set;for(const i of e||[])for(const o of Ba(i?.text||"")){const r=String(o.href||"").trim();!r||n.has(r)||(n.add(r),s.push({href:r,text:String(o.text||r).trim()||r}))}return s}function Pn(t,e){const s=$o(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function qc(t){return $o(t)||"(unknown)"}function Tr(t,e={}){const s=Ce(t),n=t.sessions?.byId||{},i=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],o=An(n),r=Tn(i,n),a=rr(e?.width);if(!s)return{color:"cyan",title:_e("Chat","cyan"),titleRight:null,animateTitleRight:!1};const l=Z(s.sessionId),u=s.isSystem?"yellow":"cyan",f=_e(s.isSystem?`⚙ ${It(s,t.branding?.title||"PilotSwarm")}`:ps(s)||"Chat",u),d=i.find(x=>x.sessionId===s.sessionId),p=hr(s.sessionId,d,o,r);p&&f.push({text:` ${p.text}`,color:p.color}),a||f.push({text:` [${l}]`,color:"gray"});const h=t.history?.bySessionId?.get(s.sessionId)||null,m=Array.isArray(t.outbox?.bySessionId?.[s.sessionId])?t.outbox.bySessionId[s.sessionId]:[],g=t.ui?.chatViewMode==="summary"?null:bc(s,h,h?.chat||[],m),S=t.connection?.mode||"local",y=cc(s,S),w=Mc(g),I=w?[...y,...y.length?[{text:" · ",color:"gray"}]:[],...w]:y;return{color:s.isSystem?"yellow":"cyan",title:f,titleRight:I.length?I:null,animateTitleRight:!!g}}function zc(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function _n(t,e=12){const s=zc(t),n=Ce(t),i=_e("Activity","gray");return n?.isGroup?{title:i,disabled:!0,lines:[{text:Fr,color:"gray"}]}:(n?.statusVersion!=null&&i.push({text:` [current session v${n.statusVersion}]`,color:"gray"}),{title:i,lines:s.length>0?s.map(o=>o.line||[{text:o.text,color:"white"}]):[{text:"No activity yet",color:"gray"}]})}function Cr(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 kr(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":Cr(e)}function Yc(t){return t==="raw"?"raw summary":"pretty text"}function Qc(t){return t?.sessionId?`session-${t.sessionId}`:null}function Xc(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},i=Qc(e);return s.filter(o=>!(!o||n.source==="currentOrchestration"&&i&&o.orchId!==i||n.level&&n.level!=="all"&&String(o.level||"").toLowerCase()!==n.level))}function Jc(t){const e=ms(t?.podName)||t?.podName||"node",s=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):""),n=String(t?.level||"info").toUpperCase(),i=t?.category==="orchestration"?"◆":t?.category==="activity"?"●":"•";return[{text:`[${t?.time||"--:--:--"}] `,color:"gray"},{text:`${i} `,color:kr(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${Z(s)}] `,color:"gray"}]:[],{text:`${n} `,color:Cr(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function Zc(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${Z(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:kr(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function eu(t,e){const s=t.logs||{},n=s.filter||{},i=[{text:"Scope: ",color:"gray"},{text:n.source==="currentOrchestration"?"current orchestration":"all nodes",color:"white"},{text:" Level: ",color:"gray"},{text:n.level||"all",color:"white"},{text:" Format: ",color:"gray"},{text:Yc(n.format),color:"white"}];if(!s.available)return[{text:s.availabilityReason||"Log tailing disabled: no K8S_CONTEXT configured in the env file.",color:"yellow"},{text:"",color:"gray"},i];if(!s.tailing)return[{text:"Press t to start log tailing.",color:"cyan",bold:!0},{text:"Press f to open log filters.",color:"gray"},{text:"",color:"gray"},i];const o=Xc(t,e);return o.length===0?[{text:"Tailing logs…",color:"cyan"},{text:"No logs match the current filter yet.",color:"gray"},{text:"",color:"gray"},i]:[i,{text:"",color:"gray"},...o.map(r=>n.format==="raw"?Jc(r):Zc(r))]}function ki(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function tu(t){return/\.(json|jsonl)$/i.test(String(t||""))}function su(t){return Te.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function nu(t=""){const e=String(t||"").split(`
50
+ `);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function Mi(t,{selected:e=!1,width:s=24,label:n=null}={}){const i=Math.max(8,s),o=ki(t)?"# ":tu(t)?"{ ":"• ",r=Mr(`${o}${n||t}`,i).padEnd(i," ");return e?Me(r):{text:r,color:ki(t)?"cyan":"white",bold:!1}}function xe(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function iu(t,e={}){if(!t)return new Set;const{childMap:s}=En(e),n=new Set([t]),i=[t];for(;i.length>0;){const o=i.shift(),r=s.get(o)||[];for(const a of r)!a||n.has(a)||(n.add(a),i.push(a))}return n}function as(t,e=xe(t)){const s=Ce(t)?.sessionId||null,n=Array.isArray(t.sessions?.flat)?t.sessions.flat.map(l=>l?.sessionId||l).filter(Boolean):[],i=Object.keys(t.files?.bySessionId||{}).filter(Boolean);if(e==="allSessions")return[...new Set([...n,...i])];const o=iu(s,t.sessions?.byId||{});if(o.size===0)return[];const r=[],a=new Set;for(const l of[s,...n,...Object.keys(t.sessions?.byId||{}),...i])!l||a.has(l)||!o.has(l)||(r.push(l),a.add(l));for(const l of o)a.has(l)||r.push(l);return r}function $t(t){const e=xe(t);Ce(t)?.sessionId;const s=t.files?.filter?.query||"",n=as(t,e),i=e==="allSessions"||n.length>1,o=[];for(const r of n){const a=ns(t.files?.bySessionId?.[r]?.entries);for(const l of a){const u=l.filename;o.push({id:`${r}/${u}`,sessionId:r,filename:u,entry:l,label:i?`[${Z(r)}] ${u}`:u})}}return o.filter(r=>Je(r.filename,s)||Je(r.sessionId,s)||Je(r.label,s))}function je(t){const e=$t(t);if(e.length===0)return null;const s=t.files?.selectedArtifactId||null;if(s){const r=e.find(a=>a.id===s);if(r)return r}if(xe(t)==="allSessions"){const r=Ce(t)?.sessionId||null,a=r&&t.files?.bySessionId?.[r]?.selectedFilename||null;if(r&&a){const l=e.find(u=>u.sessionId===r&&u.filename===a);if(l)return l}return e[0]}const i=Ce(t)?.sessionId||null,o=i&&t.files?.bySessionId?.[i]?.selectedFilename||null;return e.find(r=>r.sessionId===i&&r.filename===o)||e[0]}function On(t,e={}){const s=Ce(t),n=Math.max(12,Number(e?.listWidth)||Number(e?.width)||24),i=Math.max(18,Number(e?.previewWidth)||Number(e?.width)||36),o=e?.showHints!==!1,r=s?.sessionId||null,a=xe(t),l=t.files?.filter?.query||"",u=$t(t),f=je(t),d=f?.filename||null,p=Math.max(0,u.findIndex(F=>F.id===f?.id)),h=f?.sessionId&&d&&t.files?.bySessionId?.[f.sessionId]?.previews?.[d]||null,m=h||f?.entry||null,g=s?Z(s.sessionId):"",S=as(t,a),y=a!=="allSessions"&&S.some(F=>F&&F!==r),w=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(F=>F?.sessionId||F):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),I=a==="allSessions"&&w.some(F=>!t.files?.bySessionId?.[F]?.loaded||t.files?.bySessionId?.[F]?.loading),x=a==="allSessions"&&w.map(F=>t.files?.bySessionId?.[F]?.error).find(Boolean)||null,C=[su("files"),...s||a==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(a==="allSessions")I&&u.length===0?C.push({text:"Loading exported files across all sessions…",color:"gray"}):x&&u.length===0?C.push({text:x,color:"red"}):u.length===0?(C.push({text:l?`No artifacts matched "${l}" across any session.`:"No exported files across any session yet.",color:"gray"}),C.push({text:l?"Clear the query or switch back to the selected session.":"Switch the filter back to the selected session or wait for agents to export artifacts.",color:"gray"})):C.push(...u.map((F,Y)=>Mi(F.filename,{selected:Y===p,width:n,label:F.label})));else if(s){const F=r?t.files?.bySessionId?.[r]:null;Array.isArray(F?.entries)&&F.entries;const Y=u.filter(U=>S.includes(U.sessionId));F?.loading?C.push({text:"Loading exported files…",color:"gray"}):F?.error?C.push({text:F.error,color:"red"}):Y.length===0&&S.every(U=>{const V=t.files?.bySessionId?.[U]?.entries;return!Array.isArray(V)||V.length===0})?(C.push({text:l?`No artifacts matched "${l}" for this ${y?"session tree":"session"}.`:`No exported files for this ${y?"session tree":"session"} yet.`,color:"gray"}),C.push({text:l?"Clear the query or upload an artifact to this session.":y?"Artifacts exported by this session or any child session will appear here.":"Agents must write/export artifacts before they appear here.",color:"gray"})):C.push(...Y.map((U,V)=>Mi(U.filename,{selected:V===p,width:n,label:U.label})))}let v,k;!s&&a!=="allSessions"?(k=[{text:"Preview",color:"cyan",bold:!0}],v=[{text:"No session selected.",color:"gray"}]):d?h?.loading?(k=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||f?.sessionId&&f.sessionId!==r)&&f?.sessionId?[{text:` · ${Z(f.sessionId)}`,color:"gray"}]:[]],v=[{text:"Loading file preview…",color:"gray"}]):h?.error?(k=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||f?.sessionId&&f.sessionId!==r)&&f?.sessionId?[{text:` · ${Z(f.sessionId)}`,color:"gray"}]:[]],v=[{text:h.error,color:"red"}]):(k=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||f?.sessionId&&f.sessionId!==r)&&f?.sessionId?[{text:` · ${Z(f.sessionId)}`,color:"gray"}]:[],...h?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:h?.isBinary===!0?[{text:" [file]",color:"gray"}]:h?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],v=h?.renderMode==="markdown"?os(St(h?.content||"",{width:i})):nu(h?.content||"")):(k=[{text:"Preview",color:"cyan",bold:!0}],v=[{text:"Select a file to preview it here.",color:"gray"}]);const P=a==="allSessions"?"Files: all sessions":s?`Files: ${g}${y?" tree":""}`:"Files",O=a==="allSessions"?"all sessions":s?`${g}${y?" tree":""}`:"Files",M=a==="allSessions"?`Artifacts${u.length>0?` [${u.length}]`:""}`:`Artifacts${y?" tree":""}${u.length>0?` [${u.length}]`:""}`,$=l?` · @${l}`:"";return{panelTitle:[{text:`${P}${$}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${O}${$}`,color:"magenta",bold:!0}],listTitle:[{text:`${M}${$}`,color:"cyan",bold:!0}],listLines:C,listBodyLines:C.slice(1),selectedIndex:p,selectedFilename:d,selectedSessionId:f?.sessionId||null,scope:a,previewTitle:k,previewLines:v,previewContent:h?.content||"",previewContentType:h?.contentType||"",previewRenderMode:h?.renderMode||null,previewIsBinary:m?.isBinary===!0,previewSizeBytes:m?.sizeBytes??null,previewUploadedAt:m?.uploadedAt||"",previewSource:m?.source||null,previewError:h?.error||null,previewLoading:!!h?.loading,previewScrollOffset:t.ui.scroll.filePreview||0,fullscreen:!!t.files?.fullscreen,fullscreenTitle:[{text:P,color:"magenta",bold:!0},...d?[{text:" · ",color:"gray"},{text:d,color:"cyan",bold:!0}]:[],...o?[{text:" [f filter] [u upload] [a download] [x delete] [o open] [v/esc close fullscreen]",color:"gray"}]:[]]}}function ou(t){const e=t.admin||{},s=e.profile||null,n=e.ghcpKey||{editing:!1,draft:"",saving:!1,error:null},i=s?{provider:s.provider||"",subject:s.subject||"",email:s.email||null,displayName:s.displayName||null}:t.auth?.principal||null,o=e.systemGhcpKey||{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null},r=!!s?.isAdmin,a=r&&!!n.storeAsSystem,l=a?!!o.configured:!!s?.githubCopilotKeySet,u=a?"System key":"key",f=o.configured&&o.changedBy?` (set by ${o.changedBy})`:"",d=n.saving?"Saving...":n.editing?"Editing — Enter to save, Esc to cancel":a?o.configured?`System key configured — ownerless system sessions use it for GitHub Copilot models${f}`:"System key not configured — ownerless system sessions fall back to env GITHUB_TOKEN":s?.githubCopilotKeySet?"Configured (overrides env GITHUB_TOKEN for this user)":"Not configured (using env GITHUB_TOKEN fallback)",p=[];return n.editing?(p.push({id:"save",label:"Save",key:"Enter"}),p.push({id:"cancel",label:"Cancel",key:"Esc"})):(p.push({id:"edit",label:l?`Replace ${u}`:`Set ${u}`,key:"e"}),l&&p.push({id:"clear",label:`Clear ${u}`,key:"c"}),p.push({id:"refresh",label:"Refresh",key:"r"})),p.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:r,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:l,storeAsSystem:a,editing:!!n.editing,draft:n.draft||"",cursorIndex:Math.max(0,Math.min(Number(n.cursorIndex)||0,String(n.draft||"").length)),saving:!!n.saving,error:n.error||null,statusText:d},systemGhcpKey:{supported:!!o.supported,loading:!!o.loading,configured:!!o.configured,changedBy:o.changedBy||null,changedAt:o.changedAt||null,error:o.error||null},actions:p}}function ru(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=Ce(t),i=!!n?.pendingQuestion?.question,o=n?.sessionId&&Array.isArray(t.outbox?.bySessionId?.[n.sessionId])?t.outbox.bySessionId[n.sessionId]:[],r=o.length>0,a=o.some(w=>w?.phase==="pending"),l=t.ui.promptEdit?.sessionId===n?.sessionId,u=l&&t.ui.promptEdit?.phase==="queued",f=l&&t.ui.promptEdit?.phase==="cancelling",d=s===e?"v/esc close fullscreen":"v fullscreen";if(t.ui.modal?.type==="artifactUpload")return{left:"Upload a local file into this session's artifact store",right:"type path · left/right move · enter upload · esc cancel"};if(t.ui.modal?.type==="renameSession")return{left:"Rename the selected session title",right:"type title · left/right move · enter save · esc cancel"};if(t.ui.modal?.type==="shareSession")return{left:"Share the selected session",right:"name [r|w] grants · -name revokes · enter apply · esc close"};if(t.ui.modal?.type==="artifactPicker")return{left:"Select a linked artifact or URL",right:"up/down move · enter open/download · a/esc close"};if(t.ui.modal?.type==="modelPicker")return{left:"Select a model for the new session",right:"up/down move · enter next · esc cancel"};if(t.ui.modal?.type==="reasoningEffortPicker")return{left:"Select reasoning effort for the new session",right:"up/down move · enter create · esc cancel"};if(t.ui.modal?.type==="themePicker")return{left:"Select a shared portal/TUI theme",right:"up/down move · enter apply · esc close"};if(t.ui.modal?.type==="sessionAgentPicker")return{left:"Select an agent for the new session",right:"up/down move · enter create · esc cancel"};if(t.ui.modal?.type==="sessionGroupPicker")return{left:"Move selected session(s) to a group",right:"up/down move · enter choose · esc cancel"};if(t.ui.modal?.type==="sessionGroupName")return{left:"Name the new group",right:"type name · left/right move · enter create · esc cancel"};if(t.ui.modal?.type==="logFilter")return{left:"Adjust log filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="filesFilter")return{left:"Adjust files browser filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="sessionOwnerFilter")return{left:"Adjust session filters",right:"up/down choose · space toggle · esc close"};const p=!!t.sessions?.selectMode,h=Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds.length:0;if(p&&e===A.SESSIONS)return{left:`Select mode · ${h} selected`,right:"up/down move · space toggle · ctrl-g group · c cancel · d complete · D hard delete · V/esc exit"};const g=(t.ui?.chatViewMode==="summary"?"summary":"transcript")==="summary"?"s transcript":"s summary",S={[A.SESSIONS]:"up/down switch · ctrl-u/ctrl-d page · ctrl-g move group · f filter · P pin · V select · d done · D delete · r refresh · t title · v visibility · S share · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane · p prompt",[A.CHAT]:`${g} · j/k scroll · ctrl-u/ctrl-d page · e older history · g/G top/bottom · d done · ${d} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane · p prompt`,[A.INSPECTOR]:t.ui.inspectorTab==="logs"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · t tail · f filter · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane`:t.ui.inspectorTab==="stats"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f cycle session/fleet/users · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:t.ui.inspectorTab==="files"?t.files?.fullscreen?"a download · x delete · u/ctrl-a upload · o open · f filter · j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · v/esc close fullscreen · left/right tab · [/] resize pane · {/} columns · T themes · ? help · tab next pane":"j/k files · a download · x delete · u/ctrl-a upload · o open · f filter · ctrl-u/ctrl-d page preview · g/G preview top/bottom · d done · v fullscreen · left/right tab · [/] resize pane · {/} columns · T themes · ? help · tab next pane":t.ui.inspectorTab==="history"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f format · r refresh · a save artifact · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:t.ui.inspectorTab==="sequence"?`j/k turn · enter expand · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · h/l focus · a linked items · drag copy · m next tab · tab next pane`,[A.ACTIVITY]:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · h left · tab next pane`,[A.PROMPT]:i?`type answer · enter reply · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:l?u?`queued prompt selected · d delete · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:f?`cancelling prompt selected · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:`edit pending prompt · enter send batch · up/down cycle pending · esc cancel · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:a?`type message · enter queues · enter on empty sends batch · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:r?`type message · enter queues behind durable items · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:`type message · enter send · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`};let y=S[e]||S[A.SESSIONS];return yr(Ce(t))&&(y=`ctrl-x stop · ${y}`),{left:t.ui.statusText,right:y}}function st(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function X(t,e){if(e<=0)return[];const s=[];let n=e;for(const i of t||[]){if(n<=0)break;const o=String(i?.text||"");if(!o)continue;const r=o.length>n&&n>1?`${o.slice(0,n-1)}…`:o.slice(0,n);r&&(s.push({...i,text:r}),n-=r.length)}return s}function Re(t){return Array.from(String(t||"")).length}function Mr(t,e){const s=String(t||"");return e<=0?"":Re(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function Ve(t,e){const s=Mr(t,e),n=Math.max(0,e-Re(s));return s+" ".repeat(n)}function G(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function le(t){const e=Number(t);if(!Number.isFinite(e)||e<0)return"?";if(e<1024)return`${Math.round(e)} B`;if(e<1024*1024){const n=e/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=e/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function Ni(t,e){const s=Number(t),n=Number(e);if(!Number.isFinite(s)||!Number.isFinite(n)||s<=0||n<=0)return null;const i=s/n;return`${i>=10?i.toFixed(0):i.toFixed(1)}×`}function Nr(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?Re(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function au(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 Pr(t=[]){const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();if(!i)continue;const o=i.toLowerCase();e.has(o)||(e.add(o),s.push(i))}return s.join(" | ")}function lu(t,e=""){return Pr([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function cu(t,e=""){return Pr([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function ms(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 uu=300*1e3,du="last 5m";function Rn(t){let e=0;for(const s of t.history.bySessionId.values())for(const n of s?.events||[]){const i=n?.createdAt instanceof Date?n.createdAt.getTime():new Date(n?.createdAt||0).getTime();Number.isFinite(i)&&(e=Math.max(e,i))}return(!Number.isFinite(e)||e<=0)&&(e=Date.now()),{startMs:e-uu,endMs:e,label:du}}function fu(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 _r(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 pu=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done"]);function hu(t){return pu.has(t)}function mu(t){const e=pe(t?.createdAt),s=ms(t?.workerNodeId),n=au(t),i=Nr(n,20),o=t?.createdAt instanceof Date?t.createdAt.getTime():new Date(t?.createdAt||0).getTime(),r={time:e,createdAtMs:Number.isFinite(o)?o:0,nodeLabel:s,color:"white",detail:"",type:"other"};switch(t?.eventType){case"session.turn_started":return{...r,type:"turn_start",color:"gray",detail:`turn ${t?.data?.iteration??"?"}`};case"session.turn_completed":{const a=Number(t?.data?.turnIndex??t?.data?.iteration);return{...r,type:"turn_end",color:"gray",detail:`turn ${t?.data?.iteration??"?"} done`,...Number.isFinite(a)?{completedTurn:a}:{}}}case"user.message":return{...r,type:"user_msg",color:"white",detail:i?`>> ${i}`:">> user"};case"assistant.message":return{...r,type:"response",color:"green",detail:i?`< ${i}`:"< response"};case"system.message":return{...r,type:"system",color:"yellow",detail:i||"system"};case"session.wait_started":return{...r,type:"wait",color:"yellow",detail:`wait ${Pt(t?.data?.seconds??0)}`};case"session.wait_completed":return{...r,type:"timer",color:"yellow",detail:`${Pt(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const a=cu(t,i);return{...r,type:"dehydrate",color:"yellow",detail:a?`lossy ${a}`:"lossy handoff"}}case"session.dehydrated":return{...r,type:"dehydrate",color:"cyan",detail:`ZZ ${lu(t,i)}`.trim()};case"session.rehydrated":case"session.hydrated":return{...r,type:"hydrate",color:"green",detail:"rehydrated"};case"session.agent_spawned":return{...r,type:"spawn",color:"cyan",detail:`spawn ${t?.data?.agentId||Z(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...r,type:"cron_start",color:"magenta",detail:`cron ${Pt(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...r,type:"cron_start",color:"magenta",detail:`cron ${Js(t?.data?.nextFireAtMs??t?.data?.nextFireAt)}`};case"session.cron_fired":return{...r,type:"cron_fire",color:"magenta",detail:"cron fired"};case"session.cron_at_fired":return{...r,type:"cron_fire",color:"magenta",detail:`cron fired ${Js(t?.data?.scheduledAt)}`};case"session.cron_cancelled":case"session.cron_at_cancelled":return{...r,type:"cron_cancel",color:"magenta",detail:"cron off"};case"session.cron_at_completed":return{...r,type:"cron_cancel",color:"magenta",detail:"cron done"};case"session.command_received":return{...r,type:"cmd_recv",color:"magenta",detail:`/${t?.data?.cmd||"?"}`};case"session.command_completed":return{...r,type:"cmd_done",color:"magenta",detail:`/${t?.data?.cmd||"?"} ok`};case"session.compaction_start":return{...r,type:"compaction",color:"gray",detail:"compaction…"};case"session.compaction_complete":return{...r,type:"compaction",color:"gray",detail:"compacted"};case"session.error":return{...r,type:"error",color:"red",detail:i||"error"};default:return null}}function Or(t=[]){const e=[];for(const s of t||[]){const n=mu(s);n&&e.push({...n,nodeLabel:hu(n.type)?"orch":n.nodeLabel||"orch"})}return e}function gu(t=[]){const e=[];for(let s=0;s<t.length;s+=1){const n=t[s];if(n?.type!=="spawn"||n?.nodeLabel!=="orch"){e.push(n);continue}let i=1;for(;s+i<t.length;){const o=t[s+i];if(o?.type!=="spawn"||o?.nodeLabel!=="orch"||o?.time!==n.time)break;i+=1}if(i===1){e.push(n);continue}e.push({...n,detail:`spawn x${i}`}),s+=i-1}return e}function yu(t){const e=String(t?.error||"").trim();if(!e)return null;const s=In(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),i=Number.isFinite(n)?n:Date.now();return{time:pe(i),createdAtMs:i,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${Nr(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function Su(t,e){const s=yu(e);return!s||(t||[]).some(i=>!i||i.nodeLabel!=="orch"||i.detail!==s.detail?!1:Math.abs(Number(i.createdAtMs||0)-s.createdAtMs)<=6e4)?t:[...t||[],s]}function bu(t,e,s){if(!Number.isFinite(e)||!Number.isFinite(s)||s<e)return[];const n=new Set;for(const i of t.history.bySessionId.values()){const o=Or(i?.events||[]);for(const r of o){if(!r?.nodeLabel||r.nodeLabel==="orch")continue;const a=Number(r.createdAtMs||0);Number.isFinite(a)&&(a<e||a>s||n.add(r.nodeLabel))}}return Array.from(n).sort((i,o)=>i.localeCompare(o))}function wu(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const i of n?.events||[]){if(!_r(i,e))continue;const o=ms(i?.workerNodeId);o&&s.add(o)}return Array.from(s).sort((n,i)=>n.localeCompare(i))}function Iu(t,e,s){const n=[{text:Ve("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((i,o)=>{o>0&&n.push({text:" ",color:null}),n.push({text:Ve(i,s),color:"white",bold:!0})}),n}function xu(t,e,s){return G(`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`,"gray")}function vu(t,e,s){const n=t?.orchestration?.bySessionId?.[e?.sessionId]||null;let i="loading orchestration stats...";if(n)if(n.loading&&!n.stats)i="loading orchestration stats...";else if(!n.stats)i="orchestration stats unavailable";else{const o=n.stats,r=[],a=[];if(typeof o.orchestrationVersion=="string"&&o.orchestrationVersion&&(r.push(`v ${o.orchestrationVersion}`),a.push(`v${o.orchestrationVersion}`)),o.historyEventCount!=null&&(r.push(`hist ${Number(o.historyEventCount)||0} ev`),a.push(`h${Number(o.historyEventCount)||0}`)),o.historySizeBytes!=null){const l=le(o.historySizeBytes);r.push(l),a.push(l)}o.queuePendingCount!=null&&(r.push(`q ${Number(o.queuePendingCount)||0}`),a.push(`q${Number(o.queuePendingCount)||0}`)),o.kvUserKeyCount!=null&&(r.push(`kv ${Number(o.kvUserKeyCount)||0} keys`),a.push(`kv${Number(o.kvUserKeyCount)||0}`)),o.kvTotalValueBytes!=null&&r.push(le(o.kvTotalValueBytes)),i=s<=40?a.join(" · "):r.join(" | "),i||(i="orchestration stats unavailable")}return s<=52?[X([{text:"Stats ",color:"cyan",bold:!0},{text:i,color:"white"}],Math.max(18,s))]:ne({title:"Stats",body:i,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function Eu(t,e,s,n){const i=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],o=[{text:Ve(t.time||"",s),color:"white"},{text:" ",color:null}];return e.forEach((r,a)=>{a>0&&o.push({text:" ",color:null}),r===i?o.push({text:Ve(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):o.push({text:Ve("│",n),color:"gray"})}),o}function Au(t,e){const s=[];return t.forEach((n,i)=>{i>0&&s.push({text:" ",color:null}),s.push({text:Ve(n,e),color:"white",bold:!0})}),s}const Tu=new Set(["none","minimal","low","medium","high","xhigh","max"]);function Cu(t){const e=String(t||"").trim();if(!e)return"unknown";const s=e.split(":").filter(Boolean);if(s.length===0)return"unknown";const n=String(s[s.length-1]).toLowerCase(),i=s.length>1&&Tu.has(n)?s.length-2:s.length-1;return s[Math.max(0,i)]||s[0]||"unknown"}function Pi(t){const e=Number(t||0);if(!Number.isFinite(e))return"?K";const s=e/1e3;return`${s.toFixed(Math.abs(s)>=10?1:2)}K`}function Qe(t){return Number(t||0).toLocaleString("en-US")}function ku(t){const e=new Map;for(const s of t||[]){if(s?.eventType!=="session.turn_completed")continue;const n=Number(s?.data?.turnIndex??s?.data?.iteration);Number.isFinite(n)&&e.set(n,s.data||{})}return e}function Mu(t,{expanded:e,selected:s,maxWidth:n}){const i=e?"v":">",o=Cu(t?.model),r=t?.durationMs!=null?`${(Number(t.durationMs)/1e3).toFixed(1)}s`:"n/a",a=`${i} Mod: ${o} tok ${Pi(t?.tokensInput)}/${Pi(t?.tokensOutput)} dur ${r}`,l=[];if(s?l.push(Me(Ve(a,Math.max(18,n)))):l.push([{text:a,color:"magenta"}]),e){const u=[["model",t?.reasoningEffort?`${t?.model||"(unknown)"}:${t.reasoningEffort}`:t?.model||"(unknown)"],["duration",t?.durationMs!=null?`${Qe(t.durationMs)} ms`:null],["tokens",`${Qe(t?.tokensInput)} in / ${Qe(t?.tokensOutput)} out`],["cache",`${Qe(t?.tokensCacheRead)} read / ${Qe(t?.tokensCacheWrite)} write`],["tools",`${Qe(t?.toolCalls)} calls / ${Qe(t?.toolErrors)} errors`],["names",Array.isArray(t?.toolNames)&&t.toolNames.length?t.toolNames.join(", "):null],["worker",t?.workerNodeId||null],["result",t?.resultType||null],["error",t?.errorMessage||null]].filter(([,f])=>f!=null&&f!=="");for(const[f,d]of u)l.push([{text:` ${f}: `,color:"gray"},{text:String(d),color:"white"}])}return l}function Nu(t,e,s,n={}){const i=!!n?.allowWideColumns,o=vu(t,e,s),r=t.history.bySessionId.get(e.sessionId),a=Su(gu(Or(r?.events||[])),e);if(a.length===0)return{stickyLines:o,lines:[G("No events yet - interact with this session to populate the sequence diagram.")]};const l=Rn(t),u=a.filter(O=>fu(O,l)),f=(u.length>0?u:a).slice(-48),d=bu(t,l.startMs,l.endMs),p=Array.from(new Set(f.map(O=>O.nodeLabel).filter(O=>O&&O!=="orch"))).sort((O,M)=>O.localeCompare(M)),h=d.length>0?d:p,m=8,g=Math.max(18,s),S=Math.max(1,Math.floor((g-m-1)/6));let y=["orch",...h];if(!i&&y.length>S){const O=Math.max(1,S-1);y=[...y.slice(0,O),"…"]}const w=Math.max(0,y.length-1),I=Math.max(4,Math.floor((g-m-1-w)/Math.max(1,y.length))),x=n?.sequenceExpansion||null,C=x?ku(r?.events||[]):null,v=x?new Set((x.expandedTurns||[]).map(Number)):null,k=x&&x.selectedTurn!=null?Number(x.selectedTurn):null,P=[];for(const O of f)if(P.push(Eu(O,y,m,I)),x&&O.completedTurn!=null){const M=Number(O.completedTurn),$=C.get(M);if($)for(const F of Mu($,{expanded:v.has(M),selected:k===M,maxWidth:g}))P.push(F)}return{stickyLines:[...o,G(`Window: ${l.label}`,"gray"),Iu(y,m,I),xu(y,m,I)],lines:P}}function Pu(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 _u(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!_r(s[n],e))continue;const i=ms(s[n]?.workerNodeId);if(i)return i}return null}function Ou(t,e,s,n){const i=s>=16?t?.isSystem?It(t,e):t?.title||Z(t?.sessionId):Z(t?.sessionId),o=t?.isSystem?"⚙ ":t?.serviceKind?"⚗ ":`${ur(t)||"."} `,r=Ve(`${o}${i}`,s);return n?Me(r):{text:r,color:t?.isSystem?"yellow":gt(t),bold:!!t?.isSystem}}function Ru(t,e,s={}){const n=!!s?.allowWideColumns,i=Pu(t);if(i.length===0)return[G("No sessions available for the node map.","gray")];const o=Rn(t),r=new Map,a=wu(t,o);let l=0,u=0;for(const y of i){const w=t.sessions.byId[y];if(!w)continue;const I=t.history.bySessionId.get(y);I?.events||(l+=1);const x=_u(I,o);!x||!a.includes(x)||(u+=1,r.has(x)||r.set(x,[]),r.get(x).push(w))}if(a.length===0)return[G(`No worker activity in the ${o.label} window.`,"gray")];const f=Math.max(18,e),d=Math.max(1,Math.floor((f+1)/10));let p=a;if(!n&&a.length>d){const y=Math.max(0,d-1),w=[],I=a.slice(0,y);for(const x of a.slice(y))w.push(...r.get(x)||[]);r.set("…",w),p=[...I,"…"]}const h=Math.max(0,p.length-1),m=Math.max(8,Math.floor((f-h)/Math.max(1,p.length))),g=p.reduce((y,w)=>Math.max(y,(r.get(w)||[]).length),0),S=[G(`Window: ${o.label}`,"gray"),Au(p,m),G(p.map(()=>"─".repeat(m)).join(" "),"gray")];for(let y=0;y<g;y+=1){const w=[];p.forEach((I,x)=>{x>0&&w.push({text:" ",color:null});const C=(r.get(I)||[])[y];if(!C){w.push({text:" ".repeat(m),color:null});return}w.push(Ou(C,t.branding?.title||"PilotSwarm",m,C.sessionId===t.sessions.activeSessionId))}),S.push(w)}return l>0&&(S.push(G("","gray")),S.push(G(`Loading worker history for ${l} session(s)…`,"gray"))),u===0&&(S.push(G("","gray")),S.push(G(`No sessions mapped onto worker nodes in the ${o.label} window.`,"gray"))),S}function Lu(t,e=72){const s=t.ui.modal;if(!s||s.type!=="modelPicker")return null;const n=Array.isArray(s.groups)?s.groups:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(24,e-4),r=[],a=[];let l=0;for(const h of n){const m=X([{text:`${h.providerId}`,color:"cyan",bold:!0},{text:` (${h.providerType||"provider"})`,color:"gray"}],o);r.push(m),a.push(null);for(const g of h.models||[]){const S=Array.isArray(s.items)?s.items.findIndex(C=>C.id===g.id):-1,y=S===i,w=!!g.disabled,I=X([{text:"· ",color:"gray"},{text:g.modelName||g.qualifiedName||g.id,color:w?"gray":"white",bold:!!g.isDefault&&!w},...g.cost?[{text:` [${g.cost}]`,color:"gray"}]:[],...w?[{text:" ⊘ needs GitHub key",color:"yellow"}]:[],...g.isDefault?[{text:" ← current default",color:"gray"}]:[]],o),x=y?Me(I.map(C=>C.text).join("").padEnd(o," ")):I;y&&(l=r.length),r.push(x),a.push(S>=0?S:null)}}const u=Array.isArray(s.items)&&s.items[i]||null,f=Array.isArray(u?.supportedReasoningEfforts)?u.supportedReasoningEfforts.filter(Boolean):[],d=typeof u?.defaultReasoningEffort=="string"?u.defaultReasoningEffort:null,p=u?[[{text:u.modelName||u.qualifiedName||u.id,color:"white",bold:!0}],[{text:`${u.providerId} (${u.providerType||"provider"})`,color:"gray"}],...u.cost?[[{text:`Cost: ${u.cost}`,color:"gray"}]]:[],...f.length>0?[[{text:`Reasoning: ${f.join(", ")}`,color:"gray"}]]:[],...d?[[{text:`Default reasoning: ${d}`,color:"gray"}]]:[],...u.disabled?[[{text:"Unavailable: requires a GitHub Copilot key. Add yours in the Admin console, then reopen this picker.",color:"yellow"}]]:[],[{text:"",color:"gray"}],[{text:u.description||"No description available for this model.",color:u.description?"white":"gray"}]]:[[{text:"No model selected.",color:"gray"}]];return{title:s.title||"Select model for new session",rows:r,rowItemIndexes:a,selectedRowIndex:l,detailsTitle:"Model Details",detailsLines:p,idealWidth:Math.min(Math.max(46,r.reduce((h,m)=>Array.isArray(m)?Math.max(h,st(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function $u(t,e=76){const s=t.ui.modal;if(!s||s.type!=="sessionAgentPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(24,e-4),r=n.map((d,p)=>{const h=p===i,m=X([{text:d?.kind==="generic"?"○ ":"· ",color:"gray"},{text:d?.title||d?.agentName||d?.id||"Agent",color:"white",bold:!0},...d?.kind==="generic"?[{text:" [generic]",color:"gray"}]:[{text:` (${d?.agentName||d?.id||"agent"})`,color:"gray"}]],o);return h?Me(m.map(g=>g.text).join("").padEnd(o," ")):m}),a=n[i]||null,l=s.sessionOptions?.model||null,u=s.sessionOptions?.reasoningEffort||null,f=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"}]]:[],...u?[[{text:`Reasoning: ${u}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:a.description||(a.kind==="generic"?"Create a general-purpose session without a specialized named agent.":"No description available for this agent."),color:a.description?"white":"gray"}],[{text:"",color:"gray"}],[{text:a.tools?.length?`Tools: ${a.tools.join(", ")}`:"Tools: system defaults only",color:"gray"}]]:[[{text:"No agent selected.",color:"gray"}]];return{title:s.title||"Select agent for new session",rows:r,selectedRowIndex:i,detailsTitle:"Agent Details",detailsLines:f,idealWidth:Math.min(Math.max(52,r.reduce((d,p)=>Array.isArray(p)?Math.max(d,st(p)):Math.max(d,String(p?.text||"").length),0)+4),e)}}function Fu(t,e=64){const s=t.ui.modal;if(!s||s.type!=="reasoningEffortPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(24,e-4),r=n.map((f,d)=>{const p=d===i,h=X([{text:"· ",color:"gray"},{text:String(f?.label||f?.id||"effort"),color:"white",bold:!0},...f?.isDefault?[{text:" ← model default",color:"gray"}]:[]],o);return p?Me(h.map(m=>m.text).join("").padEnd(o," ")):h}),a=n[i]||null,l=s.modelItem||null,u=[[{text:l?.modelName||l?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${l?.providerId||"provider"} (${l?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:a?.id?`Using reasoning effort: ${a.id}`:"Choose an effort.",color:"white"}]];return{title:s.title||"Select reasoning effort",rows:r,selectedRowIndex:i,detailsTitle:"Reasoning Details",detailsLines:u,idealWidth:Math.min(Math.max(46,r.reduce((f,d)=>Array.isArray(d)?Math.max(f,st(d)):Math.max(f,String(d?.text||"").length),0)+4),e)}}function Bu(t,e=64){const s=t.ui.modal;if(!s||s.type!=="contextTierPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(24,e-4),r=n.map((d,p)=>{const h=p===i,m=X([{text:"· ",color:"gray"},{text:String(d?.label||d?.id||"tier"),color:"white",bold:!0},...d?.isDefault?[{text:" ← model default",color:"gray"}]:[]],o);return h?Me(m.map(g=>g.text).join("").padEnd(o," ")):m}),a=n[i]||null,l=s.modelItem||null,u=a?.label||a?.id,f=[[{text:l?.modelName||l?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${l?.providerId||"provider"} (${l?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:u?`Using context window: ${u}`:"Choose a context window.",color:"white"}],[{text:"Long context costs more per token.",color:"gray"}]];return{title:s.title||"Select context window",rows:r,selectedRowIndex:i,detailsTitle:"Context Window",detailsLines:f,idealWidth:Math.min(Math.max(46,r.reduce((d,p)=>Array.isArray(p)?Math.max(d,st(p)):Math.max(d,String(p?.text||"").length),0)+4),e)}}function Du(t,e=72){const s=t.ui.modal;if(!s||s.type!=="sessionGroupPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(24,e-4),r=Array.isArray(s.sessionIds)?s.sessionIds.length:0,a=n.map((f,d)=>{const p=d===i,h=f?.kind==="noGroup"?"○ ":f?.kind==="newGroup"?"+ ":"🗂 ",m=X([{text:h,color:f?.kind==="group"?"cyan":"gray",bold:f?.kind!=="noGroup"},{text:f?.label||f?.groupId||"Group",color:"white",bold:!0},...f?.kind==="group"?[{text:` (${f.memberCount??0})`,color:"gray"}]:[]],o);return p?Me(m.map(g=>g.text).join("").padEnd(o," ")):m}),l=n[i]||null,u=l?[[{text:l.label||l.groupId||"Group",color:"white",bold:!0}],[{text:`${r} session${r===1?"":"s"} selected`,color:"gray"}],...l.kind==="group"?[[{text:`${l.memberCount??0} current member${l.memberCount===1?"":"s"}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:l.description||"Move selected session(s) to this group.",color:"white"}]]:[[{text:"No group selected.",color:"gray"}]];return{title:s.title||"Move to Group",rows:a,selectedRowIndex:i,detailsTitle:"Move Details",detailsLines:u,idealWidth:Math.min(Math.max(50,a.reduce((f,d)=>Array.isArray(d)?Math.max(f,st(d)):Math.max(f,String(d?.text||"").length),0)+4),e)}}function Hu(t,e=76){const s=t.ui.modal;if(!s||s.type!=="renameSession")return null;const n=String(s.value||""),i=typeof s.agentTitlePrefix=="string"&&s.agentTitlePrefix.trim()?s.agentTitlePrefix.trim():null,o=String(s.currentTitle||"").trim(),r=n.trim()?i?`${i}: ${n.trim()}`:n.trim():i?`${i}: …`:"…",a=[[{text:"Current: ",color:"gray"},{text:o||"(untitled session)",color:o?"white":"gray"}],[{text:"Saved as: ",color:"gray"},{text:r,color:"white",bold:!0}],...i?[[{text:"Named-agent prefix stays fixed.",color:"gray"}]]:[]];return{title:s.title||"Rename Session",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:i?"Type the title after the fixed agent name":"Type a session title",helpTitle:"Rename Rules",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" save ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],[{text:"Manual titles stop future automatic LLM title changes for this session.",color:"gray"}]],detailsLines:a,idealWidth:Math.min(Math.max(56,Re(o||"(untitled session)")+18,Re(r)+18),e)}}function Gu(t,e=76){const s=t.ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=String(s.value||""),i=Array.isArray(s.sessionIds)?s.sessionIds.length:0,o=n.trim()||"…";return{title:s.title||"New Group",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:"Type a group name",helpTitle:"Group Name",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" create and move ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],[{text:`The new group will contain ${i} selected session${i===1?"":"s"}.`,color:"gray"}]],detailsLines:[[{text:"New group: ",color:"gray"},{text:o,color:"white",bold:!0}],[{text:"Groups are containers only; session actions remain per-session.",color:"gray"}]],idealWidth:Math.min(Math.max(56,Re(o)+18),e)}}function Uu(t,e=82){const s=t.ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=String(s.value||""),i=s.sessionId||t.ui.promptAttachments?.[0]?.sessionId||t.sessions?.activeSessionId||null,o=i&&t.sessions?.byId?.[i]||null,r=i?o?fr(o,t.branding?.title):Z(i):"A new session will be created on upload",a=[[{text:"Target: ",color:"gray"},{text:r,color:i?"white":"gray",bold:!!i}]];return{title:s.title||"Upload Artifact",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:"~/path/to/file.md",helpTitle:"Upload Rules",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" upload ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],[{text:"The file is uploaded into this session's artifact store immediately.",color:"gray"}],[{text:"Use the files browser or @-driven browsing in the prompt to reference it after upload.",color:"gray"}]],detailsLines:a,idealWidth:Math.min(Math.max(60,Re(n||"~/path/to/file.md")+20,Re(r)+20),e)}}function Ln(t,e={},s=96,n="Filters",i="Choose how this pane is filtered and rendered."){const o=Array.isArray(t.items)?t.items:[],r=Math.max(0,Number(t.selectedIndex)||0),a=o[r]||null,l=o.map((u,f)=>{const d=e?.[u.id]||u.options?.[0]?.id,p=(u.options||[]).map(h=>h.id===d?Me(h.label):{text:h.label,color:"white"});return{id:u.id,title:u.label,focused:f===r,description:u.description||"",lines:p.length>0?p:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(u.label||"").length+4,...(u.options||[]).map(h=>String(h?.label||"").length+4))}});return{title:t.title||n,panes:l,helpTitle:a?.label||n,helpLines:[[{text:a?.description||i,color:"white"}],[{text:"",color:"gray"}],[{text:"Tab/Shift-Tab",color:"cyan",bold:!0},{text:" switch filter ",color:"gray"},{text:"Up/Down",color:"cyan",bold:!0},{text:" change value ",color:"gray"},{text:"Enter",color:"cyan",bold:!0},{text:" close ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}]],footerRuns:[{text:"Tab/Shift-Tab",color:"cyan",bold:!0},{text:" switch filter · ",color:"gray"},{text:"Up/Down",color:"cyan",bold:!0},{text:" change value · ",color:"gray"},{text:"Enter",color:"cyan",bold:!0},{text:" close · ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],idealWidth:Math.min(Math.max(72,l.reduce((u,f)=>u+f.idealWidth,0)+Math.max(0,l.length-1)*2+4),s)}}function Rr(t,e={},s={}){return t?t.kind==="all"?e?.all===!0:e?.all===!0?!1:t.kind==="system"?e?.includeSystem===!0:t.kind==="unowned"?e?.includeUnowned===!0:t.kind==="me"?e?.includeMe===!0&&!!ue(s?.principal):t.kind==="shared"?e?.includeShared===!0:t.kind==="owner"?Array.isArray(e?.ownerKeys)&&e.ownerKeys.includes(t.ownerKey):!1:!1}function _i(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(i=>i?.kind!=="all"&&Rr(i,e,s)).map(i=>i.kind==="me"?"Me":i.label);return n.length>0?n.join(" + "):"All sessions"}function ju(t,e=88){const s=t.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return null;const n=Array.isArray(s.items)?s.items:[],i=t.sessions?.ownerFilter||{all:!0},o=t.auth||{},r=Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1))),a=n[r]||null,l=n.map((f,d)=>{const p=Rr(f,i,o),h=f.kind==="system"?"yellow":f.kind==="unowned"?"gray":f.kind==="all"?"cyan":"white",m=[{text:p?"[x] ":"[ ] ",color:p?"cyan":"gray",bold:p},{text:f.label||f.id,color:h,bold:p}];return d===r?or(m,{preserveColors:!0}):m}),u=[[{text:"Active: ",color:"gray"},{text:_i(n,i,o),color:"white",bold:!0}],[{text:"",color:"gray"}],[{text:a?.description||"Toggle which session owners appear in the session list.",color:"white"}],[{text:"",color:"gray"}],[{text:"Space",color:"cyan",bold:!0},{text:" toggle ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" close",color:"gray"}]];return{title:s.title||"Session Filter",rows:l.length>0?l:[{text:"No filter entries available.",color:"gray"}],selectedRowIndex:r,detailsTitle:a?.label||"Session Filter",detailsLines:u,idealWidth:Math.min(Math.max(48,l.reduce((f,d)=>Math.max(f,Array.isArray(d)?st(d):Re(d?.text||"")),0)+8,Re(_i(n,i,o))+16),e)}}function Wu(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:Ln(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function Ku(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:Ln(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function Vu(t,e=88){const s=t.ui.modal;if(!s||s.type!=="artifactPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=Math.max(28,e-4),r=n.filter(h=>h.kind==="artifact"),a=n.filter(h=>h.kind==="url"),l=r.reduce((h,m)=>{const g=t.files?.bySessionId?.[m.sessionId]?.downloads?.[m.filename];return h+(g?.localPath?1:0)},0),u=Math.max(0,r.length-l),f=n.map((h,m)=>{let g;if(h.kind==="downloadAll")g=X([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${u} pending]`,color:"gray"}],o);else if(h.kind==="url")g=X([{text:"go ",color:"cyan",bold:!0},{text:h.text&&h.text!==h.href?h.text:h.href,color:"white",bold:!0},...h.text&&h.text!==h.href?[{text:` ${h.href}`,color:"gray"}]:[]],o);else{const S=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];g=X([{text:S?.localPath?"ok ":"dl ",color:S?.localPath?"green":"cyan",bold:!0},{text:`${Z(h.sessionId)}/`,color:"gray"},{text:h.filename,color:"white"}],o)}return m!==i?g:Me(g.map(S=>S.text).join("").padEnd(o," "))}),d=n[i]||null;let p=[[{text:"No linked item selected.",color:"gray"}]];if(d?.kind==="downloadAll")p=[[{text:`${r.length} artifacts available`,color:"white",bold:!0}],...a.length>0?[[{text:`${a.length} links available`,color:"gray"}]]:[],[{text:`${l} already downloaded`,color:"gray"}],[{text:`${u} pending download`,color:"gray"}],...s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:"Press Enter to download all pending artifacts.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(d?.kind==="url")p=[[{text:d.text||d.href,color:"white",bold:!0}],[{text:d.href,color:"gray"}],[{text:"",color:"gray"}],[{text:"Press Enter to open this link in the browser.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(d?.kind==="artifact"){const h=t.sessions?.byId?.[d.sessionId]||null,m=t.files?.bySessionId?.[d.sessionId]?.downloads?.[d.filename]||null;p=[[{text:d.filename,color:"white",bold:!0}],[{text:h?fr(h,t.branding?.title):Z(d.sessionId),color:"gray"}],...m?.localPath?[[{text:`Saved to: ${m.localPath}`,color:"white"}]]:s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:m?.localPath?"Press Enter to download this artifact again.":"Press Enter to download this artifact.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]]}return{title:s.title||"Linked Items",rows:f.length>0?f:[{text:"No linked items available.",color:"gray"}],selectedRowIndex:i,detailsTitle:"Linked Item Details",detailsLines:p,confirmLabel:a.length>0?r.length>0?"Open / Download":"Open":"Download",idealWidth:Math.min(Math.max(54,f.reduce((h,m)=>Array.isArray(m)?Math.max(h,st(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function j(t){return t==null||!Number.isFinite(t)?"0":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e4?`${(t/1e3).toFixed(1)}K`:t>=1e3?t.toLocaleString("en-US"):String(t)}function Lr(t){if(!t)return"—";const e=Date.now()-t;return e<6e4?`${Math.max(1,Math.floor(e/1e3))}s ago`:e<36e5?`${Math.floor(e/6e4)}m ago`:e<864e5?`${Math.floor(e/36e5)}h ago`:`${Math.floor(e/864e5)}d ago`}function qu(t){if(!t)return"—";const e=Date.now()-t;if(e<6e4)return"<1min";const s=Math.floor(e/6e4);if(s<60)return`${s}min`;const n=Math.floor(s/60);if(n<24)return`${n}h${String(s%60).padStart(2,"0")}m`;const i=Math.floor(n/24);return i<14?`${i}d${String(n%24).padStart(2,"0")}h`:`${Math.floor(i/7)}w`}function jt(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);return Number.isNaN(e.getTime())?"—":e.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit",timeZoneName:"short"})}function Mt(t){return["session","fleet","users"].includes(t)?t:"session"}function gs(t,e){const s=Mt(t),n=[{text:"View ",color:"cyan",bold:!0}];for(const i of["session","fleet","users"])n.push({text:i===s?`[${i}]`:i,color:i===s?"magenta":"gray",bold:i===s}),n.push({text:" ",color:"gray"});return n.push({text:" [f cycle]",color:"gray"}),X(n,e)}function zu(t,e,s){if(!e)return[G("No session selected.")];const n=t.sessionStats?.bySessionId?.[e.sessionId]||null;if(!n||n.loading&&!n.summary)return[G("Loading session stats...")];const i=n.summary;if(!i)return[G("Session stats unavailable.")];const o=[],r=Math.max(24,s);o.push(gs("session",r)),o.push(G("")),o.push(X([{text:"Session ",color:"cyan",bold:!0},{text:Z(e.sessionId),color:"white"}],r));const a=e.isSystem?"system":e.owner?"user":"unowned",l=e.isSystem?"system":e.owner?xn(e.owner):"(?) unowned",u=e.owner?.email||"—";o.push(X([{text:"Owner ",color:"cyan",bold:!0},{text:l,color:e.owner?"white":"gray"}],r)),o.push(X([{text:"Email ",color:"cyan",bold:!0},{text:u,color:e.owner?.email?"white":"gray"}],r)),o.push(X([{text:"Type ",color:"cyan",bold:!0},{text:a,color:a==="user"?"white":"gray"}],r)),i.agentId&&o.push(X([{text:"Agent ",color:"cyan",bold:!0},{text:i.agentId,color:"white"}],r));const f=Pn(i.model||e.model,i.reasoningEffort||e.reasoningEffort);f&&o.push(X([{text:"Model ",color:"cyan",bold:!0},{text:f,color:"white"}],r)),e.createdAt&&o.push(X([{text:"Created ",color:"cyan",bold:!0},{text:jt(e.createdAt),color:"white"}],r)),e.updatedAt&&o.push(X([{text:"Updated ",color:"cyan",bold:!0},{text:jt(e.updatedAt),color:"white"}],r)),o.push(G(""));const d=Array.isArray(n.tokensByModel)?n.tokensByModel:[];d.length>1&&(o.push(...ne({title:"Models",body:d.map($=>`${qc($.model)} · ${$.turnCount||0} turns · ${j($.totalTokensInput)} in / ${j($.totalTokensOutput)} out`).join(`
51
+ `),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),o.push(G("")));const p=(i.tokensInput||0)+(i.tokensOutput||0),h=i.cacheHitRatio,m=h==null?"—":`${(h*100).toFixed(1)}%`;o.push(...ne({title:"Tokens",body:et([["Input",j(i.tokensInput)],["Output",j(i.tokensOutput)],["Total",j(p)],["Cache Read",j(i.tokensCacheRead)],["Cache Write",j(i.tokensCacheWrite)],["Hit Ratio",m]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0})),o.push(G(""));const g=Number(i.regenCount)||0,S=i.lastRegenStats&&typeof i.lastRegenStats=="object"?i.lastRegenStats:null,y=Number.isFinite(S?.toEpoch)?S.toEpoch:g,w=S?S.distillMode==="deterministic"||!S.distillMode&&!S.distillerModel?"fast":String(S.distillerModel||"llm").replace(/^[^:]*:/,""):null,I=S?`${S.turnsArchived??0} turn${S.turnsArchived===1?"":"s"} · ${(Number(S.totalMs)/1e3).toFixed(1)}s${w?` · ${w}`:""}`:null;o.push(...ne({title:"Persistence",body:et([["Epoch",String(y)],["Regens",g>0?String(g):null],["Last Regen",I],["Snapshot",le(i.snapshotSizeBytes)],["Uncompressed",i.rawSizeBytes?le(i.rawSizeBytes):null],["Compression",Ni(i.rawSizeBytes,i.snapshotSizeBytes)],["Dehydrations",String(i.dehydrationCount)],["Hydrations",String(i.hydrationCount)],["Lossy Handoffs",String(i.lossyHandoffCount)],["Last Dehydrated",i.lastDehydratedAt?jt(i.lastDehydratedAt):null],["Last Hydrated",i.lastHydratedAt?jt(i.lastHydratedAt):null]]),width:r,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const x=n.treeStats?.tree;if(x&&x.sessionCount>1){const $=x.cacheHitRatio,F=$==null?"—":`${($*100).toFixed(1)}%`,Y=(x.totalTokensInput||0)+(x.totalTokensOutput||0);o.push(G("")),o.push(...ne({title:`Tree (${x.sessionCount} sessions)`,body:et([["Input",j(x.totalTokensInput)],["Output",j(x.totalTokensOutput)],["Total",j(Y)],["Cache Read",j(x.totalTokensCacheRead)],["Cache Write",j(x.totalTokensCacheWrite)],["Hit Ratio",F],["Snapshot",le(x.totalSnapshotSizeBytes)],["Uncompressed",x.totalRawSizeBytes?le(x.totalRawSizeBytes):null],["Compression",Ni(x.totalRawSizeBytes,x.totalSnapshotSizeBytes)],["Dehydrations",String(x.totalDehydrationCount)],["Hydrations",String(x.totalHydrationCount)]]),width:r,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const U=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];U.length>1&&(o.push(G("")),o.push(...ne({title:"Tree By Model",body:ed(U),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const C=Array.isArray(n.skillUsage)?n.skillUsage:[];C.length>0&&(o.push(G("")),o.push(...ne({title:`Skills (${C.length})`,body:Oi(C,r),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const v=n.treeSkillUsage,k=Array.isArray(v?.rolledUp)?v.rolledUp:[],P=Array.isArray(v?.perSession)?v.perSession.length:0;k.length>0&&P>1&&(o.push(G("")),o.push(...ne({title:`Tree Skills (${k.length})`,body:Oi(k,r),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const O=n.factsStats,M=n.treeFactsStats;if(O&&Array.isArray(O.rows)&&O.rows.length>0){o.push(G(""));const $=$r(O.rows),F=$?$.split(`
52
+ `).length:0,Y=`${O.totalCount} · ${le(O.totalBytes)}`;let U=$;M&&M.totalCount>O.totalCount&&(U+=`
53
+ Tree (${M.sessionIds.length} sessions): ${M.totalCount} · ${le(M.totalBytes)}`),F>0&&o.push(...ne({title:`Facts (${Y})`,body:U,width:r,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return o}function et(t,e={}){const s=e.gap??2,n=(t||[]).filter(a=>Array.isArray(a)&&a[1]!=null&&a[1]!=="");if(n.length===0)return"";const i=n.reduce((a,[l])=>Math.max(a,String(l).length),0),o=n.reduce((a,[,l])=>Math.max(a,String(l).length),0),r=" ".repeat(s);return n.map(([a,l])=>`${String(a).padEnd(i)}${r}${String(l).padStart(o)}`).join(`
54
+ `)}function ys(t,e){const s=String(t??"");if(!Number.isFinite(e)||e<=0)return s;const n=Math.floor(e);return s.length<=n?s:n<=1?s.slice(0,n):`${s.slice(0,n-1)}…`}function Bt(t,e={}){const s=e.gap??2,n=(t||[]).filter(a=>Array.isArray(a)&&a.length>0);if(n.length===0)return"";const i=n.reduce((a,l)=>Math.max(a,l.length),0),o=new Array(i).fill(0);for(const a of n)for(let l=0;l<i;l+=1){const u=a[l]==null?"":String(a[l]);u.length>o[l]&&(o[l]=u.length)}const r=" ".repeat(s);return n.map(a=>a.map((l,u)=>{const f=l==null?"":String(l);return u===0?f.padEnd(o[u]):f.padStart(o[u])}).join(r)).join(`
55
+ `)}function Oi(t,e){const s=t.slice().sort((d,p)=>(p.invocations||0)-(d.invocations||0)).slice(0,12),n=s.map(d=>`${d.invocations||0} inv`),i=n.reduce((d,p)=>Math.max(d,p.length),0),a=4+2+i,l=Number.isFinite(e)&&e>0?Math.max(8,Math.floor(e)-a):1/0,u=s.map((d,p)=>{const h=d.kind==="learned"?"L":"S",m=String(d.name||"(unknown)");return[ys(`${h} ${m}`,l),n[p]]}),f=Bt(u);return t.length>s.length?`${f}
56
+ … ${t.length-s.length} more`:f}function $r(t){const s=t.slice().sort((n,i)=>(i.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),le(n.totalValueBytes||0)]);return Bt(s)}function Yu(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":Pt(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return Bt([["pending",String(Number(t.pendingTotal)||0)],["unreconciled",String(Number(t.unreconciled)||0)],["ttl-blocked",String(Number(t.ttlBlocked)||0)],["oldest",e],["reconciled",String(Number(t.reconciledUnswept)||0)]])}function Qu(t){switch(t){case"facts_search":return"facts search";case"facts_similar":return"facts similar";case"search_skills":return"skill search";case"graph_search_nodes":return"graph nodes";case"graph_search_edges":return"graph edges";case"graph_neighbourhood":return"graph hood";default:return String(t||"retrieval")}}function Xu(t,e){const s=t.slice().sort((d,p)=>(Number(p.calls)||0)-(Number(d.calls)||0)).slice(0,12),n=s.map(d=>`${Number(d.calls)||0} calls`),i=s.map(d=>`${Number(d.totalResults)||0} res`),o=n.reduce((d,p)=>Math.max(d,p.length),0),r=i.reduce((d,p)=>Math.max(d,p.length),0),a=6+o+2+r,l=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-a):1/0,u=s.map((d,p)=>{const h=d.namespace?` ${d.namespace}`:"";return[ys(`${Qu(d.operation)}${h}`,l),n[p],i[p]]}),f=Bt(u);return t.length>s.length?`${f}
57
+ … ${t.length-s.length} more`:f}function Ju(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.data)return[G("Loading fleet stats...")];const n=s.data;if(!n)return[G("Fleet stats unavailable.")];const i=[],o=Math.max(24,e);i.push(gs("fleet",o)),i.push(G(""));const r=n.windowStart?`Since: ${Lr(n.windowStart).replace(" ago","")}`:"All time",a=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";i.push(X([{text:r,color:"cyan"},{text:a?` ${a}`:"",color:"gray"}],o)),i.push(X([{text:`Sessions: ${n.totals.sessionCount}`,color:"white"},{text:` Tokens: ${j(n.totals.totalTokensInput)} in / ${j(n.totals.totalTokensOutput)} out`,color:"white"}],o)),i.push(G(""));const l=new Map;for(const g of n.byAgent||[]){const S=g.model||"(default)",y=l.get(S)||{totalTokensInput:0,totalTokensOutput:0,totalTokensCacheRead:0,totalTokensCacheWrite:0,totalSnapshotSizeBytes:0,turnCount:0};y.totalTokensInput+=Number(g.totalTokensInput)||0,y.totalTokensOutput+=Number(g.totalTokensOutput)||0,y.totalTokensCacheRead+=Number(g.totalTokensCacheRead)||0,y.totalTokensCacheWrite+=Number(g.totalTokensCacheWrite)||0,y.totalSnapshotSizeBytes+=Number(g.totalSnapshotSizeBytes)||0,y.turnCount+=Number(g.turnCount)||0,l.set(S,y)}if(l.size>0){const g=[];for(const[S,y]of l.entries()){const w=y.totalTokensInput>0?y.totalTokensCacheRead/y.totalTokensInput:null;g.push(S),g.push($n(y,w)),g.push("")}i.push(...ne({title:"Tokens By Model",body:g.join(`
58
+ `).trimEnd(),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(G(""))}const u=n.totals.cacheHitRatio,f=u==null?"—":`${(u*100).toFixed(1)}%`;i.push(...ne({title:"Fleet Totals",body:et([["Sessions",String(n.totals.sessionCount)],["Tokens In",j(n.totals.totalTokensInput)],["Tokens Out",j(n.totals.totalTokensOutput)],["Total Tokens",j(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",j(n.totals.totalTokensCacheRead)],["Cache Write",j(n.totals.totalTokensCacheWrite)],["Hit Ratio",f],["Snapshots",le(n.totals.totalSnapshotSizeBytes)]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0}));const d=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(g=>!(g&&g.agentId==="facts-manager"&&String(g.name||"").startsWith("skills/")));d.length>0&&(i.push(G("")),i.push(...ne({title:`Fleet Skills (${d.length})`,body:Zu(d,e),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const p=Array.isArray(s.retrievalUsage?.rows)?s.retrievalUsage.rows:[];if(p.length>0){const g=p.reduce((S,y)=>S+(Number(y.calls)||0),0);i.push(G("")),i.push(...ne({title:`Fleet Retrieval (${j(g)})`,body:Xu(p,e),width:o,titleColor:"magenta",borderColor:"gray",fitToContent:!0}))}const h=s.sharedFactsStats;if(h&&Array.isArray(h.rows)&&h.rows.length>0){i.push(G(""));const g=`${h.totalCount} · ${le(h.totalBytes)}`;i.push(...ne({title:`Shared Facts (${g})`,body:$r(h.rows),width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const m=s.factsTombstoneStats;return m&&Number(m.pendingTotal)>0&&(i.push(G("")),i.push(...ne({title:`Fact Tombstones (${Number(m.pendingTotal)||0})`,body:Yu(m),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),i}function Zu(t,e){const n=t.slice().sort((m,g)=>{const S=C=>C==="learned"?1:0,y=S(m.kind)-S(g.kind);if(y!==0)return y;const w=m.agentId?0:1,I=g.agentId?0:1;if(w!==I)return w-I;const x=String(m.agentId||"").localeCompare(String(g.agentId||""));return x!==0?x:String(m.name||"").localeCompare(String(g.name||""))}).slice(0,15),i=n.map(m=>`${m.invocations||0} inv`),o=n.map(m=>`${m.sessionCount||0} sess`),r=i.reduce((m,g)=>Math.max(m,g.length),0),a=o.reduce((m,g)=>Math.max(m,g.length),0),l=4,u=2,f=l+u+r+u+a,d=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-f):1/0,p=n.map((m,g)=>{const S=m.kind==="learned"?"L":"S",y=m.agentId||".",w=String(m.name||"(unknown)");return[ys(`${S} ${y}/${w}`,d),i[g],o[g]]}),h=Bt(p);return t.length>n.length?`${h}
59
+ … ${t.length-n.length} more`:h}function ed(t){const e=t.slice().sort((n,i)=>(i.totalTokensInput||0)-(n.totalTokensInput||0)),s=[];for(const n of e){const i=n.cacheHitRatio;s.push(`${String(n.model||"(unknown)")} · ${n.sessionCount||0} sess · ${n.turnCount||0} turns`),s.push($n(n,i)),s.push("")}return s.join(`
60
+ `).trimEnd()}function $n(t,e){const s=e==null?"—":`${(e*100).toFixed(1)}%`,n=(Number(t.totalTokensInput)||0)+(Number(t.totalTokensOutput)||0),i=[["Input",j(t.totalTokensInput||0)],["Output",j(t.totalTokensOutput||0)],["Total",j(n)],["Turns",j(t.turnCount||0)],["Cache Read",j(t.totalTokensCacheRead||0)],["Cache Write",j(t.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",le(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&i.push(["Orch",le(t.totalOrchestrationHistorySizeBytes||0)]),et(i).split(`
61
+ `).map(r=>` ${r}`).join(`
62
+ `)}function en(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":xn(t?.owner,"Unknown User")}function td(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=en(t);return e&&e!==s?e:""}function sd(t,e){const s=Array.isArray(t?.byModel)?t.byModel:[];if(s.length===0)return"";const n=s.slice().sort((o,r)=>(r.totalTokensInput||0)-(o.totalTokensInput||0)).slice(0,6),i=[];for(const o of n){const r=ys(String(o.model||"(default)"),Math.max(12,e-10));i.push(`${r} · ${o.sessionCount||0} sess · ${o.turnCount||0} turns`),i.push($n(o,o.cacheHitRatio)),i.push("")}return s.length>n.length&&i.push(`… ${s.length-n.length} more models`),i.join(`
63
+ `).trimEnd()}function nd(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.userStats)return[G("Loading user stats...")];const n=s.userStats;if(!n)return[G("User stats unavailable.")];const i=[],o=Math.max(24,e);i.push(gs("users",o)),i.push(G(""));const r=n.windowStart?`Since: ${Lr(n.windowStart).replace(" ago","")}`:"All time",a=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";i.push(X([{text:r,color:"cyan"},{text:a?` ${a}`:"",color:"gray"}],o)),i.push(X([{text:`Users: ${Array.isArray(n.users)?n.users.length:0}`,color:"white"},{text:` Sessions: ${n.totals.sessionCount||0}`,color:"white"}],o)),i.push(G(""));const l=n.totals.cacheHitRatio,u=l==null?"—":`${(l*100).toFixed(1)}%`;i.push(...ne({title:"User Totals",body:et([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",j(n.totals.totalTokensInput||0)],["Tokens Out",j(n.totals.totalTokensOutput||0)],["Total Tokens",j((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",j(n.totals.totalTokensCacheRead||0)],["Cache Write",j(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",u],["Snapshots",le(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",le(n.totals.totalOrchestrationHistorySizeBytes||0)]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0}));const f=Array.isArray(n.users)?n.users:[],d=f.slice().sort((p,h)=>(h.totalTokensInput||0)-(p.totalTokensInput||0)||(h.totalSnapshotSizeBytes||0)-(p.totalSnapshotSizeBytes||0)).slice(0,8);for(const p of d){const h=td(p),m=p.cacheHitRatio,g=m==null?"—":`${(m*100).toFixed(1)}%`,S=h?`${en(p)} <${h}>`:en(p),y=et([["Sessions",String(p.sessionCount||0)],["Tokens In",j(p.totalTokensInput||0)],["Tokens Out",j(p.totalTokensOutput||0)],["Total Tokens",j((p.totalTokensInput||0)+(p.totalTokensOutput||0))],["Cache Read",j(p.totalTokensCacheRead||0)],["Cache Write",j(p.totalTokensCacheWrite||0)],["Hit Ratio",g],["Snapshots",le(p.totalSnapshotSizeBytes||0)],["Orch Size",le(p.totalOrchestrationHistorySizeBytes||0)]]),w=sd(p,o);i.push(G("")),i.push(...ne({title:`${S} (${p.sessionCount||0})`,body:w?`${y}
64
+
65
+ ${w}`:y,width:o,titleColor:p.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return f.length>d.length&&(i.push(G("")),i.push(G(`… ${f.length-d.length} more users`))),i}function Ye(t,e={}){const s=Ce(t),n=t.ui.inspectorTab,i=Math.max(18,Number(e?.width)||36),o=!!e?.allowWideColumns,r=rr(i);if(s?.isGroup)return{title:_e("Inspector","magenta"),activeTab:n,tabs:Te,disabled:!0,stickyLines:[],lines:[G(Fr,"gray")]};const a=s?Z(s.sessionId):"",l=n==="sequence"||n==="nodes"?Rn(t):null,u=n==="nodes"?[..._e("Node Map","magenta"),...r?[]:[{text:` [${l.label}]`,color:"gray"}]]:s?n==="sequence"?[..._e(r?"Sequence":`Sequence: ${a}`,"magenta"),...r?[]:[{text:` [${l.label}]`,color:"gray"}]]:n==="logs"?[..._e(r?"Logs":`Logs: ${a}`,"magenta")]:n==="history"?[..._e(r?"History":`History: ${a}`,"magenta")]:n==="stats"?[..._e(r?"Stats":`Stats: ${a}`,"magenta"),{text:` [${Mt(t.ui?.statsViewMode)}]`,color:"gray"}]:[..._e(r?"Files":`Files: ${a}`,"magenta")]:n==="stats"?`Stats: ${Mt(t.ui?.statsViewMode).replace(/^./u,p=>p.toUpperCase())}`:"No session selected";let f,d=[];switch(n){case"sequence":{const p=s?Nu(t,s,i,{allowWideColumns:o,sequenceExpansion:e?.sequenceExpansion||null}):{stickyLines:[],lines:["No session selected."]};d=p.stickyLines||[],f=p.lines;break}case"logs":f=s?eu(t,s):["No session selected."];break;case"nodes":f=Ru(t,i,{allowWideColumns:o});break;case"files":f=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":f=s?ad(t,s):["No session selected."];break;case"stats":f=Mt(t.ui?.statsViewMode)==="users"?nd(t,i):Mt(t.ui?.statsViewMode)==="fleet"?Ju(t,i):s?zu(t,s,i):[gs("session",Math.max(24,i)),G(""),G("No session selected. Press f to cycle to fleet or users view.")];break;default:f=["Inspector view is scaffolded in the new architecture."];break}return{title:u,activeTab:n,tabs:Te,stickyLines:d,lines:f}}const id={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"},Fr="Select a session to see details.";function od(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=id[t.kind]||"gray",n=[],i=[{text:`#${t.eventId}`,color:"white",bold:!0},{text:` ${e}`,color:"gray"},{text:` ${t.kind}`,color:s,bold:t.kind.includes("Failed")}];if(t.sourceEventId!=null&&i.push({text:` ←#${t.sourceEventId}`,color:"cyan"}),n.push(i),t.data)try{const o=JSON.parse(t.data);if(typeof o=="object"&&o!==null)for(const[r,a]of Object.entries(o)){const l=typeof a=="string"?a:JSON.stringify(a),u=l.length>100?l.slice(0,97)+"...":l;n.push([{text:` ${r}: `,color:"yellow"},{text:u,color:"white"}])}else n.push({text:` ${String(o).slice(0,120)}`,color:"white"})}catch{const o=t.data.length>120?t.data.slice(0,117)+"...":t.data;n.push({text:` ${o}`,color:"white"})}return n}function rd(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function ad(t,e){const s=t.executionHistory?.bySessionId?.[e.sessionId];if(!s)return["No execution history loaded. Press r to refresh."];if(s.loading)return["Loading execution history..."];if(s.error)return[`Error: ${s.error}`];const n=s.events;if(!Array.isArray(n)||n.length===0)return["No history events found."];const i=t.executionHistory?.format||"pretty",o=[];if(o.push({text:`${n.length} event(s) · format: ${i}`,color:"gray"}),o.push(""),i==="raw")for(let r=0;r<n.length;r++){const a=rd(n[r]).split(`
66
+ `);for(const l of a)o.push({text:l,color:"gray"});r<n.length-1&&o.push({text:"────────────────────────────────",color:"gray"})}else for(let r=0;r<n.length;r++){const a=od(n[r]);for(const l of a)o.push(l);r<n.length-1&&o.push({text:"────────────────────────────────",color:"gray"})}return o}function ld(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:Ln(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function Ri(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 cd(t,e=80){const s=t.ui.modal;if(!s||s.type!=="themePicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),o=n[i]||null,r=s.currentThemeId||t.ui.themeId||null,a=n.find(p=>p.id===r)||null,l=o&&o.id!==r,u=Math.max(24,e-4),f=n.map((p,h)=>{const m=p.id===r?" [current]":"",g=`${p.label}${m}`.slice(0,u);return h===i?Me(g.padEnd(u," ")):[{text:g,color:p.id===r?"cyan":"white",bold:p.id===r}]}),d=o?[[{text:`theme: ${o.description||"Shared theme for the portal and native TUI."}`,color:"white"}],{text:"",color:"gray"},[{text:l?`Previewing now. Cancel reverts to ${a?.label||"the previous theme"}.`:"Currently active in this TUI session.",color:l?"yellow":"green"}],Ri([{label:"bg",color:o.tui?.background||o.terminal?.background||"#000000"},{label:"surface",color:o.tui?.surface||o.terminal?.background||"#000000"},{label:"fg",color:o.tui?.white||o.terminal?.foreground||"#ffffff"}]),Ri([{label:"blue",color:o.tui?.blue||o.terminal?.blue||"#5555ff"},{label:"green",color:o.tui?.green||o.terminal?.green||"#55ff55"},{label:"magenta",color:o.tui?.magenta||o.terminal?.magenta||"#ff55ff"},{label:"yellow",color:o.tui?.yellow||o.terminal?.yellow||"#ffff55"}]),{text:"",color:"gray"},[{text:"Selecting previews immediately. Apply Theme keeps it; Cancel restores the previous theme.",color:"gray"}]]:[{text:"No themes available.",color:"gray"}];return{title:s.title||"Theme Picker",idealWidth:Math.max(60,Math.min(e,80)),rows:f,selectedRowIndex:i,detailsTitle:"Theme Details",detailsLines:d}}function ud(t){const e=t.ui.modal;return!e||e.type!=="confirm"?null:{title:e.title||"Confirm",message:e.message||"Are you sure?",confirmLabel:e.confirmLabel||"Confirm"}}function Li(t){return new Map(t)}function $s(t){return new Set(t)}function dd(t){return Array.isArray(t)?[...t]:[]}function fd(t){return Array.isArray(t)?[...t]:[]}const pd=5e3;function tn(t,e){const s=[],n=new Set;for(const i of t||[])!i||n.has(i)||e[i]&&(n.add(i),s.push(i));return s}function Br(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Fs(t,e){return tn(t,e).filter(s=>Br(e[s]))}function hd(t=[]){const e=new Set((t||[]).map(n=>n?.sessionId).filter(Boolean)),s=new Set;for(const n of t||[]){if(!n?.sessionId)continue;n.isGroup&&s.add(n.sessionId);const i=n.parentSessionId;i&&e.has(i)&&s.add(i)}return s}function Dr(t,e){const s=hd(Object.values(e||{})),n=new Set;for(const i of t||[])s.has(i)&&n.add(i);return n}function md(t,e){const s=[],n=new Set([t]);let i=e?.[t]||null;for(;i;){let o=null;if(i.parentSessionId&&e?.[i.parentSessionId]?o=i.parentSessionId:!i.isGroup&&i.groupId&&e?.[`group:${i.groupId}`]&&(o=`group:${i.groupId}`),!o||n.has(o))break;s.push(o),n.add(o),i=e[o]||null}return s}function $i(t,e,s){const n=Dr(t,e);if(!s||!e?.[s])return n;for(const i of md(s,e))n.delete(i);return n}function Fi(t,e){if(t===e)return!0;if(!(t instanceof Set)||!(e instanceof Set)||t.size!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}function gd(t){return{...t||{}}}function Pe(t){return{...t||{}}}function Bi(t){return{...t||{}}}function Wt(t){return{...t||{}}}function Bs(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function yd(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function Sd(t){return[A.SESSIONS,A.CHAT,A.INSPECTOR,A.ACTIVITY].includes(t)?t:null}function Ds(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(J,Number(e)||J);return s.length>n?s.slice(-n):s}function sn(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i+=1)if(!sn(t[i],e[i]))return!1;return!0}if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!sn(t[i],e[i]))return!1;return!0}function Di(t){const e=t?.updatedAt;if(typeof e=="number"&&Number.isFinite(e))return e;if(e instanceof Date)return e.getTime();const s=Date.parse(e||"");return Number.isFinite(s)?s:0}function bd(t,e){const s=Di(t),n=Di(e);return s>0&&n>0&&n<=s}const wd=new Set(["completed","failed","cancelled","error"]);function Id(t,e){const s=String(e?.status??"").toLowerCase();if(t?.status!=="running"||s==="running"||wd.has(s))return!1;const n=Number(t?.statusVersion),i=Number(e?.statusVersion);return Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?i<=n:bd(t,e)}function Hi(t={},e={}){let s=t||{};const n=Id(t,e);for(const[i,o]of Object.entries(e||{}))if(o!==void 0&&!(i==="status"&&n)){if(i==="pendingQuestion"&&xd(t,o)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}sn(t?.[i],o)||(s===t&&(s={...t||{}}),s[i]=o)}return s}function Gi(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function Ui(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=Gi(e),i=t?.rowVisualStatus||Gi(t||e);if(!t)return e.rowVisualStatus===n&&e.rowVisualStatusCandidate==null&&e.rowVisualStatusCandidateSince==null?e:{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0};if(n===i)return e.rowVisualStatus===n&&e.rowVisualStatusCandidate==null&&e.rowVisualStatusCandidateSince==null?e:{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0};const r=t.rowVisualStatusCandidate===n&&Number(t.rowVisualStatusCandidateSince)||s;return s-r>=pd?{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0}:e.rowVisualStatus===i&&e.rowVisualStatusCandidate===n&&Number(e.rowVisualStatusCandidateSince)===r?e:{...e,rowVisualStatus:i,rowVisualStatusCandidate:n,rowVisualStatusCandidateSince:r}}function ji(t){return String(t?.question||"").trim()}function xd(t,e){const s=ji(t?.answeredPendingQuestion),n=ji(e);return!!(s&&n&&s===n)}function vd(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&jo(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function Wi(t=[]){const e=new Set((t||[]).map(n=>n?.sessionId).filter(Boolean)),s=new Set;for(const n of t||[]){if(!n?.sessionId)continue;n.isGroup&&s.add(n.sessionId);const i=n.parentSessionId;i&&e.has(i)&&s.add(i)}return s}function Ki(t={}){const e=String(t?.filterQuery||"").trim(),s=ss(t?.ownerFilter);return!!e||s.all!==!0}function Ed(t,e=[]){const s=wt(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(o=>o.sessionId===n)||t.sessions?.navigationIntent||n&&t.sessions?.byId?.[n]&&!Ki(t.sessions))return n;if(Ki(t.sessions))return s[0]?.sessionId||null;const i=s.length>0?s.map(o=>t.sessions?.byId?.[o.sessionId]||null).filter(Boolean):e;return vd(i)}function Ad(t,e){return e===t.sessions.activeSessionId?t.ui:{...t.ui,scroll:{...t.ui.scroll,chat:0,inspector:0,activity:0},followBottom:{...t.ui.followBottom||{},inspector:!0,activity:!0}}}function rt(t,e){let s=e;const n=s.navigationIntent||null,i=n&&n.status!=="failed"&&s.byId?.[n.sessionId]?n.sessionId:null;i&&(s={...s,activeSessionId:i,navigationIntent:n.status==="resolved"?n:{sessionId:n.sessionId,status:"resolved"}});const o=s.activeSessionId||null;if(o&&s.byId?.[o]){const d=$i(s.collapsedIds,s.byId,o);Fi(d,s.collapsedIds)||(s={...s,collapsedIds:d,flat:De(Object.values(s.byId||{}),d,s.orderById,s.pinnedIds)})}i&&s.filterExceptionId!==i&&(wt({...t,sessions:s}).some(p=>p.sessionId===i)||(s={...s,filterExceptionId:i}));const r={...t,sessions:s},a=Ed(r,Object.values(s.byId||{})),l=$i(s.collapsedIds,s.byId,a);return{sessions:{...!Fi(l,s.collapsedIds)?{...s,collapsedIds:l,flat:De(Object.values(s.byId||{}),l,s.orderById,s.pinnedIds)}:s,activeSessionId:a},ui:Ad(t,a)}}function Vi(t={},e=0,s=[]){const n=gd(t);let i=Number.isFinite(e)?e:0;for(const o of s||[]){const r=o?.sessionId;r&&typeof n[r]!="number"&&(n[r]=i,i+=1)}return{orderById:n,nextOrderOrdinal:i}}function Td(t=[],e=[]){const s=De(t,new Set,{},e),n={};let i=0;for(const o of s){const r=o?.sessionId;!r||typeof n[r]=="number"||(n[r]=i,i+=1)}for(const o of t||[]){const r=o?.sessionId;!r||typeof n[r]=="number"||(n[r]=i,i+=1)}return{orderById:n,nextOrderOrdinal:i}}function Cd(t,e,s=null){const n=String(t||""),i=Number.isFinite(e)?e:Number.isFinite(s)?s:n.length;return Math.max(0,Math.min(i,n.length))}function qi(t,e){const s=String(t||"");return(Array.isArray(e)?e.filter(Boolean):[]).filter(i=>{if(i?.kind==="image")return!0;const o=String(i?.token||"").trim();return o&&s.includes(o)})}function kd(t,e){switch(e.type){case"connection/ready":return{...t,connection:{...t.connection,connected:!0,workersOnline:e.workersOnline??t.connection.workersOnline,error:null},ui:{...t.ui,statusText:e.statusText??t.ui.statusText??"Ready"}};case"connection/error":return{...t,connection:{...t.connection,connected:!1,error:e.error},ui:{...t.ui,statusText:e.statusText||e.error||"Connection error"}};case"auth/context":return{...t,auth:{principal:e.principal??null,authorization:e.authorization??null}};case"ui/status":return{...t,ui:{...t.ui,statusText:e.text}};case"ui/theme":return{...t,ui:{...t.ui,themeId:e.themeId||t.ui.themeId}};case"profileSettings/apply":{const s=e.settings&&typeof e.settings=="object"&&!Array.isArray(e.settings)?e.settings:{},n=Object.prototype.hasOwnProperty.call(s,"themeId")&&typeof s.themeId=="string"&&s.themeId.trim(),i=Object.prototype.hasOwnProperty.call(s,"sessionOwnerFilter"),o=Object.prototype.hasOwnProperty.call(s,"layoutAdjustments"),r=Object.prototype.hasOwnProperty.call(s,"chatViewMode")&&(s.chatViewMode==="summary"||s.chatViewMode==="transcript"||s.chatViewMode==="rich"),a=Object.prototype.hasOwnProperty.call(s,"pinnedSessionIds"),l=Object.prototype.hasOwnProperty.call(s,"collapsedSessionIds"),u=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.status!=="failed"),f=Object.prototype.hasOwnProperty.call(s,"activeSessionId")&&!u,d=Object.keys(t.sessions.byId||{}).length>0,p=o?{...t.ui.layout||{},...Sn(s.layoutAdjustments)}:t.ui.layout,h=a?d?Fs(is(s.pinnedSessionIds),t.sessions.byId):is(s.pinnedSessionIds):t.sessions.pinnedIds,m=l?d?Dr(Xs(s.collapsedSessionIds),t.sessions.byId):Xs(s.collapsedSessionIds):t.sessions.collapsedIds,g=f?sr(s.activeSessionId):t.sessions.activeSessionId,S={...t.sessions,...i?{ownerFilter:ss(s.sessionOwnerFilter),ownerFilterExplicit:!0}:{},pinnedIds:h,collapsedIds:m,collapsedIdsExplicit:l?!0:t.sessions.collapsedIdsExplicit,activeSessionId:g,flat:a||l?De(Object.values(t.sessions.byId),m,t.sessions.orderById,h):t.sessions.flat},y=d&&(i||a||l||f)?rt(t,S):{sessions:S,ui:t.ui};return{...t,sessions:y.sessions,ui:{...y.ui,themeId:n?s.themeId.trim():y.ui.themeId,chatViewMode:r?s.chatViewMode:y.ui.chatViewMode,layout:p}}}case"ui/chatViewMode":return e.mode!=="summary"&&e.mode!=="transcript"&&e.mode!=="rich"?t:{...t,ui:{...t.ui,chatViewMode:e.mode,scroll:{...t.ui.scroll,chat:0}}};case"ui/modal":return{...t,ui:{...t.ui,modal:e.modal??null}};case"ui/viewport":{const s=t.ui.layout?.viewportWidth??120,n=t.ui.layout?.viewportHeight??40,i=Math.max(40,e.width??s),o=Math.max(18,e.height??n);return i===s&&o===n?t:{...t,ui:{...t.ui,layout:{...t.ui.layout||{},viewportWidth:i,viewportHeight:o}}}}case"ui/paneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},paneAdjust:Number(e.paneAdjust)||0}}};case"ui/sessionPaneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},sessionPaneAdjust:Number(e.sessionPaneAdjust)||0}}};case"ui/portalSessionColumnAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},portalSessionColumnAdjust:Number(e.portalSessionColumnAdjust)||0}}};case"ui/activityPaneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},activityPaneAdjust:Number(e.activityPaneAdjust)||0}}};case"ui/focus":return{...t,ui:{...t.ui,focusRegion:e.focusRegion}};case"ui/sequenceExpandedTurns":return{...t,ui:{...t.ui,sequenceExpandedTurns:Array.isArray(e.turns)?e.turns:[]}};case"ui/sequenceSelectedTurn":return{...t,ui:{...t.ui,sequenceSelectedTurn:e.turn==null?null:Number(e.turn)}};case"sessions/filterQuery":{const s={...t.sessions,filterQuery:typeof e.query=="string"?e.query:"",navigationIntent:null,filterExceptionId:null},n=rt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:ss(e.filter),navigationIntent:null,filterExceptionId:null},n=rt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/navigationIntent":{const s=String(e.sessionId||"").trim();if(!s)return t;const n={...t.sessions,navigationIntent:{sessionId:s,status:"pending"},filterExceptionId:null},i=rt(t,n);return{...t,sessions:i.sessions,ui:i.ui}}case"sessions/navigationIntentFailed":{const s=t.sessions.navigationIntent,n=String(e.sessionId||"").trim();return!s||n&&s.sessionId!==n?t:{...t,sessions:{...t.sessions,navigationIntent:{sessionId:s.sessionId,status:"failed",errorKind:e.errorKind==="not_found"?"not_found":"network"}}}}case"ui/modalSelection":{const s=t.ui.modal;if(!s)return t;if(s.type==="help")return{...t,ui:{...t.ui,modal:{...s,selectedIndex:Math.max(0,Number(e.index)||0)}}};if(!Array.isArray(s.items)||s.items.length===0)return t;const n=Math.max(0,Math.min(e.index??0,s.items.length-1)),i=s.type==="themePicker"?s.items[n]?.id:null;return{...t,ui:{...t.ui,...i?{themeId:i}:{},modal:{...s,selectedIndex:n}}}}case"ui/scroll":return{...t,ui:{...t.ui,scroll:{...t.ui.scroll,[e.pane]:Math.max(0,e.offset??0)}}};case"ui/followBottom":{if(e.pane!=="inspector"&&e.pane!=="activity")return t;const s=!!e.followBottom;return t.ui.followBottom?.[e.pane]===s?t:{...t,ui:{...t.ui,followBottom:{...t.ui.followBottom||{},[e.pane]:s}}}}case"ui/inspectorTab":return{...t,ui:{...t.ui,inspectorTab:e.inspectorTab,fullscreenPane:e.inspectorTab==="files"&&t.ui.fullscreenPane===A.INSPECTOR?null:t.ui.fullscreenPane,scroll:{...t.ui.scroll,inspector:0},followBottom:{...t.ui.followBottom||{},inspector:!0}},files:e.inspectorTab==="files"?t.files:{...t.files,fullscreen:!1}};case"ui/statsViewMode":return{...t,ui:{...t.ui,statsViewMode:["session","fleet","users"].includes(e.statsViewMode)?e.statsViewMode:"session",scroll:{...t.ui.scroll,inspector:0}}};case"ui/prompt":return{...t,ui:{...t.ui,prompt:e.prompt,promptCursor:Cd(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:mt(e.prompt),promptAttachments:qi(e.prompt,t.ui.promptAttachments)}};case"ui/promptEdit":return{...t,ui:{...t.ui,promptEdit:e.promptEdit??null}};case"ui/promptAttachments":return{...t,ui:{...t.ui,promptAttachments:qi(t.ui.prompt,e.attachments)}};case"sessions/gone":{const s=e.sessionId;if(!s)return t;const n=!!t.sessions.byId[s],i=t.sessions.activeSessionId===s;if(!n&&!i)return t;const o={...t.sessions.byId};delete o[s];const r=Array.isArray(t.sessions.selectedIds)?t.sessions.selectedIds.filter(a=>a!==s):t.sessions.selectedIds;return{...t,sessions:{...t.sessions,byId:o,selectedIds:r,activeSessionId:i?null:t.sessions.activeSessionId}}}case"sessions/loaded":{const s={};let n=!1;const i=Date.now();for(const I of e.sessions){const x=t.sessions.byId[I.sessionId],C=Ui(x,Hi(x,I),i);s[I.sessionId]=C,!n&&C!==x&&(n=!0)}t.sessions.activeSessionId&&t.sessions.byId[t.sessions.activeSessionId]&&!t.sessions.byId[t.sessions.activeSessionId]?.isGroup&&!s[t.sessions.activeSessionId]&&(s[t.sessions.activeSessionId]={...t.sessions.byId[t.sessions.activeSessionId]},n=!0);const o=Object.keys(t.sessions.byId),r=Object.keys(s);if(o.length!==r.length&&(n=!0),!n){for(const I of r)if(!t.sessions.byId[I]){n=!0;break}}if(!n)return t;const a=Object.values(s),l=Object.keys(t.sessions.orderById||{}).length>0,u=Wi(a),f=!!t.sessions.collapsedIdsExplicit,{orderById:d,nextOrderOrdinal:p}=l?Vi(t.sessions.orderById,t.sessions.nextOrderOrdinal,a):Td(a,t.sessions.pinnedIds),h=f?$s(t.sessions.collapsedIds):u;if(f){const I=Wi(Object.values(t.sessions.byId));for(const x of u)I.has(x)||h.add(x)}const m=Fs(t.sessions.pinnedIds,s),g=tn(t.sessions.selectedIds,s),S=De(a,h,d,m),y={...t.sessions,byId:s,collapsedIds:h,collapsedIdsExplicit:f,pinnedIds:m,selectedIds:g,selectMode:t.sessions.selectMode&&g.length>0,flat:S,activeSessionId:t.sessions.activeSessionId,orderById:d,nextOrderOrdinal:p},w=rt(t,y);return{...t,sessions:w.sessions,ui:w.ui}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=Ui(s,Hi(s,e.session),Date.now());if(n===s)return t;const i={...t.sessions.byId,[e.session.sessionId]:n},o=Fs(t.sessions.pinnedIds,i),{orderById:r,nextOrderOrdinal:a}=Vi(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(i)),l={...t.sessions,byId:i,pinnedIds:o,flat:De(Object.values(i),t.sessions.collapsedIds,r,o),activeSessionId:t.sessions.activeSessionId,orderById:r,nextOrderOrdinal:a},u=rt(t,l);return{...t,sessions:u.sessions,ui:u.ui}}case"sessions/selected":{const s=t.sessions.activeSessionId,n={...t.ui.chatScrollBySession||{}};s&&s!==e.sessionId&&(n[s]=Number(t.ui.scroll?.chat)||0);const i=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.sessionId!==e.sessionId);return{...t,sessions:{...t.sessions,activeSessionId:e.sessionId,...i?{navigationIntent:null,filterExceptionId:null}:{}},ui:{...t.ui,chatScrollBySession:n,statusText:s!==e.sessionId?"":t.ui.statusText,scroll:{...t.ui.scroll,chat:Number(n[e.sessionId])||0,inspector:0,activity:0},followBottom:{...t.ui.followBottom||{},inspector:!0,activity:!0}}}}case"ui/fullscreenPane":{const s=Sd(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=$s(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:De(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds)}}}case"sessions/expand":{const s=$s(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:De(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds)}}}case"sessions/pinToggle":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=t.sessions.byId[s];if(!Br(n))return t;const i=dd(t.sessions.pinnedIds),r=i.indexOf(s)>=0?i.filter(a=>a!==s):[...i,s];return{...t,sessions:{...t.sessions,pinnedIds:r,flat:De(Object.values(t.sessions.byId),t.sessions.collapsedIds,t.sessions.orderById,r)}}}case"sessions/selectMode":{const s=!!e.enabled;return s===!!t.sessions.selectMode&&(s||t.sessions.selectedIds.length===0)?t:{...t,sessions:{...t.sessions,selectMode:s,selectedIds:s?t.sessions.selectedIds:[]}}}case"sessions/selectToggle":{const s=String(e.sessionId||"").trim(),n=s?t.sessions.byId[s]:null;if(!n||n.isSystem||n.isGroup)return t;const i=fd(t.sessions.selectedIds),r=i.indexOf(s)>=0?i.filter(a=>a!==s):[...i,s];return{...t,sessions:{...t.sessions,selectedIds:r,selectMode:r.length>0?!0:t.sessions.selectMode}}}case"sessions/selectSet":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[],n=tn(s,t.sessions.byId).filter(i=>!t.sessions.byId[i]?.isSystem&&!t.sessions.byId[i]?.isGroup);return{...t,sessions:{...t.sessions,selectedIds:n,selectMode:n.length>0?!0:t.sessions.selectMode}}}case"sessions/selectClear":return t.sessions.selectedIds.length===0&&!t.sessions.selectMode?t:{...t,sessions:{...t.sessions,selectedIds:[],selectMode:!1}};case"history/set":{const s=t.history.bySessionId.get(e.sessionId)||null,n=s?.chat||[],i=Math.max(J,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??J)||J),o=Ds(ft(e.history?.chat||[]),i),r=n[n.length-1]?.id||null,a=o[o.length-1]?.id||null,l=e.sessionId===t.sessions.activeSessionId&&a!==r,u=Li(t.history.bySessionId);return u.set(e.sessionId,{...e.history||{},chat:o,activity:Ds(e.history?.activity||[],i),events:Ds(e.history?.events||[],i),loadedEventLimit:i}),{...t,history:{...t.history,bySessionId:u},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=Li(t.history.bySessionId);for(const r of s)n.delete(r);const i=Bi(t.outbox?.bySessionId);for(const r of s)delete i[r];const o={...t.ui.chatScrollBySession||{}};for(const r of s)delete o[r];return{...t,history:{...t.history,bySessionId:n},outbox:{...t.outbox,bySessionId:i},ui:{...t.ui,chatScrollBySession:o}}}case"outbox/setSessionItems":{const s=e.sessionId;if(!s)return t;const n=Array.isArray(e.items)?e.items.filter(Boolean):[],i=Bi(t.outbox?.bySessionId);return n.length===0?delete i[s]:i[s]=n,{...t,outbox:{...t.outbox,bySessionId:i}}}case"orchestration/statsLoading":{const s=Wt(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=Wt(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=Wt(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=Wt(t.orchestration.bySessionId);for(const i of s)delete n[i];return{...t,orchestration:{...t.orchestration,bySessionId:n}}}case"executionHistory/loading":{const s={...t.executionHistory?.bySessionId||{}};return s[e.sessionId]={...s[e.sessionId]||{},loading:!0,error:null},{...t,executionHistory:{...t.executionHistory,bySessionId:s}}}case"executionHistory/loaded":{const s={...t.executionHistory?.bySessionId||{}},n=e.events||[],i=1e3,o=n.length>i?n.slice(-i):n;return s[e.sessionId]={loading:!1,error:null,fetchedAt:e.fetchedAt||Date.now(),events:o},{...t,executionHistory:{...t.executionHistory,bySessionId:s}}}case"executionHistory/evict":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n={...t.executionHistory?.bySessionId||{}};for(const i of s)delete n[i];return{...t,executionHistory:{...t.executionHistory,bySessionId:n}}}case"executionHistory/error":{const s={...t.executionHistory?.bySessionId||{}};return s[e.sessionId]={...s[e.sessionId]||{},loading:!1,error:e.error||"Failed to load execution history",fetchedAt:e.fetchedAt||Date.now()},{...t,executionHistory:{...t.executionHistory,bySessionId:s}}}case"executionHistory/format":return{...t,executionHistory:{...t.executionHistory,format:e.format||"pretty"}};case"sessionStats/loading":{const s={...t.sessionStats?.bySessionId||{}};return s[e.sessionId]={...s[e.sessionId]||{},loading:!0},{...t,sessionStats:{...t.sessionStats,bySessionId:s}}}case"sessionStats/loaded":{const s={...t.sessionStats?.bySessionId||{}};return s[e.sessionId]={loading:!1,fetchedAt:Date.now(),summary:e.summary||null,tokensByModel:Array.isArray(e.tokensByModel)?e.tokensByModel:[],treeStats:e.treeStats||null,skillUsage:e.skillUsage||null,treeSkillUsage:e.treeSkillUsage||null,factsStats:e.factsStats||null,treeFactsStats:e.treeFactsStats||null},{...t,sessionStats:{...t.sessionStats,bySessionId:s}}}case"fleetStats/loading":return{...t,fleetStats:{...t.fleetStats,loading:!0}};case"fleetStats/loaded":return{...t,fleetStats:{loading:!1,data:e.data||null,userStats:e.userStats||null,skillUsage:e.skillUsage||null,retrievalUsage:e.retrievalUsage||null,sharedFactsStats:e.sharedFactsStats||null,factsTombstoneStats:e.factsTombstoneStats||null,fetchedAt:Date.now()}};case"admin/visibility":{const s=!!e.visible;return t.admin.visible===s?t:{...t,admin:{...t.admin,visible:s,ghcpKey:s?t.admin.ghcpKey:{editing:!1,draft:"",saving:!1,error:null,lastSavedAt:t.admin.ghcpKey.lastSavedAt}}}}case"admin/profile/loading":return{...t,admin:{...t.admin,loading:!0,loadError:null}};case"admin/profile/loaded":return{...t,admin:{...t.admin,loading:!1,loadError:null,profile:e.profile||null,ghcpKey:{...t.admin.ghcpKey,error:t.admin.ghcpKey.editing?t.admin.ghcpKey.error:null}}};case"admin/profile/loadFailed":return{...t,admin:{...t.admin,loading:!1,loadError:e.error?String(e.error):"Failed to load profile"}};case"admin/ghcpKey/beginEdit":{const s=typeof e.draft=="string"?e.draft:"";return{...t,admin:{...t.admin,ghcpKey:{editing:!0,draft:s,cursorIndex:s.length,saving:!1,error:null,lastSavedAt:t.admin.ghcpKey.lastSavedAt,storeAsSystem:!!t.admin.ghcpKey.storeAsSystem}}}}case"admin/ghcpKey/setDraft":{if(!t.admin.ghcpKey.editing)return t;const s=typeof e.draft=="string"?e.draft:"",n=Number.isFinite(e.cursorIndex)?Number(e.cursorIndex):s.length,i=Math.max(0,Math.min(n,s.length));return s===t.admin.ghcpKey.draft&&i===t.admin.ghcpKey.cursorIndex?t:{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,draft:s,cursorIndex:i,error:null}}}}case"admin/ghcpKey/cancelEdit":return!t.admin.ghcpKey.editing&&!t.admin.ghcpKey.draft?t:{...t,admin:{...t.admin,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:t.admin.ghcpKey.lastSavedAt,storeAsSystem:!!t.admin.ghcpKey.storeAsSystem}}};case"admin/ghcpKey/saving":return{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,saving:!0,error:null}}};case"admin/ghcpKey/saveFailed":return{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,saving:!1,error:e.error?String(e.error):"Failed to save key"}}};case"admin/ghcpKey/saved":return{...t,admin:{...t.admin,profile:e.profile||t.admin.profile,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:Date.now(),storeAsSystem:!!t.admin.ghcpKey.storeAsSystem}}};case"admin/ghcpKey/setSystemTarget":{const s=!!e.value;return!!t.admin.ghcpKey.storeAsSystem===s?t:{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,storeAsSystem:s,error:null}}}}case"admin/systemGhcpKey/loading":return{...t,admin:{...t.admin,systemGhcpKey:{...t.admin.systemGhcpKey,loading:!0,error:null}}};case"admin/systemGhcpKey/loaded":{const s=e.status||{};return{...t,admin:{...t.admin,systemGhcpKey:{supported:!0,loading:!1,configured:!!s.configured,changedBy:s.changedBy||null,changedAt:s.changedAt||null,error:null}}}}case"admin/systemGhcpKey/loadFailed":return{...t,admin:{...t.admin,systemGhcpKey:{...t.admin.systemGhcpKey,loading:!1,error:e.error?String(e.error):"Failed to load System key status"}}};case"admin/systemGhcpKey/saved":{const s=e.status||{};return{...t,admin:{...t.admin,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:Date.now(),storeAsSystem:!!t.admin.ghcpKey.storeAsSystem},systemGhcpKey:{supported:!0,loading:!1,configured:!!s.configured,changedBy:s.changedBy||null,changedAt:s.changedAt||null,error:null}}}}case"files/evictPreviews":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=Pe(t.files.bySessionId);for(const i of s)n[i]&&(n[i]={...n[i],previews:{}});return{...t,files:{...t.files,bySessionId:n}}}case"files/sessionLoading":{const s=Pe(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=Pe(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},i=ns(e.entries),o=a=>i.some(l=>l.filename===a),r=n.selectedFilename&&o(n.selectedFilename)?n.selectedFilename:e.selectedFilename&&o(e.selectedFilename)?e.selectedFilename:i[0]?.filename||null;return s[e.sessionId]={...n,entries:i,selectedFilename:r,loading:!1,loaded:!0,error:null},{...t,files:{...t.files,bySessionId:s}}}case"files/sessionError":{const s=Pe(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=Pe(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null};return s[e.sessionId]={...n,selectedFilename:e.filename||null},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:t.files.selectedArtifactId},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}}}case"files/selectGlobal":return{...t,files:{...t.files,selectedArtifactId:e.artifactId||null},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}};case"files/previewLoading":{const s=Pe(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.previews||{},[e.filename]:{...n.previews?.[e.filename]||{},loading:!0,error:null}};return s[e.sessionId]={...n,previews:i},{...t,files:{...t.files,bySessionId:s}}}case"files/previewLoaded":{const s=Pe(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.previews||{},[e.filename]:{loading:!1,error:null,content:e.content||"",contentType:e.contentType||"text/plain",renderMode:e.renderMode||"text",isBinary:e.isBinary===!0,sizeBytes:Number.isFinite(e.sizeBytes)?e.sizeBytes:null,uploadedAt:e.uploadedAt||"",source:e.source||"agent"}};return s[e.sessionId]={...n,previews:i},{...t,files:{...t.files,bySessionId:s}}}case"files/previewError":{const s=Pe(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.previews||{},[e.filename]:{...n.previews?.[e.filename]||{},loading:!1,error:e.error||"Failed to load file preview"}};return s[e.sessionId]={...n,previews:i},{...t,files:{...t.files,bySessionId:s}}}case"files/downloaded":{const s=Pe(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.downloads||{},[e.filename]:{localPath:e.localPath||null,downloadedAt:e.downloadedAt||Date.now()}};return s[e.sessionId]={...n,downloads:i},{...t,files:{...t.files,bySessionId:s}}}case"files/deleted":{const s=Pe(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},i=ns(n.entries).filter(d=>d.filename!==e.filename),o=n.selectedFilename===e.filename?i[0]?.filename||null:n.selectedFilename,{[e.filename]:r,...a}=n.previews||{},{[e.filename]:l,...u}=n.downloads||{},f=e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:null;return s[e.sessionId]={...n,entries:i,previews:a,downloads:u,selectedFilename:o},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:t.files.selectedArtifactId===f?o?`${e.sessionId}/${o}`:null:t.files.selectedArtifactId},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}}}case"files/fullscreen":return{...t,files:{...t.files,fullscreen:!!e.fullscreen},ui:e.fullscreen?{...t.ui,focusRegion:"inspector",fullscreenPane:null}:t.ui};case"files/filter":return{...t,files:{...t.files,filter:{...Bs(t.files.filter),...Bs(e.filter)},...Bs(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:yd(e.entries)}};case"logs/append":{const s=(Array.isArray(e.entries)?e.entries:[e.entry]).filter(Boolean);if(s.length===0)return t;const n=[...t.logs.entries||[],...s],i=n.length>1e3?n.slice(-1e3):n;return{...t,logs:{...t.logs,entries:i}}}default:return t}}function Md(t,e){let s=e;const n=new Set;return{getState(){return s},dispatch(i){const o=t(s,i);if(Object.is(o,s))return i;s=o;for(const r of n)r(s,i);return i},subscribe(i){return n.add(i),()=>n.delete(i)}}}const Nd=2e4,Pd=2e4,_d=3e4,Od=30,zi="Session refresh failed",Rd=3,Ld=200,$d=5,Fd=new Set([A.SESSIONS,A.CHAT,A.INSPECTOR,A.ACTIVITY]);function Bd(t){if(!t?.groupId)return null;const e=t.latestSummaryUpdatedAt?new Date(t.latestSummaryUpdatedAt).getTime():null,s=t.memberCount??0;return{sessionId:`group:${t.groupId}`,groupId:t.groupId,isGroup:!0,title:t.title||t.groupId,status:"group",description:t.description??null,owner:t.owner??null,shortSummary:`${s} grouped session${s===1?"":"s"}`,summaryUpdatedAt:Number.isFinite(e)?e:null,latestSummaryUpdatedAt:Number.isFinite(e)?e:null,memberCount:s,runningCount:t.runningCount??0,waitingCount:t.waitingCount??0,completedCount:t.completedCount??0,failedCount:t.failedCount??0,cancelledCount:t.cancelledCount??0,createdAt:t.createdAt?new Date(t.createdAt).getTime():0,updatedAt:t.updatedAt?new Date(t.updatedAt).getTime():Date.now()}}function Hs(t){return!t?.sessionId||t.isGroup?t:{...t,groupId:t.viewerGroupId??null,parentSessionId:t.parentSessionId??null}}function Gs(t){return String(t||"").startsWith("group:")?String(t).slice(6):null}function Dd(t){const e=new Map;for(const s of t||[]){const n=s?.reason==="system"?"system":"not found";e.set(n,(e.get(n)||0)+1)}return[...e.entries()].map(([s,n])=>`${n} ${s}`).join(", ")}function Us(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||e===403||s==="NOT_FOUND"||s==="FORBIDDEN"?"not_found":"network"}function At(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||s==="NOT_FOUND"}async function Hd(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<$d;n+=1){const i=await t.listSessionsPage({limit:Ld,cursor:s}),o=Array.isArray(i?.sessions)?i.sessions:[];if(e.push(...o),!i?.hasMore||!i?.nextCursor)break;s=i.nextCursor}return e}function Gd(t=[]){const e=[],s=new Map;for(const n of t){const i=n?.providerId||"models";let o=s.get(i);o||(o={providerId:i,providerType:n?.providerType||"provider",models:[]},s.set(i,o),e.push(o)),o.models.push(n)}return e}function nn(t){if(!Array.isArray(t))return[];const e=[];for(const s of t){const n=String(s||"").trim().toLowerCase();!n||e.includes(n)||e.push(n)}return e}function Yi(t){const e=nn(t?.supportedReasoningEfforts);if(e.length===0)return null;const s=String(t?.defaultReasoningEffort||"").trim().toLowerCase();return s&&e.includes(s)?s:e.includes("medium")?"medium":e[0]||null}function on(t){if(!Array.isArray(t))return[];const e=[];for(const s of t){const n=String(s||"").trim().toLowerCase();!n||e.includes(n)||n!=="default"&&n!=="long_context"||e.push(n)}return e}function Ud(t){const e=on(t?.supportedContextTiers);if(e.length===0)return null;const s=String(t?.defaultContextTier||"").trim().toLowerCase();return s&&e.includes(s)?s:e.includes("default")?"default":e[0]||null}const Hr={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function jd(t){const e=Number(t);return!Number.isSafeInteger(e)||e<=0?null:e%1e6===0?`${e/1e6}M`:e%1e3===0?`${e/1e3}K`:e.toLocaleString("en-US")}function Wd(t,e){const s=jd(e);return s?t==="long_context"?`Long context (${s} tokens, higher cost)`:`Default (${s} tokens)`:Hr[t]||t}function rn(t=[]){for(let e=t.length-1;e>=0;e-=1){const s=t[e];if(s?.eventType!=="session.model_changed")continue;const n=s?.data;if(!n||typeof n!="object")continue;const i=typeof n.newModel=="string"&&n.newModel?n.newModel:typeof n.model=="string"&&n.model?n.model:void 0;if(i)return{model:i,...typeof n.newReasoningEffort=="string"||n.newReasoningEffort===null?{reasoningEffort:n.newReasoningEffort}:{}}}}function Kd(t){return rn([t])}function Qi(t,e=[]){let s=Oo(t);for(const n of e){const i=Ro(s,n?.eventType,n?.data,{timestamp:n?.createdAt});i&&(s=i)}return s}function ls(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i+=1)if(!ls(t[i],e[i]))return!1;return!0}if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!ls(t[i],e[i]))return!1;return!0}function Xi(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(t instanceof Date)return t.getTime();const e=Date.parse(t||"");return Number.isFinite(e)?e:0}function Fn(t,e){const s=Xi(t?.updatedAt),n=Xi(e?.updatedAt);return s>0&&n>0&&n<=s}function Vd(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function qd(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&Vd(e?.status)&&Fn(t,e)}function zd(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!Ur(e?.status)&&!Gr(e?.orchestrationStatus)&&Fn(t,e)}function Yd(t,e){if(!e?.sessionId)return null;const s={sessionId:e.sessionId};let n=!1;for(const[a,l]of Object.entries(e))a==="sessionId"||l===void 0||ls(t?.[a],l)||(s[a]=l,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&!Fn(t,e)&&(s.pendingQuestion=null,n=!0),qd(t,e)?(s.status!==t.status&&(s.status=t.status,n=!0),s.waitReason!==t.waitReason&&(s.waitReason=t.waitReason,n=!0)):e.waitReason===void 0&&t?.waitReason&&e.status!=="waiting"&&e.status!=="input_required"&&(s.waitReason=null,n=!0),Xl(t,e)?s.error!==t.error&&(s.error=t.error,n=!0):e.error===void 0&&t?.error&&e.status!=="failed"&&e.status!=="error"&&(s.error=null,n=!0),e.result===void 0&&t?.result&&e.status!=="completed"&&(s.result=null,n=!0),zd(t,e))for(const a of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[a]!=null&&(ls(s[a],t[a])||(s[a]=t[a],n=!0));else if(e.cronActive!==!0){t?.cronReason&&(s.cronReason=null,n=!0);for(const a of["cronKind","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[a]!=null&&e[a]===void 0&&(s[a]=null,n=!0);t?.cronInterval!=null&&e.cronInterval===void 0&&(s.cronInterval=null,n=!0)}if((Ur(e.status)||Gr(e.orchestrationStatus))&&t?.contextUsage?.compaction?.state==="running"&&e.contextUsage===void 0){const a={...t.contextUsage};delete a.compaction,s.contextUsage=Object.keys(a).length>0?a:null,n=!0}return n?s:null}function Ji(t){return String(t||"").replace(/\r\n/g,`
67
+ `).trim()}function Gr(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function Ur(t){return t==="completed"||t==="failed"||t==="cancelled"}function de(t){return String(t||"").slice(0,8)}function cs(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function Kt(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Qd=cs({provider:"system",subject:"system"});function Zi(t){const e=t.auth?.principal||null,s=cs(e),n=[{id:"all",kind:"all",label:"All",description:"Show every session, including system and unowned sessions."},{id:"system",kind:"system",label:"System",description:"Show sessions created by system agents."},{id:"unowned",kind:"unowned",label:"Unowned",description:"Show non-system sessions that do not have an owner link."}];if(s){const o=Kt(e,"current user");n.push({id:"me",kind:"me",label:`Me (${o})`,ownerKey:s,description:"Show sessions owned by the authenticated user currently signed in."}),n.push({id:"shared",kind:"shared",label:"Shared with me",description:"Show sessions other users have shared with you."})}const i=new Map;for(const o of Object.values(t.sessions?.byId||{})){const r=o?.owner,a=cs(r);!a||a===s||a===Qd||i.has(a)||i.set(a,r)}for(const[o,r]of[...i.entries()].sort((a,l)=>Kt(a[1]).localeCompare(Kt(l[1])))){const a=Kt(r),l=String(r?.email||"").trim();n.push({id:`owner:${o}`,kind:"owner",ownerKey:o,label:l&&l!==a?`${a} <${l}>`:a,description:"Show sessions owned by this user."})}return n}function us(t){return cs(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,includeShared:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function Xd(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||t?.includeShared||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function Jd(t,e,s){const n=t||us(s);if(!e)return n;if(e.kind==="all")return n.all?us(s):{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]};const i={...n,all:!1,ownerKeys:Array.isArray(n.ownerKeys)?[...n.ownerKeys]:[]};if(e.kind==="system"&&(i.includeSystem=!i.includeSystem),e.kind==="unowned"&&(i.includeUnowned=!i.includeUnowned),e.kind==="me"&&(i.includeMe=!i.includeMe),e.kind==="shared"&&(i.includeShared=!i.includeShared),e.kind==="owner"&&e.ownerKey){const o=i.ownerKeys.indexOf(e.ownerKey);o>=0?i.ownerKeys.splice(o,1):i.ownerKeys.push(e.ownerKey)}return Xd(i)?i:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function Bn(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 Zd(t){const e=Bn(t);return e?Math.max(1,60-`${e}: `.length):60}function ef(t){const e=String(t?.title||"").trim();if(!e)return"";const s=Bn(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===de(t?.sessionId)?"":n}return e===de(t?.sessionId)?"":e}function eo(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 to(t){return`📎 ${String(t||"").trim()}`}function so(t,e){const s=String(t||""),n=se(s,e,s.length),o=s.slice(0,n).match(/(^|\s)(@@?)([^\s]*)$/u);if(!o)return null;const r=o[2],a=String(o[3]||"");return{kind:r==="@@"?"sessions":"artifacts",query:a,signature:`${r}${a}`,tokenStart:(o.index||0)+String(o[1]||"").length,tokenEnd:n}}function tf(t,e,s,n){const i=String(t||""),o=se(i,e),r=se(i,s),a=String(n||"");return{prompt:`${i.slice(0,o)}${a}${i.slice(r)}`,cursor:o+a.length}}function sf(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function nf(t){const e=String(t?.sessionId||"").trim(),s=de(e)||"session";return`Referenced session: ${sf(t?.title,s)} — session://${e}`}function no(t,e,s){if(!e)return We(t,String(t||"").length,s);const n=String(t||""),i=n.slice(e.tokenEnd,e.tokenEnd+1),o=!i||/\s/u.test(i);return tf(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${o?" ":""}`)}function of(t,e=[]){let s=String(t||"");for(const n of e||[]){const i=String(n?.token||"").trim();i&&(s=s.split(i).join(" "))}return s.replace(/[ \t]+\n/g,`
68
+ `).replace(/\n[ \t]+/g,`
69
+ `).replace(/[ \t]{2,}/g," ").trim()}const io=new Set(["image/png","image/jpeg","image/gif","image/webp"]),oo=4*1024*1024,js=4;function rf(t,e=[]){const s=Array.isArray(e)?e.filter(o=>o?.sessionId&&o?.filename&&o?.kind!=="image"):[];if(s.length===0)return String(t||"");const n=s.map(o=>`[Attached file: ${o.filename} — artifact://${o.sessionId}/${o.filename}]`),i=of(t,s);return n.join(`
70
+ `)+(i?`
71
+
72
+ ${i}`:"")}function at(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function jr(t){return Array.from(String(t||"")).length}function af(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=Lo(s.value||"");for(const i of n)e.push(i);continue}if(Array.isArray(s)){e.push(s);continue}e.push(s)}return e}function lf(t,e){const s=Math.max(1,Number(e)||1),n=jr(t);return Math.max(1,Math.ceil(n/s))}function lt(t,e){const s=Math.max(1,Number(e)||1);return af(t).reduce((n,i)=>{if(!i)return n+1;if(Array.isArray(i)){const o=i.reduce((r,a)=>r+jr(a?.text||""),0);return n+Math.max(1,Math.ceil(o/s))}return n+lf(i.text||"",s)},0)}function se(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function Wr(t){return String(t||"").split(`
73
+ `)}function cf(t,e){const n=String(t||"").slice(0,se(t,e)).split(`
74
+ `),i=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:i.length}}function uf(t,e,s){const n=Wr(t),i=Math.max(0,Math.min(Number(e)||0,Math.max(0,n.length-1))),o=Math.max(0,Math.min(Number(s)||0,n[i]?.length||0));let r=0;for(let a=0;a<i;a+=1)r+=(n[a]?.length||0)+1;return se(t,r+o)}function We(t,e,s){const n=String(t||""),i=se(n,e),o=String(s||"");return{prompt:`${n.slice(0,i)}${o}${n.slice(i)}`,cursor:i+o.length}}function ct(t,e){const s=String(t||""),n=se(s,e);return n<=0?{prompt:s,cursor:n}:{prompt:`${s.slice(0,n-1)}${s.slice(n)}`,cursor:n-1}}function Vt(t){return/\s/u.test(t||"")}function Kr(t,e,s){const n=String(t||"");let i=se(n,e);if(s<0){for(;i>0&&Vt(n[i-1]);)i-=1;for(;i>0&&!Vt(n[i-1]);)i-=1;return i}for(;i<n.length&&Vt(n[i]);)i+=1;for(;i<n.length&&!Vt(n[i]);)i+=1;return i}function df(t,e){const s=String(t||""),n=se(s,e),i=Kr(s,n,-1);return i===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,i)}${s.slice(n)}`,cursor:i}}function ff(t,e,s){const n=Wr(t);if(n.length<=1)return se(t,e);const i=cf(t,e),o=Math.max(0,Math.min(i.line+s,n.length-1));return o===i.line?se(t,e):uf(t,o,i.column)}const ro=3e3,pf=new Set(["logs","sequence"]),hf=2e5,mf=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),gf=new Set([".json",".jsonl"]),yf=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function Vr(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function Sf(t,e=""){const s=Vr(t),n=String(e||"").toLowerCase();return yf.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}function ao(t,e=hf){const s=String(t??"");return s.length<=e?s:`${s.slice(0,e)}
75
+
76
+ [Preview truncated at ${e.toLocaleString()} characters. Open the artifact directly if you need the full file.]`}function bf(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 wf(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${bf(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
77
+ `)}function lo(t,e,s="",n=null){const i=String(s||"").toLowerCase(),o=Vr(t);if(n?.isBinary===!0||Sf(t,s))return{content:wf(t,n?.contentType||s,n?.sizeBytes??null),contentType:n?.contentType||s||"application/octet-stream",renderMode:"note",isBinary:!0,sizeBytes:n?.sizeBytes??null,uploadedAt:n?.uploadedAt||"",source:n?.source||"agent"};const r=ao(e);if(mf.has(o)||i.includes("markdown"))return{content:r,contentType:s||"text/markdown",renderMode:"markdown",isBinary:!1,sizeBytes:n?.sizeBytes??null,uploadedAt:n?.uploadedAt||"",source:n?.source||"agent"};if(gf.has(o)||i.includes("json"))try{return{content:ao(JSON.stringify(JSON.parse(String(e??"")),null,2)),contentType:s||"application/json",renderMode:"text"}}catch{return{content:r,contentType:s||"application/json",renderMode:"text"}}return{content:r,contentType:s||"text/plain",renderMode:"text"}}class If{constructor({store:e,transport:s}){this.store=e,this.transport=s,this.catalogTimer=null,this.activeSessionUnsub=null,this.activeSessionSubscriptionId=null,this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.sessionRefreshTimer=null,this.sessionHistoryLoads=new Map,this.sessionHistoryExpansionLoads=new Map,this.sessionOrchestrationStatsLoads=new Map,this.outboxFlushPromises=new Map,this.logUnsubscribe=null,this.promptReferenceSignature=null,this.promptReferenceSyncVersion=0,this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}getState(){return this.store.getState()}subscribe(e){return this.store.subscribe(e)}dispatch(e){return this.store.dispatch(e)}setStatus(e){this.dispatch({type:"ui/status",text:e})}getPromptAttachments(){const e=this.getState().ui.promptAttachments;return Array.isArray(e)?e.filter(Boolean):[]}setPromptAttachments(e){this.dispatch({type:"ui/promptAttachments",attachments:Array.isArray(e)?e:[]})}getSessionOutbox(e){if(!e)return[];const s=this.getState().outbox?.bySessionId?.[e];return Array.isArray(s)?s.filter(Boolean):[]}setSessionOutboxItems(e,s){e&&this.dispatch({type:"outbox/setSessionItems",sessionId:e,items:Array.isArray(s)?s:[]})}buildOutboxItem(e,s="pending"){const n=`msg:${Date.now()}:${Math.random().toString(36).slice(2,10)}`,i=s==="queued"||s==="cancelling"?s:"pending";return{id:n,text:String(e||""),createdAt:Date.now(),phase:i,attempted:!1,clientMessageIds:[n]}}getPendingOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="pending")}getQueuedOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="queued")}getNavigableOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="pending"||s?.phase==="queued"||s?.phase==="cancelling")}getEditableOutboxItems(e){return this.getPendingOutboxItems(e).filter(s=>s?.attempted!==!0)}getPromptEditSessionMatch(e=this.getState().sessions.activeSessionId){const s=this.getState().ui.promptEdit;return s?.sessionId===e?s:null}enterPendingPromptEdit(e,s){if(!e||!s)return!1;const i=this.getNavigableOutboxItems(e).find(l=>l.id===s);if(!i)return!1;const o=this.getState().ui,r=this.getPromptEditSessionMatch(e),a=r?{...r,itemId:s,phase:i.phase}:{sessionId:e,itemId:s,phase:i.phase,draftPrompt:o.prompt,draftCursor:o.promptCursor};return this.dispatch({type:"ui/promptEdit",promptEdit:a}),this.setPrompt(i.text,i.text.length),this.setFocus(A.PROMPT),!0}exitPendingPromptEdit({restoreDraft:e=!0}={}){const s=this.getState().ui.promptEdit;return s?(this.dispatch({type:"ui/promptEdit",promptEdit:null}),e&&this.setPrompt(s.draftPrompt||"",Number.isFinite(s.draftCursor)?s.draftCursor:String(s.draftPrompt||"").length),!0):!1}selectPreviousPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e);if(s.length===0)return!1;const n=this.getPromptEditSessionMatch(e);if(!n)return this.enterPendingPromptEdit(e,s[s.length-1].id);const i=s.findIndex(o=>o.id===n.itemId);return i<=0?!1:this.enterPendingPromptEdit(e,s[i-1].id)}selectNextPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e),n=this.getPromptEditSessionMatch(e);if(!n)return!1;const i=s.findIndex(o=>o.id===n.itemId);return i===-1||i>=s.length-1?this.exitPendingPromptEdit({restoreDraft:!0}):this.enterPendingPromptEdit(e,s[i+1].id)}async cancelSelectedOutboxPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const n=this.getSessionOutbox(e.sessionId).find(o=>o.id===e.itemId);return n?n.phase==="cancelling"?(this.exitPendingPromptEdit({restoreDraft:!0}),!1):await this.cancelOutboxItem(e.sessionId,e.itemId)?(this.exitPendingPromptEdit({restoreDraft:!0}),!0):!1:!1}cancelSelectedPendingPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const s=this.getSessionOutbox(e.sessionId);if(!s.find(o=>o.id===e.itemId&&o.phase==="pending"))return!1;const i=s.filter(o=>o.id!==e.itemId);return this.setSessionOutboxItems(e.sessionId,i),this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"ui/status",text:"Cancelled pending prompt"}),!0}async cancelOutboxItem(e,s){if(!e||!s)return!1;const n=this.getSessionOutbox(e),i=n.find(r=>r.id===s);if(!i||i.phase==="cancelling")return!1;this.getPromptEditSessionMatch(e)?.itemId===s&&this.exitPendingPromptEdit({restoreDraft:!0});const o=Array.isArray(i.clientMessageIds)&&i.clientMessageIds.length>0?i.clientMessageIds:[i.id];if(i.phase==="queued")if(this.setSessionOutboxItems(e,n.map(r=>r.id===s?{...r,phase:"cancelling"}:r)),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,o),this.dispatch({type:"ui/status",text:"Cancelling queued prompt"})}catch(r){return this.setSessionOutboxItems(e,n),this.dispatch({type:"ui/status",text:r?.message||String(r)}),!1}else this.dispatch({type:"ui/status",text:"Queued prompt marked cancelling (local only — transport has no cancel)"});else{const r=n.filter(a=>a.id!==s);if(this.setSessionOutboxItems(e,r),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,o)}catch{}this.dispatch({type:"ui/status",text:"Cancelled pending prompt"})}return!0}async cancelLatestQueuedOutbox(e=this.getState().sessions.activeSessionId){if(!e)return!1;const s=this.getQueuedOutboxItems(e);if(s.length===0)return!1;const n=s[s.length-1];return await this.cancelOutboxItem(e,n.id)}queuePromptInOutbox(e,s,n=null){const i=this.buildOutboxItem(s,"pending");return Array.isArray(n?.attachments)&&n.attachments.length>0&&(i.attachments=n.attachments),this.setSessionOutboxItems(e,[...this.getSessionOutbox(e),i]),i}addPendingImageFiles(e){const s=Array.from(e||[]).filter(Boolean),n=this.getPromptAttachments(),i=n.filter(a=>a?.kind==="image"),o=[],r=[];for(const a of s){const l=String(a.type||"").toLowerCase();if(!io.has(l)){r.push({name:a.name||"image",reason:"unsupported type"});continue}if((Number(a.size)||0)>oo){r.push({name:a.name||"image",reason:"over 4 MB"});continue}if(i.length+o.length>=js){r.push({name:a.name||"image",reason:`max ${js} images`});continue}o.push({kind:"image",file:a,filename:String(a.name||"image"),contentType:l,sizeBytes:Number(a.size)||0})}return o.length>0&&this.setPromptAttachments([...n,...o]),r.length>0&&this.dispatch({type:"ui/status",text:`Skipped ${r.map(a=>`${a.name} (${a.reason})`).join(", ")}`}),{accepted:o.length,rejected:r}}stageUploadedImageAttachment(e,s){const n=String(e?.contentType||"").toLowerCase();return!io.has(n)||(Number(e?.sizeBytes)||0)>oo||this.getPromptAttachments().filter(o=>o?.kind==="image").length>=js?!1:(this.setPromptAttachments([...this.getPromptAttachments(),{kind:"image",uploaded:!0,sessionId:s,filename:e.filename,contentType:n,sizeBytes:Number(e?.sizeBytes)||0}]),!0)}async pasteImageFromClipboard(){if(typeof this.transport.captureClipboardImage!="function"||typeof this.transport.uploadArtifactFromPath!="function")return this.dispatch({type:"ui/status",text:"Clipboard image paste is not supported by this transport"}),!1;let e=null;try{e=await this.transport.captureClipboardImage()}catch(s){return this.dispatch({type:"ui/status",text:`Clipboard read failed: ${s?.message||s}`}),!1}if(!e?.path)return this.dispatch({type:"ui/status",text:"No image on the clipboard"}),!1;this.dispatch({type:"ui/status",text:"Attaching clipboard image..."});try{const s=this.getPromptDraftSessionId()||await this.ensurePromptAttachmentSessionId(),n=await this.transport.uploadArtifactFromPath(s,e.path),i=await this.finalizeArtifactUpload(n,{sessionId:s,suppressStatus:!0});return this.stageUploadedImageAttachment(i,s)?(this.dispatch({type:"ui/status",text:`Clipboard image attached to your next message (${i.filename})`}),!0):(this.dispatch({type:"ui/status",text:`Uploaded ${i.filename} (not attachable: type/size/count limit)`}),!1)}catch(s){return this.dispatch({type:"ui/status",text:`Clipboard image attach failed: ${s?.message||s}`}),!1}}removePendingImageAttachment(e){const s=this.getPromptAttachments(),i=s.filter(o=>o?.kind==="image")[e];i&&this.setPromptAttachments(s.filter(o=>o!==i))}async uploadPendingImageAttachments(e,s,n){const i=[],o=String(n||Date.now()).replace(/[^a-zA-Z0-9_-]/g,"").slice(-24)||"img";let r=0;for(const a of s){if(!a.file){a.uploaded&&a.filename&&i.push({filename:a.filename});continue}r+=1;const l={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[a.contentType]||"png",u=`attach-${o}-${r}.${l}`;await this.transport.uploadArtifactFromFile(e,a.file,u),i.push({filename:u})}return i}acknowledgeOutboxPrompt(e,s,n=null){if(!e)return!1;const i=this.getSessionOutbox(e);if(n){const l=i.findIndex(u=>(u?.phase==="pending"||u?.phase==="queued"||u?.phase==="cancelling")&&Array.isArray(u.clientMessageIds)&&u.clientMessageIds.includes(n));if(l!==-1){const u=i[l];return this.setSessionOutboxItems(e,i.filter((f,d)=>d!==l)),this.getPromptEditSessionMatch(e)?.itemId===u?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const o=Ji(s);if(!o)return!1;const r=i.findIndex(l=>(l?.phase==="pending"||l?.phase==="queued"||l?.phase==="cancelling")&&Ji(l.text)===o);if(r===-1)return!1;const a=i[r];return this.setSessionOutboxItems(e,i.filter((l,u)=>u!==r)),this.getPromptEditSessionMatch(e)?.itemId===a?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}acknowledgeCancelledOutboxPrompt(e,s=[]){if(!e)return!1;const n=new Set((s||[]).filter(l=>typeof l=="string"&&l));if(n.size===0)return!1;const i=this.getSessionOutbox(e),o=i.filter(l=>l?.phase!=="cancelling"?!0:!(Array.isArray(l.clientMessageIds)?l.clientMessageIds:[l.id]).some(f=>n.has(f)));if(o.length===i.length)return!1;const r=new Set(i.filter(l=>!o.some(u=>u.id===l.id)).map(l=>l.id));this.setSessionOutboxItems(e,o);const a=this.getPromptEditSessionMatch(e);return a&&r.has(a.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}scheduleOutboxDispatch(e){if(!e||(this._outboxDispatchTimers||(this._outboxDispatchTimers=new Map),this._outboxDispatchTimers.has(e)))return;const s=setTimeout(()=>{this._outboxDispatchTimers.delete(e),this.dispatchPendingOutbox(e).catch(()=>{})},10);this._outboxDispatchTimers.set(e,s)}async dispatchPendingOutbox(e){if(!e)return!1;await Promise.resolve();const s=this.outboxFlushPromises.get(e);if(s)return await s.catch(()=>{}),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e),!1;const n=this.getPendingOutboxItems(e),i=n.find(m=>m?.attempted===!0),o=i?[i]:n.filter(m=>m?.attempted!==!0);if(o.length===0)return!1;const r=o.flatMap(m=>Array.isArray(m.clientMessageIds)&&m.clientMessageIds.length>0?m.clientMessageIds:[m.id]),a=o.map(m=>String(m.text||"")).join(`
78
+
79
+ `),l=o.flatMap(m=>Array.isArray(m.attachments)?m.attachments:[]),u={id:o[0].id,text:a,createdAt:o[0].createdAt||Date.now(),phase:"pending",attempted:!0,clientMessageIds:r,...l.length>0?{attachments:l}:{}},f=new Set(o.map(m=>m.id)),d=this.getSessionOutbox(e).filter(m=>!f.has(m.id));this.setSessionOutboxItems(e,[...d,u]);const p=this.getPromptEditSessionMatch(e);p&&f.has(p.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const h=(async()=>{await this.transport.sendMessage(e,u.text,{enqueueOnly:!0,clientMessageIds:u.clientMessageIds,...Array.isArray(u.attachments)&&u.attachments.length>0?{attachments:u.attachments}:{}});const g=this.getSessionOutbox(e).map(S=>S.id===u.id?{...S,phase:"queued"}:S);return this.setSessionOutboxItems(e,g),this.syncSessionEvents(e).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(m=>{const g=m?.code==="FORBIDDEN"||m?.code==="UNAUTHORIZED"||m?.status===403||m?.status===401,S=this.getSessionOutbox(e);if(g){const y=S.map(w=>w.id===u.id?{...w,phase:"rejected"}:w);this.setSessionOutboxItems(e,y),setTimeout(()=>{const w=this.getSessionOutbox(e),I=w.filter(x=>!(x.id===u.id&&x.phase==="rejected"));I.length!==w.length&&this.setSessionOutboxItems(e,I)},6e3)}else{const y=S.map(w=>w.id===u.id?{...u,phase:"pending",attempted:!0}:w);this.setSessionOutboxItems(e,y)}throw this.dispatch({type:"ui/status",text:m?.message||String(m)}),m}).finally(()=>{this.outboxFlushPromises.delete(e),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e)});return this.outboxFlushPromises.set(e,h),await h}async flushQueuedOutbox(e){return await this.dispatchPendingOutbox(e)}maybeFlushQueuedOutbox(e){return!e||this.getPendingOutboxItems(e).length===0?!1:(this.scheduleOutboxDispatch(e),!0)}getPromptReferenceContext(){const e=this.getState();return so(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=je(s),i=n?.sessionId||s.sessions.activeSessionId||null,o=n?.filename||null;if(!i||!o)return!1;const r=to(o),a=no(s.ui.prompt,e,r),l=this.getPromptAttachments(),u=l.findIndex(p=>p?.sessionId===i&&p?.filename===o),f={...u>=0?l[u]:{},id:`${i}/${o}`,sessionId:i,filename:o,resolvedPath:o,token:r},d=u>=0?l.map((p,h)=>h===u?f:p):[...l,f];return this.setPrompt(a.prompt,a.cursor),this.setPromptAttachments(d),this.setFocus(A.PROMPT),this.dispatch({type:"ui/status",text:`Attached ${o}`}),!0}acceptSessionPromptReference(e=this.getPromptReferenceContext()){if(!e||e.kind!=="sessions")return!1;const s=this.getState(),i=wt(s)[0]||null,o=i?.sessionId&&s.sessions.byId[i.sessionId]||null;if(!o?.sessionId)return!1;const r=nf(o),a=no(s.ui.prompt,e,r);return this.setPrompt(a.prompt,a.cursor),this.setFocus(A.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${de(o.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}openSessionOwnerFilter(){const e=this.getState(),s=Zi(e);this.dispatch({type:"ui/modal",modal:{type:"sessionOwnerFilter",title:"Session Filter",previousFocus:e.ui.focusRegion,selectedIndex:0,items:s}}),this.dispatch({type:"ui/status",text:"Up/Down choose entry · Space toggle · Esc close"})}toggleSessionOwnerFilter(e=null){const s=this.getState(),n=s.ui.modal;if(!n||n.type!=="sessionOwnerFilter")return;const i=e==null?Math.max(0,Number(n.selectedIndex)||0):Math.max(0,Number(e)||0),o=n.items?.[i];if(!o)return;const r=Jd(s.sessions.ownerFilter,o,s.auth?.principal);this.dispatch({type:"sessions/ownerFilter",filter:r}),this.dispatch({type:"ui/modalSelection",index:i}),this.dispatch({type:"ui/status",text:`Session filter updated: ${o.label||o.id||"selection"}`})}refreshOpenSessionOwnerFilterModal(){const e=this.getState(),s=e.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return;const n=Zi(e),i=Array.isArray(s.items)?s.items:[];if(i.length===n.length&&i.every((u,f)=>u?.id===n[f]?.id))return;const r=i[Math.max(0,Number(s.selectedIndex)||0)]?.id,a=r!=null?n.findIndex(u=>u.id===r):-1,l=a>=0?a:Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1)));this.dispatch({type:"ui/modal",modal:{...s,items:n,selectedIndex:l}})}setFilesFilter(e={}){this.dispatch({type:"files/filter",filter:e})}clearPromptReferenceBrowser(){this.promptReferenceSignature=null,this.promptReferenceSyncVersion+=1,this.getState().sessions.filterQuery&&this.setSessionFilterQuery(""),this.getState().files.filter?.query&&this.setFilesFilter({query:""})}syncPromptReferenceBrowser(){const e=this.getState(),s=so(e.ui.prompt,e.ui.promptCursor);if(!s){this.clearPromptReferenceBrowser();return}if(this.promptReferenceSignature===s.signature)return;if(this.promptReferenceSignature=s.signature,s.kind==="sessions"){this.promptReferenceSyncVersion+=1,this.setFilesFilter({query:""}),this.setSessionFilterQuery(s.query);return}const n=e.sessions.activeSessionId;if(this.setSessionFilterQuery(""),this.setFilesFilter({scope:"selectedSession",query:s.query}),!n)return;this.selectInspectorTab("files").catch(()=>{});const i=++this.promptReferenceSyncVersion;this.ensureFilesForScope("selectedSession").then(async()=>{if(this.promptReferenceSyncVersion!==i)return;const o=new Set(as(this.getState(),"selectedSession")),a=$t(this.getState()).filter(l=>o.has(l.sessionId))[0]||null;a?.filename&&(this.dispatch({type:"files/select",sessionId:a.sessionId,filename:a.filename}),await this.ensureFilePreview(a.sessionId,a.filename).catch(()=>{}))}).catch(()=>{})}async start({initialSessionId:e=null}={}){await this.transport.start();const s=typeof this.transport.getAuthContext=="function"?this.transport.getAuthContext():null;this.dispatch({type:"auth/context",principal:s?.principal??null,authorization:s?.authorization??null}),this.getState().sessions.ownerFilterExplicit||this.dispatch({type:"sessions/ownerFilter",filter:us(s?.principal??null)});const n=typeof this.transport.getLogConfig=="function"?this.transport.getLogConfig():null;n&&this.dispatch({type:"logs/config",available:n.available,availabilityReason:n.availabilityReason}),this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,statusText:"Connected"});const i=String(e||"").trim();i&&this.dispatch({type:"sessions/navigationIntent",sessionId:i}),await this.refreshSessions(),this.catalogTimer=setInterval(()=>{this.refreshSessions().catch(o=>{this.dispatch({type:"connection/error",error:o?.message||String(o),statusText:zi})})},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}handleSessionGone(e){e&&(this.activeSessionSubscriptionId===e&&this.detachActiveSession(),this.activeSessionDetailSessionId===e&&this.activeSessionDetailTimer&&(clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null),this.dispatch({type:"sessions/gone",sessionId:e}))}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===zi,i=this.getState().sessions.activeSessionId;let o=(await Hd(this.transport)).map(Hs);if(typeof this.transport.listSessionGroups=="function"){const f=await this.transport.listSessionGroups().catch(()=>[]),d=(Array.isArray(f)?f:[]).map(Bd).filter(Boolean);d.length>0&&(o=[...d,...o])}const r=e.sessions.navigationIntent;if(r?.status==="pending"&&!o.some(f=>f?.sessionId===r.sessionId)&&typeof this.transport.getSession=="function")try{const f=await this.transport.getSession(r.sessionId);f?.sessionId?o=[...o,Hs(f)]:this.dispatch({type:"sessions/navigationIntentFailed",sessionId:r.sessionId,errorKind:"not_found"})}catch(f){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:r.sessionId,errorKind:Us(f)})}const a=i;if(a&&!o.some(f=>f?.sessionId===a)&&typeof this.transport.getSession=="function"){const f=await this.transport.getSession(a).catch(()=>null);f?.sessionId&&(o=[...o,Hs(f)])}s&&this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,...n?{statusText:"Connected"}:{}}),this.dispatch({type:"sessions/loaded",sessions:o}),this.refreshOpenSessionOwnerFilterModal();const l=this.getState().sessions.activeSessionId,u=new Set;if(l){if(l!==i){if(!this.getState().sessions.byId[l]?.isGroup){const h=this.getState().sessions.navigationIntent;if(h&&h.sessionId===l&&h.status!=="failed")try{await this.loadSession(l)}catch(m){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:l,errorKind:Us(m)})}else await this.loadSession(l)}return}if(this.getState().sessions.byId[l]?.isGroup)return;this.getState().history.bySessionId.get(l)?.events?.length||await this.ensureSessionHistory(l,{force:!0}).catch(()=>{}),this.activeSessionSubscriptionId!==l&&this.attachActiveSession(l),await this.syncSessionDetail(l).catch(()=>{}),await this.syncSessionEvents(l).catch(()=>{}),u.add(l);const d=this.getState(),p=d.sessions.byId[l]||null;if(p?.parentSessionId&&typeof this.transport.getSession=="function"){const h=Object.values(d.sessions.byId).filter(m=>m?.parentSessionId===p.parentSessionId).map(m=>m.sessionId).filter(m=>m&&m!==l).slice(0,6);await Promise.all(h.map(m=>this.syncSessionDetail(m).catch(()=>{})));for(const m of h)u.add(m)}}await this.syncVisibleSessionDetails(u).catch(()=>{}),this.ensureInspectorData().catch(()=>{}),this.evictStaleSessionState()}evictStaleSessionState(){const e=this.getState(),s=e.sessions.activeSessionId,n=Date.now(),i=6e4,o=20,r=Object.entries(e.orchestration.bySessionId||{});if(r.length>o){const f=r.filter(([d,p])=>d!==s&&!p?.loading).sort((d,p)=>(d[1]?.fetchedAt||0)-(p[1]?.fetchedAt||0)).slice(0,r.length-o).filter(([,d])=>n-(d?.fetchedAt||0)>i);f.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:f.map(([d])=>d)})}const a=Object.entries(e.executionHistory?.bySessionId||{});if(a.length>o){const f=a.filter(([d,p])=>d!==s&&!p?.loading).sort((d,p)=>(d[1]?.fetchedAt||0)-(p[1]?.fetchedAt||0)).slice(0,a.length-o).filter(([,d])=>n-(d?.fetchedAt||0)>i);f.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:f.map(([d])=>d)})}const l=Object.entries(e.files.bySessionId||{});if(l.length>o){const f=l.filter(([d])=>d!==s).slice(0,l.length-o);f.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:f.map(([d])=>d)})}const u=[...e.history.bySessionId.entries()];if(u.length>o*2){const f=u.filter(([d])=>d!==s).slice(0,u.length-o*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=_t({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??mt(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),o=Zs(s,i),r=[...new Set(o.map(a=>a.sessionId).filter(a=>a&&!e.has(a)))];r.length!==0&&await Promise.all(r.map(a=>this.syncSessionDetail(a).catch(()=>{})))}async catchUpSessionHistory(e,s,n){let o;try{o=await this.transport.getSessionEvents(e,n,1e3)}catch(f){return At(f)&&this.handleSessionGone(e),null}if(!Array.isArray(o)||o.length>=1e3)return null;if(o.length===0)return s;let r=s;for(const f of o)r=li(r,f);r={...r,loadedEventLimit:Math.max(Number(s.loadedEventLimit)||0,Array.isArray(r.events)?r.events.length:0)},this.dispatch({type:"history/set",sessionId:e,history:r});for(const f of o)this.reconcileOutboxAgainstEvent(e,f);const a=rn(o),l=this.getState().sessions.byId[e]||{},u=Qi(l.contextUsage,o);return(a||u)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...a||{},...u?{contextUsage:u}:{}}}),r}async ensureSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),i=Math.max(J,Number(n?.loadedEventLimit??J)||J);if(!s&&n?.events)return n;if(!s&&this.sessionHistoryLoads.has(e))return this.sessionHistoryLoads.get(e);const o=Number(n?.lastSeq)||0;if(s&&o>0&&Array.isArray(n?.events)&&n.events.length>0){const a=await this.catchUpSessionHistory(e,n,o);if(a)return a}const r=(async()=>{let a;try{a=await this.transport.getSessionEvents(e,void 0,i)}catch(p){if(At(p))return this.handleSessionGone(e),null;throw p}const l={...Ut(a,{requestedLimit:i}),lastSeq:a[a.length-1]?.seq||0};this.dispatch({type:"history/set",sessionId:e,history:l});for(const p of a||[])this.reconcileOutboxAgainstEvent(e,p);const u=rn(a),f=this.getState().sessions.byId[e]||{},d=Qi(f.contextUsage,a);return(u||d)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...u||{},...d?{contextUsage:d}:{}}}),l})().finally(()=>{this.sessionHistoryLoads.delete(e)});return this.sessionHistoryLoads.set(e,r),r}async ensureInspectorData(e=this.getState().ui.inspectorTab){if(e==="sequence"){const s=this.getState().sessions.activeSessionId;if(!s)return;await this.ensureSessionHistory(s).catch(()=>{}),await this.ensureOrchestrationStats(s).catch(()=>{});return}if(e==="nodes"){const s=this.getState(),n=_t({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??mt(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),o=Zs(s,i),r=[...new Set(o.map(a=>a.sessionId).filter(Boolean))];if(r.length===0)return;await Promise.allSettled(r.map(a=>this.ensureSessionHistory(a)));return}if(e==="files"&&await this.ensureFilesForScope(xe(this.getState())),e==="history"){const s=this.getState().sessions.activeSessionId,n=s&&this.getState().executionHistory?.bySessionId?.[s]||null;s&&!n&&await this.ensureExecutionHistory(s)}e==="stats"&&(await this.ensureSessionStats().catch(()=>{}),await this.ensureFleetStats().catch(()=>{}))}async ensureOrchestrationStats(e,{force:s=!1}={}){if(!e||typeof this.transport.getOrchestrationStats!="function")return null;const n=this.getState().orchestration.bySessionId?.[e]||null,i=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&i-n.fetchedAt<Nd)return n;if(!s&&this.sessionOrchestrationStatsLoads.has(e))return this.sessionOrchestrationStatsLoads.get(e);this.dispatch({type:"orchestration/statsLoading",sessionId:e});const o=(async()=>{try{const r=await this.transport.getOrchestrationStats(e);return this.dispatch({type:"orchestration/statsLoaded",sessionId:e,stats:r,fetchedAt:Date.now()}),this.getState().orchestration.bySessionId?.[e]||null}catch(r){return At(r)?(this.handleSessionGone(e),null):(this.dispatch({type:"orchestration/statsError",sessionId:e,error:r?.message||String(r),fetchedAt:Date.now()}),null)}})().finally(()=>{this.sessionOrchestrationStatsLoads.delete(e)});return this.sessionOrchestrationStatsLoads.set(e,o),o}async ensureSessionStats({force:e=!1}={}){const s=this.getState().sessions.activeSessionId;if(!s||typeof this.transport.getSessionMetricSummary!="function")return;const n=this.getState().sessionStats?.bySessionId?.[s]||null,i=Date.now();if(!(!e&&n?.loading)&&!(!e&&n&&Number.isFinite(n.fetchedAt)&&i-n.fetchedAt<Pd)){this.dispatch({type:"sessionStats/loading",sessionId:s});try{const[o,r,a,l,u,f,d]=await Promise.all([this.transport.getSessionMetricSummary(s),typeof this.transport.getSessionTokensByModel=="function"?this.transport.getSessionTokensByModel(s).catch(()=>[]):[],typeof this.transport.getSessionTreeStats=="function"?this.transport.getSessionTreeStats(s):null,typeof this.transport.getSessionSkillUsage=="function"?this.transport.getSessionSkillUsage(s).catch(()=>null):null,typeof this.transport.getSessionTreeSkillUsage=="function"?this.transport.getSessionTreeSkillUsage(s).catch(()=>null):null,typeof this.transport.getSessionFactsStats=="function"?this.transport.getSessionFactsStats(s).catch(()=>null):null,typeof this.transport.getSessionTreeFactsStats=="function"?this.transport.getSessionTreeFactsStats(s).catch(()=>null):null]);this.dispatch({type:"sessionStats/loaded",sessionId:s,summary:o,tokensByModel:r,treeStats:a,skillUsage:l,treeSkillUsage:u,factsStats:f,treeFactsStats:d})}catch{this.dispatch({type:"sessionStats/loaded",sessionId:s,summary:null,tokensByModel:[],treeStats:null,skillUsage:null,treeSkillUsage:null,factsStats:null,treeFactsStats:null})}}}async ensureFleetStats({force:e=!1}={}){if(typeof this.transport.getFleetStats!="function")return;const s=this.getState().fleetStats,n=Date.now();if(!(!e&&s?.loading)&&!(!e&&s?.data&&Number.isFinite(s.fetchedAt)&&n-s.fetchedAt<_d)){this.dispatch({type:"fleetStats/loading"});try{const o={since:new Date(Date.now()-Od*864e5),includeDeleted:!0},[r,a,l,u,f,d]=await Promise.all([this.transport.getFleetStats(o),typeof this.transport.getUserStats=="function"?this.transport.getUserStats(o).catch(()=>null):null,typeof this.transport.getFleetSkillUsage=="function"?this.transport.getFleetSkillUsage(o).catch(()=>null):null,typeof this.transport.getFleetRetrievalUsage=="function"?this.transport.getFleetRetrievalUsage(o).catch(()=>null):null,typeof this.transport.getSharedFactsStats=="function"?this.transport.getSharedFactsStats().catch(()=>null):null,typeof this.transport.getFactsTombstoneStats=="function"?this.transport.getFactsTombstoneStats().catch(()=>null):null]);this.dispatch({type:"fleetStats/loaded",data:r,userStats:a,skillUsage:l,retrievalUsage:u,sharedFactsStats:f,factsTombstoneStats:d})}catch{this.dispatch({type:"fleetStats/loaded",data:null,userStats:null,skillUsage:null,retrievalUsage:null,sharedFactsStats:null,factsTombstoneStats:null})}}}async openAdminConsole(){this.dispatch({type:"admin/visibility",visible:!0}),await this.refreshAdminProfile().catch(()=>{})}closeAdminConsole(){this.dispatch({type:"admin/visibility",visible:!1})}async refreshAdminProfile(){if(typeof this.transport.getCurrentUserProfile!="function")return this.dispatch({type:"admin/profile/loadFailed",error:"Admin Console is not available on this transport."}),null;this.dispatch({type:"admin/profile/loading"});try{const e=await this.transport.getCurrentUserProfile();return this.dispatch({type:"admin/profile/loaded",profile:e}),await this.refreshSystemGhcpKeyStatus(e),e||null}catch(e){return this.dispatch({type:"admin/profile/loadFailed",error:e?.message||String(e)}),null}}async refreshSystemGhcpKeyStatus(e=null){if(!(e||this.getState().admin?.profile||null)?.isAdmin||typeof this.transport.getSystemGitHubCopilotKeyStatus!="function")return null;this.dispatch({type:"admin/systemGhcpKey/loading"});try{const n=await this.transport.getSystemGitHubCopilotKeyStatus();return this.dispatch({type:"admin/systemGhcpKey/loaded",status:n}),n||null}catch(n){return this.dispatch({type:"admin/systemGhcpKey/loadFailed",error:n?.message||String(n)}),null}}setAdminGhcpKeyStoreAsSystem(e){e&&!this.getState().admin?.profile?.isAdmin||this.dispatch({type:"admin/ghcpKey/setSystemTarget",value:!!e})}beginAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/beginEdit",draft:""})}setAdminGhcpKeyDraft(e,s=String(e||"").length){this.dispatch({type:"admin/ghcpKey/setDraft",draft:e,cursorIndex:s})}insertAdminGhcpKeyText(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=String(e||"").replace(/\r?\n/g,""),i=We(s.draft||"",s.cursorIndex||0,n);this.setAdminGhcpKeyDraft(i.prompt,i.cursor)}deleteAdminGhcpKeyChar(){const e=this.getState().admin?.ghcpKey;if(!e?.editing)return;const s=ct(e.draft||"",e.cursorIndex||0);this.setAdminGhcpKeyDraft(s.prompt,s.cursor)}moveAdminGhcpKeyCursor(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,se(n,(s.cursorIndex||0)+e))}moveAdminGhcpKeyCursorToBoundary(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,e==="start"?0:n.length)}cancelAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/cancelEdit"})}async saveAdminGhcpKey(){const e=!!this.getState().admin.ghcpKey.storeAsSystem,s=e?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?"This deployment does not support System keys yet.":"Admin Console is not available on this transport."});return}const n=String(this.getState().admin.ghcpKey.draft||"").trim();if(n.length===0){this.dispatch({type:"admin/ghcpKey/saveFailed",error:"Enter a key, or use Clear to remove the override."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{if(e){const i=await this.transport.setSystemGitHubCopilotKey({key:n});this.dispatch({type:"admin/systemGhcpKey/saved",status:i})}else{const i=await this.transport.setCurrentUserGitHubCopilotKey({key:n});this.dispatch({type:"admin/ghcpKey/saved",profile:i})}}catch(i){this.dispatch({type:"admin/ghcpKey/saveFailed",error:i?.message||String(i)})}}async clearAdminGhcpKey(){const e=!!this.getState().admin.ghcpKey.storeAsSystem,s=e?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?"This deployment does not support System keys yet.":"Admin Console is not available on this transport."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{if(e){const n=await this.transport.setSystemGitHubCopilotKey({key:null});this.dispatch({type:"admin/systemGhcpKey/saved",status:n})}else{const n=await this.transport.setCurrentUserGitHubCopilotKey({key:null});this.dispatch({type:"admin/ghcpKey/saved",profile:n})}}catch(n){this.dispatch({type:"admin/ghcpKey/saveFailed",error:n?.message||String(n)})}}async ensureExecutionHistory(e,{force:s=!1}={}){if(!e||typeof this.transport.getExecutionHistory!="function")return null;const n=this.getState().executionHistory?.bySessionId?.[e]||null,i=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&i-n.fetchedAt<15e3)return n;this.dispatch({type:"executionHistory/loading",sessionId:e});try{const o=await this.transport.getExecutionHistory(e);this.dispatch({type:"executionHistory/loaded",sessionId:e,events:o||[],fetchedAt:Date.now()})}catch(o){console.error("[executionHistory] fetch error:",o?.message||o),this.dispatch({type:"executionHistory/error",sessionId:e,error:o?.message||String(o),fetchedAt:Date.now()})}return this.getState().executionHistory?.bySessionId?.[e]||null}async ensureFilesForScope(e=xe(this.getState()),{force:s=!1}={}){const n=as(this.getState(),e);return n.length===0?e==="allSessions"?[]:null:e==="allSessions"||n.length>1?Promise.allSettled(n.map(i=>this.ensureFilesForSession(i,{force:s}))):this.ensureFilesForSession(n[0],{force:s})}async ensureSelectedFilePreview(){const e=je(this.getState());return!e?.sessionId||!e?.filename?null:this.ensureFilePreview(e.sessionId,e.filename).catch(()=>null)}async ensureFilesForSession(e,{force:s=!1}={}){if(!e||typeof this.transport.listArtifacts!="function")return null;const n=this.getState().files.bySessionId[e];if(!s&&n?.loading)return n;if(!s&&n?.loaded)return n.selectedFilename&&await this.ensureFilePreview(e,n.selectedFilename).catch(()=>{}),n;this.dispatch({type:"files/sessionLoading",sessionId:e});try{const i=await this.transport.listArtifacts(e);this.dispatch({type:"files/sessionLoaded",sessionId:e,entries:i});const o=this.getState().files.bySessionId[e];return o?.selectedFilename&&await this.ensureFilePreview(e,o.selectedFilename).catch(()=>{}),o}catch(i){return this.dispatch({type:"files/sessionError",sessionId:e,error:i?.message||String(i)}),null}}async ensureFilePreview(e,s,{force:n=!1}={}){if(!e||!s||typeof this.transport.downloadArtifact!="function")return null;const i=this.getState().files.bySessionId[e],o=i?.previews?.[s];let r=Yl(i?.entries,s);if(!n&&o?.loading||!n&&o&&(o.content!==void 0||o.error))return o;if(!r&&typeof this.transport.getArtifactMetadata=="function")try{r=await this.transport.getArtifactMetadata(e,s)}catch{r=null}this.dispatch({type:"files/previewLoading",sessionId:e,filename:s});try{const a=r?.isBinary===!0?lo(s,"",r.contentType||"",r):lo(s,await this.transport.downloadArtifact(e,s),r?.contentType||"",r);return this.dispatch({type:"files/previewLoaded",sessionId:e,filename:s,...a}),a}catch(a){return this.dispatch({type:"files/previewError",sessionId:e,filename:s,error:a?.message||String(a)}),null}}buildArtifactPickerItems(e=[],s=[]){const n=(e||[]).map(i=>({id:`${i.sessionId}/${i.filename}`,kind:"artifact",sessionId:i.sessionId,filename:i.filename}));for(const i of s||[]){const o=String(i?.href||"").trim();o&&n.push({id:`url:${o}`,kind:"url",href:o,text:String(i?.text||o).trim()||o})}return(e||[]).length>1&&n.push({id:"__downloadAll__",kind:"downloadAll"}),n}buildArtifactPickerModal({artifactLinks:e,httpLinks:s,previousFocus:n,selectedId:i}={}){const o=this.buildArtifactPickerItems(e,s);if(o.length===0)return null;const r=o.findIndex(a=>a.id===i);return{type:"artifactPicker",title:"Linked Items",previousFocus:n,artifactLinks:e,httpLinks:s,items:o,selectedIndex:r>=0?r:0,exportDirectory:typeof this.transport.getArtifactExportDirectory=="function"?this.transport.getArtifactExportDirectory():null}}getArtifactPickerSelectionId(){const e=this.getState().ui.modal;return!e||e.type!=="artifactPicker"?null:e.items?.[e.selectedIndex||0]?.id||null}replaceArtifactPickerModal(e=null){const s=this.getState().ui.modal;if(!s||s.type!=="artifactPicker")return;const n=this.buildArtifactPickerModal({artifactLinks:s.artifactLinks||[],httpLinks:s.httpLinks||[],previousFocus:s.previousFocus,selectedId:e||this.getArtifactPickerSelectionId()});if(!n){this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:n})}async saveArtifactDownload(e,s){if(typeof this.transport.saveArtifactDownload!="function")return this.dispatch({type:"ui/status",text:"Artifact download is not supported by this transport"}),null;try{const n=await this.transport.saveArtifactDownload(e,s);this.dispatch({type:"files/downloaded",sessionId:e,filename:s,localPath:n?.localPath||"",downloadedAt:Date.now()});const i=this.getState().sessions.activeSessionId;return(e===i||this.getState().ui.inspectorTab==="files")&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),e===i&&(this.dispatch({type:"files/select",sessionId:e,filename:s}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(e,s,{force:!0}).catch(()=>null))),n}catch(n){return this.dispatch({type:"ui/status",text:`Download failed: ${n?.message||String(n)}`}),null}}async openSelectedFileInDefaultApp(){const e=this.getState(),s=je(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||xe(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:i}=s,o=xe(e);if(typeof this.transport.openPathInDefaultApp!="function"){this.dispatch({type:"ui/status",text:"Opening files in the default app is not supported by this transport"});return}let r=e.files.bySessionId[n]?.downloads?.[i]?.localPath||null;if(r||(this.dispatch({type:"ui/status",text:`Downloading ${i} to open it...`}),r=(await this.saveArtifactDownload(n,i))?.localPath||null),!r){this.dispatch({type:"ui/status",text:`Open failed: could not save ${i} locally`});return}try{await this.transport.openPathInDefaultApp(r),this.dispatch({type:"ui/status",text:o==="allSessions"?`Opened ${de(n)} ${i} in the default app`:`Opened ${i} in the default app`})}catch(a){this.dispatch({type:"ui/status",text:`Open failed: ${a?.message||String(a)}`})}}async downloadSelectedArtifact(){const e=je(this.getState());if(!e?.sessionId||!e?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),null;this.dispatch({type:"ui/status",text:`Downloading ${e.filename}...`});const s=await this.saveArtifactDownload(e.sessionId,e.filename);return s?.localPath?(this.dispatch({type:"ui/status",text:`Downloaded ${e.filename}`}),s):null}async deleteSelectedArtifact({confirmed:e=!1}={}){const s=this.getState(),n=je(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const i=xe(s),o=i==="allSessions"?`${de(n.sessionId)} ${n.filename}`:n.filename;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifact",message:`Delete artifact "${o}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteArtifact",sessionId:n.sessionId,filename:n.filename,previousFocus:s.ui.focusRegion}}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;try{await this.transport.deleteArtifact(n.sessionId,n.filename),this.dispatch({type:"files/deleted",sessionId:n.sessionId,filename:n.filename}),await this.ensureFilesForSession(n.sessionId,{force:!0}).catch(()=>null);const r=je(this.getState());return r?.sessionId&&r?.filename&&await this.ensureFilePreview(r.sessionId,r.filename).catch(()=>null),this.dispatch({type:"ui/status",text:i==="allSessions"?`Deleted ${de(n.sessionId)} ${n.filename}`:`Deleted ${n.filename}`}),!0}catch(r){return this.dispatch({type:"ui/status",text:`Delete failed: ${r?.message||String(r)}`}),!1}}async openArtifactPicker(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=Kc(e),i=Vc(e);if(n.length===0&&i.length===0){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}const o=this.getState().files.bySessionId[s]?.selectedFilename||null,r=o?`${s}/${o}`:null,a=this.buildArtifactPickerModal({artifactLinks:n,httpLinks:i,previousFocus:e.ui.focusRegion,selectedId:r});if(!a){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:a}),this.dispatch({type:"ui/status",text:"Select a linked item and press Enter to open or download it"})}async downloadArtifactModalSelection(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="url"){if(typeof this.transport.openUrlInDefaultBrowser!="function"){this.dispatch({type:"ui/status",text:"Opening URLs is not supported by this transport"});return}this.dispatch({type:"ui/status",text:`Opening ${s.href}...`}),await this.transport.openUrlInDefaultBrowser(s.href),this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Opened ${s.href}`});return}if(s.kind==="downloadAll"){const i=(e.items||[]).filter(r=>r.kind!=="artifact"?!1:!this.getState().files.bySessionId[r.sessionId]?.downloads?.[r.filename]?.localPath);if(i.length===0){this.dispatch({type:"ui/status",text:"All artifacts already downloaded"});return}this.dispatch({type:"ui/status",text:`Downloading ${i.length} artifacts...`});let o=0;for(const r of i)(await this.saveArtifactDownload(r.sessionId,r.filename))?.localPath&&(o+=1);this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${o}/${i.length} artifacts`});return}this.dispatch({type:"ui/status",text:`Downloading ${s.filename}...`}),(await this.saveArtifactDownload(s.sessionId,s.filename))?.localPath&&(this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${s.filename}`}))}async moveFileSelection(e){const s=xe(this.getState());await this.ensureFilesForScope(s);const n=$t(this.getState());if(n.length===0)return;const i=je(this.getState())||n[0],o=Math.max(0,n.findIndex(l=>l.id===i?.id)),r=Math.max(0,Math.min(n.length-1,o+e)),a=n[r];!a?.sessionId||!a?.filename||(s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:a.id}):this.dispatch({type:"files/select",sessionId:a.sessionId,filename:a.filename}),await this.ensureFilePreview(a.sessionId,a.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${de(a.sessionId)} ${a.filename}`:`Previewing ${a.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;const s=xe(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 ${de(e.sessionId)} ${e.filename}`:`Previewing ${e.filename}`})}toggleFilePreviewFullscreen(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.files.bySessionId[s],i=!!e.files.fullscreen;if(!i&&!n?.selectedFilename){this.dispatch({type:"ui/status",text:"Select a file before entering fullscreen"});return}const o=!i;this.dispatch({type:"files/fullscreen",fullscreen:o}),this.dispatch({type:"ui/status",text:o?`Fullscreen files browser: ${n?.selectedFilename||""}`:"Closed fullscreen files browser"})}toggleFocusedPaneFullscreen(){const e=this.getState(),s=e.ui.focusRegion,n=e.ui.fullscreenPane||null,i=s===A.PROMPT?n:s;if(!Fd.has(i)||i===A.INSPECTOR&&e.ui.inspectorTab==="files")return;const o=n===i?null:i;this.dispatch({type:"ui/fullscreenPane",fullscreenPane:o}),this.dispatch({type:"ui/status",text:o?`Fullscreen ${i} pane`:`Closed fullscreen ${i} pane`}),!o&&s===A.PROMPT&&this.setFocus(i)}openFilesFilter(){const e=xe(this.getState());this.dispatch({type:"ui/modal",modal:{type:"filesFilter",title:"Files Filter",previousFocus:this.getState().ui.focusRegion,selectedIndex:0,items:[{id:"scope",label:"Scope",description:"Choose whether the files browser shows the selected session tree or aggregates exported files across all sessions.",options:[{id:"selectedSession",label:"Selected session tree"},{id:"allSessions",label:"All sessions"}]}]}}),this.dispatch({type:"ui/status",text:`Editing files filter: Scope = ${e==="allSessions"?"All sessions":"Selected session tree"}`})}setNavigationIntent(e){const s=String(e||"").trim();if(!s)return;this.dispatch({type:"sessions/navigationIntent",sessionId:s});const n=this.getState();if(n.sessions.byId[s]){this.loadSession(s).catch(i=>{this.dispatch({type:"sessions/navigationIntentFailed",sessionId:s,errorKind:Us(i)})});return}Object.keys(n.sessions.byId).length>0&&this.scheduleSessionsRefresh(0)}async loadSession(e){if(!e)return;if(this.getState().sessions.activeSessionId!==e&&(this.getState().ui.promptEdit&&this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"sessions/selected",sessionId:e}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.getState().sessions.byId[e]?.isGroup){this.detachActiveSession();return}await this.ensureSessionHistory(e,{force:!0}),await this.syncSessionDetail(e).catch(()=>{}),this.attachActiveSession(e),this.ensureInspectorData().catch(()=>{})}reconcileOutboxAgainstEvent(e,s){if(!(!e||!s)){if(s.eventType==="user.message"){const n=s?.data?.content,i=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(o=>typeof o=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];if(i.length>0)for(const o of i)this.acknowledgeOutboxPrompt(e,n,o);else typeof n=="string"&&n.trim()&&this.acknowledgeOutboxPrompt(e,n);return}if(s.eventType==="pending_messages.cancelled"){const n=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(i=>typeof i=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];this.acknowledgeCancelledOutboxPrompt(e,n)}}}mergeSessionEvent(e,s){if(!e||!s)return!1;const i=this.getState().history.bySessionId.get(e)||{chat:[],activity:[],lastSeq:0};if(s.seq<=(i.lastSeq||0))return!1;this.dispatch({type:"history/set",sessionId:e,history:li(i,s)}),s.eventType==="session.input_required_started"&&s.data?.question&&this.dispatch({type:"sessions/merged",session:{sessionId:e,status:"input_required",pendingQuestion:{question:s.data.question,choices:Array.isArray(s.data.choices)?s.data.choices:void 0,allowFreeform:s.data.allowFreeform??!0}}}),this.reconcileOutboxAgainstEvent(e,s);const o=Kd(s),r=this.getState().sessions.byId[e]||{sessionId:e},a=Ro(r.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(o||a)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...o||{},...a?{contextUsage:a}:{}}}),this.maybeFlushQueuedOutbox(e,this.getState().sessions.byId[e]||r),this.scheduleSessionDetailSync(e),!0}async syncSessionEvents(e){if(!e||typeof this.transport.getSessionEvents!="function")return;const s=this.getState().history.bySessionId.get(e);if(!s?.events){await this.ensureSessionHistory(e,{force:!0});return}const n=Number(s.lastSeq||0);let i=null;try{i=await this.transport.getSessionEvents(e,n,200)}catch(o){if(At(o)){this.handleSessionGone(e);return}throw o}if(!(!Array.isArray(i)||i.length===0))for(const o of i)this.mergeSessionEvent(e,o)}attachActiveSession(e){this.activeSessionSubscriptionId===e&&this.activeSessionUnsub||(this.detachActiveSession(),this.activeSessionSubscriptionId=e,this.activeSessionUnsub=this.transport.subscribeSession(e,s=>{this.mergeSessionEvent(e,s)}),this.syncSessionEvents(e).catch(()=>{}))}scheduleSessionDetailSync(e,s=250){typeof this.transport.getSession!="function"||!e||(this.activeSessionDetailTimer&&clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailSessionId=e,this.activeSessionDetailTimer=setTimeout(()=>{const n=this.activeSessionDetailSessionId;this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.syncSessionDetail(n).catch(()=>{})},s))}scheduleSessionsRefresh(e=0){this.sessionRefreshTimer&&clearTimeout(this.sessionRefreshTimer),this.sessionRefreshTimer=setTimeout(()=>{this.sessionRefreshTimer=null,this.refreshSessions().catch(()=>{})},Math.max(0,e))}async syncSessionDetail(e){if(typeof this.transport.getSession!="function"||!e)return;let s=null;try{s=await this.transport.getSession(e)}catch(o){if(At(o)){this.handleSessionGone(e);return}throw o}if(!s)return;const n=this.getState().sessions.byId[e]||null,i=Yd(n,s);(i||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:i||{sessionId:e}}),this.maybeFlushQueuedOutbox(e,s)}async createSession(e={}){try{const s=this.applyActiveGroupDefault(e),n=await this.transport.createSession(s);return await this.placeCreatedSessionInGroup(n,s.groupId??null),await this.refreshSessions(),await this.loadSession(n.sessionId),this.setFocus(A.PROMPT),this.dispatch({type:"ui/status",text:`Created session ${n.sessionId.slice(0,8)}`}),n}catch(s){return this.dispatch({type:"ui/status",text:s?.message||String(s)||"Failed to create session"}),null}}async createSessionForAgent(e,s={}){if(typeof this.transport.createSessionForAgent!="function")throw new Error("Named-agent session creation is not supported by this transport");try{const n=this.applyActiveGroupDefault(s),i=await this.transport.createSessionForAgent(e,n);return await this.placeCreatedSessionInGroup(i,n.groupId??null),await this.refreshSessions(),await this.loadSession(i.sessionId),this.setFocus(A.PROMPT),this.dispatch({type:"ui/status",text:`Created ${eo(e,s.title)} session ${i.sessionId.slice(0,8)}`}),i}catch(n){return this.dispatch({type:"ui/status",text:n?.message||String(n)||"Failed to create session"}),null}}async placeCreatedSessionInGroup(e,s){!s||!e?.sessionId||typeof this.transport.placeSessionsInGroup=="function"&&(e.viewerGroupId??null)!==s&&await this.transport.placeSessionsInGroup([e.sessionId],s).catch(()=>{})}getMovableGroupSessionSelection(){const e=this.getState();return(Array.isArray(e.sessions.selectedIds)&&e.sessions.selectedIds.length>0?e.sessions.selectedIds:e.sessions.activeSessionId?[e.sessions.activeSessionId]:[]).map(n=>e.sessions.byId[n]).filter(n=>n&&!n.isSystem&&!n.isGroup&&!n.parentSessionId)}async openMoveToGroupModal(){const e=this.getState(),s=this.getMovableGroupSessionSelection();if(s.length===0)return this.dispatch({type:"ui/status",text:"Select a top-level non-system session to move"}),null;if(typeof this.transport.listSessionGroups!="function")return this.dispatch({type:"ui/status",text:"Session groups are not supported by this transport"}),null;const n=await this.transport.listSessionGroups().catch(()=>[]),i=s.map(l=>l.sessionId),o=s.length===1&&s[0].groupId||null,r=[{id:"__no_group__",kind:"noGroup",label:"[No Group]",description:"Remove the selected session(s) from any group.",groupId:null,memberCount:0},{id:"__new_group__",kind:"newGroup",label:"[New Group]",description:"Create a new group, then move the selected session(s) into it.",groupId:null,memberCount:0},...(Array.isArray(n)?n:[]).map(l=>({id:l.groupId,kind:"group",label:l.title||l.groupId,description:l.description||"Move selected session(s) into this group.",groupId:l.groupId,memberCount:l.memberCount??0}))],a=o?Math.max(0,r.findIndex(l=>l.groupId===o)):Math.min(1,r.length-1);return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupPicker",title:s.length===1?"Move Session to Group":`Move ${s.length} Sessions to Group`,previousFocus:e.ui.focusRegion,sessionIds:i,sessionLabels:s.map(l=>l.title||l.sessionId.slice(0,8)),selectedIndex:a>=0?a:0,items:r}}),this.dispatch({type:"ui/status",text:"Choose a group, [New Group], or [No Group]"}),r}async createSessionGroupFromSelection(){return this.openMoveToGroupModal()}async moveSessionsToGroup(e,s,{statusTitle:n=null}={}){const i=Array.from(new Set((Array.isArray(s)?s:[]).map(d=>String(d||"").trim()).filter(Boolean)));if(i.length===0)return this.dispatch({type:"ui/status",text:"No sessions selected to move"}),null;let o=null;if(typeof this.transport.placeSessionsInGroup=="function")o=await this.transport.placeSessionsInGroup(i,e??null);else if(typeof this.transport.moveSessionsToGroup=="function")await this.transport.moveSessionsToGroup(e??null,i);else if(e&&typeof this.transport.assignSessionsToGroup=="function")await this.transport.assignSessionsToGroup(e,i);else return this.dispatch({type:"ui/status",text:"Moving sessions between groups is not supported by this transport"}),null;const r=Array.isArray(o)?o.filter(Boolean):null,a=r?r.filter(d=>d.placed!==!0):[],l=r?r.filter(d=>d.placed===!0).length:i.length;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&l>0&&await this.loadSession(`group:${e}`).catch(()=>{});const u=e?`group ${n||e}`:"No Group",f=a.length>0?` · skipped ${a.length} (${Dd(a)})`:"";return this.dispatch({type:"ui/status",text:l>0?`Moved ${l} session${l===1?"":"s"} to ${u}${f}`:`No sessions moved to ${u}${f}`}),l>0}async confirmSessionGroupPickerModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="newGroup"){const i=(e.sessionLabels||[]).length===1?`${e.sessionLabels[0]} Group`:`${(e.sessionIds||[]).length} Session Group`;this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.previousFocus,sessionIds:e.sessionIds||[],value:i,cursorIndex:i.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{await this.moveSessionsToGroup(s.kind==="noGroup"?null:s.groupId,e.sessionIds||[],{statusTitle:s.label})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}updateSessionGroupNameModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setSessionGroupNameValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="sessionGroupName")return;const i=at(e,n.maxLength||80),o=se(i,s);this.updateSessionGroupNameModal({value:i,cursorIndex:o})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=We(s.value||"",s.cursorIndex||0,at(e,s.maxLength||80));this.setSessionGroupNameValue(n.prompt,n.cursor)}deleteSessionGroupNameChar(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=ct(e.value||"",e.cursorIndex||0);this.setSessionGroupNameValue(s.prompt,s.cursor)}moveSessionGroupNameCursor(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",se(s.value||"",(s.cursorIndex||0)+e))}moveSessionGroupNameCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmSessionGroupNameModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"Group name cannot be empty"});return}if(typeof this.transport.createSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{const i=await this.transport.createSessionGroup({title:s,description:`${(e.sessionIds||[]).length} grouped session${(e.sessionIds||[]).length===1?"":"s"}`,sessionIds:e.sessionIds||[]});await this.moveSessionsToGroup(i.groupId,e.sessionIds||[],{statusTitle:i.title||s})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}applyActiveGroupDefault(e={}){if(e&&Object.prototype.hasOwnProperty.call(e,"groupId"))return e;const s=this.getState(),n=s.sessions?.activeSessionId?s.sessions.byId[s.sessions.activeSessionId]:null,i=n?.isGroup?n.groupId||Gs(n.sessionId):n?.groupId;return i?{...e,groupId:i}:e}getActiveSession(e=this.getState()){const s=e.sessions?.activeSessionId;return s&&e.sessions.byId[s]||null}toggleChatViewMode(){if(this.getActiveSession()?.isGroup){this.dispatch({type:"ui/status",text:"Session groups show group details"});return}const s=this.getState().ui?.chatViewMode==="summary"?"transcript":"summary";this.dispatch({type:"ui/chatViewMode",mode:s}),this.dispatch({type:"ui/status",text:s==="summary"?"Showing session summary":"Showing chat transcript"})}setChatViewMode(e){e!=="summary"&&e!=="transcript"&&e!=="rich"||this.getActiveSession()?.isGroup||this.dispatch({type:"ui/chatViewMode",mode:e})}async openSessionAgentPicker(e={}){const s=typeof this.transport.listCreatableAgents=="function"?await this.transport.listCreatableAgents():[],i=(typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0;if(!Array.isArray(s)||s.length===0){if(!i){this.dispatch({type:"ui/status",text:"No user-creatable agents are available for this app"});return}await this.createSession(e);return}const o=[];i&&o.push({id:"__generic__",kind:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,splashMobile:null,initialPrompt:null});for(const r of s){const a=String(r?.name||"").trim();a&&o.push({id:a,kind:"agent",agentName:a,title:eo(a,r?.title),description:String(r?.description||"").trim(),tools:Array.isArray(r?.tools)?r.tools.filter(Boolean):[],splash:typeof r?.splash=="string"&&r.splash.trim()?r.splash:null,splashMobile:typeof r?.splashMobile=="string"&&r.splashMobile.trim()?r.splashMobile:null,initialPrompt:typeof r?.initialPrompt=="string"&&r.initialPrompt.trim()?r.initialPrompt:null})}this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",items:o,selectedIndex:0,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select an agent and press Enter"})}async openNewSessionFlow(e={}){if((typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0){await this.createSession(e);return}if(typeof this.transport.listModels=="function"){await this.openModelPicker(e);return}await this.openSessionAgentPicker(e)}async openReasoningEffortPicker(e,s={}){const n=nn(e?.supportedReasoningEfforts),i=s?.reasoningEffort||Yi(e);if(!n.length||!i){await this.openContextTierPicker(e,s);return}const o=n.map(a=>({id:a,effort:a,label:a,isDefault:i===a})),r=Math.max(0,o.findIndex(a=>a.id===i));this.dispatch({type:"ui/modal",modal:{type:"reasoningEffortPicker",title:s?.mode==="switchModel"?`Switch reasoning for ${e?.modelName||e?.qualifiedName||"model"}`:`Reasoning effort for ${e?.modelName||e?.qualifiedName||"model"}`,items:o,selectedIndex:r,previousFocus:this.getState().ui.focusRegion,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a reasoning effort and press Enter"})}async openContextTierPicker(e,s={}){const n=on(e?.supportedContextTiers),i=s?.contextTier||Ud(e);if(!n.length||!i){if(s?.mode==="switchModel"){await this.switchSessionModel({...s,model:e?.id});return}await this.openSessionAgentPicker(s);return}const o=n.map(a=>({id:a,tier:a,tokenLimit:e?.contextWindowSizes?.[a]||null,label:Wd(a,e?.contextWindowSizes?.[a]),isDefault:i===a})),r=Math.max(0,o.findIndex(a=>a.id===i));this.dispatch({type:"ui/modal",modal:{type:"contextTierPicker",title:`Context window for ${e?.modelName||e?.qualifiedName||"model"}`,items:o,selectedIndex:r,previousFocus:this.getState().ui.focusRegion,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a context window and press Enter"})}async openModelPicker(e={}){if(typeof this.transport.listModels!="function"){await this.openSessionAgentPicker(e);return}const s=await this.transport.listModels();if(!Array.isArray(s)||s.length===0){this.dispatch({type:"ui/status",text:"No models available"});return}const n=typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0,i=typeof this.transport.getModelsByProvider=="function"?this.transport.getModelsByProvider():Gd(s),o=await this._resolveGhcpUserKeySet(),r=[],a=i.map(f=>({providerId:f.providerId,providerType:f.type||f.providerType,models:(f.models||[]).map(d=>{const p=d.providerType||f.type||f.providerType,h=p==="github"&&d.credentialAvailable===!1&&o===!1,m={id:d.qualifiedName,qualifiedName:d.qualifiedName,modelName:d.modelName||d.qualifiedName,providerId:d.providerId||f.providerId,providerType:p,description:d.description||"",cost:d.cost||null,supportedReasoningEfforts:nn(d.supportedReasoningEfforts),defaultReasoningEffort:d.defaultReasoningEffort||null,supportedContextTiers:on(d.supportedContextTiers),defaultContextTier:d.defaultContextTier||null,contextWindowSizes:d.contextWindowSizes||null,isDefault:n===d.qualifiedName,ghcpKeyMissing:h,disabled:h};return r.push(m),m})})).filter(f=>f.models.length>0),l=e?.model||n;let u=r.findIndex(f=>f.qualifiedName===l&&!f.disabled);u<0&&(u=r.findIndex(f=>!f.disabled)),u<0&&(u=0),this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:e?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:r,groups:a,selectedIndex:u,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async _resolveGhcpUserKeySet(){const e=this.getState().admin?.profile;if(typeof e?.githubCopilotKeySet=="boolean")return e.githubCopilotKeySet;if(typeof this.transport.getCurrentUserProfile!="function")return null;try{const s=await this.transport.getCurrentUserProfile();return s&&typeof s.githubCopilotKeySet=="boolean"?s.githubCopilotKeySet:!1}catch{return null}}async openSwitchModelPicker(e=null){this._onSwitchModelApplied=typeof e=="function"?e:null;const s=this.getState(),n=s.sessions.activeSessionId,i=n&&s.sessions.byId[n]||null;if(!i||i.isGroup){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Select a session before switching model"});return}if(typeof this.transport.setSessionModel!="function"){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.openModelPicker({mode:"switchModel",sessionId:n,model:i.model||void 0,reasoningEffort:i.reasoningEffort||void 0})}async switchSessionModel(e={}){const s=e.sessionId||this.getState().sessions.activeSessionId,n=String(e.model||"").trim();if(!s||!n){this.dispatch({type:"ui/status",text:"Select a model before switching"});return}if(typeof this.transport.setSessionModel!="function"){this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.transport.setSessionModel(s,{model:n,..."reasoningEffort"in e?{reasoningEffort:e.reasoningEffort??null}:{},..."contextTier"in e?{contextTier:e.contextTier??null}:{},source:"ui"});const i=e.reasoningEffort?`${n}:${e.reasoningEffort}`:n,o=e.contextTier?` · ${Hr[e.contextTier]||e.contextTier}`:"";this.dispatch({type:"ui/status",text:`Next turn will use ${i}${o}`}),await this.refreshSessions();const r=this._onSwitchModelApplied;this._onSwitchModelApplied=null,typeof r=="function"&&r()}openHelpModal(){this.dispatch({type:"ui/modal",modal:{type:"help",title:"Keybindings",selectedIndex:0,previousFocus:this.getState().ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Keybindings — ? or Esc to close"})}openThemePicker(){const e=Vl().map(i=>({id:i.id,label:i.label,description:i.description,page:i.page,terminal:i.terminal,tui:i.tui}));if(e.length===0){this.dispatch({type:"ui/status",text:"No themes available"});return}const s=this.getState().ui.themeId,n=Math.max(0,e.findIndex(i=>i.id===s));this.dispatch({type:"ui/modal",modal:{type:"themePicker",title:"Theme Picker",items:e,selectedIndex:n,previousFocus:this.getState().ui.focusRegion,currentThemeId:s}}),this.dispatch({type:"ui/status",text:"Select a theme and press Enter"})}getPromptDraftSessionId(){return this.getPromptAttachments()[0]?.sessionId||null||this.getState().sessions.activeSessionId||null}openArtifactUploadModal(){if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}const e=this.getState(),s=this.getPromptDraftSessionId();this.dispatch({type:"ui/modal",modal:{type:"artifactUpload",title:s?`Upload Artifact (${de(s)})`:"Upload Artifact",sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0}}),this.dispatch({type:"ui/status",text:s?"Paste a local file path and press Enter to upload it into this session's artifacts":"Paste a local file path and press Enter to upload it; a new session will be created if needed"})}updateArtifactUploadModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setArtifactUploadValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="artifactUpload")return;const i=String(e||"").replace(/\r?\n/g,""),o=se(i,s);this.updateArtifactUploadModal({value:i,cursorIndex:o})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=We(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=ct(e.value||"",e.cursorIndex||0);this.setArtifactUploadValue(s.prompt,s.cursor)}moveArtifactUploadCursor(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",se(s.value||"",(s.cursorIndex||0)+e))}moveArtifactUploadCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",e==="start"?0:String(s.value||"").length)}async ensurePromptAttachmentSessionId(){const e=this.getPromptAttachments()[0]?.sessionId||null;if(e)return this.getState().sessions.activeSessionId!==e&&await this.loadSession(e),e;const s=this.getState().sessions.activeSessionId;if(s)return s;const n=await this.createSession({});if(!n?.sessionId)throw new Error("Create a session before attaching files");return n.sessionId}async finalizeArtifactUpload(e,{sessionId:s=null,suppressStatus:n=!1}={}){const i=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!i||!e?.filename)throw new Error("Upload did not return a session id and filename");return this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),await this.ensureFilesForSession(i,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:i,filename:e.filename}),await this.ensureFilePreview(i,e.filename,{force:!0}).catch(()=>null),n||this.dispatch({type:"ui/status",text:`Uploaded ${e.filename}`}),{sessionId:i,filename:e.filename}}async applyUploadedPromptAttachment(e,{sessionId:s=null,suppressStatus:n=!1}={}){const i=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!i||!e?.filename)throw new Error("Upload did not return a session id and filename");const o=to(e.filename),r=this.getState().ui.prompt,a=this.getState().ui.promptCursor,l=this.getPromptAttachments(),u=l.findIndex(d=>d?.sessionId===i&&d?.filename===e.filename);if(this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),u===-1||!r.includes(l[u]?.token||o)){const d=We(r,a,`${o} `);this.setPrompt(d.prompt,d.cursor)}const f=u>=0?l.map((d,p)=>p===u?{...d,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:o}:d):[...l,{id:`${i}/${e.filename}`,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:o}];return this.setPromptAttachments(f),await this.ensureFilesForSession(i,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:i,filename:e.filename}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(i,e.filename,{force:!0}).catch(()=>null),this.setFocus(A.PROMPT),n||this.dispatch({type:"ui/status",text:u>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:i,existingAttachmentIndex:u,token:o}}async uploadArtifactFiles(e=[],{sessionId:s=null}={}){const n=Array.isArray(e)?e.filter(l=>l&&typeof l.name=="string"):[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No files selected"}),[];if(typeof this.transport.uploadArtifactFromFile!="function")return this.dispatch({type:"ui/status",text:"Browser file uploads are not supported by this transport"}),[];this.dispatch({type:"ui/status",text:n.length===1?`Uploading ${n[0].name}...`:`Uploading ${n.length} artifact files...`});const i=s||await this.ensurePromptAttachmentSessionId(),o=[];let r=0,a=null;for(const l of n)try{const u=await this.transport.uploadArtifactFromFile(i,l);o.push(u),await this.finalizeArtifactUpload(u,{sessionId:i,suppressStatus:!0})}catch(u){r+=1,a=u}return o.length>0?this.dispatch({type:"ui/status",text:r>0?`Uploaded ${o.length}/${n.length} file(s); last error: ${a?.message||String(a)}`:o.length===1?`Uploaded ${o[0].filename}`:`Uploaded ${o.length} files`}):a&&this.dispatch({type:"ui/status",text:`Upload failed: ${a?.message||String(a)}`}),o}async uploadPromptAttachmentFiles(e=[]){return this.uploadArtifactFiles(e)}async confirmArtifactUploadModal(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"File path cannot be empty"});return}if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}this.dispatch({type:"ui/status",text:"Uploading artifact..."});try{const n=e.sessionId||await this.ensurePromptAttachmentSessionId(),i=await this.transport.uploadArtifactFromPath(n,s),o=await this.finalizeArtifactUpload(i,{sessionId:n,suppressStatus:!0});if(this.dispatch({type:"ui/modal",modal:null}),this.stageUploadedImageAttachment(o,n)){this.dispatch({type:"ui/status",text:`Uploaded ${o.filename} — attached to your next message`});return}this.dispatch({type:"ui/status",text:`Uploaded ${o.filename}`})}catch(n){this.dispatch({type:"ui/status",text:`Upload failed: ${n?.message||String(n)}`})}}openRenameSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.sessions.byId[s];if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System session titles are fixed"});return}const i=ef(n),o=Bn(n),r=Zd(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:`Rename (${de(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:i,cursorIndex:i.length,agentTitlePrefix:o,currentTitle:String(n.title||"").trim(),maxLength:r}}),this.dispatch({type:"ui/status",text:o?`Rename title for ${o}; the agent-name prefix stays fixed`:"Type a new session title and press Enter to save"})}async openTerminatePickerModal(){const e=this.getState(),s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[];if(e.sessions.selectMode&&s.length>=1){const o=this.getBulkSelectedSessionActions(e).eligible;if(o.length===0){this.dispatch({type:"ui/status",text:"No selected sessions can be terminated"});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:"Terminate Selected Sessions",previousFocus:e.ui.focusRegion,bulkCount:o.length,skippedCount:s.length-o.length,selectedIds:o.map(r=>r.sessionId)}}),this.dispatch({type:"ui/status",text:"Choose what to do with the selected sessions"});return}const n=e.sessions.activeSessionId;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}const i=e.sessions.byId[n];if(!i){this.dispatch({type:"ui/status",text:"No session selected"});return}if(i.isSystem){const o=String(i.title||i.agentId||n.slice(0,8)).trim();this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:"Restart System Session",sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:o,state:String(i.state||"").trim(),systemRestart:!0}}),this.dispatch({type:"ui/status",text:"Choose how to restart the system session"});return}if(i.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; manage sessions individually."});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:`Lifecycle (${de(n)})`,sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:String(i.title||"").trim(),state:String(i.state||"").trim(),canRegenerate:typeof this.transport.regenerateSession=="function"&&!i.serviceKind}})}async pickTerminateAction(e){const s=this.getState().ui.modal;if(!s||s.type!=="terminatePicker")return;const n=s.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),e==="complete"?await this.completeActiveSession():e==="cancel"?await this.cancelActiveSession():e==="delete"?await this.deleteActiveSession():e==="regenerate"&&await this.regenerateActiveSession()}getBulkSelectedSessionActions(e=this.getState()){const s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[],i=[...new Set(s.map(r=>String(r||"").trim()).filter(Boolean))].map(r=>e.sessions.byId[r]).filter(Boolean),o=i.filter(r=>!r.isSystem&&!r.isGroup);return{selected:i,eligible:o,skippedCount:i.length-o.length}}updateRenameSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setRenameSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="renameSession")return;const i=at(e,n.maxLength),o=se(i,s);this.updateRenameSessionModal({value:i,cursorIndex:o})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=We(s.value||"",s.cursorIndex||0,at(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=ct(e.value||"",e.cursorIndex||0);this.setRenameSessionValue(s.prompt,s.cursor)}moveRenameSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",se(s.value||"",(s.cursorIndex||0)+e))}moveRenameSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmRenameSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim();if(!n){this.dispatch({type:"ui/status",text:"Title cannot be empty"});return}const i=this.getState().sessions.byId[s],o=i?.isGroup?i.groupId||Gs(s):null;if(o){if(typeof this.transport.updateSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group renaming is not supported by this transport"});return}const a=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),a&&this.setFocus(a),this.dispatch({type:"ui/status",text:`Renaming group ${o.slice(0,8)}...`});try{await this.transport.updateSessionGroup(o,{title:n}),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Renamed group ${n}`})}catch(l){this.dispatch({type:"ui/status",text:`Rename failed: ${l?.message||String(l)}`})}return}if(typeof this.transport.renameSession!="function"){this.dispatch({type:"ui/status",text:"Session renaming is not supported by this transport"});return}const r=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r),this.dispatch({type:"ui/status",text:`Renaming ${de(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${de(s)}`})}catch(a){this.dispatch({type:"ui/status",text:`Rename failed: ${a?.message||String(a)}`})}}async cycleSessionVisibility(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups don't have visibility"});return}if(typeof this.transport.setSessionVisibility!="function"){this.dispatch({type:"ui/status",text:"Not supported by this transport"});return}const i=it(["private","shared_read","shared_write"],n.visibility||"private",1);try{await this.transport.setSessionVisibility(s,i),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Visibility → ${i}`})}catch(o){this.dispatch({type:"ui/status",text:o?.message||String(o)})}}async openShareSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups can't be shared"});return}if(typeof this.transport.listSessionShares!="function"){this.dispatch({type:"ui/status",text:"Session sharing is not supported by this transport"});return}let i;try{i=await this.transport.listSessionShares(s)}catch(o){this.dispatch({type:"ui/status",text:o?.message||String(o)});return}this.dispatch({type:"ui/modal",modal:{type:"shareSession",title:`Share (${de(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0,shares:Array.isArray(i)?i:[],visibility:n.visibility||"private"}}),this.dispatch({type:"ui/status",text:"name [r|w] grants · -name revokes · Enter apply"})}updateShareSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setShareSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="shareSession")return;const i=at(e,120),o=se(i,s);this.updateShareSessionModal({value:i,cursorIndex:o})}insertShareSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=We(s.value||"",s.cursorIndex||0,at(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=ct(e.value||"",e.cursorIndex||0);this.setShareSessionValue(s.prompt,s.cursor)}moveShareSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",se(s.value||"",(s.cursorIndex||0)+e))}moveShareSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmShareSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim(),i=e.previousFocus;if(!n){this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);return}const o=n.startsWith("-")?n.slice(1).trim():n.toLowerCase().startsWith("revoke ")?n.slice(7).trim():null;if(o!==null){const h=o.toLowerCase(),m=(e.shares||[]).find(g=>g.subject&&String(g.subject).toLowerCase()===h||g.email&&String(g.email).toLowerCase()===h||g.displayName&&String(g.displayName).toLowerCase()===h);if(!m){this.dispatch({type:"ui/status",text:`No grant matching "${o}"`});return}this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.revokeSessionShare(s,{provider:m.provider,subject:m.subject}),this.dispatch({type:"ui/status",text:`Revoked ${o}`})}catch(g){this.dispatch({type:"ui/status",text:g?.message||String(g)})}return}const r=n.split(/\s+/),a={r:"read",read:"read",w:"write",write:"write"},l=r.length>1?r[r.length-1].toLowerCase():null,u=l&&a[l]?a[l]:"read",f=l&&a[l]?r.slice(0,-1).join(" "):n,d=f.toLowerCase();let p=null;if(typeof this.transport.listKnownUsers=="function"){let h=[];try{h=await this.transport.listKnownUsers({limit:500})}catch{h=[]}const m=Array.isArray(h)?h:[];if(p=m.find(g=>g.displayName&&g.displayName.toLowerCase()===d||g.email&&g.email.toLowerCase()===d||g.subject&&g.subject.toLowerCase()===d)||null,!p){const g=m.filter(S=>S.displayName&&S.displayName.toLowerCase().includes(d)||S.email&&S.email.toLowerCase().includes(d)||S.subject&&S.subject.toLowerCase().includes(d));if(g.length===1)p=g[0];else if(g.length>1){this.dispatch({type:"ui/status",text:`"${f}" is ambiguous (${g.length} matches)`});return}}}p||(p={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:f,email:null,displayName:null}),this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.grantSessionShare(s,{provider:p.provider,subject:p.subject,email:p.email??null,displayName:p.displayName??null},u),this.dispatch({type:"ui/status",text:`Granted ${u} to ${f}`})}catch(h){this.dispatch({type:"ui/status",text:h?.message||String(h)})}}closeModal(){const e=this.getState().ui.modal;e&&(this.dispatch({type:"ui/modal",modal:null}),e.type==="themePicker"&&e.currentThemeId&&this.dispatch({type:"ui/theme",themeId:e.currentThemeId}),e.previousFocus&&this.setFocus(e.previousFocus),this.dispatch({type:"ui/status",text:"Connected"}))}moveModalSelection(e){const s=this.getState().ui.modal;if(!s)return;if(s.type==="help"){const o=Math.max(0,Number(s.selectedIndex)||0);this.dispatch({type:"ui/modalSelection",index:Math.max(0,o+e)});return}if(!Array.isArray(s.items)||s.items.length===0)return;if(s.type==="logFilter"||s.type==="filesFilter"||s.type==="historyFormat"){const o=Math.max(0,Math.min(Number(s.selectedIndex)||0,s.items.length-1)),r=s.items[o];if(!r||!Array.isArray(r.options)||r.options.length===0)return;const a=r.options.map(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],u=it(a,l,e),f=r.options.find(d=>d.id===u)||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]:u},...s.type==="historyFormat"?{format:u}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(u).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||u}`});return}const n=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(0,Math.min(n+e,s.items.length-1));this.dispatch({type:"ui/modalSelection",index:i})}moveModalPane(e){const s=this.getState().ui.modal;if(!s||s.type!=="logFilter"&&s.type!=="filesFilter"&&s.type!=="historyFormat"||!Array.isArray(s.items)||s.items.length===0)return;const i=(Math.max(0,Number(s.selectedIndex)||0)+e+s.items.length)%s.items.length,o=s.items[i],r=s.type==="filesFilter"?this.getState().files.filter?.[o.id]||o.options?.[0]?.id:s.type==="historyFormat"?this.getState().executionHistory?.format||o.options?.[0]?.id:this.getState().logs.filter?.[o.id]||o.options?.[0]?.id,a=o.options?.find(l=>l.id===r)||o.options?.[0];this.dispatch({type:"ui/modalSelection",index:i}),this.dispatch({type:"ui/status",text:`Editing ${o.label}: ${a?.label||r||""}`})}async confirmModal(){const e=this.getState().ui.modal;if(e){if(e.type==="help"){this.closeModal();return}if(e.type==="confirm"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s),e.action==="cancelSession"?await this.cancelActiveSession({confirmed:!0}):e.action==="completeSession"?await this.completeActiveSession("Completed by user",{confirmed:!0}):e.action==="deleteSession"?await this.deleteActiveSession({confirmed:!0}):e.action==="regenerateSession"?await this.regenerateActiveSession({confirmed:!0,...e.extras||{}}):e.action==="deleteArtifact"&&await this.deleteSelectedArtifact({confirmed:!0});return}if(e.type==="artifactUpload"){await this.confirmArtifactUploadModal();return}if(e.type==="renameSession"){await this.confirmRenameSessionModal();return}if(e.type==="shareSession"){await this.confirmShareSessionModal();return}if(e.type==="sessionGroupPicker"){await this.confirmSessionGroupPickerModal();return}if(e.type==="sessionGroupName"){await this.confirmSessionGroupNameModal();return}if(e.type==="sessionOwnerFilter"){this.toggleSessionOwnerFilter();return}if(e.type==="filesFilter"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s);return}if(e.type==="themePicker"){const s=e.items?.[e.selectedIndex||0],n=ze(s?.id);if(!n){this.dispatch({type:"ui/status",text:"Unable to apply that theme"});return}const i=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i),this.dispatch({type:"ui/status",text:`Applied theme: ${n.label}`});return}if(e.type==="modelPicker"){const s=e.items?.[e.selectedIndex||0];if(s?.disabled){this.dispatch({type:"ui/status",text:s.ghcpKeyMissing?"This model needs a GitHub Copilot key — add yours in the Admin console first":"This model is not available"});return}const n=e.previousFocus;if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s){if(e.sessionOptions?.mode==="switchModel"){this.dispatch({type:"ui/status",text:"No model selected"});return}await this.openSessionAgentPicker({});return}const i=Yi(s);if(e.sessionOptions?.mode==="switchModel"){await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,reasoningEffort:i??null});return}await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,...i?{reasoningEffort:i}:{}});return}if(e.type==="reasoningEffortPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),await this.openContextTierPicker(e.modelItem,{...i,...s?.id?{reasoningEffort:s.id}:{}});return}if(e.type==="contextTierPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);const o={...i,...s?.id?{contextTier:s.id}:{}};if(i?.mode==="switchModel"){await this.switchSessionModel({...o,model:e.modelItem?.id||i.model});return}await this.openSessionAgentPicker(o);return}if(e.type==="sessionAgentPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s||s.kind==="generic"){await this.createSession(i);return}await this.createSessionForAgent(s.agentName,{...i,...s.title?{title:s.title}:{},...s.splash?{splash:s.splash}:{},...s.splashMobile?{splashMobile:s.splashMobile}:{},...s.initialPrompt?{initialPrompt:s.initialPrompt}:{}});return}if(e.type==="logFilter"){this.closeModal();return}if(e.type==="historyFormat"){this.closeModal();return}e.type==="artifactPicker"&&await this.downloadArtifactModalSelection()}}openLogFilter(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"logFilter",title:"Log Filters",previousFocus:e,selectedIndex:0,items:[{id:"source",label:"Source nodes",description:"Choose whether the log pane shows logs from all nodes or only the current orchestration.",options:[{id:"allNodes",label:"All nodes"},{id:"currentOrchestration",label:"Current orchestration"}]},{id:"level",label:"Levels",description:"Filter logs by severity/verbosity level.",options:[{id:"all",label:"All"},{id:"info",label:"Info"},{id:"warn",label:"Warn"},{id:"error",label:"Error"},{id:"debug",label:"Debug"},{id:"trace",label:"Trace"}]},{id:"format",label:"Format",description:"Raw shows the structured time/node/level summary. Pretty shows the cleaned message text, colored by orchestration vs activity.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw summary"}]}]}}),this.dispatch({type:"ui/status",text:"Tab/Shift-Tab switch filters · Up/Down change values · Enter close · Esc cancel"})}openHistoryFormat(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"historyFormat",title:"Execution History Format",previousFocus:e,selectedIndex:0,items:[{id:"format",label:"Format",description:"Pretty prints a human-readable view with colored event kinds. Raw JSON shows the full event objects.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw JSON"}]}]}}),this.dispatch({type:"ui/status",text:"Up/Down change format · Enter close · Esc cancel"})}toggleLogTail(){const e=this.getState().logs;if(!e.available){this.dispatch({type:"ui/status",text:e.availabilityReason||"Log tailing is not available in this environment"});return}if(e.tailing){this.detachLogStream(),typeof this.transport.stopLogTail=="function"&&this.transport.stopLogTail().catch(()=>{}),this.dispatch({type:"logs/tailing",tailing:!1}),this.dispatch({type:"ui/status",text:"Log tailing stopped"});return}if(typeof this.transport.startLogTail!="function"){this.dispatch({type:"ui/status",text:"Log tailing is not supported by this transport"});return}this.logUnsubscribe=this.transport.startLogTail(s=>{const n=Array.isArray(s)?s:[s];n.length>0&&this.dispatch({type:"logs/append",entries:n})}),this.dispatch({type:"logs/tailing",tailing:!0}),this.dispatch({type:"ui/status",text:"Log tailing started"})}async sendPrompt(){const e=this.getState(),s=e.ui.prompt,n=this.getPromptAttachments(),i=n[0]?.sessionId||null,o=rf(s,n);let r=e.sessions.activeSessionId;i&&(r=i,e.sessions.activeSessionId!==i&&await this.loadSession(i));let a=r&&e.sessions.byId[r]||null;if(r&&!a&&(a=this.getState().sessions.byId[r]||null),!r){const g=await this.createSession({});if(!g?.sessionId)return;r=g.sessionId,a=this.getState().sessions.byId[r]||null}const l=n.some(g=>g?.kind==="image");if(!o.trim()&&!l){r&&this.getPendingOutboxItems(r).length>0&&await this.dispatchPendingOutbox(r).catch(()=>{});return}const u=a?.pendingQuestion||null,f=!!u?.question,d=this.getPromptEditSessionMatch(r);if(d){const g=this.getSessionOutbox(r).find(S=>S.id===d.itemId);if(g?.phase==="queued"||g?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(r).catch(()=>{});return}if(f&&typeof this.transport.sendAnswer=="function"){const g=Date.now(),S={...u,answer:o,answeredAt:g,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:r,pendingQuestion:null,answeredPendingQuestion:S}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(r,o),this.dispatch({type:"sessions/merged",session:{sessionId:r,answeredPendingQuestion:{...S,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(r,100),this.syncSessionEvents(r).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(y){this.dispatch({type:"sessions/merged",session:{sessionId:r,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:r,pendingQuestion:u}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(o,String(o||"").length),this.dispatch({type:"ui/status",text:y?.message||String(y)})}return}const p=n.filter(g=>g?.kind==="image");let h=null;if(p.length>0){if(p.some(y=>y.file)&&typeof this.transport.uploadArtifactFromFile!="function"){this.dispatch({type:"ui/status",text:"This transport does not support image attachments."});return}const S=this.buildOutboxItem("","pending");this.dispatch({type:"ui/status",text:`Uploading ${p.length} image${p.length>1?"s":""}...`});try{h=await this.uploadPendingImageAttachments(r,p,S.id),this.dispatch({type:"ui/status",text:""})}catch(y){this.dispatch({type:"ui/status",text:`Image upload failed: ${y?.message||y}`});return}}const m=o.trim()?o:h&&h.length>0?"See the attached image(s).":o;this.queuePromptInOutbox(r,m,h?{attachments:h}:null),this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(r).catch(()=>{})}setPrompt(e,s=String(e||"").length){const n=String(e||""),i=Math.max(0,Math.min(Number.isFinite(s)?s:n.length,n.length)),o=this.getState().ui;if(!(o.prompt===n&&o.promptCursor===i)){if(o.promptEdit?.sessionId&&o.promptEdit?.itemId){const a=this.getSessionOutbox(o.promptEdit.sessionId).map(l=>l.id===o.promptEdit.itemId&&l.phase==="pending"&&l.attempted!==!0?{...l,text:n}:l);this.setSessionOutboxItems(o.promptEdit.sessionId,a)}this.dispatch({type:"ui/prompt",prompt:n,promptCursor:i}),this.syncPromptReferenceBrowser()}}setPromptCursor(e){const s=this.getState().ui.prompt||"";this.setPrompt(s,e)}insertPromptText(e){const s=this.getState().ui,n=We(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=ct(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=df(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,se(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,Kr(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=ff(s.prompt,s.promptCursor,e);if(n!==s.promptCursor){this.setPrompt(s.prompt,n);return}e<0&&this.selectPreviousPendingPrompt()||e>0&&this.selectNextPendingPrompt()||this.setPrompt(s.prompt,n)}getCurrentLayout(e={}){const s=this.getState().ui.layout||{},n=this.getState().ui,i=e.prompt??n.prompt;return _t({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??mt(i),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===A.SESSIONS?e.bodyHeight:e.sessionPaneHeight;return Math.max(3,s-2)}setViewport(e={}){const s=Math.max(40,Number(e.width)||120),n=Math.max(18,Number(e.height)||40),i=this.getState().ui.layout||{};(i.viewportWidth!==s||i.viewportHeight!==n)&&this.dispatch({type:"ui/viewport",width:s,height:n});const o=this.getCurrentLayout({width:s,height:n}),r=this.getState().ui.focusRegion,a=Fe(r,o);a!==r&&this.setFocus(a)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:Fe(e,this.getCurrentLayout())})}focusNext(){const e=this.getCurrentLayout(),s=Fe(this.getState().ui.focusRegion,e),n=Qs(e);this.setFocus(it(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=Fe(this.getState().ui.focusRegion,e),n=Qs(e);this.setFocus(it(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=Fe(this.getState().ui.focusRegion,e);this.setFocus(Sl(s,e))}focusRight(){const e=this.getCurrentLayout(),s=Fe(this.getState().ui.focusRegion,e);this.setFocus(bl(s,e))}adjustPaneSplit(e){const s=this.getState().ui.layout||{},n=s.viewportWidth??120,i=Math.max(-n,Math.min(n,(s.paneAdjust||0)+e));this.dispatch({type:"ui/paneAdjust",paneAdjust:i});const o=this.getCurrentLayout({paneAdjust:i}),r=this.getState().ui.focusRegion,a=Fe(r,o);a!==r&&this.setFocus(a)}adjustSessionPaneSplit(e){const s=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,o=Math.max(-i,Math.min(i,(s.sessionPaneAdjust||0)+e));this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:o});const r=this.getCurrentLayout({sessionPaneAdjust:o}),a=this.getState().ui.focusRegion,l=Fe(a,r);l!==a&&this.setFocus(l)}adjustActivityPaneSplit(e){const s=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,o=Math.max(-i,Math.min(i,(s.activityPaneAdjust||0)+e));this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:o});const r=this.getCurrentLayout({activityPaneAdjust:o}),a=this.getState().ui.focusRegion,l=Fe(a,r);l!==a&&this.setFocus(l)}resizeFocusedPane(e){const s=this.getState().ui.focusRegion,n=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??n.viewportHeight??40,o=n.viewportHeight??40,r=(a,l,u,f)=>{const d=Math.max(u,f);return Math.max(u,Math.min(d,(a||0)+l))};if(s===A.SESSIONS||s===A.CHAT){const a=Jo(i),l=bt+1,u=Math.min(Zo(o,i),i-fs-1),f=s===A.CHAT?-e:e,d=r(n.sessionPaneAdjust,f,l-a,u-a);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:d})}else if(s===A.INSPECTOR||s===A.ACTIVITY){const a=Math.max(ht,Math.floor(i*Xo)),l=ht+1,u=i-ts-1,f=s===A.INSPECTOR?-e:e,d=r(n.activityPaneAdjust,f,l-a,u-a);this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:d})}}getActiveSequenceCompletedTurns(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return[];const n=e.history.bySessionId?.get?.(s),i=[],o=new Set;for(const r of n?.events||[]){if(r?.eventType!=="session.turn_completed")continue;const a=Number(r?.data?.turnIndex??r?.data?.iteration);!Number.isFinite(a)||o.has(a)||(o.add(a),i.push(a))}return i.sort((r,a)=>r-a),i}moveSequenceSelection(e){const s=this.getActiveSequenceCompletedTurns();if(s.length===0)return;const n=s.indexOf(Number(this.getState().ui.sequenceSelectedTurn)),i=n===-1?s.length-1:Math.max(0,Math.min(s.length-1,n+e));this.dispatch({type:"ui/sequenceSelectedTurn",turn:s[i]})}toggleSequenceTurnExpanded(){const e=this.getActiveSequenceCompletedTurns();if(e.length===0)return;let s=Number(this.getState().ui.sequenceSelectedTurn);e.includes(s)||(s=e[e.length-1],this.dispatch({type:"ui/sequenceSelectedTurn",turn:s}));const n=Array.isArray(this.getState().ui.sequenceExpandedTurns)?this.getState().ui.sequenceExpandedTurns.map(Number):[],i=n.includes(s)?n.filter(o=>o!==s):[...n,s];this.dispatch({type:"ui/sequenceExpandedTurns",turns:i})}nextInspectorTab(){const e=this.getState().ui.inspectorTab,s=it(Te,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=it(Te,this.getState().ui.inspectorTab,-1);this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),this.ensureInspectorData(e).catch(()=>{})}cycleInspectorTab(){this.nextInspectorTab()}toggleStatsView(){const e=["session","fleet","users"],s=this.getState().ui.statsViewMode,n=e.includes(s)?e.indexOf(s):0,i=e[(n+1)%e.length];this.setStatsViewMode(i)}setStatsViewMode(e){this.dispatch({type:"ui/statsViewMode",statsViewMode:e}),this.getState().ui.inspectorTab==="stats"&&this.ensureInspectorData("stats").catch(()=>{})}async selectInspectorTab(e){Te.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=wt(s);if(n.length===0)return;const i=s.sessions.activeSessionId||n[0].sessionId,o=Math.max(0,n.findIndex(l=>l.sessionId===i)),r=Math.max(0,Math.min(n.length-1,o+e)),a=n[r].sessionId;await this.loadSession(a)}getSessionPageSize(){const e=this.getCurrentLayout(),s=e.fullscreenPane===A.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 pf.has(this.getState().ui.inspectorTab)}paneUsesStickyBottomFollow(e,s=this.getState()){return e==="activity"?!0:e==="inspector"?s.ui.inspectorTab==="logs":!1}isPaneFollowingBottom(e,s=this.getState()){return this.paneUsesStickyBottomFollow(e,s)?s.ui.followBottom?.[e]!==!1:!1}getPaneVisualScrollOffset(e,s=this.getState()){const n=this.getPaneMaxScrollOffset(e,s),i=Math.max(0,Math.min(Number(s.ui.scroll?.[e])||0,n));return this.isPaneFollowingBottom(e,s)?Math.max(0,n-i):i}applyPaneVisualScrollOffset(e,s,n={},i=this.getState()){const o=this.getPaneMaxScrollOffset(e,i),r=Math.max(0,Math.min(Number(s)||0,o));if(this.paneUsesStickyBottomFollow(e,i)){const a=n.followBottom!==void 0?!!n.followBottom:n.atBottom!==void 0?!!n.atBottom:r>=o;return this.dispatch({type:"ui/followBottom",pane:e,followBottom:a}),this.dispatch({type:"ui/scroll",pane:e,offset:a?0:r}),r}return this.dispatch({type:"ui/scroll",pane:e,offset:r}),r}updatePaneScrollFromViewport(e,s,n={}){const i=this.getState();if(this.paneUsesStickyBottomFollow(e,i)){this.applyPaneVisualScrollOffset(e,s,n,i);return}this.scrollPaneTo(e,s)}expandActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/expand",sessionId:e})}collapseActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/collapse",sessionId:e})}scrollPane(e,s){const n=this.getState(),i=this.getPaneMaxScrollOffset(e,n);if(this.paneUsesStickyBottomFollow(e,n)){const a=this.getPaneVisualScrollOffset(e,n),l=Math.max(0,Math.min(a-s,i));this.applyPaneVisualScrollOffset(e,l,{followBottom:l>=i},n);return}const o=Math.max(0,Math.min(Number(n.ui.scroll?.[e])||0,i)),r=Math.max(0,Math.min(o+s,i));this.dispatch({type:"ui/scroll",pane:e,offset:r}),e==="chat"&&s>0?o>=i?this.handleChatTopHistoryScrollIntent(r).catch(()=>{}):r>=i&&this.armChatTopHistoryLoad():e==="chat"&&s<0&&this.disarmChatTopHistoryLoad()}scrollPaneTo(e,s){const n=this.getState(),i=this.getPaneMaxScrollOffset(e,n),o=Math.max(0,Math.min(Number(s)||0,i));if(this.paneUsesStickyBottomFollow(e,n)){this.applyPaneVisualScrollOffset(e,o,{followBottom:o>=i},n);return}this.dispatch({type:"ui/scroll",pane:e,offset:o}),e==="chat"&&(i>0&&o>=i?this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad())}armChatTopHistoryLoad(){const e=this.getState().sessions.activeSessionId;e&&(this.chatTopHistoryLoadArmed=!0,this.chatTopHistoryLoadSessionId=e)}disarmChatTopHistoryLoad(){this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}async handleChatTopHistoryScrollIntent(e,s={}){const i=this.getState().sessions.activeSessionId;if(i){if(!s.force&&(!this.chatTopHistoryLoadArmed||this.chatTopHistoryLoadSessionId!==i)){this.armChatTopHistoryLoad();return}await this.maybeAutoExpandActiveHistory(e,{pages:Rd,force:!!s.force})}}getScrollablePaneForFocus(){const e=this.getState().ui.focusRegion;return e===A.CHAT?"chat":e===A.ACTIVITY?"activity":e===A.INSPECTOR?this.getState().ui.inspectorTab==="files"?"filePreview":"inspector":null}scrollCurrentPane(e){const s=this.getScrollablePaneForFocus();if(!s)return;if(this.paneUsesStickyBottomFollow(s)){this.scrollPane(s,e);return}const n=s==="inspector"&&this.inspectorUsesBottomScroll(),i=s==="inspector"||s==="filePreview";this.scrollPane(s,i&&!n?-e:e)}scrollCurrentPaneToTop(){const e=this.getScrollablePaneForFocus();if(!e)return;if(this.paneUsesStickyBottomFollow(e)){this.applyPaneVisualScrollOffset(e,0,{followBottom:!1});return}const s=e==="inspector"&&this.inspectorUsesBottomScroll();if(e==="chat"||e==="activity"||s){this.scrollPaneTo(e,Number.MAX_SAFE_INTEGER);return}this.scrollPaneTo(e,0)}scrollCurrentPaneToBottom(){const e=this.getScrollablePaneForFocus();if(!e)return;if(this.paneUsesStickyBottomFollow(e)){this.applyPaneVisualScrollOffset(e,Number.MAX_SAFE_INTEGER,{followBottom:!0});return}const s=e==="inspector"&&this.inspectorUsesBottomScroll();if(e==="chat"||e==="activity"||s){this.scrollPaneTo(e,0);return}this.scrollPaneTo(e,Number.MAX_SAFE_INTEGER)}async expandActiveHistory(){const e=this.getState().sessions.activeSessionId;e&&await this.expandSessionHistory(e)}getActiveChatRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.leftHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.leftWidth-4),i=Math.max(1,s.chatPaneHeight-2),o=Mn(e,n),r=[...Nn(e,n),...kn(e)],a=Math.min(Math.max(0,Math.floor(i*.34)),lt(r,n)),l=lt(o,n);return{contentWidth:n,contentHeight:Math.max(1,i-a),totalLines:l}}getActivityRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.activityHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.rightWidth-4),i=Math.max(1,s.activityPaneHeight-2),o=e.sessions.activeSessionId,r={sessions:{activeSessionId:o,byId:o?{[o]:e.sessions.byId[o]||null}:{}},history:{bySessionId:o?new Map([[o,e.history.bySessionId.get(o)||null]]):new Map}},a=_n(r);return{contentWidth:n,contentHeight:i,totalLines:lt(a.lines,n)}}getInspectorRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.inspectorHidden)return{contentWidth:20,contentHeight:1,stickyLineCount:0,totalLines:0};const n=Math.max(20,s.rightWidth-4),i=e.sessions.activeSessionId,o=i&&e.orchestration.bySessionId?.[i]||null,r={branding:e.branding,sessions:{activeSessionId:i,byId:e.sessions.byId,flat:e.sessions.flat},history:{bySessionId:e.history.bySessionId},orchestration:{bySessionId:i&&o?{[i]:o}:{}},logs:e.logs,sessionStats:e.sessionStats,fleetStats:e.fleetStats,ui:{inspectorTab:e.ui.inspectorTab,statsViewMode:e.ui.statsViewMode},executionHistory:e.executionHistory},a=Ye(r,{width:n}),l=a.tabs.map(p=>({text:p===a.activeTab?`[${p}] `:`${p} `,color:p===a.activeTab?"magenta":"gray",bold:p===a.activeTab})),u=(a.lines||[]).map(p=>typeof p=="string"?{text:p,color:"white"}:p),f=a.activeTab==="sequence"?[l,...(a.stickyLines||[]).map(p=>typeof p=="string"?{text:p,color:"white"}:p)]:[],d=a.activeTab==="sequence"?u:[l,...u];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:lt(f,n),totalLines:lt(d,n)}}getFilePreviewRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if((s.rightHidden||s.inspectorHidden)&&!e.files?.fullscreen)return{contentWidth:20,contentHeight:1,totalLines:0};const n=e.ui.inspectorTab==="files"&&!!e.files?.fullscreen,i=n?s.totalWidth:s.rightWidth,o=n?Math.max(10,s.bodyHeight):s.inspectorPaneHeight,r=Math.max(20,i-4),a=Math.max(8,r-4),l=e.sessions.activeSessionId,u=l&&e.sessions.byId[l]||null,f={sessions:{activeSessionId:l,byId:l&&u?{[l]:u}:{},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=On(f,{listWidth:a,previewWidth:a}),p=Math.max(9,o-4),h=Math.max(5,Math.min(10,Math.floor(p*.35)));let m=Math.max(5,Math.min(h,(d.listBodyLines||[]).length+2)),g=Math.max(5,p-m-1);const S=8;if(g<S){const y=S-g;m=Math.max(5,m-y),g=Math.max(5,p-m-1)}return{contentWidth:a,contentHeight:Math.max(1,g-2),totalLines:lt(d.previewLines,a)}}getPaneMaxScrollOffset(e,s=this.getState()){if(!e)return 0;if(e==="chat"){const n=this.getActiveChatRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="activity"){const n=this.getActivityRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="inspector"){const n=this.getInspectorRenderMetrics(s),i=Math.min(n.contentHeight,n.stickyLineCount||0),o=Math.max(0,n.contentHeight-i);return Math.max(0,n.totalLines-o)}if(e==="filePreview"){const n=this.getFilePreviewRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}return 0}async maybeAutoExpandActiveHistory(e,s={}){const n=this.getState(),i=n.sessions.activeSessionId;if(!i)return;const o=n.history.bySessionId.get(i);if(!o?.hasOlderEvents||this.sessionHistoryExpansionLoads.has(i))return;if(Number(o.loadedEventCount||0)>=ro){this.dispatch({type:"ui/status",text:"Reached automatic history limit. Press e to load more older CMS events."});return}const r=Array.isArray(o?.chat)&&o.chat.length>0;if(!s.force&&r){const{contentHeight:a,totalLines:l}=this.getActiveChatRenderMetrics(n),u=Math.max(0,l-a);if(e<u)return}await this.expandSessionHistory(i,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages,eventTypes:Ka})}async expandSessionHistory(e,s={}){if(!e)return;if(this.sessionHistoryExpansionLoads.has(e))return this.sessionHistoryExpansionLoads.get(e);const n=this.getState(),i=n.history.bySessionId.get(e),o=Math.max(J,Number(i?.loadedEventLimit??J)||J),r=J,a=Array.isArray(i?.events)&&i.events.length>0?Number(i.events[0]?.seq||0):0;if(!i?.hasOlderEvents||a<=1){this.dispatch({type:"ui/status",text:"Already showing the oldest loaded history"});return}const l=e===n.sessions.activeSessionId,u=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),f=l?this.getActiveChatRenderMetrics(n).totalLines:0,d=(async()=>{let p;const h=Math.max(1,Math.floor(Number(s.pages)||1)),m=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&a>0){p=i||Ut([],{requestedLimit:o});for(let y=0;y<h;y+=1){const w=Array.isArray(p?.events)&&p.events.length>0?Number(p.events[0]?.seq||0):0;if(!p?.hasOlderEvents||w<=1){p={...p,hasOlderEvents:!1};break}if(Number(p.loadedEventCount||0)>=ro)break;const I=await this.transport.getSessionEventsBefore(e,w,r,m);if(!Array.isArray(I)||I.length===0){p={...p,hasOlderEvents:!1};break}const x=Ut(I,{requestedLimit:r}),C=[...x.events||[],...p?.events||[]];if(p={chat:ft([...x.chat||[],...p?.chat||[]]),activity:[...x.activity||[],...p?.activity||[]],events:C,lastSeq:p?.lastSeq||p?.events?.[p?.events?.length-1]?.seq||I[I.length-1]?.seq||0,loadedEventLimit:C.length,loadedEventCount:C.length,hasOlderEvents:I.length>=r&&Number(I[0]?.seq||0)>1},!p.hasOlderEvents)break}}else{const y=dl(o);if(y<=o){this.dispatch({type:"ui/status",text:i?.hasOlderEvents?`Already showing a large recent history window (${o} events)`:"Already showing the oldest loaded history"});return}const w=await this.transport.getSessionEvents(e,void 0,y);p={...Ut(w,{requestedLimit:y}),lastSeq:w[w.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:p});for(const y of p?.events||[])this.reconcileOutboxAgainstEvent(e,y);const g=Array.isArray(i?.chat)&&i.chat.length>0;if(l&&!g)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(l&&u>0){const y=this.getState(),w=this.getActiveChatRenderMetrics(y).totalLines,I=Math.max(0,w-f);I>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:u+I})}const S=p.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${p.loadedEventCount} events loaded)`:`Loaded older history page (${p.loadedEventCount} events loaded)`:`Loaded full available history (${p.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:S}),p.hasOlderEvents?s.autoTriggered&&l&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,d),d}async cancelActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:r,skippedCount:a}=this.getBulkSelectedSessionActions(s);if(r.length===0){this.dispatch({type:"ui/status",text:"No cancellable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Sessions",message:`Cancel ${r.length} selected session${r.length===1?"":"s"}?${a>0?` (${a} selected row${a===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Cancel Sessions",action:"cancelSession",previousFocus:s.ui.focusRegion}});return}let l=0;const u=[];for(const d of r)try{await this.transport.cancelSession(d.sessionId),l+=1}catch(p){u.push(`${d.sessionId.slice(0,8)}: ${p?.message||String(p)}`)}this.dispatch({type:"sessions/selectClear"});const f=u.length===0?`Cancelled ${l} session${l===1?"":"s"}`:`Cancelled ${l}/${r.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:f}),await this.refreshSessions();return}const i=s.sessions.activeSessionId;if(!i)return;const o=s.sessions.byId[i];if(o?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; cancel sessions individually."});return}if(o?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const r=o.title||o.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Terminate & Restart System Session",message:`Terminate system session "${r}" and start a fresh one?`,confirmLabel:"Terminate & Restart",action:"cancelSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(o.agentId||i,{disposition:"terminate",reason:"Terminated by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${o.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const a=o?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Session",message:`Cancel session "${a}"? The session will stop processing.`,confirmLabel:"Cancel Session",action:"cancelSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.cancelSession(i),this.dispatch({type:"ui/status",text:`Cancelled ${i.slice(0,8)}`}),await this.refreshSessions()}updateConfirmExtras(e){const s=this.getState().ui.modal;!s||s.type!=="confirm"||this.dispatch({type:"ui/modal",modal:{...s,extras:{...s.extras||{},...e||{}}}})}async regenerateActiveSession({confirmed:e=!1,instructions:s="",distillMode:n="llm"}={}){const i=this.getState(),o=i.sessions.activeSessionId;if(!o)return;if(typeof this.transport.regenerateSession!="function"){this.dispatch({type:"ui/status",text:"Session regeneration is not supported by this deployment"});return}const r=i.sessions.byId[o];if(r?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; regenerate sessions individually."});return}if(r?.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be regenerated."});return}if(r?.serviceKind){this.dispatch({type:"ui/status",text:"Service sessions are runtime machinery and cannot be regenerated."});return}if(!e){const a=r?.title||o.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Regenerate Session",message:`Regenerate context for "${a}"? The transcript is archived and distilled, then the session rebuilds fresh from it at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved. As an operator action this overrides the rate limits (cooldown / minimum age).`,confirmLabel:"Regenerate",action:"regenerateSession",sessionId:o,previousFocus:i.ui.focusRegion,extras:{instructions:"",distillMode:"llm"}}});return}try{const a=String(s||"").trim();await this.transport.regenerateSession(o,{force:!0,...a?{instructions:a.slice(0,4e3)}:{},...n==="deterministic"?{distillMode:"deterministic"}:{}}),this.dispatch({type:"ui/status",text:`Regeneration requested for ${o.slice(0,8)} — rebuilding at the next boundary`})}catch(a){this.dispatch({type:"ui/status",text:`Regenerate failed: ${a?.message||String(a)}`});return}await this.refreshSessions()}async stopActiveSessionTurn(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n||n.isGroup){this.dispatch({type:"ui/status",text:"Select a session to stop its turn."});return}if(typeof this.transport.stopSessionTurn!="function"){this.dispatch({type:"ui/status",text:"Stop turn is not supported by this transport"});return}if(this._stopTurnInFlight||(this._stopTurnInFlight=new Set),!this._stopTurnInFlight.has(s)){this._stopTurnInFlight.add(s),this.dispatch({type:"ui/status",text:`Stopping turn for ${s.slice(0,8)}…`});try{const o=(await this.transport.stopSessionTurn(s,{reason:"Stopped by user"}))?.outcome||"stopped";o==="no_active_turn"?this.dispatch({type:"ui/status",text:"No active turn to stop"}):o==="timeout"?this.dispatch({type:"ui/status",text:"Stop requested — waiting for the turn to unwind"}):this.dispatch({type:"ui/status",text:`Stopped turn for ${s.slice(0,8)}`})}catch(i){this.dispatch({type:"ui/status",text:`Stop turn failed: ${i?.message||i}`})}finally{this._stopTurnInFlight.delete(s)}await this.refreshSessions(),await this.refreshActiveSessionDetail?.().catch?.(()=>{})}}togglePinActiveSession(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n)return;if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be pinned."});return}if(!n.isGroup&&(n.parentSessionId||n.groupId)){this.dispatch({type:"ui/status",text:"Sessions inside groups or parents cannot be pinned."});return}const i=Array.isArray(e.sessions.pinnedIds)&&e.sessions.pinnedIds.includes(s);this.dispatch({type:"sessions/pinToggle",sessionId:s}),this.dispatch({type:"ui/status",text:i?`Unpinned ${s.slice(0,8)}`:`Pinned ${s.slice(0,8)}`})}toggleSessionSelectMode(){const e=this.getState(),s=!e.sessions.selectMode;if(this.dispatch({type:"sessions/selectMode",enabled:s}),s){const n=e.sessions.activeSessionId;n&&e.sessions.byId[n]&&this.dispatch({type:"sessions/selectToggle",sessionId:n}),this.dispatch({type:"ui/status",text:"Select mode: space toggles, Ctrl+G moves, c cancels, V/esc exits"})}else this.dispatch({type:"ui/status",text:"Select mode off"})}toggleActiveSessionSelection(){const e=this.getState(),s=e.sessions.activeSessionId;s&&(e.sessions.selectMode||this.dispatch({type:"sessions/selectMode",enabled:!0}),this.dispatch({type:"sessions/selectToggle",sessionId:s}))}setSessionSelection(e){const s=Array.isArray(e)?e:[];this.dispatch({type:"sessions/selectSet",sessionIds:s})}clearSessionSelection(){this.dispatch({type:"sessions/selectClear"})}async completeActiveSession(e="Completed by user",{confirmed:s=!1}={}){const n=this.getState(),i=Array.isArray(n.sessions.selectedIds)?n.sessions.selectedIds:[];if(n.sessions.selectMode&&i.length>=1){const{eligible:a,skippedCount:l}=this.getBulkSelectedSessionActions(n);if(a.length===0){this.dispatch({type:"ui/status",text:"No completable sessions in selection (system sessions and groups are skipped)."});return}if(!s){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Sessions",message:`Complete ${a.length} selected session${a.length===1?"":"s"}? This will cascade to their sub-agents.${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Complete Sessions",action:"completeSession",previousFocus:n.ui.focusRegion}});return}let u=0;const f=[];for(const p of a)try{await this.transport.completeSession(p.sessionId,e),u+=1}catch(h){f.push(`${p.sessionId.slice(0,8)}: ${h?.message||String(h)}`)}this.dispatch({type:"sessions/selectClear"});const d=f.length===0?`Completed ${u} session${u===1?"":"s"}`:`Completed ${u}/${a.length}; ${f.length} failed: ${f.slice(0,2).join(", ")}${f.length>2?"…":""}`;this.dispatch({type:"ui/status",text:d}),await this.refreshSessions();return}const o=this.getState().sessions.activeSessionId;if(!o)return;const r=this.getState().sessions.byId[o];if(r?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; complete sessions individually."});return}if(r?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!s){const a=r.title||r.agentId||o.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete & Restart System Session",message:`Mark system session "${a}" complete and start a fresh one?`,confirmLabel:"Complete & Restart",action:"completeSession",sessionId:o,previousFocus:this.getState().ui.focusRegion}});return}await this.transport.restartSystemSession(r.agentId||o,{disposition:"complete",reason:e}),this.dispatch({type:"ui/status",text:`Restarted system session ${r.agentId||o.slice(0,8)}`}),await this.refreshSessions();return}if(typeof this.transport.completeSession!="function"){this.dispatch({type:"ui/status",text:"Session completion is not supported by this transport"});return}if(r?.status==="completed"&&!r?.cronActive&&!r?.cronInterval){this.dispatch({type:"ui/status",text:`${o.slice(0,8)} is already completed`});return}if(!s){const a=r?.title||o.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Session",message:`Complete session "${a}"? This will cascade to all sub-agents.`,confirmLabel:"Complete",action:"completeSession",sessionId:o,previousFocus:this.getState().ui.focusRegion}});return}this.dispatch({type:"ui/status",text:`Completing ${o.slice(0,8)} (cascading to sub-agents)...`});try{await this.transport.completeSession(o,e),await this.refreshSessions(),this.scheduleSessionDetailSync(o,100),this.scheduleSessionsRefresh(900)}catch(a){await this.loadSession(o).catch(()=>{}),this.dispatch({type:"ui/status",text:`Failed to send /done: ${a?.message||String(a)}`})}}async deleteActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:r,skippedCount:a}=this.getBulkSelectedSessionActions(s);if(r.length===0){this.dispatch({type:"ui/status",text:"No deletable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete Sessions",message:`Hard delete ${r.length} selected session${r.length===1?"":"s"}? This action cannot be undone.${a>0?` (${a} selected row${a===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Hard Delete Sessions",action:"deleteSession",previousFocus:s.ui.focusRegion}});return}let l=0;const u=[];for(const d of r)try{await this.transport.deleteSession(d.sessionId),this.handleSessionGone(d.sessionId),l+=1}catch(p){u.push(`${d.sessionId.slice(0,8)}: ${p?.message||String(p)}`)}this.dispatch({type:"sessions/selectClear"});const f=u.length===0?`Deleted ${l} session${l===1?"":"s"}`:`Deleted ${l}/${r.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:f}),await this.refreshSessions();return}const i=s.sessions.activeSessionId;if(!i)return;const o=s.sessions.byId[i];if(o?.isGroup){const r=o.groupId||Gs(i);if(!r||typeof this.transport.deleteSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group deletion is not supported by this transport"});return}if(Number(o.memberCount||0)>0){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Group Not Empty",message:`Group "${o.title||r}" is not empty. Move all sessions out of the group before deleting it.`,confirmLabel:"OK",action:"alert",alert:!0,previousFocus:s.ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Move all sessions out of the group before deleting it."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Group",message:`Delete empty group "${o.title||r}"? This action cannot be undone.`,confirmLabel:"Delete Group",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSessionGroup(r),this.dispatch({type:"ui/status",text:`Deleted group ${o.title||r}`}),await this.refreshSessions();return}if(o?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const r=o.title||o.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete & Restart System Session",message:`Hard delete system session "${r}" and start a fresh one? This removes the current orchestration immediately.`,confirmLabel:"Hard Delete & Restart",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(o.agentId||i,{disposition:"hard_delete",reason:"Hard-deleted by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${o.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const a=o?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Session",message:`Delete session "${a}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSession(i),this.handleSessionGone(i),this.dispatch({type:"ui/status",text:`Deleted ${i.slice(0,8)}`}),await this.refreshSessions()}async handleCommand(e){switch(e){case E.REFRESH:await this.refreshSessions();return;case E.NEW_SESSION:await this.openNewSessionFlow();return;case E.OPEN_MODEL_PICKER:await this.openModelPicker();return;case E.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case E.OPEN_THEME_PICKER:this.openThemePicker();return;case E.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case E.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case E.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case E.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case E.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case E.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case E.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case E.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case E.TOGGLE_CHAT_VIEW:this.toggleChatViewMode();return;case E.CLOSE_MODAL:this.closeModal();return;case E.MODAL_PREV:this.moveModalSelection(-1);return;case E.MODAL_NEXT:this.moveModalSelection(1);return;case E.MODAL_PANE_PREV:this.moveModalPane(-1);return;case E.MODAL_PANE_NEXT:this.moveModalPane(1);return;case E.MODAL_CONFIRM:await this.confirmModal();return;case E.SEND_PROMPT:await this.sendPrompt();return;case E.FOCUS_NEXT:this.focusNext();return;case E.FOCUS_PREV:this.focusPrev();return;case E.FOCUS_LEFT:this.focusLeft();return;case E.FOCUS_RIGHT:this.focusRight();return;case E.FOCUS_PROMPT:this.setFocus(A.PROMPT);return;case E.FOCUS_SESSIONS:this.setFocus(A.SESSIONS);return;case E.MOVE_SESSION_UP:await this.moveSession(-1);return;case E.MOVE_SESSION_DOWN:await this.moveSession(1);return;case E.EXPAND_SESSION:this.expandActiveSession();return;case E.COLLAPSE_SESSION:this.collapseActiveSession();return;case E.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case E.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case E.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case E.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case E.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case E.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case E.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case E.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case E.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case E.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case E.OPEN_HELP:this.openHelpModal();return;case E.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case E.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case E.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case E.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case E.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case E.OPEN_LOG_FILTER:this.openLogFilter();return;case E.OPEN_FILES_FILTER:this.openFilesFilter();return;case E.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case E.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case E.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case E.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case E.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case E.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case E.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case E.SCROLL_UP:this.scrollCurrentPane(1);return;case E.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case E.PAGE_UP:if(this.getState().ui.focusRegion===A.SESSIONS){await this.moveSessionPage(-1);return}this.scrollCurrentPane(10);return;case E.PAGE_DOWN:if(this.getState().ui.focusRegion===A.SESSIONS){await this.moveSessionPage(1);return}this.scrollCurrentPane(-10);return;case E.EXPAND_HISTORY:await this.expandActiveHistory();return;case E.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case E.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case E.CANCEL_SESSION:await this.cancelActiveSession();return;case E.STOP_TURN:await this.stopActiveSessionTurn();return;case E.DONE_SESSION:await this.completeActiveSession();return;case E.DELETE_SESSION:await this.deleteActiveSession();return;case E.REGENERATE_SESSION:await this.regenerateActiveSession();return;case E.PIN_SESSION:this.togglePinActiveSession();return;case E.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case E.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case E.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case E.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case E.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case E.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case E.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case E.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case E.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case E.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case E.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case E.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case E.ADMIN_CLEAR_GHCP_KEY:await this.clearAdminGhcpKey();return;default:return}}async exportExecutionHistory(){const e=this.getState().sessions.activeSessionId;if(!e){this.dispatch({type:"ui/status",text:"No session selected."});return}if(typeof this.transport.exportExecutionHistory!="function"){this.dispatch({type:"ui/status",text:"History export is not supported by this transport."});return}this.dispatch({type:"ui/status",text:"Exporting execution history..."});try{const s=await this.transport.exportExecutionHistory(e);s?.filename&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:e,filename:s.filename}),this.dispatch({type:"files/selectGlobal",artifactId:`${e}/${s.filename}`}),await this.ensureFilePreview(e,s.filename,{force:!0}).catch(()=>null)),this.dispatch({type:"ui/status",text:s?.filename?`History saved as artifact ${s.filename}`:`History exported → ${s?.artifactLink||"artifact created"}`})}catch(s){this.dispatch({type:"ui/status",text:`Export failed: ${s?.message||String(s)}`})}}}const Ss=0;function be(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Object.is(t[i],e[i]))return!1;return!0}function Ws(){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 xf(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 vf(t){const e=t?.principal;if(!e)return null;const s=e.displayName||e.email||e.subject||null;return s?t?.authorization?.role==="admin"||Array.isArray(e.roles)&&e.roles.includes("admin")?`(*) ${s}`:s:null}function Ef(t,e=null,s=null){const n=[],i=typeof s=="string"?s.trim():"";i&&n.push({text:i,color:"yellow",bold:!0}),Array.isArray(t)&&t.length>0&&(n.length>0&&n.push({text:" ",color:"gray"}),n.push(...t));const o=typeof e=="string"?e.trim():"";return o?(n.length>0&&n.push({text:" ",color:"gray"}),n.push({text:o,color:"cyan",bold:!0}),n):n.length>0?n:null}function Af(t=2e3){const[e,s]=c.useState(()=>Ws());return c.useEffect(()=>{if(Ws()==null)return;const n=()=>{const o=Ws();o!=null&&s(r=>r===o?r:o)};n();const i=setInterval(n,t);return()=>clearInterval(i)},[t]),c.useMemo(()=>xf(e),[e])}function vt(t,e){return t&&e?{[t]:e}:{}}function co(t){return typeof t=="string"?{text:t,color:"white"}:t}function Dt(t,e,s,n,i,o){const r=(e.tabs||Te).map(d=>({text:d===e.activeTab?`[${d}] `:`${d} `,color:d===e.activeTab?"magenta":"gray",bold:d===e.activeTab})),a=(e.lines||[]).map(co),l=(e.stickyLines||[]).map(co),u=e.activeTab==="sequence"?[r,...l]:[],f=e.activeTab==="sequence"?a:[r,...a];return c.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:i,stickyLines:u,marginBottom:Ss,lines:f,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="sequence"||e.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:o})}function uo(t,e){const s=String(t||"");return e<=0?"":s.length<=e?s:e===1?s.slice(0,1):`${s.slice(0,e-1)}...`}c.memo(function({controller:e,maxRows:s,width:n,height:i,frame:o,versionLabel:r=null}){const a=Ee(),l=Af(),u=z(e,m=>({sessions:m.sessions,mode:m.connection?.mode||"local",brandingTitle:m.branding?.title||"PilotSwarm",focused:m.ui.focusRegion==="sessions",identityLabel:vf(m.auth)}),be),f=c.useMemo(()=>Ef(l,r,u.identityLabel),[l,r,u.identityLabel]),d=c.useMemo(()=>({sessions:u.sessions,connection:{mode:u.mode},branding:{title:u.brandingTitle}}),[u.brandingTitle,u.mode,u.sessions]),p=c.useMemo(()=>Zs(d,s),[d,s]),h=c.useMemo(()=>p.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:p.map(m=>m.active?or(m.runs,{preserveColors:!0}):m.runs),[p]);return c.createElement(a.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:f,color:"yellow",focused:u.focused,width:n,height:i,marginBottom:Ss,lines:h,paneId:"sessions",paneLabel:"Sessions",frame:o})});c.memo(function({controller:e,width:s,height:n,frame:i}){const o=Ee(),r=z(e,I=>{const x=I.sessions.activeSessionId;return{activeSessionId:x,activeSession:x&&I.sessions.byId[x]||null,activeHistory:x&&I.history.bySessionId.get(x)||null,activeOutbox:x&&I.outbox?.bySessionId?.[x]||null,authPrincipal:I.auth?.principal||null,branding:I.branding,connectionError:I.connection.error,connectionMode:I.connection.mode,chatViewMode:I.ui.chatViewMode||"transcript",chatScroll:I.ui.scroll.chat,focused:I.ui.focusRegion==="chat"}},be),a=Math.max(20,s-4),l=c.useMemo(()=>{const I=new Map;return r.activeSessionId&&r.activeHistory&&I.set(r.activeSessionId,r.activeHistory),{branding:r.branding,auth:{principal:r.authPrincipal},connection:{error:r.connectionError,mode:r.connectionMode},ui:{chatViewMode:r.chatViewMode},sessions:{activeSessionId:r.activeSessionId,byId:vt(r.activeSessionId,r.activeSession)},history:{bySessionId:I},outbox:{bySessionId:r.activeSessionId&&r.activeOutbox?{[r.activeSessionId]:r.activeOutbox}:{}}}},[r.activeHistory,r.activeSessionId,r.activeSession,r.activeOutbox,r.authPrincipal,r.branding,r.chatViewMode,r.connectionError,r.connectionMode]),u=c.useMemo(()=>Tr(l,{width:a}),[a,l]),f=Po(!!u?.animateTitleRight),d=c.useMemo(()=>_o(u?.titleRight,f),[f,u?.titleRight]),p=!r.activeSessionId&&r.connectionError,h=c.useMemo(()=>p?[{kind:"markup",value:r.branding.splash},{text:"",color:"gray"},{text:"Startup failed",color:"red",bold:!0},{text:r.connectionError,color:"white"},{text:"",color:"gray"},{text:"Check env credentials and model provider config, then relaunch.",color:"yellow"}]:Mn(l,a),[r.branding.splash,r.connectionError,a,l,p]),m=String(r.activeSession?.status||"").toLowerCase()==="running",g=No(m),S=c.useMemo(()=>p?[]:kn(l,{spinnerFrame:g,maxWidth:a}),[l,p,g,a]),y=c.useMemo(()=>p?[]:Nn(l,a),[l,p,a]),w=c.useMemo(()=>y.length>0||S.length>0?[...y,...S]:[],[y,S]);return c.createElement(o.Panel,{title:u.title,titleRight:d,color:u.color,focused:r.focused,width:s,height:n,lines:h,bottomStickyLines:w,scrollOffset:r.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:i})});const Tf=c.memo(function({controller:e,width:s,height:n,shellTitle:i,focused:o=!1,frame:r,showFullscreenTitle:a=!1,embedded:l=!1}){const u=Ee(),f=z(e,M=>({activeSessionId:M.sessions.activeSessionId,activeSession:M.sessions.activeSessionId&&M.sessions.byId[M.sessions.activeSessionId]||null,sessionsFlat:M.sessions.flat,filesBySessionId:M.files.bySessionId,filesFullscreen:!!M.files.fullscreen,selectedArtifactId:M.files.selectedArtifactId,filesFilter:M.files.filter,filePreviewScroll:M.ui.scroll.filePreview}),be),d=Math.max(20,s-4),p=c.useMemo(()=>({sessions:{activeSessionId:f.activeSessionId,byId:f.activeSessionId&&f.activeSession?{[f.activeSessionId]:f.activeSession}:{},flat:f.sessionsFlat},files:{bySessionId:f.filesBySessionId,fullscreen:f.filesFullscreen,selectedArtifactId:f.selectedArtifactId,filter:f.filesFilter},ui:{scroll:{filePreview:f.filePreviewScroll}}}),[f]),h=c.useMemo(()=>On(p,{listWidth:Math.max(8,d-4),previewWidth:Math.max(8,d-4)}),[d,p]),m=i||(a?h.fullscreenTitle:h.panelTitle||h.listTitle)||[{text:"Files",color:"magenta",bold:!0}],g=Math.max(9,n-4),S=Math.max(5,Math.min(10,Math.floor(g*.35)));let y=Math.max(5,Math.min(S,(h.listBodyLines||[]).length+2)),w=Math.max(5,g-y-1);const I=8;if(w<I){const M=I-w;y=Math.max(5,y-M),w=Math.max(5,g-y-1)}const x=Math.max(1,y-2),C=Math.max(0,h.selectedIndex-Math.floor(x/2)),v=!l&&r?{x:r.x+2,y:r.y+2,width:d,height:y}:null,k=!l&&r?{x:r.x+2,y:r.y+2+y+1,width:d,height:w}:null,P=Te.map(M=>({text:M==="files"?`[${M}] `:`${M} `,color:M==="files"?"magenta":"gray",bold:M==="files"})),O=c.createElement(u.Column,{width:d},c.createElement(u.Lines,{lines:[P]}),c.createElement(u.Panel,{title:h.listTitle,color:"gray",focused:!1,width:d,height:y,lines:h.listBodyLines||h.listLines.slice(1),scrollOffset:C,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:v}),c.createElement(u.Panel,{title:h.previewTitle,color:"gray",focused:!1,width:d,height:w,lines:h.previewLines,scrollOffset:h.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:k}));return l?O:c.createElement(u.Panel,{title:m,color:"magenta",focused:o,width:s,height:n,marginBottom:Ss,paneId:"inspector",paneLabel:"Inspector",frame:r},O)}),Cf=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Ee(),a=Math.max(20,s-4),l=z(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null}),be),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:vt(l.activeSessionId,l.activeSession)},ui:{inspectorTab:"files"}}),[l.activeSession,l.activeSessionId]),f=c.useMemo(()=>Ye(u,{width:a}),[a,u]);return c.createElement(r.Panel,{title:f.title,color:"magenta",focused:o.focused,width:s,height:n,marginBottom:Ss,paneId:"inspector",paneLabel:"Inspector",frame:i},c.createElement(Tf,{controller:e,width:s,height:n,frame:i,focused:o.focused,embedded:!0}))}),kf=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Ee(),a=Math.max(20,s-4),l=z(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,expandedTurns:d.ui.sequenceExpandedTurns,selectedTurn:d.ui.sequenceSelectedTurn}),be),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:vt(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=c.useMemo(()=>Ye(u,{width:a,sequenceExpansion:{expandedTurns:l.expandedTurns||[],selectedTurn:l.selectedTurn??null}}),[a,u,l.expandedTurns,l.selectedTurn]);return Dt(r,f,o,s,n,i)}),Mf=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Ee(),a=Math.max(20,s-4),l=z(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,logs:d.logs}),be),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:vt(l.activeSessionId,l.activeSession)},logs:l.logs,ui:{inspectorTab:"logs"}}),[l.activeSession,l.activeSessionId,l.logs]),f=c.useMemo(()=>Ye(u,{width:a}),[a,u]);return Dt(r,f,o,s,n,i)}),Nf=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Ee(),a=Math.max(20,s-4),l=z(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,executionHistory:d.executionHistory}),be),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:vt(l.activeSessionId,l.activeSession)},executionHistory:l.executionHistory,ui:{inspectorTab:"history"}}),[l.activeSession,l.activeSessionId,l.executionHistory]),f=c.useMemo(()=>Ye(u,{width:a}),[a,u]);return Dt(r,f,o,s,n,i)}),Pf=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Ee(),a=Math.max(20,s-4),l=z(e,d=>({activeSessionId:d.sessions.activeSessionId,sessionsById:d.sessions.byId,sessionsFlat:d.sessions.flat,histories:d.history.bySessionId}),be),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:l.sessionsById,flat:l.sessionsFlat},history:{bySessionId:l.histories},ui:{inspectorTab:"nodes"}}),[l.activeSessionId,l.histories,l.sessionsById,l.sessionsFlat]),f=c.useMemo(()=>Ye(u,{width:a}),[a,u]);return Dt(r,f,o,s,n,i)}),_f=c.memo(function({controller:e,width:s,height:n,frame:i,meta:o}){const r=Ee(),a=Math.max(20,s-4),l=z(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,sessionStats:d.sessionStats,fleetStats:d.fleetStats,statsViewMode:d.ui.statsViewMode}),be),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:vt(l.activeSessionId,l.activeSession)},sessionStats:l.sessionStats,fleetStats:l.fleetStats,ui:{inspectorTab:"stats",statsViewMode:l.statsViewMode}}),[l.activeSession,l.activeSessionId,l.fleetStats,l.sessionStats,l.statsViewMode]),f=c.useMemo(()=>Ye(u,{width:a}),[a,u]);return Dt(r,f,o,s,n,i)});c.memo(function({controller:e,width:s,height:n,frame:i}){const o=z(e,r=>({inspectorTab:r.ui.inspectorTab,inspectorScroll:r.ui.scroll.inspector,inspectorFollowBottom:r.ui.followBottom?.inspector!==!1,focused:r.ui.focusRegion==="inspector"}),be);return o.inspectorTab==="files"?c.createElement(Cf,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="sequence"?c.createElement(kf,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="logs"?c.createElement(Mf,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="history"?c.createElement(Nf,{controller:e,width:s,height:n,frame:i,meta:o}):o.inspectorTab==="stats"?c.createElement(_f,{controller:e,width:s,height:n,frame:i,meta:o}):c.createElement(Pf,{controller:e,width:s,height:n,frame:i,meta:o})});c.memo(function({controller:e,width:s,height:n,maxLines:i,frame:o}){const r=Ee(),a=z(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,followBottom:f.ui.followBottom?.activity!==!1,focused:f.ui.focusRegion==="activity"}},be),l=c.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]),u=c.useMemo(()=>_n(l,i),[i,l]);return c.createElement(r.Panel,{title:u.title,color:"gray",focused:a.focused,width:s,height:n,lines:u.lines,scrollOffset:a.scroll,scrollMode:a.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:o})});c.memo(function({controller:e,rows:s}){const n=Ee(),i=z(e,o=>{const r=o.sessions.activeSessionId,a=r&&o.sessions.byId[r]||null,l=r&&o.outbox?.bySessionId?.[r]?o.outbox.bySessionId[r]:[];return{prompt:o.ui.prompt,promptCursor:o.ui.promptCursor,focused:o.ui.focusRegion==="prompt",answeringQuestion:!!a?.pendingQuestion?.question,editingPending:o.ui.promptEdit?.sessionId===r,hasOutbox:l.length>0,hasPendingOutbox:l.some(u=>u?.phase==="pending")}},be);return c.createElement(n.Input,{label:i.answeringQuestion?"answer":i.editingPending?"pending":"you",value:i.prompt,cursorIndex:i.promptCursor,focused:i.focused,placeholder:i.answeringQuestion?"Type an answer and press Enter":i.editingPending?"Edit pending prompt, Enter sends batch, Esc cancels":i.hasOutbox?"Type a message and press Enter to queue it":"Type a message and press Enter",rows:s})});c.memo(function({controller:e}){const s=Ee(),n=z(e,f=>({connected:f.connection.connected,workersOnline:f.connection.workersOnline,focusRegion:f.ui.focusRegion,inspectorTab:f.ui.inspectorTab,chatViewMode:f.ui.chatViewMode||"transcript",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,selectedIds:f.sessions.selectedIds,selectMode:f.sessions.selectMode}),be),i=c.useMemo(()=>({connection:{connected:n.connected,workersOnline:n.workersOnline,mode:n.mode},ui:{focusRegion:n.focusRegion,inspectorTab:n.inspectorTab,chatViewMode:n.chatViewMode,fullscreenPane:n.fullscreenPane,statusText:n.statusText,modal:n.modal},logs:{available:n.logsAvailable,tailing:n.logsTailing},files:{fullscreen:n.filesFullscreen},sessions:{activeSessionId:n.activeSessionId,selectedIds:n.selectedIds,selectMode:n.selectMode,byId:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{}}}),[n]),o=c.useMemo(()=>ru(i),[i]),r=typeof s.getViewport=="function"?s.getViewport():{width:120},a=Math.max(20,(r.width||120)-4),l=Math.min(Math.max(18,Math.floor(a*.45)),a-8),u=Math.max(8,a-l-3);return c.createElement(s.StatusLine,{left:uo(o.left,u),right:uo(o.right,l)})});const Of="modulepreload",Rf=function(t){return"/"+t},fo={},Lf=function(e,s,n){let i=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(f=>Promise.resolve(f).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const r=document.querySelector("meta[property=csp-nonce]"),a=r?.nonce||r?.getAttribute("nonce");i=l(s.map(u=>{if(u=Rf(u),u in fo)return;fo[u]=!0;const f=u.endsWith(".css"),d=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const p=document.createElement("link");if(p.rel=f?"stylesheet":Of,f||(p.as="script"),p.crossOrigin="",p.href=u,a&&p.setAttribute("nonce",a),document.head.appendChild(p),f)return new Promise((h,m)=>{p.addEventListener("load",h),p.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return i.then(r=>{for(const a of r||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})};var qr=Ia();const $f=920,zr=7,Yr=19,Dn=.24,Qr=16,Xr=8,Ff=224,Bf=190,Df=48,He=16,Jr=.5,Tt=Jr,Hf=24,Gf=700,Uf=5e3,jf=new Set(["low","medium","high","xhigh"]),Wf=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],Kf=["pilotswarm_theme","pilotswarm_session_owner_filter"],Vf={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"History",files:"Files",stats:"Stats"},qf={sequence:"⇶",logs:"≣",nodes:"⬡",history:"⟲",files:"⧉",stats:"▁▄▇"};function zf(t,e,s){const n=Array.isArray(t)?t.filter(Boolean):[];if(n.length===0)return e;const i=n.indexOf(e),r=((i===-1?0:i)+s+n.length)%n.length;return n[r]}function Yf(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function Qf(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function Xf(t){return typeof t?.transport?.listArtifacts=="function"}function Jf(t){return typeof t?.transport?.deleteArtifact=="function"}function Zf(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const ep="Session link copied to clipboard",tp="Only people with access can open this link.";function sp(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function po(t){navigator?.clipboard?.writeText&&navigator.clipboard.writeText(t).catch(()=>{})}async function np(t,e){try{const s=t.transport;if(typeof s?.getSessionAccess=="function"&&((await s.getSessionAccess(e))?.visibility||"private")==="private"){const i=typeof s.listSessionShares=="function"?await s.listSessionShares(e).catch(()=>[]):[];return!Array.isArray(i)||i.length===0}}catch{}return!1}function ip(){if(!(typeof window>"u")){try{for(const t of Wf)window.localStorage.removeItem(t)}catch{}try{for(const t of Kf)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function yt(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{},s={};if(typeof e.themeId=="string"&&e.themeId.trim()&&(s.themeId=e.themeId.trim()),Se(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=Se(n,"includeShared")?n:{...n,includeShared:!0}}if(Se(e,"layoutAdjustments")&&(s.layoutAdjustments=Sn(e.layoutAdjustments)),Se(e,"pinnedSessionIds")&&(s.pinnedSessionIds=is(e.pinnedSessionIds)),Se(e,"collapsedSessionIds")&&(s.collapsedSessionIds=op(e.collapsedSessionIds)),Se(e,"activeSessionId")){const n=e.activeSessionId==null?null:String(e.activeSessionId).trim();s.activeSessionId=n||null}return(e.chatViewMode==="summary"||e.chatViewMode==="transcript"||e.chatViewMode==="rich")&&(s.chatViewMode=e.chatViewMode),s}function op(t){if(t instanceof Set){const n=[];for(const i of t){const o=String(i||"").trim();o&&n.push(o)}return n.sort(),n}if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();!i||e.has(i)||(e.add(i),s.push(i))}return s.sort(),s}function Se(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function Ks(t){return yt({themeId:t.themeId,sessionOwnerFilter:t.ownerFilter,layoutAdjustments:{paneAdjust:t.paneAdjust,sessionPaneAdjust:t.sessionPaneAdjust,portalSessionColumnAdjust:t.portalSessionColumnAdjust,activityPaneAdjust:t.activityPaneAdjust},pinnedSessionIds:t.pinnedIds,collapsedSessionIds:t.collapsedSessionIds,activeSessionId:t.activeSessionId,chatViewMode:t.chatViewMode})}function ho(t){return yt({themeId:t?.ui?.themeId,sessionOwnerFilter:us(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,chatViewMode:t?.ui?.chatViewMode})}function rp(t,e){const s=yt(t),n=yt(e);return yt({themeId:Se(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:Se(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:Se(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:Se(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,...Se(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...Se(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...Se(s,"chatViewMode")?{chatViewMode:s.chatViewMode}:{}})}async function ap(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:yt(e)})}function Hn(t){return Xf(t)?Te:Te.filter(e=>e!=="files")}function ke(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Object.is(t[i],e[i]))return!1;return!0}function an(t,e,s){return Math.max(e,Math.min(s,t))}function ln(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-Qr-Xr*2),n=s*Dn,i=Math.max(0,s-Ff);return{minAdjust:-n,maxAdjust:i-n}}function lp(t,e){const s=ln(t),n=Math.max(0,Number(t)||0),o=Math.max(0,n-Qr-Xr*2)*Dn;return an(o+(Number(e)||0),0,o+s.maxAdjust)}function cp(t){return t<=Df?"hidden":t<=Bf?"compact":"wrap"}function Zr(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:mt(t?.ui?.prompt||"")}function bs(t){return _t({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,Zr(t),t.ui.layout?.sessionPaneAdjust??0)}function up(t,e){const s=e==="sequence"?3:0;return Math.max(20,t-4-s)}function me(t){const e=[],s=n=>{const i=String(n||"");return!i.includes("\\n")||i.includes(`
80
+ `)?i:i.replace(/\\n/g,`
81
+ `)};for(const n of t||[]){if(n?.kind==="markup"){const i=n.splashAlt?[{text:n.value,variant:"desktop"},{text:n.splashAlt,variant:"mobile"}]:[{text:n.value,variant:null}];for(const o of i)for(const r of Lo(o.text||""))e.push({kind:"runs",runs:r,preserve:!0,splashVariant:o.variant});continue}if(n?.kind==="markdownTable"||n?.kind==="cardStart"||n?.kind==="cardEnd"||n?.kind==="imageAttachments"){e.push(n);continue}if(n?.kind==="runs"){const i=Array.isArray(n.runs)?n.runs:[];if(i.length===1){const o=i[0]||{},r=s(o.text||"");if(r.includes(`
82
+ `)){const a=r.split(`
83
+ `);for(const l of a)e.push({kind:"runs",runs:[{...o,text:l}]});continue}e.push({kind:"runs",runs:[{...o,text:r}]});continue}e.push({kind:"runs",runs:i.map(o=>({...o,text:s(o?.text||"")}))});continue}if(Array.isArray(n)){e.push({kind:"runs",runs:n});continue}if(n&&typeof n=="object"&&typeof n.text=="string"){const i=s(n.text);if(i.includes(`
84
+ `)){const o=i.split(`
85
+ `);for(const r of o)e.push({kind:"text",...n,text:r});continue}e.push({kind:"text",...n,text:i});continue}e.push({kind:"text",...n})}return e}function fe(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function ea(t=[]){return t.map(e=>String(e?.text||"")).join("")}function mo(t){return Array.isArray(t)?ea(t):String(t||"")}function go(t,e=40){if(!Array.isArray(t)){const o=String(t||"");return[{text:o.length>e?`${o.slice(0,e-1)}…`:o,color:"white",bold:!0}]}const s=[],n=o=>/^[\s·—-]+$/.test(String(o?.text||""));let i=Math.max(8,e);for(const o of t){if(i<=0)break;if(o?.color==="gray"&&s.length>0&&!n(o))continue;const a=String(o?.text||"");if(!a)continue;if(n(o)&&i<a.length+2)break;const l=a.length>i&&i>1?`${a.slice(0,i-1)}…`:a.slice(0,i);l&&(s.push({...o,text:l}),i-=l.length)}for(;s.length>0&&n(s[s.length-1]);)s.pop();return s.length>0?s:t}function dp(t){const e=ze(t);if(!e||typeof document>"u")return;const s=document.documentElement;s.style.setProperty("--ps-page-background",e.page.background),s.style.setProperty("--ps-page-foreground",e.page.foreground),s.style.setProperty("--ps-surface",e.tui.surface),s.style.setProperty("--ps-background",e.tui.background),s.style.setProperty("--ps-foreground",e.tui.foreground),s.style.setProperty("--ps-muted",e.tui.gray),s.style.setProperty("--ps-border",e.tui.border||e.tui.gray),s.style.setProperty("--ps-selection-background",e.tui.selectionBackground),s.style.setProperty("--ps-selection-foreground",e.tui.selectionForeground),s.style.setProperty("--ps-highlight-background",e.tui.activeHighlightBackground),s.style.setProperty("--ps-highlight-foreground",e.tui.activeHighlightForeground),s.style.setProperty("--ps-modal-backdrop",e.page.modalBackdrop),s.style.setProperty("--ps-modal-background",e.page.modalBackground),s.style.setProperty("--ps-modal-border",e.page.modalBorder),s.style.setProperty("--ps-modal-foreground",e.page.modalForeground),s.style.setProperty("--ps-modal-muted",e.page.modalMuted),s.style.setProperty("--ps-modal-selected-background",e.page.modalSelectedBackground),s.style.setProperty("--ps-modal-selected-border",e.page.modalSelectedBorder),s.style.setProperty("--ps-modal-selected-foreground",e.page.modalSelectedForeground)}function yo(t){const[e,s]=c.useState({width:0,height:0});return c.useLayoutEffect(()=>{const n=t.current;if(!n)return;const i=()=>{s({width:n.clientWidth,height:n.clientHeight})};i();const o=new ResizeObserver(i);return o.observe(n),window.addEventListener("resize",i),()=>{o.disconnect(),window.removeEventListener("resize",i)}},[t]),e}function fp(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/zr)),height:Math.max(18,Math.floor(s/Yr))}}function pp(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function hp(t){return pp(t)<=Jr}function mp(t,e,s,n=!1){if(!t)return 0;const i=Math.max(0,t.scrollHeight-t.clientHeight);if(n)return Math.max(0,Math.min(t.scrollTop,i));const o=Math.max(0,Number(e)||0)*He;return s==="bottom"?Math.max(0,i-o):Math.min(i,o)}function gp(t,e,s,n,i,o,{stickyBottom:r=!1}={}){const a=c.useMemo(()=>me(e),[e]),l=c.useRef(null),u=c.useRef({scrollMode:n,scrollOffset:s}),f=c.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),d=c.useRef({width:null,height:null}),[p,h]=c.useState(0);c.useLayoutEffect(()=>{const x=t.current;if(!x||typeof ResizeObserver>"u")return;d.current={width:x.clientWidth,height:x.clientHeight};const C=new ResizeObserver(()=>{const v={width:x.clientWidth,height:x.clientHeight},k=d.current;v.width===k.width&&v.height===k.height||(d.current=v,h(P=>P+1))});return C.observe(x),()=>C.disconnect()},[t]),c.useLayoutEffect(()=>{const x=t.current;if(!x)return;const C=u.current,v=f.current,k=typeof performance<"u"?performance.now():Date.now(),P=v.touching||k-(v.lastUserScrollAt||0)<Gf,O=v.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-v.lastDispatchedOffset)<2;if(P&&n===C?.scrollMode&&(s===C?.scrollOffset||O)){u.current={scrollMode:n,scrollOffset:s};return}const M=r&&n==="top"&&C?.scrollMode==="top"&&C?.scrollOffset===s,$=mp(x,s,n,M);if(Math.abs(x.scrollTop-$)>Tt){const F={target:$};l.current=F,x.scrollTop=$,window.requestAnimationFrame(()=>{l.current===F&&(l.current=null)})}u.current={scrollMode:n,scrollOffset:s}},[a,t,n,s,r,p]);const m=c.useCallback(()=>{const x=t.current;if(!x||!i)return;const C=l.current;if(C){if(Math.abs(x.scrollTop-C.target)<=Tt)return;l.current=null}f.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const v=Math.max(0,x.scrollHeight-x.clientHeight);if(v<=0)return;if(r&&typeof o.updatePaneScrollFromViewport=="function"){const P=Math.max(0,x.scrollTop)/He;f.current.lastDispatchedOffset=P,o.updatePaneScrollFromViewport(i,P,{atBottom:hp(x)});return}const k=n==="bottom"?Math.max(0,v-x.scrollTop):Math.max(0,x.scrollTop);f.current.lastDispatchedOffset=k/He,o.dispatch({type:"ui/scroll",pane:i,offset:k/He}),i==="chat"&&n==="bottom"&&x.scrollTop<=Tt&&o.armChatTopHistoryLoad?.()},[o,i,t,n,r]),g=c.useCallback(x=>{const C=t.current;if(!C||i!=="chat"||n!=="bottom"||x.deltaY>=0||C.scrollTop>Tt)return;const v=Math.max(0,C.scrollHeight-C.clientHeight);o.handleChatTopHistoryScrollIntent?.(v/He)},[o,i,t,n]),S=c.useRef({startY:null,fired:!1}),y=c.useCallback(x=>{f.current.touching=!0,!(i!=="chat"||n!=="bottom")&&(S.current={startY:x.touches?.[0]?.clientY??null,fired:!1})},[i,n]),w=c.useCallback(()=>{f.current.touching=!1,f.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),I=c.useCallback(x=>{const C=t.current,v=S.current;if(!C||i!=="chat"||n!=="bottom"||v.fired||v.startY==null||C.scrollTop>Tt)return;const k=x.touches?.[0]?.clientY;if(k==null||k-v.startY<Hf)return;v.fired=!0;const P=Math.max(0,C.scrollHeight-C.clientHeight);o.handleChatTopHistoryScrollIntent?.(P/He+1,{force:!0})},[o,i,t,n]);return{normalizedLines:a,onScroll:m,onWheel:g,onTouchStart:y,onTouchMove:I,onTouchEnd:w}}function ye({runs:t,theme:e}){return c.createElement(c.Fragment,null,(t||[]).map((s,n)=>{const i={color:fe(e,s.color),backgroundColor:fe(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"},o=String(s?.href||"").trim();return/^https?:\/\//i.test(o)?c.createElement("a",{key:`${n}:${s.text||""}`,className:"ps-md-link",href:o,target:"_blank",rel:"noreferrer",style:i},s.text||""):c.createElement("span",{key:`${n}:${s.text||""}`,style:i},s.text||"")}))}function yp({line:t,theme:e}){const s=String(t?.body||"").trim();return c.createElement("details",{className:"ps-system-notice"},c.createElement("summary",{className:"ps-system-notice-summary",style:{color:fe(e,t?.color)||"var(--ps-muted)"}},c.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),s?c.createElement("div",{className:"ps-system-notice-body"},c.createElement(Gn,{content:s,theme:e})):null)}function ge({line:t,theme:e,className:s=""}){const n=s?`ps-line ${s}`:"ps-line";return t?t.kind==="systemNotice"?c.createElement(yp,{line:t,theme:e}):t.kind==="runs"?c.createElement("div",{className:n},c.createElement(ye,{runs:t.runs,theme:e})):c.createElement("div",{className:n,style:{color:fe(e,t.color),backgroundColor:fe(e,t.backgroundColor),fontWeight:t.bold?700:400,textDecoration:t.underline?"underline":"none"}},t.text||" "):c.createElement("div",{className:n}," ")}function Ie(t){return t?t.kind==="runs"?ea(t.runs):String(t.text||""):""}function Sp(t,e,s,n){const i=c.useRef(!1);return c.useLayoutEffect(()=>{const o=t.current;if(!o)return;const r=Math.max(0,o.scrollHeight-o.clientHeight),a=Math.min(r,Math.max(0,Number(e)||0)*He);Math.abs(o.scrollTop-a)>2&&(i.current=!0,o.scrollTop=a,window.requestAnimationFrame(()=>{i.current=!1}))},[t,e]),c.useCallback(()=>{if(i.current)return;const o=t.current;!o||!s||o.scrollHeight<=o.clientHeight||n.dispatch({type:"ui/scroll",pane:s,offset:Math.max(0,o.scrollTop)/He})},[n,s,t])}const bp={js:"js",jsx:"js",mjs:"js",cjs:"js",javascript:"js",ts:"js",tsx:"js",typescript:"js",json:"json",jsonc:"json",py:"python",python:"python",sh:"shell",bash:"shell",zsh:"shell",shell:"shell",console:"shell",sql:"sql",postgres:"sql",postgresql:"sql",psql:"sql",rs:"rust",rust:"rust",go:"go",golang:"go",yaml:"yaml",yml:"yaml",css:"css",scss:"css"};function ta(t){return String(t||"").trim().toLowerCase()==="mermaid"}const So={js:new Set(["async","await","break","case","catch","class","const","continue","default","delete","do","else","export","extends","finally","for","from","function","if","import","in","instanceof","let","new","of","return","static","super","switch","this","throw","try","typeof","var","void","while","yield","true","false","null","undefined","interface","type","enum","implements","readonly","public","private","protected"]),python:new Set(["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","None","nonlocal","not","or","pass","raise","return","True","False","try","while","with","yield","self"]),shell:new Set(["if","then","else","elif","fi","for","while","do","done","case","esac","in","function","return","export","local","set","echo","cd","sudo","source"]),sql:new Set(["select","from","where","insert","into","values","update","set","delete","create","table","alter","drop","index","join","left","right","inner","outer","on","group","order","by","having","limit","offset","and","or","not","null","as","distinct","union","all","case","when","then","else","end","with","returning","primary","key","foreign","references","default","constraint","begin","commit","rollback"]),rust:new Set(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","false","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","Self","static","struct","super","trait","true","type","unsafe","use","where","while"]),go:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var","nil","true","false"]),json:new Set(["true","false","null"]),yaml:new Set(["true","false","null","yes","no"]),css:new Set(["important","media","keyframes","import","supports"])};function wp(t){const e={type:"comment",re:/#[^\n]*/y},s={type:"comment",re:/\/\/[^\n]*|\/\*[\s\S]*?\*\//y},n={type:"comment",re:/--[^\n]*|\/\*[\s\S]*?\*\//y},i={type:"number",re:/\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b0[xX][0-9a-fA-F]+\b/y},o={type:"identifier",re:/[A-Za-z_$][\w$]*/y},r={type:"string",re:/"(?:\\.|[^"\\])*"?/y},a={type:"string",re:/'(?:\\.|[^'\\])*'?/y},l={type:"string",re:/`(?:\\.|[^`\\])*`?/y},u={type:"string",re:/"""[\s\S]*?"""|'''[\s\S]*?'''/y};switch(t){case"python":return[e,u,r,a,i,o];case"shell":return[e,r,a,i,o];case"sql":return[n,a,r,i,o];case"yaml":return[e,r,a,i,o];case"json":return[r,i,o];case"css":return[{type:"comment",re:/\/\*[\s\S]*?\*\//y},r,a,i,o];default:return[s,r,a,l,i,o]}}const Ip={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},xp=2e4,Xe=new Map,vp=120;function Ep(t,e){const s=`${e||""}\0${t}`,n=Xe.get(s);if(n)return Xe.delete(s),Xe.set(s,n),n;const i=Ap(t,e);return Xe.set(s,i),Xe.size>vp&&Xe.delete(Xe.keys().next().value),i}function Ap(t,e){const s=bp[String(e||"").trim().toLowerCase()]||"default",n=So[s]||So.js,i=wp(s),o=[];let r=0,a=0;const l=u=>{u>a&&o.push({type:"plain",text:t.slice(a,u)})};for(;r<t.length;){let u=null;for(const d of i){d.re.lastIndex=r;const p=d.re.exec(t);if(p&&p.index===r&&p[0].length>0){u={type:d.type,text:p[0]};break}}if(!u){r+=1;continue}let f=u.type;if(f==="identifier")if(n.has(u.text))f="keyword";else{const d=t.slice(r+u.text.length);f=/^\s*\(/.test(d)?"fn":"plain"}if(f==="plain"){r+=u.text.length;continue}l(r),o.push({type:f,text:u.text}),r+=u.text.length,a=r}return l(t.length),o}function sa(t,e,s){const n=String(t||"");if(!n||n.length>xp)return n;let i;try{i=Ep(n,e)}catch{return n}return i.map((o,r)=>{const a=Ip[o.type];return a?c.createElement("span",{key:`t:${r}`,className:`ps-code-token is-${o.type}`,style:{color:fe(s,a)||void 0}},o.text):c.createElement(c.Fragment,{key:`t:${r}`},o.text)})}let qt=null;function Tp(){return qt||(qt=Lf(()=>import("./mermaid.core-DCEXqVUL.js").then(t=>t.bp),[]).then(t=>t.default||t).catch(t=>{throw qt=null,t})),qt}function Cp(t,e){return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"default":"dark",fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"}),t}let bo=0,wo=Promise.resolve();function kp(t){const e=wo.then(t,t);return wo=e.then(()=>{},()=>{}),e}function na({code:t,theme:e,fallback:s}){const[n,i]=c.useState(null),[o,r]=c.useState(!1),[a,l]=c.useState(""),u=c.useMemo(()=>Tl(e),[e]);return c.useEffect(()=>{let f=!0;const d=String(t||"").trim();if(d)return r(!1),Tp().then(p=>kp(async()=>{if(!f)return;Cp(p,u),bo+=1;const h=`ps-mermaid-${bo}`;await p.parse(d);const{svg:m}=await p.render(h,d);f&&i(m)})).catch(p=>{f&&(i(null),r(!0),l(String(p?.message||p)))}),()=>{f=!1}},[t,u]),n&&!o?c.createElement("div",{className:"ps-mermaid",dangerouslySetInnerHTML:{__html:n}}):o&&a?c.createElement("div",{className:"ps-mermaid-failed"},c.createElement("div",{className:"ps-mermaid-error"},`Diagram could not be rendered — ${String(a).split(`
86
+ `)[0]}`),s):s}function Oe(t,e,s="md"){return hn(t).map((n,i)=>{const o=`${s}:${i}`;return n.type==="code"?c.createElement("code",{key:o,className:"ps-md-inline-code"},n.text):n.type==="strong"?c.createElement("strong",{key:o,className:"ps-md-strong"},Oe(n.text,e,`${o}:strong`)):n.type==="em"?c.createElement("em",{key:o,className:"ps-md-em"},Oe(n.text,e,`${o}:em`)):n.type==="link"?c.createElement("a",{key:o,className:"ps-md-link",href:n.href,target:"_blank",rel:"noreferrer",style:{color:fe(e,"cyan")}},n.text):c.createElement(c.Fragment,{key:o},n.text)})}function cn(t=""){return String(t||"").replace(/\s+/g," ").trim()}const Mp=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],Np=24,Pp=32,_p=6,Io=30,Op=56,Vs=.4,Rp=1.4,Lp=2;function ia(t=[]){const e=Math.max(0,...t.map(m=>m.length));if(e<=0)return null;const s=t[0]||[],n=Math.max(1,t.length-1),i=Array.from({length:e},()=>({max:0,spaceCells:0}));for(let m=0;m<t.length;m+=1){const g=t[m];for(let S=0;S<e;S+=1){const y=cn(g[S]||"");y.length>i[S].max&&(i[S].max=y.length),m>0&&/\s/.test(y)&&(i[S].spaceCells+=1)}}let o=-1,r=0;for(let m=0;m<e;m+=1){const g=i[m];if(g.max<Np||g.spaceCells/n<.4)continue;const y=cn(s[m]||"").toLowerCase(),w=Mp.some(x=>y.includes(x))?60:0,I=g.max+w;I>r&&(r=I,o=m)}if(o<0)return null;const a=i.map((m,g)=>g===o?0:Math.max(_p,Math.min(m.max+2,Pp))),l=a.reduce((m,g)=>m+g,0),u=i[o],f=Math.max(Io,Math.min(u.max*.45,Op,Math.max(Io,l*Rp))),d=a.map((m,g)=>g===o?f:m),p=d.reduce((m,g)=>m+g,0);if(p>0&&d[o]/p<Vs){const m=p-d[o];d[o]=m*(Vs/(1-Vs))}const h=d.reduce((m,g)=>m+g,0);return h>0?{widths:d.map(m=>`${(m/h*100).toFixed(2)}%`),flexIndex:o,minWidth:`${Math.ceil(h+Lp)}ch`}:null}function oa(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(o=>cn(o?.[n]||"")).filter(Boolean).join(" / ")||null)}function xo(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 vo(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function $p(t=""){const s=String(t||"").replace(/\r\n?/g,`
87
+ `).split(`
88
+ `),n=[];for(let i=0;i<s.length;){const o=s[i],r=o.trim();if(!r){i+=1;continue}const a=/^```(\S*)\s*$/.exec(r);if(a){const d=a[1]||"",p=[];for(i+=1;i<s.length&&!/^```/.test(s[i].trim());)p.push(s[i]),i+=1;i<s.length&&(i+=1),n.push({type:"code",language:d,content:p.join(`
89
+ `)});continue}const l=/^(#{1,6})\s+(.*)$/.exec(o);if(l){n.push({type:"heading",level:l[1].length,text:l[2].trim()}),i+=1;continue}if(o.includes("|")&&i+1<s.length&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(s[i+1].trim())){const d=vo(o);i+=2;const p=[];for(;i<s.length&&s[i].includes("|")&&s[i].trim();)p.push(vo(s[i])),i+=1;n.push({type:"table",header:d,rows:p});continue}if(/^\s*>/.test(o)){const d=[];for(;i<s.length&&/^\s*>/.test(s[i]);)d.push(s[i].replace(/^\s*>\s?/,"")),i+=1;n.push({type:"blockquote",text:d.join(`
90
+ `).trim()});continue}const u=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(o);if(u){const d=/\d+\./.test(u[2]),p=[];for(;i<s.length;){const h=s[i],m=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(h);if(!m||/\d+\./.test(m[2])!==d)break;const g=[m[3].trim()];for(i+=1;i<s.length&&s[i].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[i])&&!xo(s[i],s[i+1]||"");)g.push(s[i].trim()),i+=1;if(p.push(g.join(" ")),!s[i]?.trim())break}n.push({type:"list",ordered:d,items:p});continue}const f=[o.trim()];for(i+=1;i<s.length&&s[i].trim()&&!xo(s[i],s[i+1]||"");)f.push(s[i].trim()),i+=1;n.push({type:"paragraph",text:f.join(" ")})}return n}function Gn({content:t,theme:e}){const s=c.useMemo(()=>$p(t),[t]);return s.length===0?c.createElement("div",{className:"ps-empty-state"},"No preview content."):c.createElement("div",{className:"ps-markdown-preview"},s.map((n,i)=>{if(n.type==="heading")return c.createElement("div",{key:`block:${i}`,className:`ps-md-heading is-h${n.level}`},Oe(n.text,e,`heading:${i}`));if(n.type==="code"){const o=c.createElement("section",{key:`block:${i}`,className:"ps-md-code-block"},c.createElement("div",{className:"ps-md-code-header"},n.language||"text"),c.createElement("pre",{className:"ps-md-code-pre"},c.createElement("code",null,sa(n.content,n.language,e))));return ta(n.language)?c.createElement(na,{key:`block:${i}`,code:n.content,theme:e,fallback:o}):o}if(n.type==="blockquote")return c.createElement("blockquote",{key:`block:${i}`,className:"ps-md-quote"},Oe(n.text,e,`quote:${i}`));if(n.type==="list"){const o=n.ordered?"ol":"ul";return c.createElement(o,{key:`block:${i}`,className:`ps-md-list${n.ordered?" is-ordered":""}`},n.items.map((r,a)=>c.createElement("li",{key:`item:${a}`,className:"ps-md-list-item"},Oe(r,e,`list:${i}:${a}`))))}if(n.type==="table"){const o=Math.max(n.header.length||0,...n.rows.map(m=>m.length)),r=o>0&&o<=6,a=r?ia([n.header,...n.rows]):null,l=!!a,u=a?a.flexIndex:-1,f=m=>m===u?"is-flex-column":null,d=oa([n.header],o),p=`ps-md-table${r?" is-fit-width":""}${l?" has-flex-column":""}`,h=`ps-md-table-wrap${r?" is-fit-width":""}${l?" has-flex-column":""}`;return c.createElement("div",{key:`block:${i}`,className:h},c.createElement("table",{className:p,style:a?.minWidth?{"--ps-table-min-width":a.minWidth}:void 0},a?c.createElement("colgroup",null,a.widths.map((m,g)=>c.createElement("col",{key:`col:${g}`,className:f(g)||void 0,style:{width:m}}))):null,c.createElement("thead",null,c.createElement("tr",null,n.header.map((m,g)=>c.createElement("th",{key:`head:${g}`,className:f(g)||void 0},Oe(m,e,`table:${i}:head:${g}`))))),c.createElement("tbody",null,n.rows.map((m,g)=>c.createElement("tr",{key:`row:${g}`},m.map((S,y)=>c.createElement("td",{key:`cell:${g}:${y}`,className:f(y)||void 0,"data-label":d[y]||void 0},c.createElement("span",{className:"ps-table-cell-value"},Oe(S,e,`table:${i}:${g}:${y}`)))))))))}return c.createElement("p",{key:`block:${i}`,className:"ps-md-paragraph"},Oe(n.text,e,`para:${i}`))}))}function Fp({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:o,theme:r,content:a}){const l=c.useRef(null),u=Sp(l,i,o,t);return c.createElement(tt,{title:e,color:s,focused:n,theme:r},c.createElement("div",{ref:l,className:"ps-scroll-panel ps-markdown-scroll",onScroll:u},c.createElement(Gn,{content:a,theme:r})))}function Bp(t){const e=Number(t);if(!Number.isFinite(e)||e<0)return"Unknown size";if(e<1024)return`${Math.round(e)} B`;if(e<1024*1024){const n=e/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=e/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function Dp({title:t,color:e,focused:s,theme:n,filename:i,contentType:o,sizeBytes:r,source:a,uploadedAt:l,controller:u=null,sessionId:f=null}){const d=[];o&&d.push(o),r!=null&&d.push(Bp(r)),a&&d.push(a);const p=l?new Date(l).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"",h=/^image\/(png|jpeg|gif|webp)$/i.test(String(o||"")),[m,g]=c.useState(null);return c.useEffect(()=>{if(g(null),!h||!u||!f||!i)return;let S=!1;return la(u,f,i).then(y=>{S||g(y)}).catch(()=>{S||g("error")}),()=>{S=!0}},[h,u,f,i]),c.createElement(tt,{title:t,color:e,focused:s,theme:n},c.createElement("div",{className:"ps-binary-preview-card"},c.createElement("div",{className:"ps-binary-preview-kicker"},h?"Image artifact":"Binary artifact"),c.createElement("h3",{className:"ps-binary-preview-title"},i||"Artifact"),d.length>0?c.createElement("div",{className:"ps-binary-preview-meta"},d.join(" • ")):null,p?c.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${p}`):null,h&&m&&m!=="error"?c.createElement("img",{className:"ps-binary-preview-image",src:m,alt:i||"artifact image",onClick:()=>{try{window.open(m,"_blank","noopener")}catch{}}}):c.createElement("p",{className:"ps-binary-preview-copy"},h?m==="error"?"Could not load the image preview. Use Download to save the file.":"Loading image preview…":"Preview is intentionally disabled for non-text artifacts in the browser workspace. Use Download to save the file and open it in the default app.")))}function Qt(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function qs(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function Hp(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function Ot(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function Gp(t){const e=String(Ie(t)||"").trim();return Qt(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function Up(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=Ie(t);return Ot(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function jp(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 Eo(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?jp(t.runs.slice(1,-1)):[{text:Ie(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function Wp(t){const e=String(t||"").trim();return Ot(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function Kp(t="",e=""){const s=String(t||"").trimEnd(),n=String(e||"").trimStart();if(!s||!n)return!1;const i=s.slice(-1),o=n[0];return!!(/^[,.;:!?%)\]}>]/u.test(o)||/^[._/\\-]/u.test(o)||/[([{<._/\\-]$/u.test(i)||/\.[A-Za-z0-9]{0,4}$/u.test(s)&&/^[A-Za-z0-9]/u.test(o))}function Vp(t=[]){const e=(Array.isArray(t)?t:[t]).map(s=>String(s||"").trim()).filter(Boolean);return e.length===0?"":e.slice(1).reduce((s,n)=>Kp(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function Ao(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>Vp(t.map(i=>String(i[n]||"").trim()).filter(Boolean)))}function ra(t=[]){const e=[];for(let s=0;s<t.length;){const n=t[s];if(n?.preserve){const o=n.splashVariant||null,r=[];for(;s<t.length&&t[s]?.preserve&&(t[s].splashVariant||null)===o;)r.push(t[s]),s+=1;e.push({type:"preserve",lines:r,splashVariant:o});continue}if(n?.kind==="cardStart"){const o=[];for(s+=1;s<t.length&&t[s]?.kind!=="cardEnd";)o.push(t[s]),s+=1;s<t.length&&(s+=1),s<t.length&&Ie(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:ra(o)});continue}if(n?.kind==="imageAttachments"){e.push({type:"imageAttachments",sessionId:n.sessionId||null,attachments:Array.isArray(n.attachments)?n.attachments:[]}),s+=1;continue}if(n?.kind==="markdownTable"){e.push({type:"table",headerRows:Array.isArray(n.header)&&n.header.length>0?[n.header]:[],bodyRows:Array.isArray(n.rows)?n.rows:[]}),s+=1;continue}const i=Ie(n);if(Qt(i)&&i.includes("┬")){const o=[],r=[];let a=[],l=!0;for(s+=1;s<t.length;){const u=t[s],f=Ie(u);if(qs(f)){if(a.length>0){const d=Ao(a);d.length>0&&(l?o.push(d):r.push(d))}s+=1;break}if(Hp(f)){if(a.length>0){const d=Ao(a);d.length>0&&(l?o.push(d):r.push(d))}a=[],l=!1,s+=1;continue}if(Ot(f)){const d=Wp(f);d.length>0&&a.push(d)}s+=1}e.push({type:"table",headerRows:o,bodyRows:r});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&Qt(i)){const o=Gp(n),r=[];for(s+=1;s<t.length;){const a=t[s],l=Ie(a);if(qs(l)){s+=1;break}Ot(l)?r.push(Up(a)):r.push(Ie(a)),s+=1}s<t.length&&Ie(t[s]).trim().length===0&&(s+=1),e.push({type:"code",language:o||"text",content:r.join(`
91
+ `)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&Qt(i)){const o=Eo(n),r=n.runs[0]?.color||"gray",a=[];for(s+=1;s<t.length;){const l=t[s],u=Ie(l);if(qs(u)){s+=1;break}Ot(u)?a.push(Eo(l)):a.push(l?.kind==="runs"?l.runs:[{text:Ie(l),color:l?.color||null}]),s+=1}s<t.length&&Ie(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:o,bodyLines:a,borderColor:r});continue}e.push({type:"line",line:n}),s+=1}return e}function aa({lines:t,theme:e,controller:s=null}){const n=c.useMemo(()=>ra(t),[t]);return c.createElement(ua,{blocks:n,theme:e,controller:s})}function qp({blocks:t,theme:e,controller:s=null}){return c.createElement("div",{className:"ps-rich-chat"},(t||[]).map((n,i)=>{if(n.kind==="message"){const o=n.header||{},r=n.role==="user"?" is-user":" is-assistant",a=n.pendingPhase?` is-${n.pendingPhase}`:"",l=String(n.text||""),u=n.role==="user"&&o.fromOtherPerson,f=t[i-1],d=f&&f.kind==="message"&&f.role===n.role&&!(f.header&&f.header.fromOtherPerson)&&!u;return c.createElement("article",{key:n.id!=null?`msg:${n.id}`:`msg:${i}`,className:`ps-rich-msg${r}${a}${d?" is-continued":""}`},c.createElement("header",{className:"ps-rich-msg-head"},u?c.createElement("span",{className:"ps-rich-msg-label",style:{color:fe(e,o.roleColor)||void 0}},o.roleLabel):null,c.createElement("span",{className:"ps-rich-msg-meta"},o.glyph?c.createElement("span",{className:"ps-rich-msg-glyph",title:n.pendingPhase||void 0,style:{color:fe(e,o.glyphColor)||void 0}},o.glyph):null,o.time?c.createElement("span",{className:"ps-rich-msg-time"},o.time):null)),l.trim()?c.createElement("div",{className:"ps-rich-msg-body"},c.createElement(Gn,{content:l,theme:e})):null,n.attachments?c.createElement(ca,{controller:s,sessionId:n.attachments.sessionId,attachments:n.attachments.attachments}):null)}return c.createElement("div",{key:`lines:${i}`,className:`ps-rich-lineblock is-${n.variant||"event"}`},c.createElement(aa,{lines:me(n.lines||[]),theme:e,controller:s}))}))}const Be=new Map,zp=60;function la(t,e,s){const n=`${e}/${s}`,i=Be.get(n);if(i)return Be.delete(n),Be.set(n,i),i;const o=t?.transport?.api?.downloadArtifactResponse;if(typeof o!="function")return Promise.reject(new Error("artifact download unavailable"));const r=o.call(t.transport.api,e,s).then(async a=>{if(!a?.ok)throw new Error(`download failed (${a?.status})`);const l=await a.blob();return URL.createObjectURL(l)}).catch(a=>{throw Be.get(n)===r&&Be.delete(n),a});for(Be.set(n,r);Be.size>zp;){const[a,l]=Be.entries().next().value;Be.delete(a),Promise.resolve(l).then(u=>URL.revokeObjectURL(u)).catch(()=>{})}return r}function ca({controller:t,sessionId:e,attachments:s}){const[n,i]=c.useState({});return c.useEffect(()=>{if(!t||!e)return;let o=!1;for(const r of s){const a=r?.filename;a&&la(t,e,a).then(l=>{o||i(u=>u[a]===l?u:{...u,[a]:l})}).catch(()=>{o||i(l=>l[a]==="error"?l:{...l,[a]:"error"})})}return()=>{o=!0}},[t,e,s]),c.createElement("div",{className:"ps-chat-image-strip"},s.map((o,r)=>{const a=o?.filename||`image-${r}`,l=n[a];return l&&l!=="error"?c.createElement("img",{key:`thumb:${r}:${a}`,className:"ps-chat-image-thumb",src:l,alt:a,title:`${a} — click to view full size`,onClick:()=>{try{window.open(l,"_blank","noopener")}catch{}}}):c.createElement("div",{key:`thumb:${r}:${a}`,className:`ps-chat-image-thumb is-pending${l==="error"?" is-error":""}`,title:a},l==="error"?"⚠":"🖼")}))}function ua({blocks:t,theme:e,controller:s=null}){return c.createElement(c.Fragment,null,(t||[]).map((n,i)=>{if(n.type==="imageAttachments")return c.createElement(ca,{key:`imageAttachments:${i}`,controller:s,sessionId:n.sessionId,attachments:n.attachments});if(n.type==="preserve"){const o=n.splashVariant?` is-splash-${n.splashVariant}`:"";return c.createElement("div",{key:`preserve:${i}`,className:`ps-chat-preserve-block${o}`},n.lines.map((r,a)=>c.createElement(ge,{key:`preserve:${i}:${a}`,line:r,theme:e,className:"ps-line-preserve"})))}if(n.type==="code"){const o=c.createElement("section",{key:`code:${i}`,className:"ps-md-code-block ps-chat-code-block"},c.createElement("div",{className:"ps-md-code-header"},n.language||"text"),c.createElement("pre",{className:"ps-md-code-pre"},c.createElement("code",null,sa(n.content||"",n.language,e))));return ta(n.language)?c.createElement(na,{key:`code:${i}`,code:n.content||"",theme:e,fallback:o}):o}if(n.type==="card")return c.createElement("section",{key:`card:${i}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":fe(e,n.borderColor)||"var(--ps-border)"}},c.createElement("header",{className:"ps-chat-card-header"},c.createElement(ye,{runs:n.headerRuns,theme:e})),c.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?c.createElement(ua,{blocks:n.blocks,theme:e,controller:s}):(n.bodyLines||[]).map((o,r)=>c.createElement("div",{key:`card:${i}:line:${r}`,className:"ps-chat-card-line"},c.createElement(ye,{runs:o,theme:e})))));if(n.type==="table"){const o=n.headerRows||[],r=n.bodyRows||[],a=Math.max(1,...o.map(S=>S.length),...r.map(S=>S.length)),l=a<=6,u=l?ia([...o,...r]):null,f=!!u,d=u?u.flexIndex:-1,p=S=>S===d?"is-flex-column":null,h=oa(o,a),m=`ps-chat-table${l?" is-fit-width":""}${f?" has-flex-column":""}`,g=`ps-chat-table-wrap${l?" is-fit-width":""}${f?" has-flex-column":""}`;return c.createElement("div",{key:`table:${i}`,className:g},c.createElement("table",{className:m,style:u?.minWidth?{"--ps-table-min-width":u.minWidth}:void 0},u?c.createElement("colgroup",null,u.widths.map((S,y)=>c.createElement("col",{key:`col:${y}`,className:p(y)||void 0,style:{width:S}}))):null,o.length>0?c.createElement("thead",null,o.map((S,y)=>c.createElement("tr",{key:`thead:${y}`},Array.from({length:a},(w,I)=>c.createElement("th",{key:`th:${y}:${I}`,className:p(I)||void 0},Oe(S[I]||"",e,`chat-table:${i}:head:${y}:${I}`)))))):null,c.createElement("tbody",null,r.map((S,y)=>c.createElement("tr",{key:`tbody:${y}`},Array.from({length:a},(w,I)=>c.createElement("td",{key:`td:${y}:${I}`,className:p(I)||void 0,"data-label":h[I]||void 0},c.createElement("span",{className:"ps-table-cell-value"},Oe(S[I]||"",e,`chat-table:${i}:${y}:${I}`)))))))))}return c.createElement(ge,{key:`line:${i}`,line:n.line,theme:e})}))}function Yp(t){return Array.isArray(t)?t.map(e=>{const s=String(e?.text??""),n=/^(\s*)\[(.+)\](\s*)$/.exec(s);return n?{...e,text:`${n[1]}${n[2]}${n[3]}`}:e}):t}function tt({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:i=null,children:o,theme:r,className:a=""}){const l=fe(r,s);return c.createElement("section",{className:`ps-panel${n?" is-focused":""}${a?` ${a}`:""}`,style:{"--ps-panel-accent":l||"var(--ps-border)"}},c.createElement("header",{className:"ps-panel-header"},c.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?c.createElement(ye,{runs:t,theme:r}):mo(t)),e||i?c.createElement("div",{className:"ps-panel-header-right"},e?c.createElement("div",{className:"ps-panel-title-right"},Array.isArray(e)?c.createElement(ye,{runs:e,theme:r}):mo(e)):null,i?c.createElement("div",{className:"ps-panel-actions"},i):null):null),c.createElement("div",{className:"ps-panel-body"},o))}function Qp({lines:t,theme:e,completionByTurn:s}){const[n,i]=c.useState(()=>new Set),o=c.useCallback(f=>{i(d=>{const p=new Set(d);return p.has(f)?p.delete(f):p.add(f),p})},[]),r=f=>Number(f||0).toLocaleString("en-US"),a=f=>{const d=Number(f||0);if(!Number.isFinite(d))return"?K";const p=d/1e3,h=Math.abs(p)>=10?1:2;return`${p.toFixed(h)}K`},l=f=>{const d=Number(f||0);return Number.isFinite(d)?`${(d/1e3).toFixed(1)}s`:"?s"},u=f=>{const d=String(f||"").trim();if(!d)return"unknown";const p=d.split(":").filter(Boolean),h=p[p.length-1]||"",m=p.length>1&&jf.has(h.toLowerCase())?p.length-2:p.length-1;return p[Math.max(0,m)]||p[0]||"unknown"};return c.createElement(c.Fragment,null,t.map((f,d)=>{const p=f?.kind==="runs"&&Array.isArray(f.runs)?f.runs.find(k=>k?.completedTurn!=null)?.completedTurn:null,h=p!=null?s.get(Number(p)):null;if(!h)return c.createElement(ge,{key:`line:${d}`,line:f,theme:e});const m=h.data||{},g=String(h.seq??`${m.turnIndex??p}:${h.createdAt??d}`),S=n.has(g),y=m.reasoningEffort?`${m.model||"(unknown)"}:${m.reasoningEffort}`:m.model||"(unknown)",w=u(m.model),I=m.durationMs!=null?l(m.durationMs):"duration n/a",x=m.durationMs!=null?`${r(m.durationMs)} ms`:"duration n/a",C=`${a(m.tokensInput)} / ${a(m.tokensOutput)}`,v=[["model",y],["started",m.startedAt?new Date(m.startedAt).toLocaleString():null],["ended",m.endedAt?new Date(m.endedAt).toLocaleString():null],["duration",x],["tokens",`${r(m.tokensInput)} in / ${r(m.tokensOutput)} out`],["cache",`${r(m.tokensCacheRead)} read / ${r(m.tokensCacheWrite)} write`],["tools",`${r(m.toolCalls)} calls / ${r(m.toolErrors)} errors`],["names",Array.isArray(m.toolNames)&&m.toolNames.length?m.toolNames.join(", "):null],["worker",m.workerNodeId||null],["result",m.resultType||null],["error",m.errorMessage||null]].filter(([,k])=>k!=null&&k!=="");return c.createElement(c.Fragment,{key:`seq:${d}`},c.createElement(ge,{line:f,theme:e}),c.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>o(g)},c.createElement("span",{className:"ps-sequence-turn-caret"},S?"v":">"),c.createElement("span",{className:"ps-sequence-turn-rule"},"--- "),c.createElement("span",{className:"ps-sequence-turn-key"},"Mod: "),c.createElement("span",{className:"ps-sequence-turn-model"},w),c.createElement("span",{className:"ps-sequence-turn-rule"}," ("),c.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),c.createElement("span",{className:"ps-sequence-turn-tokens"},C),c.createElement("span",{className:"ps-sequence-turn-rule"},", "),c.createElement("span",{className:"ps-sequence-turn-key"},"dur: "),c.createElement("span",{className:"ps-sequence-turn-duration"},I),c.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),S?c.createElement("div",{className:"ps-sequence-turn-details"},v.map(([k,P])=>c.createElement("div",{key:k},c.createElement("span",{className:"ps-sequence-turn-detail-label"},`${k}: `),c.createElement("span",null,String(P))))):null)}))}function ws({title:t,titleRight:e=null,color:s,focused:n,actions:i,lines:o,stickyLines:r=[],bottomStickyLines:a=[],scrollOffset:l=0,scrollMode:u="top",paneKey:f,controller:d,className:p="",panelClassName:h="",topContent:m=null,bottomContent:g=null,structuredBlocks:S=!1,stickyBottom:y=!1,renderBody:w=null}){const I=z(d,_=>_.ui.themeId),x=ze(I),C=c.useRef(null),v=c.useRef(null),k=c.useRef(!1),{normalizedLines:P,onScroll:O,onWheel:M,onTouchStart:$,onTouchMove:F,onTouchEnd:Y}=gp(C,o,l,u,f,d,{stickyBottom:y}),U=c.useMemo(()=>me(r),[r]),V=c.useMemo(()=>me(a),[a]),q=p.includes("is-preserve")&&h.includes("has-preserved-sticky"),ee=c.useCallback((_,L)=>{!_||!L||Math.abs((L.scrollLeft||0)-(_.scrollLeft||0))<=1||(k.current=!0,L.scrollLeft=_.scrollLeft,window.requestAnimationFrame(()=>{k.current=!1}))},[]),[we,R]=c.useState({up:!1,down:!1}),K=c.useCallback(_=>{if(!_)return;const L=_.scrollHeight-_.scrollTop-_.clientHeight>4,B=_.scrollTop>4;R(D=>D.up===L&&D.down===B?D:{up:L,down:B})},[]),b=c.useCallback(_=>{O(),K(_.currentTarget),!(!q||k.current)&&ee(_.currentTarget,v.current)},[O,q,ee,K]);c.useEffect(()=>{K(C.current)});const T=c.useCallback(_=>{!q||k.current||ee(_.currentTarget,C.current)},[q,ee]);return c.createElement(tt,{title:t,titleRight:e,color:s,focused:n,actions:i,theme:x,className:h},m,U.length>0?c.createElement("div",{ref:v,className:`ps-panel-sticky${q?" is-scroll-sync":""}`,onScroll:T},U.map((_,L)=>c.createElement(ge,{key:`sticky:${L}`,line:_,theme:x}))):null,c.createElement("div",{ref:C,className:`ps-scroll-panel ${p}${we.down?" is-scrolled-down":""}${we.up?" is-scrolled-up":""}`.trim(),onScroll:b,onWheel:M,onTouchStart:$,onTouchMove:F,onTouchEnd:Y,onTouchCancel:Y},typeof w=="function"?w(P,x):S?c.createElement(aa,{lines:P,theme:x,controller:d}):P.map((_,L)=>c.createElement(ge,{key:`line:${L}`,line:_,theme:x}))),V.length>0?c.createElement("div",{className:"ps-panel-bottom-sticky"},V.map((_,L)=>c.createElement(ge,{key:`bottom-sticky:${L}`,line:_,theme:x}))):null,g)}const Xp={group:"🗂",system:"⚙",service:"⚗"};function Jp({row:t,theme:e}){const s=t.chrome;if(!s)return c.createElement(da,{row:t,theme:e,structured:!0});const n=Xp[s.kind]||null,i=fe(e,s.accentColor)||void 0,o=Array.isArray(t.detailRuns)?t.detailRuns:[];return c.createElement("div",{className:"ps-rich-session-row"},c.createElement("div",{className:"ps-rich-session-main"},s.selectMode?c.createElement("span",{className:`ps-rich-session-check${s.checked?" is-checked":""}`},s.checked?"✓":""):null,n?c.createElement("span",{className:"ps-rich-session-kind"},n):c.createElement("span",{className:"ps-rich-session-dot",style:{background:fe(e,s.statusColor)||void 0},title:t.status||void 0}),s.owner?c.createElement("span",{className:`ps-rich-session-owner${s.owner.isMine?" is-mine":""}`,title:s.owner.initials},s.owner.initials):null,c.createElement("span",{className:`ps-rich-session-title${s.untitled?" is-untitled":""}`,style:s.kind==="session"?void 0:{color:i},title:s.title},s.title),s.pinned?c.createElement("span",{className:"ps-rich-session-pin",title:"Pinned"},"📌"):null,s.cron?c.createElement("span",{className:"ps-rich-session-cron",title:"Scheduled"},"⏱"):null,s.childBadge?c.createElement("span",{className:"ps-rich-session-count",style:{color:fe(e,s.childBadge.color)||void 0}},s.childBadge.text):null,s.ctx?c.createElement("span",{className:"ps-rich-session-ctx",style:{color:fe(e,s.ctx.color)||void 0}},s.ctx.text):null),o.length>0?c.createElement("div",{className:"ps-rich-session-detail"},c.createElement(ye,{runs:o,theme:e})):null)}function da({row:t,theme:e,structured:s=!1}){if(!(s&&Array.isArray(t.titleRuns)))return Array.isArray(t.runs)?c.createElement(ye,{runs:t.runs,theme:e}):t.text;const i=Array.isArray(t.ctxRuns)?t.ctxRuns:[],o=Array.isArray(t.detailRuns)?t.detailRuns:Array.isArray(t.selectedMetaRuns)?t.selectedMetaRuns:[],r=i.length>0,a=t.active&&o.length>0;return c.createElement(c.Fragment,null,c.createElement("div",{className:"ps-session-row-line"},c.createElement("div",{className:"ps-session-row-title"},c.createElement(ye,{runs:t.titleRuns,theme:e})),r?c.createElement("div",{className:"ps-session-row-ctx"},c.createElement(ye,{runs:i,theme:e})):null),a?c.createElement("div",{className:"ps-session-row-detail"},c.createElement(ye,{runs:o,theme:e})):null)}function Un({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1}){const i=z(t,R=>R.ui.themeId),o=ze(i),r=c.useRef(new Map),a=z(t,R=>({activeSessionId:R.sessions.activeSessionId,sessionsById:R.sessions.byId,sessionsFlat:R.sessions.flat,filterQuery:R.sessions.filterQuery||"",ownerFilter:R.sessions.ownerFilter,pinnedIds:R.sessions.pinnedIds,selectedIds:R.sessions.selectedIds,selectMode:R.sessions.selectMode,auth:R.auth,connectionMode:R.connection?.mode||"local",modalOpen:!!R.ui.modal,focused:R.ui.focusRegion==="sessions",rich:R.ui.chatViewMode==="rich"}),ke),l=c.useMemo(()=>wt({sessions:{activeSessionId:a.activeSessionId,byId:a.sessionsById,flat:a.sessionsFlat,filterQuery:a.filterQuery,ownerFilter:a.ownerFilter,pinnedIds:a.pinnedIds,selectedIds:a.selectedIds,selectMode:a.selectMode},auth:a.auth,connection:{mode:a.connectionMode}}),[a.activeSessionId,a.auth,a.connectionMode,a.filterQuery,a.ownerFilter,a.pinnedIds,a.selectedIds,a.selectMode,a.sessionsById,a.sessionsFlat]),u=a.activeSessionId&&a.sessionsById[a.activeSessionId]||null,[f,d]=c.useState(!1),[p,h]=c.useState(null),m=c.useRef(!1),g=["modelPicker","reasoningEffortPicker","contextTierPicker"],S=z(t,R=>g.includes(R.ui.modal?.type));c.useEffect(()=>{!S&&m.current&&(m.current=!1,d(!0))},[S]);const y=()=>{m.current=!0,d(!1),t.openSwitchModelPicker(()=>{m.current=!1}).then(()=>{!g.includes(t.getState().ui.modal?.type)&&m.current&&(m.current=!1,d(!0))}).catch(R=>{m.current=!1,d(!0),t.dispatch({type:"ui/status",text:R?.message||String(R)||"Failed to switch model"})})},w=a.auth?.principal||null,I=a.auth?.authorization?.role,x=I==="admin"||I==="anonymous",C=!!(u?.owner&&w&&String(u.owner.provider)===String(w.provider)&&String(u.owner.subject)===String(w.subject)),v=!!(u&&!u.isSystem&&!u.isGroup&&(x||C)),k=Array.isArray(a.selectedIds)?a.selectedIds.length:0,P=k>1,O=!!(u&&!u.isSystem&&(u.isGroup||!u.parentSessionId&&!u.groupId)),M=!!(u&&Array.isArray(a.pinnedIds)&&a.pinnedIds.includes(u.sessionId)),$=!!(u?.isGroup&&Number(u.memberCount||0)===0),F=P?Array.isArray(a.selectedIds)&&a.selectedIds.some(R=>{const K=a.sessionsById[R];return K&&!K.isSystem&&!K.isGroup}):u?.isGroup?!0:!!u,U=k>0?a.selectedIds.filter(R=>{const K=a.sessionsById[R];return K&&!K.isSystem&&!K.isGroup&&!K.parentSessionId}):u&&!u.isSystem&&!u.isGroup&&!u.parentSessionId?[u.sessionId]:[],V=U.length>0,q=`ps-session-pane${a.rich?" is-rich":""}${s?` ${s}`:""}`,ee=c.useCallback((R,K)=>{R&&(K?r.current.set(R,K):r.current.delete(R))},[]);c.useEffect(()=>{if(a.modalOpen||!a.focused||!a.activeSessionId)return;const R=r.current.get(a.activeSessionId);R&&(document.activeElement!==R&&R.focus({preventScroll:!0}),R.scrollIntoView({block:"nearest"}))},[a.activeSessionId,a.focused,a.modalOpen]);const we=c.createElement(c.Fragment,null,P?c.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",fontSize:"12px",opacity:.85},title:"Multiple sessions selected. Move to group or cancel selected sessions; click Clear to exit."},`${k} selected`):null,P?c.createElement(oe,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(E.CLEAR_SESSION_SELECTION).catch(()=>{})}):c.createElement(oe,{className:"ps-mini-button",icon:"📌",onClick:()=>t.handleCommand(E.PIN_SESSION).catch(()=>{}),disabled:!O,active:M,label:O?M?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"}),c.createElement(oe,{className:"ps-mini-button",icon:U.length>1?`⊞${U.length}`:"⊞",onClick:()=>t.handleCommand(E.OPEN_MOVE_TO_GROUP).catch(()=>{}),disabled:!V,label:V?U.length>1?`Move ${U.length} selected sessions to a group`:"Move this session to a group":"Select a top-level non-system session to move to a group"}),c.createElement(oe,{className:"ps-mini-button",icon:c.createElement(eh),onClick:()=>d(!0),disabled:!v||P,label:P?"Disabled while multiple sessions are selected":"Manage session — rename, switch model, and sharing"}),c.createElement(oe,{className:"ps-mini-button",icon:c.createElement(th),onClick:()=>{const R=u?.sessionId;if(!R)return;const K=sp(R);K&&(po(K),h({url:K,warn:!1}),np(t,R).then(b=>{h(T=>T&&T.url===K?{...T,warn:b}:T)}).catch(()=>{}))},disabled:!u||u.isGroup||P,label:"Copy link — copy a direct link to this session"}),c.createElement(oe,{className:"ps-mini-button",icon:u?.isSystem?"↻":u?.isGroup?"⊗":c.createElement(sh),onClick:()=>t.handleCommand(u?.isGroup?E.DELETE_SESSION:E.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!F,label:P?`Terminate ${k} selected sessions (Mark Completed, Cancel, or Delete)`:u?.isGroup?$?"Delete this empty group":"This group cannot be deleted yet":u?.isSystem?"Restart this system session (complete, terminate, or hard delete)":"Lifecycle — regenerate context, mark completed, cancel, or delete"}),e);return c.createElement(c.Fragment,null,c.createElement(tt,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:a.focused,theme:o,actions:we,className:q},c.createElement("div",{className:"ps-action-list ps-session-list"},l.length===0?c.createElement("div",{className:"ps-empty-state"},a.filterQuery?`No sessions matched "@@${a.filterQuery}".`:"No sessions yet."):l.map(R=>c.createElement("button",{key:R.sessionId,type:"button",ref:K=>ee(R.sessionId,K),className:`ps-list-button ps-session-list-button${R.active?" is-selected":""}${R.selected?" is-multiselected":""}${R.pinned?" is-pinned":""}`,tabIndex:R.active?0:-1,"aria-selected":R.active?"true":"false",onClick:K=>{if(K.metaKey||K.ctrlKey){K.preventDefault(),a.selectMode||t.dispatch({type:"sessions/selectMode",enabled:!0}),t.dispatch({type:"sessions/selectToggle",sessionId:R.sessionId}),t.setFocus("sessions");return}if(K.shiftKey&&a.activeSessionId){K.preventDefault();const T=l.map(B=>B.sessionId),_=T.indexOf(a.activeSessionId),L=T.indexOf(R.sessionId);if(_>=0&&L>=0){const[B,D]=_<=L?[_,L]:[L,_],W=T.slice(B,D+1),ae=Array.from(new Set([...a.selectedIds||[],...W]));t.setSessionSelection(ae),t.setFocus("sessions");return}}if(R.hasChildren&&R.active){t.dispatch({type:R.collapsed?"sessions/expand":"sessions/collapse",sessionId:R.sessionId}),t.setFocus("sessions");return}a.selectMode&&t.dispatch({type:"sessions/selectClear"}),t.setFocus("sessions"),R.active||t.loadSession(R.sessionId).catch(()=>{})}},c.createElement("div",{className:a.rich?"ps-session-row-content is-rich":"ps-line ps-session-row-content",style:{paddingInlineStart:a.rich?`${Math.max(0,R.depth)*14}px`:`${Math.max(0,R.depth)*4}px`}},a.rich?c.createElement(Jp,{row:R,theme:o}):c.createElement(da,{row:R,theme:o,structured:n})))))),f&&u&&!u.isGroup?c.createElement(ih,{controller:t,sessionId:u.sessionId,initialTitle:u.title||"",currentModel:u.model||"",currentReasoningEffort:u.reasoningEffort||"",principal:a.auth?.principal||null,onClose:()=>d(!1),onSwitchModel:y,onChanged:()=>{}}):null,p?c.createElement(Zp,{url:p.url,warn:p.warn,onCopyAgain:()=>{po(p.url),t.dispatch({type:"ui/status",text:ep})},onClose:()=>h(null)}):null)}function Zp({url:t,warn:e,onCopyAgain:s,onClose:n}){const i=c.useRef(null);c.useEffect(()=>{const r=i.current;r&&(r.focus(),r.select())},[]);const o=r=>r.stopPropagation();return c.createElement("div",{className:"ps-share-overlay",onClick:n},c.createElement("div",{className:"ps-link-modal",onClick:o},c.createElement("div",{className:"ps-share-modal-head"},c.createElement("span",null,"Link copied"),c.createElement("button",{className:"ps-modal-close",onClick:n},"✕")),c.createElement("div",{className:"ps-share-section-sub"},"Copied to your clipboard — anyone with access can open the session from this link."),c.createElement("div",{className:"ps-link-row"},c.createElement("input",{ref:i,className:"ps-link-input",readOnly:!0,value:t,onFocus:()=>i.current?.select()}),c.createElement("button",{className:"ps-mini-button",onClick:s},"Copy")),e?c.createElement("div",{className:"ps-link-warn"},tp):null))}const To={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function eh(){return c.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},c.createElement("line",{x1:"4",y1:"6",x2:"20",y2:"6"}),c.createElement("line",{x1:"4",y1:"12",x2:"20",y2:"12"}),c.createElement("line",{x1:"4",y1:"18",x2:"20",y2:"18"}),c.createElement("circle",{cx:"9",cy:"6",r:"2",fill:"currentColor"}),c.createElement("circle",{cx:"15",cy:"12",r:"2",fill:"currentColor"}),c.createElement("circle",{cx:"8",cy:"18",r:"2",fill:"currentColor"}))}function th(){return c.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},c.createElement("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),c.createElement("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}))}function sh(){return c.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},c.createElement("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),c.createElement("path",{d:"M3 3v5h5"}),c.createElement("path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"}),c.createElement("path",{d:"M21 21v-5h-5"}))}function nh(t,e,s){const[n,i]=c.useState({access:null,loading:!1}),o=c.useCallback(()=>{if(!e||s||typeof t.transport.getSessionAccess!="function"){i({access:null,loading:!1});return}let r=!1;return i(a=>({...a,loading:!0})),t.transport.getSessionAccess(e).then(a=>{r||i({access:a,loading:!1})}).catch(()=>{r||i({access:null,loading:!1})}),()=>{r=!0}},[t,e,s]);return c.useEffect(()=>o(),[o]),{access:n.access,loading:n.loading,reload:o}}function ih({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:i,principal:o,onClose:r,onSwitchModel:a,onChanged:l}){const[u,f]=c.useState("general"),[d,p]=c.useState(null),[h,m]=c.useState(s||""),[g,S]=c.useState([]),[y,w]=c.useState([]),[I,x]=c.useState("private"),[C,v]=c.useState(""),[k,P]=c.useState("write"),[O,M]=c.useState([]),[$,F]=c.useState(!1),[Y,U]=c.useState(null);c.useEffect(()=>{let N=!1;return t.transport.getSessionAccess(e).then(Q=>{!N&&Q&&(p(Q),x(Q.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(Q=>{N||M(Array.isArray(Q)?Q:[])}).catch(()=>{}),()=>{N=!0}},[t,e]);const V=c.useCallback(()=>{t.transport.listSessionShares(e).then(N=>{const Q=Array.isArray(N)?N:[];S(Q),w(Q)}).catch(()=>{S([]),w([])})},[t,e]);c.useEffect(()=>{V()},[V]);const q=async N=>{F(!0),U(null);try{await N(),l?.()}catch(Q){U(Q?.message||String(Q))}finally{F(!1)}},ee=()=>q(async()=>{await t.transport.renameSession(e,h.trim())}),we=N=>{const Q=N.trim().toLowerCase();if(!Q)return null;const Ne=O.find(he=>he.displayName&&he.displayName.toLowerCase()===Q||he.email&&he.email.toLowerCase()===Q||he.subject&&he.subject.toLowerCase()===Q);return Ne||{provider:o?.provider||"dev",subject:N.trim(),email:null,displayName:null}},R=N=>`${N.provider}${N.subject}`,K=N=>{const Q=R(N);w(Ne=>[...Ne.filter(he=>R(he)!==Q),{provider:N.provider,subject:N.subject,email:N.email??null,displayName:N.displayName??null,access:k}]),v("")},b=()=>{const N=we(C);N&&K(N)},T=N=>{const Q=R(N);w(Ne=>Ne.filter(he=>R(he)!==Q))},_=new Set(y.map(R)),L=d?.owner?`${d.owner.provider}${d.owner.subject}`:null,B=C.trim().toLowerCase(),D=B?O.filter(N=>{const Q=R(N);return Q===L||_.has(Q)?!1:N.displayName&&N.displayName.toLowerCase().includes(B)||N.email&&N.email.toLowerCase().includes(B)||N.subject&&N.subject.toLowerCase().includes(B)}).slice(0,25):[],W=!!d?.canManage,ae=d?.visibility||"private",ie=new Set(y.map(N=>`${R(N)}:${N.access}`)),nt=new Set(g.map(N=>`${R(N)}:${N.access}`)),Wn=ie.size!==nt.size||[...ie].some(N=>!nt.has(N)),Ht=W&&(I!==ae||Wn),pa=()=>q(async()=>{I!==ae&&await t.transport.setSessionVisibility(e,I);const N=new Map(g.map(Le=>[R(Le),Le])),Q=new Map(y.map(Le=>[R(Le),Le]));for(const[Le,$e]of Q){const Vn=N.get(Le);(!Vn||Vn.access!==$e.access)&&await t.transport.grantSessionShare(e,{provider:$e.provider,subject:$e.subject,email:$e.email??null,displayName:$e.displayName??null},$e.access)}for(const[Le,$e]of N)Q.has(Le)||await t.transport.revokeSessionShare(e,{provider:$e.provider,subject:$e.subject});const Ne=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(Ne)&&(S(Ne),w(Ne));const he=await t.transport.getSessionAccess(e).catch(()=>null);he&&(p(he),x(he.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),ha=a||(()=>{r(),t.openSwitchModelPicker().catch(N=>{t.dispatch({type:"ui/status",text:N?.message||String(N)||"Failed to switch model"})})}),ma=n?i?`${n}:${i}`:n:"—",Kn=[{id:"general",label:"General"},...W?[{id:"access",label:"Access"}]:[]],Gt=Kn.some(N=>N.id===u)?u:"general",ga=N=>N.stopPropagation();return c.createElement("div",{className:"ps-share-overlay",onClick:r},c.createElement("div",{className:"ps-share-modal",onClick:ga},c.createElement("div",{className:"ps-share-modal-head"},c.createElement("span",null,"Manage session"),c.createElement("button",{className:"ps-modal-close",onClick:r},"✕")),c.createElement("div",{className:"ps-manage-tabs",role:"tablist"},Kn.map(N=>c.createElement("button",{key:N.id,type:"button",role:"tab","aria-selected":Gt===N.id?"true":"false",className:`ps-manage-tab${Gt===N.id?" is-active":""}`,onClick:()=>f(N.id)},N.label))),Gt==="general"?c.createElement(c.Fragment,null,c.createElement("div",{className:"ps-share-section-label"},"Name"),c.createElement("div",{className:"ps-share-add-row"},c.createElement("input",{className:"ps-share-add-input",placeholder:"Session title",value:h,disabled:$,onChange:N=>m(N.target.value),onKeyDown:N=>{N.key==="Enter"&&ee()}}),c.createElement("button",{className:"ps-mini-button",disabled:$||!h.trim(),onClick:ee},"Save")),c.createElement("div",{className:"ps-share-section-label"},"Model"),c.createElement("div",{className:"ps-share-section-sub"},"The model this session uses on its next turn."),c.createElement("div",{className:"ps-share-add-row"},c.createElement("span",{className:"ps-manage-model-current"},ma),c.createElement("button",{className:"ps-mini-button",disabled:$,onClick:ha},"Switch model…"))):null,Gt==="access"&&W?c.createElement(c.Fragment,null,c.createElement("div",{className:"ps-share-section-label"},"General access"),c.createElement("div",{className:"ps-share-section-sub"},"The baseline level for everyone signed in to this workspace."),["private","shared_read","shared_write"].map(N=>c.createElement("label",{key:N,className:`ps-share-radio${I===N?" is-active":""}`},c.createElement("input",{type:"radio",name:"visibility",checked:I===N,disabled:$,onChange:()=>x(N)}),c.createElement("span",{className:"ps-share-radio-glyph"},To[N].glyph),c.createElement("span",null,To[N].label),c.createElement("span",{className:"ps-share-radio-hint"},N==="private"?"only you and admins":N==="shared_read"?"everyone here can view":"everyone here can view and send"))),c.createElement("div",{className:"ps-share-section-label"},"Special access"),c.createElement("div",{className:"ps-share-section-sub"},"Give specific people more than the general level. A person's grant wins over general access."),y.length===0?c.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):y.map(N=>c.createElement("div",{key:`${N.provider}/${N.subject}`,className:"ps-share-grant-row"},c.createElement("span",{className:"ps-share-grant-name"},N.displayName||N.subject),c.createElement("span",{className:"ps-share-grant-access"},`can ${N.access}`),c.createElement("button",{className:"ps-mini-button",disabled:$,onClick:()=>T(N)},"Remove"))),c.createElement("div",{className:"ps-share-add-wrap"},c.createElement("div",{className:"ps-share-add-row"},c.createElement("input",{className:"ps-share-add-input",placeholder:"Name, email, or id",value:C,disabled:$,autoComplete:"off",onChange:N=>v(N.target.value),onKeyDown:N=>{N.key==="Enter"&&b()}}),c.createElement("select",{className:"ps-share-add-select",value:k,disabled:$,onChange:N=>P(N.target.value)},c.createElement("option",{value:"read"},"can read"),c.createElement("option",{value:"write"},"can write")),c.createElement("button",{className:"ps-mini-button",disabled:$||!C.trim(),onClick:b},"Add")),D.length>0?c.createElement("div",{className:"ps-share-suggestions"},D.map(N=>c.createElement("button",{key:`${N.provider}/${N.subject}`,type:"button",className:"ps-share-suggestion",disabled:$,onClick:()=>K(N)},c.createElement("span",{className:"ps-share-suggestion-name"},N.displayName||N.subject),N.email?c.createElement("span",{className:"ps-share-suggestion-email"},N.email):null))):null),c.createElement("div",{className:"ps-share-foot-hint"},"Sharing applies to this session and its sub-agents. Suggestions are people who have signed in before — you can also grant by email to someone who hasn't; it takes effect when they first sign in."),c.createElement("div",{className:"ps-manage-apply-bar"},c.createElement("span",{className:"ps-share-section-sub"},Ht?"Unsaved access changes.":"No changes to apply."),c.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:$||!Ht,onClick:pa},"Apply"))):null,Y?c.createElement("div",{className:"ps-share-error"},Y):null))}function jn({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const i=z(t,M=>M.ui.themeId),o=ze(i),r=z(t,M=>{const $=M.sessions.activeSessionId,F=bs(M),Y=s||e?F.totalWidth:F.leftWidth,U=Math.max(20,Y-4);return{activeSessionId:$,activeHistory:$&&M.history.bySessionId.get($)||null,activeOutbox:$&&M.outbox?.bySessionId?.[$]?M.outbox.bySessionId[$]:[],branding:M.branding,connection:M.connection,sessionsById:M.sessions.byId,sessionsFlat:M.sessions.flat,inspectorTab:M.ui.inspectorTab,chatViewMode:M.ui.chatViewMode||"transcript",activeSessionIsGroup:!!($&&M.sessions.byId[$]?.isGroup),activeSessionStatus:$?String(M.sessions.byId[$]?.status||"").toLowerCase():"",focused:M.ui.focusRegion==="chat",scroll:M.ui.scroll.chat,authPrincipal:M.auth?.principal||null,contentWidth:U}},ke),a=c.useMemo(()=>({branding:r.branding,connection:r.connection,auth:{principal:r.authPrincipal},sessions:{activeSessionId:r.activeSessionId,byId:r.sessionsById,flat:r.sessionsFlat},history:{bySessionId:r.activeSessionId&&r.activeHistory?new Map([[r.activeSessionId,r.activeHistory]]):new Map},outbox:{bySessionId:r.activeSessionId?{[r.activeSessionId]:r.activeOutbox}:{}},ui:{inspectorTab:r.inspectorTab,chatViewMode:r.chatViewMode}}),[r.activeHistory,r.activeSessionId,r.activeOutbox,r.authPrincipal,r.branding,r.connection,r.chatViewMode,r.inspectorTab,r.sessionsById,r.sessionsFlat]),l=c.useMemo(()=>Tr(a,{width:r.contentWidth}),[a,r.contentWidth]),u=Po(!!l.animateTitleRight),f=c.useMemo(()=>_o(l.titleRight,l.animateTitleRight?u:""),[u,l.animateTitleRight,l.titleRight]),d=r.chatViewMode==="rich"&&!r.activeSessionIsGroup,p=c.useMemo(()=>d?jc(a,r.contentWidth,{tableMode:"sentinel"}):null,[d,a,r.contentWidth]),h=c.useMemo(()=>p?p.map((M,$)=>({text:M.kind==="message"?`m:${M.id??$}:${(M.text||"").length}:${M.pendingPhase||""}`:`l:${$}:${(M.lines||[]).length}`})):Mn(a,r.contentWidth,{tableMode:"sentinel"}),[p,a,r.contentWidth]),m=No(r.activeSessionStatus==="running"),S=c.useMemo(()=>kn(a,{spinnerFrame:m,maxWidth:r.contentWidth}),[a,m,r.contentWidth]),y=c.useMemo(()=>Nn(a,r.contentWidth,{tableMode:"sentinel"}),[a,r.contentWidth]),w=c.useMemo(()=>S.length>0?[...y,...S]:y,[y,S]),{access:I}=nh(t,r.activeSessionId,r.activeSessionIsGroup),x=z(t,fc,ke),C=n&&!r.activeSessionIsGroup&&r.chatViewMode!=="summary",v=!!r.sessionsById?.[r.activeSessionId]?.serviceKind,k=v||!!I&&I.canWrite===!1,P=C?c.createElement("div",{className:"ps-chat-composer"},k?c.createElement("div",{className:"ps-composer-readonly"},v?"⚗ Service session — runtime machinery. Its transcript is a read-only trace; it does not accept messages.":`You have view access to this session. Ask ${I.owner?.displayName||I.owner?.email||"the owner"} for write access to participate.`):c.createElement(ch,{controller:t,mobile:e,active:!0})):null,O=!!(r.activeSessionId&&r.sessionsById[r.activeSessionId]);return x&&!O?c.createElement(tt,{title:l.title,color:l.color,focused:r.focused,theme:o,className:"ps-chat-panel"},c.createElement("div",{className:"ps-empty-state ps-nav-error-state"},c.createElement("div",{className:"ps-nav-error-message"},x.message),x.retryable?c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(x.sessionId)},"Retry"):null)):c.createElement(ws,{controller:t,title:(()=>{const M=e?go(l.title,28):l.title;return d?Yp(M):M})(),titleRight:e&&f?go(f,18):f,actions:null,color:l.color,focused:r.focused,lines:h,bottomStickyLines:w,scrollOffset:r.scroll,scrollMode:"bottom",paneKey:"chat",className:d?"is-wrapped is-rich":"is-wrapped",panelClassName:d?"ps-chat-panel is-rich":"ps-chat-panel",bottomContent:P,structuredBlocks:!0,renderBody:p?(M,$)=>c.createElement(qp,{blocks:p,theme:$,controller:t}):null})}function oh({controller:t}){return c.createElement("div",{className:"ps-mobile-workspace"},c.createElement(Un,{controller:t,panelClassName:"ps-mobile-session-pane"}),c.createElement("div",{className:"ps-mobile-chat-pane"},c.createElement(jn,{controller:t,mobile:!0,fullWidth:!0})))}function fa({activeTab:t,controller:e}){const s=c.useMemo(()=>Hn(e),[e]);return c.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>c.createElement(oe,{key:n,icon:qf[n]||"•",label:Vf[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function rh({controller:t,focused:e,mobile:s=!1}){const n=z(t,y=>y.ui.themeId),i=ze(n),o=c.useRef(null),r=z(t,y=>{const w=y.sessions.activeSessionId,I=bs(y),x=s||y.files.fullscreen?y.ui.layout?.viewportWidth??120:I.rightWidth;return{activeSessionId:w,sessionsById:y.sessions.byId,sessionsFlat:y.sessions.flat,filesBySessionId:y.files.bySessionId,filesFilter:y.files.filter,selectedArtifactId:y.files.selectedArtifactId,focused:e,previewScroll:y.ui.scroll.filePreview,fullscreen:!!y.files.fullscreen,contentWidth:Math.max(20,x-4),canBrowserUpload:Yf(t),canPathUpload:Qf(t),canDeleteArtifacts:Jf(t),canOpenLocally:Zf(t)}},ke),a=c.useMemo(()=>({sessions:{activeSessionId:r.activeSessionId,byId:r.sessionsById,flat:r.sessionsFlat},files:{bySessionId:r.filesBySessionId,selectedArtifactId:r.selectedArtifactId,filter:r.filesFilter,fullscreen:r.fullscreen},ui:{scroll:{filePreview:r.previewScroll}}}),[r.activeSessionId,r.filesBySessionId,r.filesFilter,r.fullscreen,r.previewScroll,r.selectedArtifactId,r.sessionsById,r.sessionsFlat]),l=c.useMemo(()=>On(a,{listWidth:Math.max(18,r.contentWidth-4),previewWidth:Math.max(18,r.contentWidth-4),showHints:!1}),[a,r.contentWidth]),u=c.useMemo(()=>$t(a),[a]),f=u.length>0,d=c.useCallback(y=>{const w=Array.isArray(y)?y.filter(Boolean):[];w.length!==0&&t.uploadArtifactFiles(w).catch(()=>{})},[t]),p=c.useCallback(()=>{if(r.canBrowserUpload&&o.current){o.current.click();return}r.canPathUpload&&t.handleCommand(E.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,r.canBrowserUpload,r.canPathUpload]),h=c.createElement(c.Fragment,null,c.createElement("input",{ref:o,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:y=>{d(Array.from(y.currentTarget.files||[])),y.currentTarget.value=""}}),c.createElement(oe,{icon:"↥",label:"Upload",onClick:p,disabled:!r.canBrowserUpload&&!r.canPathUpload}),c.createElement(oe,{icon:"↧",label:"Download",onClick:()=>t.handleCommand(E.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!f}),r.canDeleteArtifacts?c.createElement(oe,{icon:"✕",label:"Delete",onClick:()=>t.handleCommand(E.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,r.canOpenLocally?c.createElement(oe,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(E.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,c.createElement(oe,{icon:"▾",label:"Filter",onClick:()=>t.handleCommand(E.OPEN_FILES_FILTER).catch(()=>{})}),c.createElement(oe,{icon:r.fullscreen?"⇱":"⛶",label:r.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(E.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),m=u.length===0?me(l.listBodyLines||[]).map((y,w)=>c.createElement(ge,{key:`empty:${w}`,line:y,theme:i})):u.map((y,w)=>c.createElement("button",{key:y.id,type:"button",className:`ps-list-button${w===l.selectedIndex?" is-selected":""}`,onClick:()=>{t.setFocus("inspector"),t.selectFileBrowserItem(y).catch(()=>{})}},c.createElement(ge,{line:me([l.listBodyLines?.[w]])[0],theme:i}))),g=l.previewRenderMode==="markdown"&&!l.previewLoading&&!l.previewError?c.createElement(Fp,{controller:t,title:l.previewTitle,color:"cyan",focused:!1,scrollOffset:r.previewScroll,paneKey:"filePreview",theme:i,content:l.previewContent||""}):l.previewIsBinary&&!l.previewLoading&&!l.previewError?c.createElement(Dp,{title:l.previewTitle,color:"cyan",focused:!1,theme:i,filename:l.selectedFilename,contentType:l.previewContentType,sizeBytes:l.previewSizeBytes,source:l.previewSource,uploadedAt:l.previewUploadedAt,controller:t,sessionId:l.selectedSessionId}):c.createElement(ws,{controller:t,title:l.previewTitle,color:"cyan",focused:!1,lines:l.previewLines,scrollOffset:r.previewScroll,scrollMode:"top",paneKey:"filePreview",className:"is-preview is-wrapped"}),S=r;return c.createElement(tt,{title:S.fullscreen?l.fullscreenTitle:s&&l.panelTitleMobile?l.panelTitleMobile:l.panelTitle,color:"magenta",focused:S.focused,actions:h,theme:i},c.createElement(fa,{activeTab:"files",controller:t}),S.fullscreen?g:c.createElement("div",{className:"ps-files-grid"},c.createElement(tt,{title:l.listTitle,color:"cyan",theme:i},c.createElement("div",{className:"ps-action-list"},m)),g))}function Nt({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const i=z(t,d=>{const p=bs(d),h=d.ui.inspectorTab,m=e?d.ui.layout?.viewportWidth??120:p.rightWidth;return{inspectorTab:h,statsViewMode:d.ui.statsViewMode,activeSessionId:d.sessions.activeSessionId,sessionsById:d.sessions.byId,sessionsFlat:d.sessions.flat,historyBySessionId:d.history.bySessionId,sessionStats:d.sessionStats,fleetStats:d.fleetStats,connection:d.connection,orchestrationBySessionId:d.orchestration.bySessionId,executionHistoryBySessionId:d.executionHistory?.bySessionId||{},executionHistoryFormat:d.executionHistory?.format||"pretty",logs:d.logs,files:d.files,focused:d.ui.focusRegion==="inspector",scroll:d.ui.scroll.inspector,followBottom:d.ui.followBottom?.inspector!==!1,logsTailing:d.logs.tailing,filesFullscreen:!!d.files.fullscreen,contentWidth:up(m,h)}},ke),o=c.useMemo(()=>({sessions:{activeSessionId:i.activeSessionId,byId:i.sessionsById,flat:i.sessionsFlat},history:{bySessionId:i.historyBySessionId},sessionStats:i.sessionStats,fleetStats:i.fleetStats,connection:i.connection,ui:{inspectorTab:i.inspectorTab,statsViewMode:i.statsViewMode,scroll:{inspector:i.scroll}},logs:i.logs,files:i.files,orchestration:{bySessionId:i.orchestrationBySessionId},executionHistory:{bySessionId:i.executionHistoryBySessionId,format:i.executionHistoryFormat}}),[i.activeSessionId,i.connection,i.executionHistoryBySessionId,i.executionHistoryFormat,i.fleetStats,i.files,i.historyBySessionId,i.inspectorTab,i.sessionStats,i.statsViewMode,i.logs,i.orchestrationBySessionId,i.scroll,i.sessionsById,i.sessionsFlat]),r=c.useMemo(()=>Ye(o,{width:i.contentWidth,allowWideColumns:e}),[e,o,i.contentWidth]),a=c.useMemo(()=>{const d=i.activeSessionId&&i.historyBySessionId?.get(i.activeSessionId)||null,p=new Map;for(const h of d?.events||[]){if(h?.eventType!=="session.turn_completed")continue;const m=Number(h?.data?.turnIndex??h?.data?.iteration);Number.isFinite(m)&&p.set(m,h)}return p},[i.activeSessionId,i.historyBySessionId]),l=c.useCallback((d,p)=>c.createElement(Qp,{lines:d,theme:p,completionByTurn:a}),[a]);if(i.inspectorTab==="files"&&!r.disabled)return c.createElement(rh,{controller:t,focused:i.focused,mobile:e});const u=[];if(i.inspectorTab==="logs")u.push(c.createElement(oe,{key:"tail",icon:i.logsTailing?"■":"⇣",label:i.logsTailing?"Stop tailing":"Tail (follow)",active:i.logsTailing,onClick:()=>t.handleCommand(E.TOGGLE_LOG_TAIL).catch(()=>{})})),u.push(c.createElement(oe,{key:"filter",icon:"▾",label:"Filter",onClick:()=>t.handleCommand(E.OPEN_LOG_FILTER).catch(()=>{})}));else if(i.inspectorTab==="history")u.push(c.createElement(oe,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(E.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),u.push(c.createElement(oe,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(E.EXPORT_EXECUTION_HISTORY).catch(()=>{})}));else if(i.inspectorTab==="stats"){const d={session:"◉",fleet:"⬢",users:"⚇"};for(const p of["session","fleet","users"])u.push(c.createElement(oe,{key:`stats-view:${p}`,icon:d[p],label:`${p.replace(/^./u,h=>h.toUpperCase())} stats`,active:i.statsViewMode===p,onClick:()=>t.setStatsViewMode(p)}))}const f=n?u.concat(n):u;return c.createElement(ws,{controller:t,title:r.title,color:"magenta",focused:i.focused,actions:f,topContent:c.createElement(fa,{activeTab:r.activeTab,controller:t}),stickyLines:r.stickyLines||[],lines:r.lines,renderBody:r.activeTab==="sequence"?l:null,scrollOffset:i.scroll,scrollMode:r.activeTab==="sequence"||r.activeTab==="logs"&&i.followBottom?"bottom":"top",stickyBottom:r.activeTab==="logs",paneKey:"inspector",className:r.activeTab==="history"||r.activeTab==="logs"?"is-wrapped":"is-preserve",panelClassName:`ps-inspector-pane${r.activeTab==="sequence"?" has-preserved-sticky":""}${s?` ${s}`:""}`.trim()})}function un({controller:t,panelClassName:e="",extraActions:s=null}){const n=z(t,r=>{const a=r.sessions.activeSessionId,l=bs(r),u=Math.max(3,l.activityPaneHeight-2);return{activeSessionId:a,activeSession:a&&r.sessions.byId[a]||null,activeHistory:a&&r.history.bySessionId.get(a)||null,focused:r.ui.focusRegion==="activity",scroll:r.ui.scroll.activity,followBottom:r.ui.followBottom?.activity!==!1,maxLines:u}},ke),i=c.useMemo(()=>({sessions:{activeSessionId:n.activeSessionId,byId:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{}},history:{bySessionId:n.activeSessionId&&n.activeHistory?new Map([[n.activeSessionId,n.activeHistory]]):new Map}}),[n.activeHistory,n.activeSession,n.activeSessionId]),o=c.useMemo(()=>_n(i,n.maxLines),[i,n.maxLines]);return c.createElement(ws,{controller:t,title:o.title,color:"gray",focused:n.focused,actions:s,lines:o.lines,scrollOffset:n.scroll,scrollMode:n.followBottom?"bottom":"top",stickyBottom:!0,paneKey:"activity",className:"is-wrapped",panelClassName:`ps-activity-pane${e?` ${e}`:""}`})}const dn=[{id:"sessions",label:"Sessions",side:"left"},{id:"inspector",label:"Inspector",side:"right"},{id:"activity",label:"Activity",side:"right"}];function ah({controller:t,pane:e,onClose:s,mobile:n=!1}){if(!e)return null;let i=null;e==="sessions"?i=c.createElement(Un,{controller:t,panelClassName:"ps-chat-focus-pane",structuredRows:n,actions:c.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}):e==="inspector"?i=c.createElement(Nt,{controller:t,mobile:!1,panelClassName:"ps-chat-focus-pane",extraActions:c.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}):e==="activity"&&(i=c.createElement(un,{controller:t,panelClassName:"ps-chat-focus-pane",extraActions:c.createElement("button",{type:"button",className:"ps-mini-button",onClick:s},"Close")}));const o=dn.find(r=>r.id===e);return c.createElement("div",{className:`ps-chat-focus-overlay${o?.side==="left"?" is-left":" is-right"}`},i)}function lh({controller:t,openPane:e,onTogglePane:s,onExitFocus:n,mobile:i=!1}){const o=z(t,a=>a.ui.focusRegion),r=i?c.createElement("div",{className:"ps-chat-focus-rail"},c.createElement("button",{type:"button",className:"ps-mini-button ps-chat-focus-button",onClick:n},"Exit Focus"),c.createElement("button",{type:"button",className:`ps-mini-button ps-chat-focus-button${e==="sessions"?" is-active":""}`,onClick:()=>s("sessions")},"Sessions")):c.createElement("div",{className:"ps-chat-focus-rail"},dn.map(a=>c.createElement("button",{key:a.id,type:"button",className:`ps-mini-button ps-chat-focus-button${e===a.id?" is-active":""}`,"aria-pressed":e===a.id?"true":"false",onClick:()=>s(a.id)},a.label)),c.createElement("div",{className:"ps-chat-focus-status"},e?`Focused: ${dn.find(a=>a.id===e)?.label||e}`:`Focused: ${o==="prompt"?"Prompt":"Chat"}`));return c.createElement("div",{className:"ps-chat-focus-shell"},r,c.createElement("div",{className:"ps-chat-focus-body"},c.createElement(jn,{controller:t,mobile:i,fullWidth:!0}),c.createElement(ah,{controller:t,pane:e,onClose:()=>s(e),mobile:i})))}const Co=Object.freeze([]);function ko(t){const e=Number(t)||0;return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function ch({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const i=z(t,v=>{const k=v.sessions.activeSessionId,P=k&&v.sessions.byId[k]||null,O=k&&v.outbox?.bySessionId?.[k]?v.outbox.bySessionId[k]:[];return{value:v.ui.prompt,cursor:v.ui.promptCursor,focused:v.ui.focusRegion==="prompt",modalOpen:!!v.ui.modal,answerMode:!!P?.pendingQuestion?.question,canStopTurn:yr(P),hasOutbox:O.length>0,hasPendingOutbox:O.some(M=>M?.phase==="pending"),pendingCount:O.filter(M=>M?.phase==="pending").length,editingPending:v.ui.promptEdit?.sessionId===k,selectedOutboxPhase:v.ui.promptEdit?.sessionId===k&&v.ui.promptEdit?.phase||null,promptAttachments:v.ui.promptAttachments||Co}},ke),o=c.useRef(null),r=c.useRef(null),[a,l]=c.useState(!1),u=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",f=u?i.promptAttachments.filter(v=>v?.kind==="image"):Co,d=c.useRef(new Map);c.useEffect(()=>{const v=d.current,k=new Set(f.map(P=>P.file));for(const[P,O]of v)k.has(P)||(URL.revokeObjectURL(O),v.delete(P));for(const P of f)if(P.file&&!v.has(P.file))try{v.set(P.file,URL.createObjectURL(P.file))}catch{}},[f]),c.useEffect(()=>()=>{for(const v of d.current.values())URL.revokeObjectURL(v);d.current.clear()},[]);const p=c.useCallback(v=>{if(!u)return 0;const k=Array.from(v||[]).filter(O=>O&&typeof O.type=="string"&&O.type.startsWith("image/"));return k.length===0?0:t.addPendingImageFiles(k)?.accepted||0},[t,u]);c.useEffect(()=>{const v=o.current;if(!(!s||i.modalOpen||!i.focused||!v)){if(document.activeElement!==v)try{v.focus({preventScroll:!0})}catch{v.focus()}v.setSelectionRange(i.cursor,i.cursor)}},[s,i.cursor,i.focused,i.modalOpen]);const h=c.useCallback(()=>{t.handleCommand(E.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[m,g]=c.useState(!1),S=c.useCallback(()=>{g(!0),t.handleCommand(E.STOP_TURN).catch(()=>{}).finally(()=>g(!1))},[t]),y=c.useCallback(()=>{if(t.getState().ui.promptEdit){typeof t.cancelSelectedOutboxPrompt=="function"?t.cancelSelectedOutboxPrompt().catch(()=>{}):t.cancelSelectedPendingPrompt();return}typeof t.cancelLatestQueuedOutbox=="function"&&t.cancelLatestQueuedOutbox().catch(()=>{})},[t]),w=i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"⇪":i.hasOutbox?"+":"❯",I=i.selectedOutboxPhase==="queued",x=i.selectedOutboxPhase==="cancelling",C=I||x;return c.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}${a?" is-drag-over":""}`,...u?{onDragOver:v=>{v.dataTransfer?.types?.includes?.("Files")&&(v.preventDefault(),l(!0))},onDragLeave:v=>{v.currentTarget.contains(v.relatedTarget)||l(!1)},onDrop:v=>{l(!1),v.dataTransfer?.files?.length&&(v.preventDefault(),p(v.dataTransfer.files))}}:{}},f.length>0?c.createElement("div",{className:"ps-prompt-attachments"},f.map((v,k)=>{const P=v.file?d.current.get(v.file):null;return c.createElement("div",{key:`attach:${k}:${v.filename}`,className:"ps-attach-chip",title:`${v.filename} · ${ko(v.sizeBytes)}`},P?c.createElement("img",{className:"ps-attach-thumb",src:P,alt:v.filename}):c.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),c.createElement("div",{className:"ps-attach-size"},ko(v.sizeBytes)),c.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${v.filename}`,"aria-label":`Remove attachment ${v.filename}`,onClick:()=>t.removePendingImageAttachment(k)},"✕"))})):null,(()=>{const v=i.answerMode?"answer":x?"cancelling":I?"queued":i.editingPending?"pending":"you";return c.createElement("label",{className:`ps-prompt-label${v==="you"?" is-default":""}`},v)})(),c.createElement("textarea",{ref:o,className:"ps-prompt-input",rows:e?2:Math.max(2,mt(i.value)),value:i.value,readOnly:C,placeholder:i.answerMode?"Type an answer and press Enter":i.editingPending?x?"Cancellation requested":I?"Queued message selected":"Edit the pending message, then send or cancel it":i.hasOutbox?"Type a message and press Enter to queue it behind the pending batch":"Type a message and press Enter",enterKeyHint:"send",onFocus:()=>t.setFocus("prompt"),onSelect:v=>t.setPromptCursor(v.currentTarget.selectionStart||0),onChange:v=>t.setPrompt(v.currentTarget.value,v.currentTarget.selectionStart||v.currentTarget.value.length),onPaste:u?v=>{const P=Array.from(v.clipboardData?.items||[]).filter(O=>O.kind==="file"&&O.type.startsWith("image/")).map(O=>O.getAsFile()).filter(Boolean);P.length>0&&p(P)>0&&v.preventDefault()}:void 0,onKeyDown:v=>{if(v.key==="Tab"&&!v.shiftKey&&t.acceptPromptReferenceAutocomplete()){v.preventDefault();return}if(v.key==="ArrowUp"&&!v.shiftKey&&!v.metaKey&&!v.altKey){v.preventDefault(),t.movePromptCursorVertical(-1);return}if(v.key==="ArrowDown"&&!v.shiftKey&&!v.metaKey&&!v.altKey){v.preventDefault(),t.movePromptCursorVertical(1);return}if(v.key==="Escape"&&i.editingPending){if(v.preventDefault(),C){t.exitPendingPromptEdit({restoreDraft:!0});return}y();return}v.key==="Enter"&&!v.shiftKey&&!v.metaKey&&!e&&(v.preventDefault(),h())}}),c.createElement("div",{className:"ps-prompt-actions"},u?c.createElement(c.Fragment,null,c.createElement("input",{ref:r,type:"file",accept:"image/*",multiple:!0,className:"ps-hidden-file-input","aria-hidden":!0,tabIndex:-1,onChange:v=>{p(v.currentTarget.files),v.currentTarget.value=""}}),c.createElement("button",{type:"button",className:"ps-mini-button ps-attach-button",title:"Attach images (or paste / drop them into the composer)","aria-label":"Attach images",onClick:()=>r.current?.click()},"📎")):null,i.editingPending&&!x?c.createElement("button",{type:"button",className:"ps-mini-button",title:I?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":I?"Delete selected queued prompt":"Cancel selected pending prompt",onClick:y},I?"Delete":"Cancel"):null,i.canStopTurn||m?c.createElement("button",{type:"button",className:`ps-stop-button${m?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:m,onClick:S},"■"):null,c.createElement("button",{type:"button",className:`ps-send-button${e?" is-inline":""}`,title:i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"Send all queued prompts":i.hasOutbox?"Queue prompt behind the pending batch":"Send prompt","aria-label":i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"Send queued prompts":i.hasOutbox?"Queue prompt":"Send prompt",onClick:h},w)))}const uh=1e3;function oe({icon:t,label:e,onClick:s,disabled:n=!1,active:i=!1,className:o="ps-toolbar-button"}){const[r,a]=c.useState(null),l=c.useRef(null),u=c.useRef(null),f=c.useRef(null),d=c.useRef(!1);c.useLayoutEffect(()=>{if(!r||!u.current||typeof window>"u")return;const k=u.current.offsetWidth/2,P=6,O=Math.max(k+P,Math.min(r.x,window.innerWidth-k-P));u.current.style.left=`${O}px`},[r]);const p=(k=!1)=>{const P=l.current;if(!P||typeof window>"u")return;const O=P.getBoundingClientRect(),M=k?O.top-44<0:O.bottom+44<window.innerHeight;a({x:O.left+O.width/2,y:M?O.bottom+6:O.top-6,placement:M?"below":"above"})},h=c.useRef(null),m=c.useRef(null),g=k=>{k.pointerType==="mouse"&&(clearTimeout(f.current),clearTimeout(h.current),f.current=setTimeout(p,uh))},S=k=>{k.pointerType==="mouse"&&(clearTimeout(f.current),clearTimeout(h.current),a(null))},y=k=>{k.pointerType!=="mouse"&&(d.current=!1,m.current={x:k.clientX,y:k.clientY},clearTimeout(f.current),clearTimeout(h.current),f.current=setTimeout(()=>{d.current=!0,p(!0)},450))},w=k=>{if(k.pointerType==="mouse"||!m.current)return;const P=k.clientX-m.current.x,O=k.clientY-m.current.y;P*P+O*O>100&&(m.current=null,clearTimeout(f.current),a(null))},I=k=>{k.pointerType!=="mouse"&&(m.current=null,clearTimeout(f.current),d.current?(clearTimeout(h.current),h.current=setTimeout(()=>a(null),3e3),setTimeout(()=>{d.current=!1},250)):a(null))};c.useEffect(()=>()=>{clearTimeout(f.current),clearTimeout(h.current)},[]);const x=k=>{if(d.current){d.current=!1,k.preventDefault?.();return}n||s?.(k)},C=k=>{k.preventDefault?.()},v=r&&typeof document<"u"&&document.body?qr.createPortal(c.createElement("span",{ref:u,className:`ps-icon-tooltip is-${r.placement}`,role:"tooltip",style:{left:`${r.x}px`,top:`${r.y}px`}},e),document.body):null;return c.createElement("button",{ref:l,type:"button",className:`${o} ps-icon-button${i?" is-active":""}`,onClick:x,disabled:n,"aria-label":e,onPointerEnter:g,onPointerLeave:S,onPointerDown:y,onPointerMove:w,onPointerUp:I,onPointerCancel:I,onContextMenu:C},c.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),v)}function dh({controller:t,mobile:e,chatFocusMode:s=!1,onToggleChatFocus:n=null,chatFocusDisabled:i=!1}){const o=z(t,h=>h.ui.chatViewMode==="rich"),[r,a]=c.useState(null);c.useEffect(()=>{typeof document>"u"||a(o&&!e?document.getElementById("ps-header-toolbar-slot"):null)},[o,e]);const l=z(t,h=>!!h.admin?.visible),u=z(t,h=>({mode:h.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(h.sessions.activeSessionId&&h.sessions.byId[h.sessions.activeSessionId]?.isGroup)}),ke),f=[{key:"new",icon:"+",label:"New session",onClick:()=>t.handleCommand(E.NEW_SESSION).catch(()=>{})},{key:"model",icon:"+⚙",label:"New session + choose model",onClick:()=>t.handleCommand(E.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:"▾",label:"Filter sessions",onClick:()=>t.handleCommand(E.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:"◑",label:"Theme",onClick:()=>t.handleCommand(E.OPEN_THEME_PICKER).catch(()=>{})},{key:"rich",icon:"Aa",label:u.activeSessionIsGroup?"Groups show group details":u.mode==="rich"?"Show terminal transcript":"Rich chat view (experimental)",onClick:()=>t.setChatViewMode(u.mode==="rich"?"transcript":"rich"),disabled:u.activeSessionIsGroup,active:u.mode==="rich"},{key:"summary",icon:u.mode==="summary"?"💬":"≣",label:u.activeSessionIsGroup?"Groups show group details":u.mode==="summary"?"Show chat transcript":"Show summary",onClick:()=>t.setChatViewMode(u.mode==="summary"?"transcript":"summary"),disabled:u.activeSessionIsGroup,active:u.mode==="summary"},...n?[{key:"focus",icon:s?"⇱":"⛶",label:s?"Exit focus mode":"Focus the chat pane",onClick:n,disabled:i,active:s}]:[],{key:"admin",icon:"⚙",label:l?"Close admin console":"Admin console",onClick:()=>t.handleCommand(l?E.CLOSE_ADMIN_CONSOLE:E.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:l}],d=h=>c.createElement(oe,{key:h.key,icon:h.icon,label:h.label,onClick:h.onClick,disabled:!!h.disabled,active:!!h.active});if(e)return c.createElement("div",{className:"ps-toolbar is-mobile"},c.createElement("div",{className:"ps-toolbar-row ps-toolbar-row-primary"},c.createElement("div",{className:"ps-toolbar-row-actions"},f.map(d))));const p=c.createElement("div",{className:"ps-toolbar"},c.createElement("div",{className:"ps-toolbar-actions"},f.map(d)));return r?qr.createPortal(p,r):p}function fh({controller:t,paneAdjust:e=0}){const s=c.useRef(null),[n,i]=c.useState(!1);return c.useEffect(()=>{if(!n)return;const o=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")},r=a=>{const l=s.current;if(!l)return;const u=Math.round((a.clientX-l.startX)/zr),f=u-l.appliedCells;f&&(t.adjustPaneSplit(f),l.appliedCells=u)};return window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o),()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),c.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector column. Double-click to reset.","aria-label":"Resize inspector column",onPointerDown:o=>{o.button===0&&(o.preventDefault(),s.current={startX:o.clientX,appliedCells:0},i(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{e&&t.adjustPaneSplit(-e)},onKeyDown:o=>{if(o.key==="ArrowLeft"){o.preventDefault(),t.handleCommand(E.GROW_RIGHT_PANE).catch(()=>{});return}o.key==="ArrowRight"&&(o.preventDefault(),t.handleCommand(E.GROW_LEFT_PANE).catch(()=>{}))}},c.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"})))}function ph({controller:t,portalSessionColumnAdjust:e=0}){const s=c.useRef(null),[n,i]=c.useState(!1);return c.useEffect(()=>{if(!n)return;const o=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")},r=a=>{const l=s.current;if(!l)return;const u=an(l.startAdjust+(a.clientX-l.startX),l.minAdjust,l.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:u})};return window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o),()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),c.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the sessions and chat columns. Double-click to reset.","aria-label":"Resize sessions and chat columns",onPointerDown:o=>{if(o.button!==0)return;o.preventDefault();const r=o.currentTarget.closest(".ps-workspace-main-grid"),a=ln(r?.getBoundingClientRect?.().width);s.current={startX:o.clientX,startAdjust:Number(e)||0,minAdjust:a.minAdjust,maxAdjust:a.maxAdjust},i(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>{t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:0})},onKeyDown:o=>{const r=o.currentTarget.closest(".ps-workspace-main-grid"),a=ln(r?.getBoundingClientRect?.().width),l=u=>{const f=an((Number(e)||0)+u,a.minAdjust,a.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:f})};if(o.key==="ArrowLeft"){o.preventDefault(),l(-24);return}o.key==="ArrowRight"&&(o.preventDefault(),l(24))}},c.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"})))}function hh({controller:t,activityPaneAdjust:e=0}){const s=c.useRef(null),[n,i]=c.useState(!1);return c.useEffect(()=>{if(!n)return;const o=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-y")},r=a=>{const l=s.current;if(!l)return;const u=Math.round((a.clientY-l.startY)/Yr),f=u-l.appliedCells;f&&(t.adjustActivityPaneSplit(-f),l.appliedCells=u)};return window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o),()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),document.body.classList.remove("is-resizing-pane-y")}},[t,n]),c.createElement("button",{type:"button",className:`ps-row-resizer${n?" is-dragging":""}`,title:"Drag to resize the activity pane. Double-click to reset.","aria-label":"Resize activity pane",onPointerDown:o=>{o.button===0&&(o.preventDefault(),s.current={startY:o.clientY,appliedCells:0},i(!0),document.body.classList.add("is-resizing-pane-y"))},onDoubleClick:()=>{e&&t.adjustActivityPaneSplit(-e)},onKeyDown:o=>{if(o.key==="ArrowUp"){o.preventDefault(),t.adjustActivityPaneSplit(1);return}o.key==="ArrowDown"&&(o.preventDefault(),t.adjustActivityPaneSplit(-1))}},c.createElement("span",{className:"ps-row-resizer-handle","aria-hidden":"true"},c.createElement("span",{className:"ps-row-resizer-dot"}),c.createElement("span",{className:"ps-row-resizer-dot"}),c.createElement("span",{className:"ps-row-resizer-dot"})))}function mh({activePane:t,setActivePane:e,controller:s}){const n=[{id:"workspace",label:"Main",focus:"chat"},{id:"inspector",label:"Inspector",focus:"inspector"},{id:"activity",label:"Activity",focus:"activity"}];return c.createElement("div",{className:"ps-mobile-nav"},n.map(i=>c.createElement("button",{key:i.id,type:"button",className:`ps-mobile-nav-button${t===i.id?" is-active":""}`,onClick:()=>{e(i.id),s.setFocus(i.focus)}},i.label)))}function gh({controller:t}){const e=z(t,p=>p.ui.themeId),s=ze(e),n=z(t,p=>({rawModal:p.ui.modal,themePicker:cd(p),modelPicker:Lu(p),reasoningEffortPicker:Fu(p),contextTierPicker:Bu(p),sessionAgentPicker:$u(p),sessionGroupPicker:Du(p),sessionGroupName:Gu(p),artifactPicker:Vu(p),logFilter:Wu(p),filesFilter:Ku(p),historyFormat:ld(p),renameSession:Hu(p),sessionOwnerFilter:ju(p),artifactUpload:Uu(p),confirm:ud(p),logsFilter:p.logs.filter,filesFilterState:p.files.filter,historyFormatState:p.executionHistory?.format||"pretty"}),ke),i=n.rawModal,o=c.useRef(null),r=c.useRef(null),a=c.useRef(null);if(c.useEffect(()=>{if(i?.type!=="renameSession"||!n.renameSession)return;const p=o.current;if(p){if(document.activeElement!==p)try{p.focus({preventScroll:!0})}catch{p.focus()}p.setSelectionRange(n.renameSession.cursorIndex,n.renameSession.cursorIndex)}},[i?.type,n.renameSession?.cursorIndex,n.renameSession?.value]),c.useEffect(()=>{if(i?.type!=="sessionGroupName"||!n.sessionGroupName)return;const p=r.current;if(p){if(document.activeElement!==p)try{p.focus({preventScroll:!0})}catch{p.focus()}p.setSelectionRange(n.sessionGroupName.cursorIndex,n.sessionGroupName.cursorIndex)}},[i?.type,n.sessionGroupName?.cursorIndex,n.sessionGroupName?.value]),c.useEffect(()=>{if(!i||!["themePicker","modelPicker","reasoningEffortPicker","contextTierPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(i.type))return;const p=a.current;if(!p)return;const h=p.querySelector(".ps-list-button.is-selected");h&&typeof h.scrollIntoView=="function"&&h.scrollIntoView({block:"nearest"})},[i?.type,i?.selectedIndex,n.themePicker?.selectedRowIndex,n.modelPicker?.selectedRowIndex,n.reasoningEffortPicker?.selectedRowIndex,n.contextTierPicker?.selectedRowIndex,n.sessionAgentPicker?.selectedRowIndex,n.sessionGroupPicker?.selectedRowIndex,n.artifactPicker?.selectedRowIndex,n.sessionOwnerFilter?.selectedRowIndex,n.logFilter?.selectedRowIndex,n.filesFilter?.selectedRowIndex,n.historyFormat?.selectedRowIndex]),!i)return null;const l=()=>t.handleCommand(E.CLOSE_MODAL).catch(()=>{}),u=(p,h="Apply")=>{const m=Array.isArray(p.rows)?p.rows:[],g=Array.isArray(p.rowItemIndexes)?p.rowItemIndexes:null,S=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",y=g&&g.length===m.length?m.map((w,I)=>{const x=g[I],C=Array.isArray(w)?w:me([w])[0]?.runs||[{text:w?.text||"",color:w?.color}];if(x==null||x<0)return c.createElement("div",{key:`row:${I}`,className:"ps-line ps-modal-list-heading-line"},c.createElement(ye,{runs:C,theme:s}));const v=i.items?.[x];return c.createElement("button",{key:v?.id||`row:${I}`,type:"button",className:`ps-list-button ps-modal-list-button${x===i.selectedIndex?" is-selected":""}${S?" is-hanging":""}${v?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:x})},c.createElement("div",{className:"ps-line ps-modal-list-line"},c.createElement(ye,{runs:C,theme:s})))}):(i.items||[]).map((w,I)=>c.createElement("button",{key:w.id||I,type:"button",className:`ps-list-button ps-modal-list-button${I===i.selectedIndex?" is-selected":""}${S?" is-hanging":""}${w?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:I})},c.createElement("div",{className:"ps-line ps-modal-list-line"},c.createElement(ye,{runs:Array.isArray(m?.[I])?m[I]:me([m?.[I]])[0]?.runs||[{text:m?.[I]?.text||"",color:m?.[I]?.color}],theme:s}))));return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:`ps-modal${i.type==="themePicker"?" is-theme-picker":""}`,onClick:w=>w.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},p.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("div",{className:"ps-modal-grid"},c.createElement("div",{ref:a,className:"ps-modal-list"},y),c.createElement("div",{className:"ps-modal-details"},c.createElement("div",{className:"ps-modal-details-title"},p.detailsTitle||"Details"),me(p.detailsLines||[]).map((w,I)=>c.createElement(ge,{key:`detail:${I}`,line:w,theme:s,className:"ps-modal-detail-line"})))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(E.MODAL_CONFIRM).catch(()=>{})},h))))};if(i.type==="confirm"&&n.confirm){const p=!!i.alert,h=!p&&i.action==="deleteSession",m=i.action==="regenerateSession",g=i.extras||{};return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:S=>S.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.confirm.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},c.createElement("p",{style:{color:"#94a3b8",margin:0}},n.confirm.message)),m?c.createElement("div",{className:"ps-modal-body",style:{padding:"0 20px 12px",display:"flex",flexDirection:"column",gap:10}},c.createElement("label",{style:{color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8}},"Distillation",c.createElement("select",{className:"ps-modal-input",style:{flex:"1",padding:"4px 8px"},value:g.distillMode||"llm",onChange:S=>t.updateConfirmExtras({distillMode:S.currentTarget.value})},c.createElement("option",{value:"llm"},"Intelligent (LLM reads the whole transcript)"),c.createElement("option",{value:"deterministic"},"Fast (no LLM — tail + pointers)"))),(g.distillMode||"llm")==="llm"?c.createElement("textarea",{className:"ps-modal-input",style:{width:"100%",minHeight:"64px",resize:"vertical",fontFamily:"inherit",fontSize:"13px"},placeholder:'Distilling instructions (optional) — e.g. "preserve every SQL snippet verbatim"',value:g.instructions||"",maxLength:4e3,onChange:S=>t.updateConfirmExtras({instructions:S.currentTarget.value})}):null):null,c.createElement("div",{className:"ps-modal-footer"},p?null:c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:`ps-modal-button ${h?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(E.MODAL_CONFIRM).catch(()=>{})},n.confirm.confirmLabel))))}if(i.type==="themePicker"&&n.themePicker)return u(n.themePicker,"Apply Theme");const f=i.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(i.type==="modelPicker"&&n.modelPicker)return u(n.modelPicker,f);if(i.type==="reasoningEffortPicker"&&n.reasoningEffortPicker)return u(n.reasoningEffortPicker,f);if(i.type==="contextTierPicker"&&n.contextTierPicker)return u(n.contextTierPicker,f);if(i.type==="sessionAgentPicker"&&n.sessionAgentPicker)return u(n.sessionAgentPicker,"Create Session");if(i.type==="sessionGroupPicker"&&n.sessionGroupPicker)return u(n.sessionGroupPicker,"Move");if(i.type==="artifactPicker"&&n.artifactPicker)return u(n.artifactPicker,n.artifactPicker.confirmLabel||"Open / Download");if(i.type==="sessionOwnerFilter"&&n.sessionOwnerFilter){const p=n.sessionOwnerFilter,h=Array.isArray(p.rows)?p.rows:[];return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal",onClick:m=>m.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},p.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("div",{className:"ps-modal-grid"},c.createElement("div",{ref:a,className:"ps-modal-list"},(i.items||[]).map((m,g)=>c.createElement("button",{key:m.id||g,type:"button",className:`ps-list-button ps-modal-list-button${g===i.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(g)},c.createElement("div",{className:"ps-line ps-modal-list-line"},c.createElement(ye,{runs:Array.isArray(h?.[g])?h[g]:me([h?.[g]])[0]?.runs||[{text:h?.[g]?.text||"",color:h?.[g]?.color}],theme:s}))))),c.createElement("div",{className:"ps-modal-details"},c.createElement("div",{className:"ps-modal-details-title"},p.detailsTitle||"Details"),me(p.detailsLines||[]).map((m,g)=>c.createElement(ge,{key:`detail:${g}`,line:m,theme:s,className:"ps-modal-detail-line"})))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:l},"Done"))))}if(i.type==="renameSession"&&n.renameSession)return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:p=>p.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.renameSession.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("input",{ref:o,className:"ps-modal-input",value:n.renameSession.value,placeholder:n.renameSession.placeholder,onChange:p=>t.setRenameSessionValue(p.currentTarget.value,p.currentTarget.selectionStart??p.currentTarget.value.length),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),t.handleCommand(E.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),c.createElement("div",{className:"ps-modal-details"},me(n.renameSession.helpLines||[]).map((p,h)=>c.createElement(ge,{key:`help:${h}`,line:p,theme:s,className:"ps-modal-detail-line"}))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(E.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(i.type==="sessionGroupName"&&n.sessionGroupName)return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:p=>p.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.sessionGroupName.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("input",{ref:r,className:"ps-modal-input",value:n.sessionGroupName.value,placeholder:n.sessionGroupName.placeholder,onChange:p=>t.setSessionGroupNameValue(p.currentTarget.value,p.currentTarget.selectionStart??p.currentTarget.value.length),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),t.handleCommand(E.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),c.createElement("div",{className:"ps-modal-details"},me(n.sessionGroupName.helpLines||[]).map((p,h)=>c.createElement(ge,{key:`help:${h}`,line:p,theme:s,className:"ps-modal-detail-line"}))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(E.MODAL_CONFIRM).catch(()=>{})},"Create and Move"))));if(i.type==="terminatePicker"){const p=Number(i.bulkCount)>1,h=!!i.systemRestart,m=String(i.sessionTitle||"").trim()||"this session",g=Number(i.bulkCount)||0,S=p?`What should happen to the ${g} selected sessions? Choose an action; you'll be asked to confirm.`:h?`How should "${m}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${m}"? Choose an action; you'll be asked to confirm.`,y=w=>()=>{t.pickTerminateAction(w).catch(()=>{})};return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:w=>w.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},i.title||"Session Lifecycle"),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},c.createElement("p",{style:{color:"#94a3b8",margin:0}},S)),c.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},i.canRegenerate?c.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},title:"Archive and distill the transcript, then rebuild context fresh at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved.",onClick:y("regenerate")},"Regenerate Context"):null,c.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:y("complete")},p?`Mark ${g} Completed`:h?"Complete & Restart":"Mark Completed"),c.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:y("cancel")},p?`Cancel ${g} Sessions`:h?"Terminate & Restart":"Cancel Session"),c.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:y("delete")},p?`Hard Delete ${g} Sessions`:h?"Hard Delete & Restart":"Delete Session")),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Close"))))}if(i.type==="artifactUpload"&&n.artifactUpload)return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:p=>p.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.artifactUpload.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("input",{className:"ps-modal-input",value:n.artifactUpload.value,placeholder:n.artifactUpload.placeholder,onChange:p=>t.setArtifactUploadValue(p.currentTarget.value,p.currentTarget.selectionStart||p.currentTarget.value.length),autoFocus:!0}),c.createElement("div",{className:"ps-modal-details"},me(n.artifactUpload.helpLines||[]).map((p,h)=>c.createElement(ge,{key:`help:${h}`,line:p,theme:s,className:"ps-modal-detail-line"}))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(E.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const d=i.type==="logFilter"?n.logFilter:i.type==="filesFilter"?n.filesFilter:i.type==="historyFormat"?n.historyFormat:null;return d?c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-wide",onClick:p=>p.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},d.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l},"Close")),c.createElement("div",{className:"ps-filter-grid"},(i.items||[]).map((p,h)=>{const m=i.type==="filesFilter"?n.filesFilterState?.[p.id]||p.options?.[0]?.id:i.type==="historyFormat"?n.historyFormatState:n.logsFilter?.[p.id]||p.options?.[0]?.id;return c.createElement("div",{key:p.id||h,className:"ps-filter-column"},c.createElement("div",{className:"ps-filter-title"},p.label),(p.options||[]).map(g=>c.createElement("button",{key:g.id,type:"button",className:`ps-filter-option${g.id===m?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:h}),i.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:g.id}):i.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[p.id]:g.id}}),t.ensureFilesForScope(g.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[p.id]:g.id}})}},g.label)))})),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:l},"Done")))):null}function yh(t,e){c.useEffect(()=>{const s=n=>{const i=n.target,o=i instanceof HTMLElement&&(i.tagName==="TEXTAREA"||i.tagName==="INPUT"||i.tagName==="SELECT"||i.isContentEditable),r=t.getState().ui.modal,a=Hn(t),l=t.getState().ui.inspectorTab,u=t.getState().ui.focusRegion,f=!n.metaKey&&!n.ctrlKey&&!n.altKey,d=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="T"&&n.shiftKey,p=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="N"&&n.shiftKey,h=m=>{const g=zf(a,l,m);t.selectInspectorTab(g).catch(()=>{})};if(!o&&d){n.preventDefault(),t.handleCommand(E.OPEN_THEME_PICKER).catch(()=>{});return}if(!o&&p){n.preventDefault(),t.handleCommand(E.OPEN_MODEL_PICKER).catch(()=>{});return}if(r&&!o){if(n.key==="Escape"||r.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(E.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||r.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(E.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(E.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(E.MODAL_PANE_NEXT).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(E.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(E.MODAL_NEXT).catch(()=>{}));return}if(!o){if(n.key==="r"&&f&&u!=="prompt"){n.preventDefault(),t.handleCommand(E.REFRESH).catch(()=>{});return}if(u==="chat"&&n.key==="s"&&f){n.preventDefault(),t.handleCommand(E.TOGGLE_CHAT_VIEW).catch(()=>{});return}if(n.key==="n"&&f){n.preventDefault(),t.handleCommand(E.NEW_SESSION).catch(()=>{});return}if(u==="inspector"&&l==="files"&&(n.key==="u"&&f||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(E.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(u==="inspector"&&l==="files"&&n.key==="a"&&f){n.preventDefault(),t.handleCommand(E.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&l==="files"&&n.key==="x"&&f){n.preventDefault(),t.handleCommand(E.DELETE_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&l==="files"&&n.key==="o"&&f){n.preventDefault(),t.handleCommand(E.OPEN_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&l==="files"&&n.key==="f"&&f){n.preventDefault(),t.handleCommand(E.OPEN_FILES_FILTER).catch(()=>{});return}if(u==="inspector"&&l==="stats"&&n.key==="f"&&f){n.preventDefault(),t.handleCommand(E.TOGGLE_STATS_VIEW).catch(()=>{});return}if(u==="inspector"&&l==="files"&&n.key==="v"&&f){n.preventDefault(),t.handleCommand(E.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(u==="inspector"&&l==="logs"&&n.key==="t"&&f){n.preventDefault(),t.handleCommand(E.TOGGLE_LOG_TAIL).catch(()=>{});return}if(u==="inspector"&&l==="logs"&&n.key==="f"&&f){n.preventDefault(),t.handleCommand(E.OPEN_LOG_FILTER).catch(()=>{});return}if(u==="inspector"&&l==="history"&&n.key==="f"&&f){n.preventDefault(),t.handleCommand(E.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(u==="inspector"&&l==="history"&&n.key==="r"&&f){n.preventDefault(),t.handleCommand(E.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(u==="inspector"&&l==="history"&&n.key==="a"&&f){n.preventDefault(),t.handleCommand(E.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&f){n.preventDefault(),t.handleCommand(E.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&f){n.preventDefault(),t.handleCommand(E.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&f){n.preventDefault(),t.handleCommand(E.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&f){n.preventDefault(),t.handleCommand(E.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(E.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&f&&u==="inspector"){n.preventDefault(),h(1);return}if(n.key==="["&&f){n.preventDefault(),t.handleCommand(E.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&f){n.preventDefault(),t.handleCommand(E.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&f){n.preventDefault(),t.handleCommand(E.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&f){n.preventDefault(),t.handleCommand(E.GROW_SESSION_PANE).catch(()=>{});return}if(u==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),h(-1);return}if(u==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),h(1);return}if(u==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(E.MOVE_SESSION_UP).catch(()=>{});return}if(u==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(E.MOVE_SESSION_DOWN).catch(()=>{});return}if(u==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(E.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(u==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(E.PAGE_UP).catch(()=>{});return}if(u==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(E.PAGE_DOWN).catch(()=>{});return}if(u==="sessions"&&n.key==="t"&&f){n.preventDefault(),t.handleCommand(E.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(E.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(E.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&f){n.preventDefault(),t.handleCommand(E.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(E.SCROLL_BOTTOM).catch(()=>{});return}if(u!=="prompt"&&n.key==="h"&&f){n.preventDefault(),t.handleCommand(E.FOCUS_LEFT).catch(()=>{});return}if(u!=="prompt"&&n.key==="l"&&f){n.preventDefault(),t.handleCommand(E.FOCUS_RIGHT).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(E.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(E.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(E.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function Sh(t){if(!t)return"Unknown user";const e=String(t.displayName||"").trim(),s=String(t.email||"").trim();if(e&&s&&e.toLowerCase()!==s.toLowerCase())return`${e} <${s}>`;if(e)return e;if(s)return s;const n=String(t.provider||"").trim(),i=String(t.subject||"").trim();return[n,i].filter(Boolean).join(":")||"user"}function bh({controller:t}){const e=z(t,ou,ke),s=c.useRef(null);c.useEffect(()=>{if(e.ghcpKey.editing){const d=window.requestAnimationFrame(()=>{s.current&&s.current.focus()});return()=>window.cancelAnimationFrame(d)}},[e.ghcpKey.editing]);const n=c.useCallback(()=>{t.closeAdminConsole()},[t]),i=c.useCallback(()=>{t.refreshAdminProfile().catch(()=>{})},[t]),o=c.useCallback(()=>{t.beginAdminEditGhcpKey()},[t]),r=c.useCallback(()=>{t.cancelAdminEditGhcpKey()},[t]),a=c.useCallback(()=>{t.clearAdminGhcpKey().catch(()=>{})},[t]),l=c.useCallback(d=>{d.preventDefault(),t.saveAdminGhcpKey().catch(()=>{})},[t]),u=c.useCallback(d=>{t.setAdminGhcpKeyDraft(d.target.value)},[t]),f=Sh(e.principal);return c.createElement("div",{className:"ps-admin-console"},c.createElement("header",{className:"ps-admin-console__header"},c.createElement("h2",null,"Admin Console"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:n},"Close")),c.createElement("section",{className:"ps-admin-console__identity"},c.createElement("dl",null,c.createElement("dt",null,"Signed in as"),c.createElement("dd",null,f))),e.loadError?c.createElement("div",{className:"ps-admin-console__error",role:"alert"},e.loadError):null,c.createElement("section",{className:"ps-admin-console__section"},c.createElement("h3",null,"GitHub Copilot key"),e.ghcpKey.storeAsSystem?c.createElement("p",{className:"ps-admin-console__hint"},"System-wide key for platform-managed (ownerless) system ","sessions — agent tuners, repo cache managers, and other ","sessions with no owner resolve this key for GitHub Copilot ","models. Clearing it reverts them to the worker default."):c.createElement("p",{className:"ps-admin-console__hint"},"Per-user override for the GitHub Copilot model provider token. ","When set, this key is used instead of the worker's env-supplied ","GITHUB_TOKEN for sessions you own. Clearing the key reverts to ","the worker default."),e.isAdmin&&e.systemGhcpKey.supported?c.createElement("label",{className:"ps-admin-console__system-toggle"},c.createElement("input",{type:"checkbox",checked:e.ghcpKey.storeAsSystem,disabled:e.ghcpKey.saving,onChange:d=>t.setAdminGhcpKeyStoreAsSystem(d.target.checked)}),"Store as System key"):null,c.createElement("p",{className:`ps-admin-console__status${e.ghcpKey.error?" is-error":""}`},e.ghcpKey.error||e.ghcpKey.statusText),e.ghcpKey.editing?c.createElement("form",{className:"ps-admin-console__form",onSubmit:l},c.createElement("input",{ref:s,type:"password",autoComplete:"off",spellCheck:!1,value:e.ghcpKey.draft,disabled:e.ghcpKey.saving,placeholder:"Paste GitHub Copilot key",onChange:u}),c.createElement("div",{className:"ps-admin-console__actions"},c.createElement("button",{type:"submit",className:"ps-primary-button",disabled:e.ghcpKey.saving},e.ghcpKey.saving?"Saving...":"Save"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:r,disabled:e.ghcpKey.saving},"Cancel"))):c.createElement("div",{className:"ps-admin-console__actions"},c.createElement("button",{type:"button",className:"ps-primary-button",onClick:o},e.ghcpKey.targetConfigured?e.ghcpKey.storeAsSystem?"Replace System key":"Replace key":e.ghcpKey.storeAsSystem?"Set System key":"Set key"),e.ghcpKey.targetConfigured?c.createElement("button",{type:"button",className:"ps-mini-button",onClick:a},e.ghcpKey.storeAsSystem?"Clear System key":"Clear key"):null,c.createElement("button",{type:"button",className:"ps-mini-button",onClick:i},e.loading?"Refreshing...":"Refresh"))))}function Ih({transport:t,mode:e="remote",branding:s=null}={}){ip();const n=Md(kd,Ql({mode:e,branding:s}));return new If({store:n,transport:t})}function xh({controller:t}){const e=z(t,T=>T.ui.chatViewMode==="rich");c.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-rich-ui",e),()=>document.body.classList.remove("ps-rich-ui")},[e]);const s=c.useRef(null),n=c.useRef(null),i=yo(s),o=yo(n),r=fp(i);c.useEffect(()=>{const T=()=>{const B=document.createElement("span");B.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const D=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");D&&(B.style.font=window.getComputedStyle(D).font),B.textContent="0".repeat(100),(D?.parentElement||document.body).appendChild(B);const W=B.getBoundingClientRect().width/100||8;B.remove(),t.dispatch({type:"ui/viewport",width:Math.floor(window.innerWidth/W),height:Math.floor(window.innerHeight/He)})};T();let _;const L=()=>{clearTimeout(_),_=setTimeout(T,150)};return window.addEventListener("resize",L),window.addEventListener("orientationchange",L),()=>{clearTimeout(_),window.removeEventListener("resize",L),window.removeEventListener("orientationchange",L)}},[t]);const[a,l]=c.useState(!1),[u,f]=c.useState(null),d=z(t,T=>({themeId:T.ui.themeId,ownerFilter:T.sessions.ownerFilter,pinnedIds:T.sessions.pinnedIds,collapsedSessionIds:T.sessions.collapsedIds,activeSessionId:T.sessions.activeSessionId||null,promptRows:Zr(T),chatViewMode:T.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(T.sessions.activeSessionId&&T.sessions.byId[T.sessions.activeSessionId]?.isGroup),paneAdjust:T.ui.layout?.paneAdjust??0,sessionPaneAdjust:T.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:T.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:T.ui.layout?.activityPaneAdjust??0,focusRegion:T.ui.focusRegion,inspectorTab:T.ui.inspectorTab,filesFullscreen:!!T.files.fullscreen,adminVisible:!!T.admin?.visible}),ke),p=c.useRef(!1),h=c.useRef(null),m=c.useRef(null),g=c.useRef(null),S=c.useRef(!1),y=c.useRef(!1),w=c.useRef(null),I=c.useRef(null),[x,C]=c.useState("workspace"),v=(i.width||window.innerWidth||0)<$f,P=d.activeSessionIsGroup||d.chatViewMode==="summary"?0:d.promptRows;yh(t,v),c.useEffect(()=>{t.setViewport(r)},[t,r.height,r.width]),c.useEffect(()=>{let T=!0;p.current=!1,h.current=null,w.current=null,I.current=ho(t.getState()),m.current&&(clearTimeout(m.current),m.current=null),g.current&&(clearInterval(g.current),g.current=null),S.current=!1,y.current=!1;const _=t.transport;if(typeof _?.getCurrentUserProfile!="function"||typeof _?.setCurrentUserProfileSettings!="function")return p.current=!0,()=>{T=!1};const L=async()=>{if(!(!T||S.current)){S.current=!0;try{const B=await _.getCurrentUserProfile();if(!T)return;I.current=ho(t.getState());const D=rp(B?.profileSettings,I.current),W=JSON.stringify(D),ae=Ks(t.getState()),ie=JSON.stringify(ae),nt=p.current&&h.current!=null&&ie!==h.current;!(m.current||y.current||nt)&&w.current!==W&&(t.dispatch({type:"profileSettings/apply",settings:D}),w.current=W);const Ht=Ks(t.getState());h.current=JSON.stringify(Ht),p.current=!0}catch{if(!T)return;p.current=!0}finally{S.current=!1}}};return L().catch(()=>{}),g.current=setInterval(()=>{L().catch(()=>{})},Uf),()=>{T=!1,m.current&&(clearTimeout(m.current),m.current=null),g.current&&(clearInterval(g.current),g.current=null),S.current=!1}},[t]),c.useEffect(()=>{if(!p.current)return;const T=Ks(d),_=JSON.stringify(T);h.current!==_&&(h.current=_,m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{m.current=null,y.current=!0,ap(t,T).catch(()=>{}).finally(()=>{y.current=!1})},400))},[t,d.activeSessionId,d.activityPaneAdjust,d.chatViewMode,d.collapsedSessionIds,d.ownerFilter,d.paneAdjust,d.pinnedIds,d.portalSessionColumnAdjust,d.sessionPaneAdjust,d.themeId]),c.useEffect(()=>{dp(d.themeId)},[d.themeId]),c.useEffect(()=>{v&&d.focusRegion!=="prompt"&&C(d.focusRegion==="activity"?"activity":d.focusRegion==="inspector"?"inspector":"workspace")},[v,d.focusRegion]),c.useEffect(()=>{const T=Hn(t);!T.includes(d.inspectorTab)&&T.length>0&&t.selectInspectorTab(T[0]).catch(()=>{})},[t,d.inspectorTab]);const O=c.useMemo(()=>_t(r,d.paneAdjust,P,d.sessionPaneAdjust,d.activityPaneAdjust),[r,d.activityPaneAdjust,d.paneAdjust,P,d.sessionPaneAdjust]),M=d.filesFullscreen&&d.inspectorTab==="files";c.useEffect(()=>{!M||!a||(l(!1),f(null))},[a,M]);const $=c.useCallback(()=>{l(T=>{const _=!T;return _?t.setFocus("chat"):f(null),_})},[t]),F=c.useCallback(T=>{f(_=>{const L=_===T?null:T;return t.setFocus(L||"chat"),L})},[t]),Y=Math.max(0,(i.width||0)*.68),U=o.width||Y,V=lp(U,d.portalSessionColumnAdjust),q=cp(V),ee=q==="hidden"?"0px":`clamp(0px, calc(${Dn*100}% + ${Number(d.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,we=c.createElement("div",{className:"ps-workspace-grid",style:{gridTemplateColumns:`minmax(0, ${O.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${O.rightWidth}fr)`}},c.createElement("div",{ref:n,className:`ps-workspace-main-grid is-session-${q}`,style:{gridTemplateColumns:`${ee} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},q!=="hidden"?c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},c.createElement(Un,{controller:t,structuredRows:!0})):null,c.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},c.createElement(ph,{controller:t,portalSessionColumnAdjust:d.portalSessionColumnAdjust})),c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},c.createElement(jn,{controller:t}))),c.createElement(fh,{controller:t,paneAdjust:d.paneAdjust}),c.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`${O.inspectorPaneHeight}fr var(--ps-resizer-track, 16px) ${O.activityPaneHeight}fr`}},c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},O.inspectorHidden?null:c.createElement(Nt,{controller:t,mobile:!1})),c.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},c.createElement(hh,{controller:t,activityPaneAdjust:d.activityPaneAdjust})),c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},O.activityHidden?null:c.createElement(un,{controller:t})))),R=c.createElement(lh,{controller:t,openPane:u,onTogglePane:F,onExitFocus:$,mobile:v}),K=c.createElement("div",{className:"ps-workspace-full"},c.createElement(Nt,{controller:t,mobile:!1}));let b=null;return M?b=c.createElement("div",{className:"ps-mobile-pane-fill"},c.createElement(Nt,{controller:t,mobile:!0})):x==="inspector"?b=c.createElement("div",{className:"ps-mobile-pane-fill"},c.createElement(Nt,{controller:t,mobile:!0})):x==="activity"?b=c.createElement("div",{className:"ps-mobile-pane-fill"},c.createElement(un,{controller:t})):b=c.createElement(oh,{controller:t}),c.createElement("div",{ref:s,className:"ps-web-shell"},v&&(a||x==="inspector"||x==="activity")?null:c.createElement(dh,{controller:t,mobile:v,chatFocusMode:a,onToggleChatFocus:$,chatFocusDisabled:M}),c.createElement("div",{className:"ps-workspace"},d.adminVisible?c.createElement(bh,{controller:t}):M?K:a?R:v?b:we),v&&!a?c.createElement(mh,{activePane:x,setActivePane:C,controller:t}):null,c.createElement(gh,{controller:t}))}export{xh as P,c as R,Lf as _,Ia as a,ru as b,Ih as c,ya as g,Mo as r,wh as s};