pilotswarm 0.5.30 → 0.5.32

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 (83) hide show
  1. package/package.json +2 -2
  2. package/tui/src/node-sdk-transport.js +4 -0
  3. package/ui/core/src/controller.js +102 -30
  4. package/ui/core/src/reducer.js +50 -1
  5. package/ui/core/src/selectors.js +68 -22
  6. package/ui/core/src/state.js +2 -0
  7. package/ui/core/src/themes/doom.js +106 -0
  8. package/ui/core/src/themes/helpers.js +7 -1
  9. package/ui/core/src/themes/index.js +4 -0
  10. package/ui/core/src/themes/winamp.js +104 -0
  11. package/ui/react/src/components.js +25 -0
  12. package/ui/react/src/web-app.js +320 -51
  13. package/web/api/ws.js +7 -0
  14. package/web/authz.js +14 -81
  15. package/web/dist/assets/{abnfDiagram-VRR7QNED-Cimc0f-u.js → abnfDiagram-VRR7QNED-mXFQ4a3c.js} +1 -1
  16. package/web/dist/assets/{arc-D8-_Dx5J.js → arc-BPuuvbge.js} +1 -1
  17. package/web/dist/assets/{architectureDiagram-ZJ3FMSHR-lzMAuQHJ.js → architectureDiagram-ZJ3FMSHR-Dt4uUYIe.js} +1 -1
  18. package/web/dist/assets/{blockDiagram-677ZJIJ3-Dp2CWjVS.js → blockDiagram-677ZJIJ3-Ax8Q22vV.js} +1 -1
  19. package/web/dist/assets/{c4Diagram-LMCZKHZV-DF93UkOy.js → c4Diagram-LMCZKHZV-CPiukyHt.js} +1 -1
  20. package/web/dist/assets/channel-BCzDctYg.js +1 -0
  21. package/web/dist/assets/{chunk-2Q5K7J3B-pbsQRM-F.js → chunk-2Q5K7J3B-VJLqCZJX.js} +1 -1
  22. package/web/dist/assets/{chunk-32BRIVSS-B_f-gG1O.js → chunk-32BRIVSS-DqOshxhf.js} +1 -1
  23. package/web/dist/assets/{chunk-5VM5RSS4-gqlpJDmt.js → chunk-5VM5RSS4-KPqV21jV.js} +1 -1
  24. package/web/dist/assets/{chunk-EX3LRPZG-Cms7hPmM.js → chunk-EX3LRPZG-DfhiCVl_.js} +1 -1
  25. package/web/dist/assets/{chunk-JWPE2WC7-Boq5PtPI.js → chunk-JWPE2WC7-H6khJPuW.js} +1 -1
  26. package/web/dist/assets/{chunk-MOJQB5TN-DVn9i8zt.js → chunk-MOJQB5TN-BKMAzQxj.js} +1 -1
  27. package/web/dist/assets/{chunk-RYQCIY6F-a1vKs3UX.js → chunk-RYQCIY6F-DNXRTxtj.js} +1 -1
  28. package/web/dist/assets/{chunk-V7JOEXUC-i60p5fHd.js → chunk-V7JOEXUC-B56PM6Gv.js} +1 -1
  29. package/web/dist/assets/{chunk-VR4S4FIN-a8p0o-8B.js → chunk-VR4S4FIN-Boi3hGkB.js} +1 -1
  30. package/web/dist/assets/{chunk-XXDRQBXY-BwP1yBKd.js → chunk-XXDRQBXY-DmJyn890.js} +1 -1
  31. package/web/dist/assets/classDiagram-OUVF2IWQ-ChqjVZil.js +1 -0
  32. package/web/dist/assets/classDiagram-v2-EOCWNBFH-ChqjVZil.js +1 -0
  33. package/web/dist/assets/{cose-bilkent-JH36ORCC-HW6kGgze.js → cose-bilkent-JH36ORCC-BRdFlFWt.js} +1 -1
  34. package/web/dist/assets/{cynefin-VYW2F7L2-YUFMn-vE.js → cynefin-VYW2F7L2-DqE-xib2.js} +1 -1
  35. package/web/dist/assets/{cynefinDiagram-TSTJHNR4-Brdy17i4.js → cynefinDiagram-TSTJHNR4-D-QBZjIL.js} +1 -1
  36. package/web/dist/assets/{dagre-VKFMJZFB-CAiSJJj-.js → dagre-VKFMJZFB-DYu9oQV6.js} +1 -1
  37. package/web/dist/assets/{diagram-FQU43EPY-B63Cqe0J.js → diagram-FQU43EPY-DOwYccCg.js} +1 -1
  38. package/web/dist/assets/{diagram-G47NLZAW-ByktrDJ2.js → diagram-G47NLZAW-DTSEmrPr.js} +1 -1
  39. package/web/dist/assets/{diagram-NH7WQ7WH-BLSfRMoE.js → diagram-NH7WQ7WH-OqbzzquA.js} +1 -1
  40. package/web/dist/assets/{diagram-OA4YK3LP-DNVu-zpk.js → diagram-OA4YK3LP-BMVG6A8I.js} +1 -1
  41. package/web/dist/assets/{diagram-WEI45ONY-CNf4Sz-I.js → diagram-WEI45ONY-Rn2Q5xaz.js} +1 -1
  42. package/web/dist/assets/{ebnfDiagram-CCIWWBDH-9CT3ergx.js → ebnfDiagram-CCIWWBDH-aL32_v5y.js} +1 -1
  43. package/web/dist/assets/{erDiagram-Q63AITRT-BPJHAMgl.js → erDiagram-Q63AITRT-DKCpyczx.js} +1 -1
  44. package/web/dist/assets/{flowDiagram-23GEKE2U-BVtpr6Iu.js → flowDiagram-23GEKE2U-CrZTPgR_.js} +1 -1
  45. package/web/dist/assets/{ganttDiagram-NO4QXBWP-BTHnv9sV.js → ganttDiagram-NO4QXBWP-DnSE1OtC.js} +1 -1
  46. package/web/dist/assets/{gitGraphDiagram-IHSO6WYX-BfmtqbL5.js → gitGraphDiagram-IHSO6WYX-C5SeYPUR.js} +1 -1
  47. package/web/dist/assets/{index-Bmb8qK39.js → index-B-TEKrRB.js} +6 -6
  48. package/web/dist/assets/index-D2B5bzSN.css +1 -0
  49. package/web/dist/assets/{infoDiagram-FWYZ7A6U-kU4i4HRu.js → infoDiagram-FWYZ7A6U-DDnJZp0X.js} +1 -1
  50. package/web/dist/assets/{ishikawaDiagram-FXEZZL3T-Ch7i-E8O.js → ishikawaDiagram-FXEZZL3T-ewhzfFkq.js} +1 -1
  51. package/web/dist/assets/{journeyDiagram-5HDEW3XC-CPQxp0ps.js → journeyDiagram-5HDEW3XC-T0iWWkLM.js} +1 -1
  52. package/web/dist/assets/{kanban-definition-HUTT4EX6-BBgMVqoJ.js → kanban-definition-HUTT4EX6-D1MFQZjb.js} +1 -1
  53. package/web/dist/assets/{linear-rwksvzXJ.js → linear-BKfPK9wE.js} +1 -1
  54. package/web/dist/assets/{mermaid.core-o7PszRUc.js → mermaid.core-CyzD7dTc.js} +4 -4
  55. package/web/dist/assets/{mindmap-definition-LN4V7U3C-wgOTdzlq.js → mindmap-definition-LN4V7U3C-CWXtcTlP.js} +1 -1
  56. package/web/dist/assets/{papaparse.min-BRXtjEI6.js → papaparse.min-DLUoV5k5.js} +1 -1
  57. package/web/dist/assets/{pegDiagram-2B236MQR-BkhQqqTm.js → pegDiagram-2B236MQR-BFjZun-r.js} +1 -1
  58. package/web/dist/assets/{pieDiagram-ENE6RG2P-CcMnvxUz.js → pieDiagram-ENE6RG2P-DMDtW4g7.js} +1 -1
  59. package/web/dist/assets/pilotswarm-DA0u7Cq_.js +99 -0
  60. package/web/dist/assets/{quadrantDiagram-ABIIQ3AL-_KD1QeEr.js → quadrantDiagram-ABIIQ3AL-CAwPVaYL.js} +1 -1
  61. package/web/dist/assets/{railroadDiagram-RFXS5EU6-CqI0olIe.js → railroadDiagram-RFXS5EU6-Co102PkQ.js} +1 -1
  62. package/web/dist/assets/{requirementDiagram-TGXJPOKE-1JxRwusF.js → requirementDiagram-TGXJPOKE-D19VlRSl.js} +1 -1
  63. package/web/dist/assets/{sankeyDiagram-HTMAVEWB-9IpFoKzi.js → sankeyDiagram-HTMAVEWB-Sd_a3ukL.js} +1 -1
  64. package/web/dist/assets/{sequenceDiagram-DBY2YBRQ-teyObSQ9.js → sequenceDiagram-DBY2YBRQ-CojDRK1c.js} +1 -1
  65. package/web/dist/assets/{sizeCapture-X5ZJPWSS-DVhU2J_6.js → sizeCapture-X5ZJPWSS-XqXcxnDo.js} +1 -1
  66. package/web/dist/assets/{stateDiagram-2N3HPSRC-DHPoWpIQ.js → stateDiagram-2N3HPSRC-BcN_w699.js} +1 -1
  67. package/web/dist/assets/stateDiagram-v2-6OUMAXLB-BV_w1D3C.js +1 -0
  68. package/web/dist/assets/{swimlanes-5IMT3BWC-BxTtDQoB.js → swimlanes-5IMT3BWC-BcO6ai_I.js} +2 -2
  69. package/web/dist/assets/swimlanesDiagram-G3AALYLV-BnYdP0qP.js +8 -0
  70. package/web/dist/assets/{timeline-definition-FHXFAJF6-D0wXZx-4.js → timeline-definition-FHXFAJF6-DOPfYxUq.js} +1 -1
  71. package/web/dist/assets/{vennDiagram-L72KCM5P-BSFyI3iV.js → vennDiagram-L72KCM5P-BSKLkEOC.js} +1 -1
  72. package/web/dist/assets/{wardleyDiagram-EHGQE667-BN-S7hh0.js → wardleyDiagram-EHGQE667-BdcYAVw2.js} +1 -1
  73. package/web/dist/assets/{xychartDiagram-FW5EYKEG-nDNuPs7o.js → xychartDiagram-FW5EYKEG-C6EJT4jB.js} +1 -1
  74. package/web/dist/index.html +3 -3
  75. package/web/runtime.js +55 -0
  76. package/web/server.js +7 -0
  77. package/web/dist/assets/channel-OwWeiCox.js +0 -1
  78. package/web/dist/assets/classDiagram-OUVF2IWQ-CDaP7nuC.js +0 -1
  79. package/web/dist/assets/classDiagram-v2-EOCWNBFH-CDaP7nuC.js +0 -1
  80. package/web/dist/assets/index-B37T1c2s.css +0 -1
  81. package/web/dist/assets/pilotswarm-DYXtzuUN.js +0 -99
  82. package/web/dist/assets/stateDiagram-v2-6OUMAXLB-DJjZWYLS.js +0 -1
  83. package/web/dist/assets/swimlanesDiagram-G3AALYLV-CV12vDcK.js +0 -8
@@ -1,99 +0,0 @@
1
- function _l(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ys={exports:{}},q={};var Pi;function $l(){if(Pi)return q;Pi=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"),r=Symbol.for("react.consumer"),o=Symbol.for("react.context"),a=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),f=Symbol.iterator;function m(v){return v===null||typeof v!="object"?null:(v=f&&v[f]||v["@@iterator"],typeof v=="function"?v:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},h=Object.assign,y={};function S(v,$,H){this.props=v,this.context=$,this.refs=y,this.updater=H||g}S.prototype.isReactComponent={},S.prototype.setState=function(v,$){if(typeof v!="object"&&typeof v!="function"&&v!=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,v,$,"setState")},S.prototype.forceUpdate=function(v){this.updater.enqueueForceUpdate(this,v,"forceUpdate")};function E(){}E.prototype=S.prototype;function x(v,$,H){this.props=v,this.context=$,this.refs=y,this.updater=H||g}var w=x.prototype=new E;w.constructor=x,h(w,S.prototype),w.isPureReactComponent=!0;var b=Array.isArray;function I(){}var k={H:null,A:null,T:null,S:null},P=Object.prototype.hasOwnProperty;function M(v,$,H){var C=H.ref;return{$$typeof:t,type:v,key:$,ref:C!==void 0?C:null,props:H}}function B(v,$){return M(v.type,$,v.props)}function O(v){return typeof v=="object"&&v!==null&&v.$$typeof===t}function _(v){var $={"=":"=0",":":"=2"};return"$"+v.replace(/[=:]/g,function(H){return $[H]})}var L=/\/+/g;function W(v,$){return typeof v=="object"&&v!==null&&v.key!=null?_(""+v.key):$.toString(36)}function Y(v){switch(v.status){case"fulfilled":return v.value;case"rejected":throw v.reason;default:switch(typeof v.status=="string"?v.then(I,I):(v.status="pending",v.then(function($){v.status==="pending"&&(v.status="fulfilled",v.value=$)},function($){v.status==="pending"&&(v.status="rejected",v.reason=$)})),v.status){case"fulfilled":return v.value;case"rejected":throw v.reason}}throw v}function te(v,$,H,C,N){var F=typeof v;(F==="undefined"||F==="boolean")&&(v=null);var U=!1;if(v===null)U=!0;else switch(F){case"bigint":case"string":case"number":U=!0;break;case"object":switch(v.$$typeof){case t:case e:U=!0;break;case p:return U=v._init,te(U(v._payload),$,H,C,N)}}if(U)return N=N(v),U=C===""?"."+W(v,0):C,b(N)?(H="",U!=null&&(H=U.replace(L,"$&/")+"/"),te(N,$,H,"",function(pe){return pe})):N!=null&&(O(N)&&(N=B(N,H+(N.key==null||v&&v.key===N.key?"":(""+N.key).replace(L,"$&/")+"/")+U)),$.push(N)),1;U=0;var z=C===""?".":C+":";if(b(v))for(var Q=0;Q<v.length;Q++)C=v[Q],F=z+W(C,Q),U+=te(C,$,H,F,N);else if(Q=m(v),typeof Q=="function")for(v=Q.call(v),Q=0;!(C=v.next()).done;)C=C.value,F=z+W(C,Q++),U+=te(C,$,H,F,N);else if(F==="object"){if(typeof v.then=="function")return te(Y(v),$,H,C,N);throw $=String(v),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(v).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return U}function ne(v,$,H){if(v==null)return v;var C=[],N=0;return te(v,C,"","",function(F){return $.call(H,F,N++)}),C}function Pe(v){if(v._status===-1){var $=v._result;$=$(),$.then(function(H){(v._status===0||v._status===-1)&&(v._status=1,v._result=H)},function(H){(v._status===0||v._status===-1)&&(v._status=2,v._result=H)}),v._status===-1&&(v._status=0,v._result=$)}if(v._status===1)return v._result.default;throw v._result}var ee=typeof reportError=="function"?reportError:function(v){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof v=="object"&&v!==null&&typeof v.message=="string"?String(v.message):String(v),error:v});if(!window.dispatchEvent($))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",v);return}console.error(v)},ye={map:ne,forEach:function(v,$,H){ne(v,function(){$.apply(this,arguments)},H)},count:function(v){var $=0;return ne(v,function(){$++}),$},toArray:function(v){return ne(v,function($){return $})||[]},only:function(v){if(!O(v))throw Error("React.Children.only expected to receive a single React element child.");return v}};return q.Activity=d,q.Children=ye,q.Component=S,q.Fragment=s,q.Profiler=i,q.PureComponent=x,q.StrictMode=n,q.Suspense=c,q.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=k,q.__COMPILER_RUNTIME={__proto__:null,c:function(v){return k.H.useMemoCache(v)}},q.cache=function(v){return function(){return v.apply(null,arguments)}},q.cacheSignal=function(){return null},q.cloneElement=function(v,$,H){if(v==null)throw Error("The argument must be a React element, but you passed "+v+".");var C=h({},v.props),N=v.key;if($!=null)for(F in $.key!==void 0&&(N=""+$.key),$)!P.call($,F)||F==="key"||F==="__self"||F==="__source"||F==="ref"&&$.ref===void 0||(C[F]=$[F]);var F=arguments.length-2;if(F===1)C.children=H;else if(1<F){for(var U=Array(F),z=0;z<F;z++)U[z]=arguments[z+2];C.children=U}return M(v.type,N,C)},q.createContext=function(v){return v={$$typeof:o,_currentValue:v,_currentValue2:v,_threadCount:0,Provider:null,Consumer:null},v.Provider=v,v.Consumer={$$typeof:r,_context:v},v},q.createElement=function(v,$,H){var C,N={},F=null;if($!=null)for(C in $.key!==void 0&&(F=""+$.key),$)P.call($,C)&&C!=="key"&&C!=="__self"&&C!=="__source"&&(N[C]=$[C]);var U=arguments.length-2;if(U===1)N.children=H;else if(1<U){for(var z=Array(U),Q=0;Q<U;Q++)z[Q]=arguments[Q+2];N.children=z}if(v&&v.defaultProps)for(C in U=v.defaultProps,U)N[C]===void 0&&(N[C]=U[C]);return M(v,F,N)},q.createRef=function(){return{current:null}},q.forwardRef=function(v){return{$$typeof:a,render:v}},q.isValidElement=O,q.lazy=function(v){return{$$typeof:p,_payload:{_status:-1,_result:v},_init:Pe}},q.memo=function(v,$){return{$$typeof:u,type:v,compare:$===void 0?null:$}},q.startTransition=function(v){var $=k.T,H={};k.T=H;try{var C=v(),N=k.S;N!==null&&N(H,C),typeof C=="object"&&C!==null&&typeof C.then=="function"&&C.then(I,ee)}catch(F){ee(F)}finally{$!==null&&H.types!==null&&($.types=H.types),k.T=$}},q.unstable_useCacheRefresh=function(){return k.H.useCacheRefresh()},q.use=function(v){return k.H.use(v)},q.useActionState=function(v,$,H){return k.H.useActionState(v,$,H)},q.useCallback=function(v,$){return k.H.useCallback(v,$)},q.useContext=function(v){return k.H.useContext(v)},q.useDebugValue=function(){},q.useDeferredValue=function(v,$){return k.H.useDeferredValue(v,$)},q.useEffect=function(v,$){return k.H.useEffect(v,$)},q.useEffectEvent=function(v){return k.H.useEffectEvent(v)},q.useId=function(){return k.H.useId()},q.useImperativeHandle=function(v,$,H){return k.H.useImperativeHandle(v,$,H)},q.useInsertionEffect=function(v,$){return k.H.useInsertionEffect(v,$)},q.useLayoutEffect=function(v,$){return k.H.useLayoutEffect(v,$)},q.useMemo=function(v,$){return k.H.useMemo(v,$)},q.useOptimistic=function(v,$){return k.H.useOptimistic(v,$)},q.useReducer=function(v,$,H){return k.H.useReducer(v,$,H)},q.useRef=function(v){return k.H.useRef(v)},q.useState=function(v){return k.H.useState(v)},q.useSyncExternalStore=function(v,$,H){return k.H.useSyncExternalStore(v,$,H)},q.useTransition=function(){return k.H.useTransition()},q.version="19.2.4",q}var _i;function Eo(){return _i||(_i=1,Ys.exports=$l()),Ys.exports}var Rl=Eo();const l=_l(Rl);var Xs={exports:{}},Ie={};var $i;function Ol(){if($i)return Ie;$i=1;var t=Eo();function e(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var p=2;p<arguments.length;p++)u+="&args[]="+encodeURIComponent(arguments[p])}return"Minified React error #"+c+"; 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 r(c,u,p){var d=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:d==null?null:""+d,children:c,containerInfo:u,implementation:p}}var o=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function a(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return Ie.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,Ie.createPortal=function(c,u){var p=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 r(c,u,null,p)},Ie.flushSync=function(c){var u=o.T,p=n.p;try{if(o.T=null,n.p=2,c)return c()}finally{o.T=u,n.p=p,n.d.f()}},Ie.preconnect=function(c,u){typeof c=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,n.d.C(c,u))},Ie.prefetchDNS=function(c){typeof c=="string"&&n.d.D(c)},Ie.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var p=u.as,d=a(p,u.crossOrigin),f=typeof u.integrity=="string"?u.integrity:void 0,m=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;p==="style"?n.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:d,integrity:f,fetchPriority:m}):p==="script"&&n.d.X(c,{crossOrigin:d,integrity:f,fetchPriority:m,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},Ie.preinitModule=function(c,u){if(typeof c=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var p=a(u.as,u.crossOrigin);n.d.M(c,{crossOrigin:p,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&n.d.M(c)},Ie.preload=function(c,u){if(typeof c=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var p=u.as,d=a(p,u.crossOrigin);n.d.L(c,p,{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})}},Ie.preloadModule=function(c,u){if(typeof c=="string")if(u){var p=a(u.as,u.crossOrigin);n.d.m(c,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:p,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else n.d.m(c)},Ie.requestFormReset=function(c){n.d.r(c)},Ie.unstable_batchedUpdates=function(c,u){return c(u)},Ie.useFormState=function(c,u,p){return o.H.useFormState(c,u,p)},Ie.useFormStatus=function(){return o.H.useHostTransitionStatus()},Ie.version="19.2.4",Ie}var Ri;function Ll(){if(Ri)return Xs.exports;Ri=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=Ol(),Xs.exports}const Fl=l.createContext(null);function Ge(){const t=l.useContext(Fl);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function Z(t,e,s=Object.is){const n=l.useRef(e),i=l.useRef(s);n.current=e,i.current=s;const[r,o]=l.useState(()=>e(t.getState())),a=l.useRef(r);return l.useEffect(()=>{a.current=r},[r]),l.useEffect(()=>t.subscribe(c=>{const u=n.current(c);i.current(a.current,u)||(a.current=u,o(u))}),[t]),r}const Oi=[".  ",".. ","..."],Li=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function vo(t,e=120){const[s,n]=l.useState(0);return l.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(r=>(r+1)%Li.length)},e);return()=>clearInterval(i)},[t,e]),t?Li[s]:""}function ko(t,e=360){const[s,n]=l.useState(0);return l.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(r=>(r+1)%Oi.length)},e);return()=>clearInterval(i)},[t,e]),t?Oi[s]:""}function Ao(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 T={SESSIONS:"sessions",CHAT:"chat",INSPECTOR:"inspector",ACTIVITY:"activity",PROMPT:"prompt"},We=["sequence","logs","nodes","history","files","stats"],A={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_SHOW_GHCP:"adminShowGhcp",ADMIN_SHOW_PACKAGES:"adminShowPackages",ADMIN_SHOW_WORKERS:"adminShowWorkers",ADMIN_WORKERS_REFRESH:"adminWorkersRefresh",ADMIN_PACKAGES_REFRESH:"adminPackagesRefresh",ADMIN_PACKAGES_NEXT:"adminPackagesNext",ADMIN_PACKAGES_PREV:"adminPackagesPrev",ADMIN_BEGIN_EDIT_GHCP_KEY:"adminBeginEditGhcpKey",ADMIN_CANCEL_EDIT_GHCP_KEY:"adminCancelEditGhcpKey",ADMIN_SAVE_GHCP_KEY:"adminSaveGhcpKey",ADMIN_CLEAR_GHCP_KEY:"adminClearGhcpKey"};function gt(t,e,s){const n=t.indexOf(e),r=((n===-1?0:n)+s+t.length)%t.length;return t[r]}function Yn(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 Cn(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 Bl(t){const e=Yn(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function Dl(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=Yn(t);return e==null?null:{text:`ctx ${Cn(t.currentTokens)}/${Cn(t.tokenLimit)} ${e}%`,color:Bl(t)}}function Hl(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 Co(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function Gl(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function To(t,e,s={},n={}){if(!e)return null;const i=Co(t)||{},r=Gl(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:r,completedAt:void 0,error:void 0},i):e==="session.compaction_complete"?(i.compaction={...i.compaction||{},state:s.success===!1?"failed":"succeeded",completedAt:r,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 jl(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 ${Cn(s.tokensRemoved)}`,color:"gray"}]:[]]}const Tn=/\{(\/?)([a-z-]+)\}/g,Ul={color:null,bold:!1,underline:!1},Ss=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,Fi=/session:\/\/([A-Za-z0-9-]+)/g,Wl={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function hs(t){return{color:t.color,bold:t.bold,underline:t.underline}}function Kl(t,e,s){const n=hs(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:Wl[i]||null,n}return n}function Xn(t){return String(t||"").replace(Tn,"")}function No(t){const e=[],n=String(t||"").split(`
2
- `);for(const i of n){const r=[];let o=hs(Ul),a=0,c;for(;(c=Tn.exec(i))!==null;){const[u,p,d]=c;c.index>a&&r.push({text:i.slice(a,c.index),...hs(o)}),o=Kl(o,d,p==="/"),a=c.index+u.length}(a<i.length||r.length===0)&&r.push({text:i.slice(a),...hs(o)}),e.push(r),Tn.lastIndex=0}return e}function ce(t){return String(t||"").slice(0,8)}function Mo(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}let Qs=null,Js=null,Zs=null,en=null;function Vl(){return Qs||(Qs=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})),Qs}function Po(){return Js||(Js=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})),Js}function ql(){return Zs||(Zs=new Intl.DateTimeFormat("en-GB",{month:"short"})),Zs}function zl(){return en||(en=new Intl.DateTimeFormat("en-GB",{month:"short",day:"numeric"})),en}function _o(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t);if(Number.isNaN(s.getTime()))return"";if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return Po().format(s);const i=Vl().format(s),r=String(s.getDate()),o=ql().format(s),a=s.getFullYear()===e.getFullYear()?"":String(s.getFullYear()).slice(-2);return`${r}${o}${a} ${i}`}catch{return""}}function Ne(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t),n=Po().format(s);if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return n;const r=zl().format(s),o=s.getFullYear()===e.getFullYear()?"":` ${s.getFullYear()}`;return`${r}${o} ${n}`}catch{return""}}function Et(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 Yl(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function Xl(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function bs(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function Bi(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!(bs(i)&&bs(n))}function Ql(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!(bs(n)&&bs(i))}function Di(t,e,s){let n=s;for(;n<t.length;){const i=t.indexOf(e,n);if(i<0)return-1;if(Ql(t,i,e))return i;n=i+e.length}return-1}function Jl(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 Zl(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function Gt(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 Ze(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 $o(t){return(t||[]).map(e=>e?.text||"").join("")}function ms(t){return Fe($o(t))}function ec(t,e){const s=Math.max(0,Number(e)||0);if(s<=0)return[];const n=[];let i=s;for(const r of t||[]){if(i<=0)break;const o=String(r?.text||"");if(!o)continue;const a=ts(o,i);a&&(n.push({...r,text:a}),i-=Fe(a))}return n}function Ro(t,e){const s=Math.max(0,Number(e)||0),n=ec(t,s),i=ms(n),r=Math.max(0,s-i);return r>0&&n.push({text:" ".repeat(r),color:null,bold:!1,underline:!1}),n}function Oo(t,e){const s=Math.max(1,Number(e)||1),n=[];let i=[],r=0;function o(){if(i.length===0){n.push([{text:"",color:null,bold:!1,underline:!1}]);return}n.push(i),i=[],r=0}for(const a of t||[]){let c=String(a?.text||"");if(c)for(;c.length>0;){const u=Math.max(1,s-r),p=ts(c,u);if(!p)break;if(p.length===c.length||Fe(p)<u){i.push({...a,text:p}),r+=Fe(p),c=c.slice(p.length),r>=s&&o();continue}const d=p.lastIndexOf(" ");if(d>0&&(r>0||d>0)){const f=p.slice(0,d+1);i.push({...a,text:f}),r+=Fe(f),c=c.slice(f.length),o()}else i.push({...a,text:p}),r+=Fe(p),c=c.slice(p.length),r>=s&&o()}}return(i.length>0||n.length===0)&&o(),n}function Hi(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function Lo(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 tc(t){const e=String(t||"");return Ss.lastIndex=0,[...e.matchAll(Ss)].map(s=>{const n=s[1],i=Lo(s[2]);return!n||!i?null:{sessionId:n,filename:i,uri:`artifact://${n}/${i}`}}).filter(Boolean)}function ut(t){const e=String(t||"");if(!e)return e;Ss.lastIndex=0;const s=e.replace(Ss,(n,i,r,o,a)=>{if(a.slice(Math.max(0,o-2),o)==="](")return n;const c=Lo(r);return!i||!c?n:`[artifact: ${c}](artifact://${i}/${c}) (press a to download)`});return Fi.lastIndex=0,s.replace(Fi,(n,i)=>i?`[session: ${ce(i)}](session://${i})`:n)}function Qn(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const r=Zl(e,"`",n),o="`".repeat(r),a=Xl(e,o,n+r);if(a>n+r-1){Ze(s,{type:"code",text:e.slice(n+r,a)}),n=a+r;continue}}if(e.startsWith("**",n)||e.startsWith("__",n)){const r=e.slice(n,n+2),o=Bi(e,n,r)?Di(e,r,n+2):-1;if(o>n+2){Ze(s,{type:"strong",text:e.slice(n+2,o)}),n=o+2;continue}}if(e[n]==="["){const r=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(r){Ze(s,{type:"link",text:r[1],href:r[2]}),n+=r[0].length;continue}}if(e.startsWith("<http://",n)||e.startsWith("<https://",n)){const r=e.indexOf(">",n+1);if(r>n+1){const o=e.slice(n+1,r);Ze(s,{type:"link",text:o,href:o}),n=r+1;continue}}if(e.startsWith("http://",n)||e.startsWith("https://",n)){let r=n;for(;r<e.length&&!/\s/u.test(e[r]||"");)r+=1;const{url:o,trailing:a}=Jl(e.slice(n,r));if(o){Ze(s,{type:"link",text:o,href:o}),a&&Ze(s,{type:"text",text:a}),n=r;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&Bi(e,n,e[n])){const r=e[n],o=Di(e,r,n+1);if(o>n+1){Ze(s,{type:"em",text:e.slice(n+1,o)}),n=o+1;continue}}let i=e.length;for(const r of["<https://","<http://","https://","http://","**","__","`","[","*","_"]){const o=e.indexOf(r,n+1);o!==-1&&o<i&&(i=o)}Ze(s,{type:"text",text:e.slice(n,i)}),n=i}return s.length>0?s:[{type:"text",text:""}]}function sc(t=""){return Qn(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 Kt(t){const e=Qn(t),s=[];for(const n of e){if(n.type==="code"){Gt(s,n.text,{color:"cyan"});continue}if(n.type==="strong"){Gt(s,n.text,{bold:!0});continue}if(n.type==="em"){Gt(s,n.text,{underline:!0});continue}if(n.type==="link"){Gt(s,n.text,{color:"cyan",underline:!0,href:n.href});continue}Gt(s,n.text)}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function vt(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function kt(t){const e=String(t||"").trim().replace(/^\|/,"").replace(/\|$/,""),s=[];let n="",i=!1;for(const r of e){if(i){n+=r,i=!1;continue}if(r==="\\"){i=!0;continue}if(r==="|"){s.push(n.trim()),n="";continue}n+=r}return s.push(n.trim()),s}function ws(t){return t.length>0&&t.every(e=>/^:?-+:?$/.test(String(e||"").replace(/\s+/g,"")))}function Fe(t){return Array.from(String(t||"")).length}function ts(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 Fo(t,e){const s=String(t||""),n=Math.max(0,e-Fe(s));return s+" ".repeat(n)}function Bo(t){return $o(Kt(t))}function nc(t,e){const s=Bo(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),i=[];let r="";const o=a=>{let c=a;for(;Fe(c)>e;){const u=ts(c,e);if(!u)break;r&&(i.push(r),r=""),i.push(u),c=c.slice(u.length)}return c};for(const a of n){const c=o(a);if(!c)continue;if(!r){r=c;continue}const u=`${r} ${c}`;Fe(u)<=e?r=u:(i.push(r),r=c)}return r&&i.push(r),i.length>0?i:[""]}function ic(t,e){const s=Math.max(1,...t.map(p=>p.length)),n=Math.max(s*3,e-(s*3+1)),i=Array.from({length:s},(p,d)=>Math.max(3,...t.map(f=>Fe(f[d]||"")))),r=Array.from({length:s},(p,d)=>Math.max(3,...t.map(f=>Math.max(0,...String(f[d]||"").split(/\s+/).filter(Boolean).map(m=>Fe(m)))))),o=Array.from({length:s},(p,d)=>Math.max(3,Math.min(Math.max(Fe(t[0]?.[d]||"")||3,r[d]),24)));if(i.reduce((p,d)=>p+d,0)<=n)return i;const c=o.slice();let u=n-c.reduce((p,d)=>p+d,0);if(u<0){const p=Math.max(3,Math.floor(n/s));return c.map((d,f)=>f===s-1?Math.max(3,n-p*(s-1)):p)}for(;u>0;){let p=0,d=-1/0;for(let f=0;f<s;f++){const m=i[f]-c[f];m>d&&(d=m,p=f)}if(d<=0){c[s-1]+=u;break}c[p]+=1,u-=1}return c}function rc(t,e){if(!t||t.length===0)return"";const s=Math.max(1,...t.map(f=>f.length)),i=t.map(f=>Array.from({length:s},(m,g)=>f[g]||"")).map(f=>f.map(m=>Bo(m))),r=ic(i,e),o=[],a=`┌${r.map(f=>"─".repeat(f+2)).join("┬")}┐`,c=`├${r.map(f=>"─".repeat(f+2)).join("┼")}┤`,u=`└${r.map(f=>"─".repeat(f+2)).join("┴")}┘`,p=f=>{const m=f.map((h,y)=>nc(h,r[y])),g=Math.max(...m.map(h=>h.length));for(let h=0;h<g;h++){const y=m.map((S,E)=>Fo(S[h]||"",r[E]));o.push(`│ ${y.join(" │ ")} │`)}};o.push(a),p(i[0]),o.push(c);const d=i.slice(1);for(const f of d)p(f);return o.push(u),o.join(`
3
- `)}function oc(t,e){const s=String(t||"").split(`
4
- `),n=[];let i=!1;for(let r=0;r<s.length;r++){const o=s[r];if(o.trim().startsWith("```")){i=!i,n.push(o);continue}if(i){n.push(o);continue}const c=s[r+1];if(!vt(o)||!vt(c)){n.push(o);continue}const u=kt(o),p=kt(c);if(!ws(p)||u.length!==p.length){n.push(o);continue}const d=[u];for(r+=1;r+1<s.length&&vt(s[r+1]);){r+=1;const f=kt(s[r]);ws(f)||d.push(f)}n.push(rc(d,e))}return n.join(`
5
- `)}function ac(t,e){const s=String(t||"");if(!s)return[""];const n=[];let i=s;for(;i.length>0;){const r=ts(i,e);if(!r)break;n.push(r),i=i.slice(r.length)}return n.length>0?n:[""]}function Gi(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",i=ts(n,Math.max(1,s-4)),r=Math.max(0,s-i.length-2);return[{text:`┌${i}${"─".repeat(r)}┐`,color:"gray"}]}function ji(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function Ui(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),i=[];for(const r of t){const o=ac(r,n);for(const a of o)i.push([{text:"│",color:"gray"},{text:Fo(a,n),color:"cyan"},{text:"│",color:"gray"}]);o.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 _t(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),i=e.tableMode==="sentinel"?"sentinel":"boxArt",o=(i==="boxArt"?oc(String(t||""),n):String(t||"")).split(`
6
- `);let a=!1,c="",u=[];for(let p=0;p<o.length;p+=1){const d=o[p],f=d.trim();if(f.startsWith("```")){a?(s.push(Gi(c,Math.max(8,n))),s.push(...Ui(u,Math.max(8,n))),s.push(ji(Math.max(8,n))),a=!1,c="",u=[]):(a=!0,c=f.slice(3).trim(),u=[]);continue}if(a){u.push(d);continue}if(i==="sentinel"&&d&&vt(d)){const S=o[p+1]||"";if(vt(S)){const E=kt(d),x=kt(S);if(ws(x)&&E.length===x.length){const w=[];let b=p+2;for(;b<o.length&&vt(o[b]);){const I=kt(o[b]);ws(I)||w.push(I),b+=1}s.push({kind:"markdownTable",header:E,rows:w}),p=b-1;continue}}}if(!d){s.push([{text:"",color:null}]);continue}const m=/^(#{1,6})\s+(.*)$/.exec(d);if(m){s.push([{text:m[2],color:"white",bold:!0}]);continue}const g=/^>\s?(.*)$/.exec(d);if(g){s.push([{text:"> ",color:"gray"},...Kt(g[1]).map(S=>({...S,color:S.color||"gray"}))]);continue}const h=/^\s*[-*]\s+(.*)$/.exec(d);if(h){s.push([{text:"• ",color:"gray"},...Kt(h[1])]);continue}const y=/^\s*(\d+)\.\s+(.*)$/.exec(d);if(y){s.push([{text:`${y[1]}. `,color:"gray"},...Kt(y[2])]);continue}s.push(Kt(d))}return a&&(s.push(Gi(c,Math.max(8,n))),s.push(...Ui(u,Math.max(8,n))),s.push(ji(Math.max(8,n)))),s}function me({title:t="SYSTEM",timestamp:e="",body:s="",width:n=80,titleColor:i="yellow",borderColor:r="gray",bodyColor:o=null,fitToContent:a=!1,tableMode:c=null}={}){const u=Math.max(a?12:20,Number(n)||(a?12:20)),p=Math.max(1,u-4),d=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:i,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]];if(c==="sentinel"){const x=_t(String(s||""),{width:p,tableMode:c}),w=o?x.map(b=>Array.isArray(b)?Hi(b,o):b):x;return[{kind:"cardStart",runs:d,borderColor:r},...w,{kind:"cardEnd"},[{text:"",color:null}]]}const f=_t(String(s||""),{width:p}),m=f.length>0?f.flatMap(x=>Oo(x,p)):[[{text:"",color:null}]],g=o?m.map(x=>Hi(x,o)):m,h=g.reduce((x,w)=>Math.max(x,ms(w)),0),y=a?Math.min(u,Math.max(12,ms(d)+3,h+4)):u,S=Math.max(1,y-4),E=Math.max(0,y-ms(d)-3);return[[{text:"┌─",color:r},...d,{text:`${"─".repeat(E)}┐`,color:r}],...g.map(x=>[{text:"│ ",color:r},...Ro(x,S),{text:" │",color:r}]),[{text:`└${"─".repeat(Math.max(1,y-2))}┘`,color:r}],[{text:"",color:null}]]}function Ft(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 Do(t){const e=Ft(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}const le=300,lc=[le,1e3,3e3,1e4],cc=["user.message","assistant.message","system.message","session.epoch_committed","session.regenerate_refused","session.regenerate_failed"];function Ho(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:Ne(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Go(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:Ne(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function jo(t){const e=t?.data&&typeof t.data=="object"?t.data:{},s=typeof e.error=="string"?e.error:"";return{id:`${t.sessionId}:${t.seq}:regen-failed`,kind:"regen-failed",role:"regen-failed",stage:typeof e.stage=="string"?e.stage:"unknown",error:s,time:Ne(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Re(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(le,Number(e)||le);return s.length>n?s.slice(-n):s}function Je(t){return String(t||"").replace(/\r\n/g,`
7
- `).trim()}function Wi(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 Uo=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,uc=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function Jn(t){return Uo.test(Je(t))}function st(t){const e=String(t||"").replace(/\r\n/g,`
8
- `).trim();if(!e)return"";const s=e.replace(uc,"").trimStart();return s!==e?s.trim():Jn(e)?e.replace(Uo,"").trim():e}function Wo(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 r=0;r<e.length;){const o=e[r];if(!/^\s*\[SYSTEM:/i.test(o)){n.push(o),r+=1;continue}const a=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(o);if(a){i(),s.push({kind:"system",text:a[1].trim()}),r+=1;continue}const c=[o.replace(/^\s*\[SYSTEM:\s*/i,"")];let u=-1;for(let p=r+1;p<e.length;p+=1){const d=e[p];if(d.trim()==="]"){u=p;break}if(/\]\s*$/.test(d.trim())){const f=d.replace(/\]\s*$/,"");f.trim()&&c.push(f),u=p;break}c.push(d)}if(u===-1){n.push(o),r+=1;continue}i(),s.push({kind:"system",text:c.join(`
12
- `).trim()}),r=u+1}return i(),s}function Ko(t,e){const s=String(t||"").replace(/\r\n/g,`
13
- `);return e==="user"||e==="assistant"?Wo(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
14
- `).trim():s.trim()}function dc(t,e){return e!=="user"&&e!=="assistant"?[]:Wo(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function Ki(t){const e=Je(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=Ko(e,t.role);if(s)return s}return st(e)}function Fs(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 r=e.slice(s.length,i),o=e.slice(i+n.length,-1);return!r.trim()||!o.trim()?null:{question:r,answer:o}}function pc(t){return Je(Xn(t)).length>0}function fc(t){const e=Je(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 hc(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(Je(t))}function yt(t,e){const s=String(t||""),n=`${e}=`,i=s.indexOf(n);if(i<0)return"";const r=s.slice(i+n.length),o=[" request_id="," from="," subject="," reason="," expects_response="," expires_at="," verdict="];let a=r.length;for(const c of o){const u=r.indexOf(c);u>=0&&(a=Math.min(a,u))}return r.slice(0,a).trim()}function mc(t,e){const s=Je(e);if(!s)return null;const n=/^\[SESSION_MESSAGE\s+([^\]]+)\]\n?/i.exec(s);if(n){const r=n[1],o=`
17
- Request body:
18
- `,a=s.indexOf(o),c=a>=0?s.slice(a+o.length).trim():s.slice(n[0].length).trim(),u=yt(r,"request_id"),p=yt(r,"from"),d=yt(r,"subject"),f=/\bexpects_response=true\b/i.test(r),m=[p?`From: session-${ce(p)}`:"",u?`Request ID: ${u}`:"",d?`Subject: ${d}`:"",f?"Response: required":"Response: not required","",c].filter((g,h)=>h===4||String(g||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:m.join(`
19
- `),time:Ne(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:f?"Session Request":"Session Message",cardTitleColor:"cyan",cardBorderColor:"cyan"}}const i=/^\[SESSION_MESSAGE_RESPONSE\s+([^\]]+)\]\n?/i.exec(s);if(i){const r=i[1],o=/^This is the requested cross-session response\.[^\n]*\n\n?/i,a=s.slice(i[0].length).trim().replace(o,"").trim(),c=yt(r,"request_id"),u=yt(r,"from"),p=yt(r,"verdict")||"answered",d=[u?`From: session-${ce(u)}`:"",c?`Request ID: ${c}`:"",`Verdict: ${p}`,"",a].filter((f,m)=>m===3||String(f||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:d.join(`
20
- `),time:Ne(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 gc(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&fc(s)?"system":e}function yc(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 Sc(t,e){if(!t||!e||t.role!==e.role)return!1;const s=Ki(t),n=Ki(e);if(!s||!n||s!==n)return!1;const i=yc(t,e);if(i!=null)return i;const r=Number(t.createdAt||0),o=Number(e.createdAt||0);return t.optimistic||e.optimistic?!0:!r||!o?!1:Math.abs(r-o)<=1e4}function At(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!Sc(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),r=Number(s?.createdAt||0),o=r>=i?s:n;if(o.role==="user"&&!n?.optimistic&&!s?.optimistic){const a=Math.min(Number(n?.firstDeliveredAt||i||1/0),Number(s?.firstDeliveredAt||r||1/0));e[e.length-1]={...o,redelivered:!0,...Number.isFinite(a)?{firstDeliveredAt:a}:{}};continue}e[e.length-1]=o}return e}function bc(t){return typeof t=="string"?t.replace(/^\[FROM:[^\]\n]*\]\n?/,""):t}function Ct(t,e){const s=Bt(t),n=mc(t,s);if(n)return n;const i=bc(Ko(s,e));if(!pc(i))return null;const r=Array.isArray(t?.data?.clientMessageIds)?t.data.clientMessageIds.filter(c=>typeof c=="string"&&c):[],o=t?.data?.sender&&typeof t.data.sender=="object"?t.data.sender:null,a=Array.isArray(t?.data?.attachments)?t.data.attachments.filter(c=>c&&typeof c.filename=="string"&&c.filename):[];return{id:`${t.sessionId}:${t.seq}`,role:gc(t,e,i),text:i,time:Ne(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...r.length>0?{clientMessageIds:r}:{},...o?{sender:o}:{},...a.length>0?{attachments:a}:{}}}function Vo(t){return t?.eventType!=="system.message"?!1:!hc(Bt(t))}function Is(t,e){return dc(Bt(t),e).map((s,n)=>Jt({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function wc(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=Je(e.text),n=Fs(e.text),i=n?Je(n.answer):"";let r=!1;return t.filter(o=>{if(r||!o?.optimistic||o.role!==e.role)return!0;const a=Je(o.text);return a!==s&&a!==i?!0:(r=!0,!1)})}function Bt(t){const e=t?.data;if(typeof e=="string")return e;if(e&&typeof e=="object"){if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;if(typeof e.message=="string")return e.message;if(typeof e.question=="string")return e.question}return Yl(e)}function Ic(t){return(t||[]).map(e=>e?.text||"").join("")}function xc(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function Zn(t=[]){const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();if(!i)continue;const r=i.toLowerCase();e.has(r)||(e.add(r),s.push(i))}return s.join(" | ")}function Ec(t,e=""){return Zn([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function vc(t,e=""){return Zn([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function kc(t,e=""){const s=Bt(t),n=st(e);return Zn([st(s),n,t?.data?.detail,t?.data?.message])}function Ac(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 Cc(t,e){if(!e||typeof e!="object")return"";if(t==="wait"){const i=e.seconds!=null?`${e.seconds}s`:"?",r=e.preserveWorkerAffinity===!0?" preserve=true":"",o=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${i}${r}${o}`}if(t==="cron"){if(e.action==="cancel")return" cancel";const i=e.seconds!=null?`${e.seconds}s`:"?",r=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${i}${r}`}const s=Object.entries(e).slice(0,4).map(([i,r])=>`${i}=${Ac(r)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function ei(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function ue(t,e,s,n="",i="white"){return[...ei(t),{text:e,color:s},...n?[{text:` ${n}`,color:i}]:[]]}function Tc(t,e=96){return xc(Xn(Bt(t)),e)||""}function tn(t,e,s="start"){const n=typeof e?.data?.toolCallId=="string"?e.data.toolCallId:"",i=typeof e?.data?.requestId=="string"?e.data.requestId:"",r=e?.data?.toolName||e?.data?.name||(n?`tool call ${n.slice(0,8)}`:i?`tool request ${i.slice(0,8)}`:"tool"),o=e?.data?.arguments||e?.data?.args,a=e?.data?.durableSessionId,c=Cc(r,o),u=s==="start"?"▶":s==="partial"?"…":"✓",p=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...ei(t),{text:`${u} ${r}${c}`,color:p},...a?[{text:` [sess ${ce(a)}]`,color:"gray"}]:[]]}function Jt(t){const e=Ne(t.createdAt),s=Tc(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=tn(e,t,"start");break;case"tool.execution_complete":n=tn(e,t,"complete");break;case"tool.execution_partial_result":n=tn(e,t,"partial");break;case"tool.execution_progress":{const i=(t?.data??{})||{},r=i.toolName||i.name||"tool",o=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=ue(e,"[tool]","cyan",`${r} ${o}`,"white");break}case"assistant.reasoning":n=ue(e,"[reasoning]","gray",s||"…","white");break;case"assistant.intent":{const i=(t?.data??{})||{},r=typeof i.summary=="string"&&i.summary?i.summary:typeof i.intent=="string"&&i.intent?i.intent:s||"";n=ue(e,"[intent]","gray",r||"…","white");break}case"assistant.turn_start":n=ue(e,"[turn start]","gray",s);break;case"session.turn_completed":n=ue(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=ue(e,"[lossy handoff]","yellow",vc(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=ue(e,"[dehydrated]","cyan",Ec(t,s));break;case"session.hydrated":case"session.rehydrated":n=ue(e,"[rehydrated]","green",s);break;case"session.wait_started":{const i=t?.data?.seconds!=null?`${t.data.seconds}s`:"?",r=typeof t?.data?.reason=="string"&&t.data.reason?` reason=${JSON.stringify(t.data.reason)}`:"",o=t?.data?.preserveAffinity?" preserve=true":"";n=ue(e,"[wait]","yellow",`${i}${o}${r}`.trim());break}case"session.input_required_started":n=ue(e,"[input]","yellow",s);break;case"session.agent_spawned":n=ue(e,"[spawn]","cyan",t?.data?.agentId||ce(t?.data?.childSessionId),"white");break;case"session.cron_started":n=ue(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=ue(e,"[cron]","magenta",`scheduled${t?.data?.nextFireAt?` ${Wi(t.data.nextFireAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_fired":n=ue(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=ue(e,"[cron]","magenta",`fired${t?.data?.scheduledAt?` ${Wi(t.data.scheduledAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_cancelled":case"session.cron_at_cancelled":n=ue(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=ue(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=ue(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=ue(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.compaction_start":case"session.compaction_complete":n=jl(e,t.eventType,t.data||{});break;case"session.error":n=ue(e,"[error]","red",s||"session error","white");break;case"system.message":Jn(Bt(t))?n=ue(e,"[rehydrated]","green",kc(t,s)||"conversation preserved"):n=ue(e,"[system]","gray",s||"system message");break;default:n=[...ei(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:Ic(n),line:n}}function Nc(t=le){const e=Math.max(le,Number(t)||le);return lc.find(n=>n>e)||Math.min(1e5,e*2)}function os(t=[],e={}){const s=Math.max(le,Number(e.requestedLimit??e.eventLimit??le)||le),n=[],i=[],r=[];for(const o of t){if(r.push(o),o.eventType==="user.message"){i.push(...Is(o,"user"));const c=Ct(o,"user");c&&n.push(c);continue}if(o.eventType==="assistant.message"){i.push(...Is(o,"assistant"));const c=Ct(o,"assistant");c&&n.push(c);continue}if(o.eventType==="system.message"){if(Vo(o)){const c=Jt(o);c&&i.push(c)}else{const c=Ct(o,"system");c&&n.push(c)}continue}if(o.eventType==="session.epoch_committed"){n.push(Ho(o));continue}if(o.eventType==="session.regenerate_refused"){n.push(Go(o));continue}if(o.eventType==="session.regenerate_failed"){n.push(jo(o));continue}const a=Jt(o);a&&i.push(a)}return{chat:At(n),activity:i,events:r.slice(-s),loadedEventLimit:s,loadedEventCount:r.length,hasOlderEvents:r.length>=s}}function Vi(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max(le,Number(t?.loadedEventLimit??le)||le),i=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),r={chat:Re(t?.chat||[],n),activity:Re(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(c=>typeof c=="string"&&c):[];if(a.length>0){const c=new Set([...r.stoppedMessageIds,...a]);r.stoppedMessageIds=Array.from(c),r.chat=r.chat.map(u=>Array.isArray(u.clientMessageIds)&&u.clientMessageIds.some(p=>c.has(p))?{...u,stopped:!0}:u)}return r}if(e.eventType==="user.message"){r.activity.push(...Is(e,"user")),r.activity=Re(r.activity,n);const a=Ct(e,"user");return a&&(Array.isArray(a.clientMessageIds)&&a.clientMessageIds.some(c=>r.stoppedMessageIds.includes(c))&&(a.stopped=!0),r.chat=wc(r.chat,a),r.chat.push(a),r.chat=Re(At(r.chat),n)),r}if(e.eventType==="assistant.message"){r.activity.push(...Is(e,"assistant")),r.activity=Re(r.activity,n);const a=Ct(e,"assistant");return a&&(r.chat.push(a),r.chat=Re(At(r.chat),n)),r}if(e.eventType==="system.message"){if(Vo(e)){const a=Jt(e);a&&(r.activity.push(a),r.activity=Re(r.activity,n))}else{const a=Ct(e,"system");if(!a)return r;r.chat.push(a),r.chat=Re(At(r.chat),n)}return r}if(e.eventType==="session.epoch_committed")return r.chat.push(Ho(e)),r.chat=Re(r.chat,n),r;if(e.eventType==="session.regenerate_refused")return r.chat.push(Go(e)),r.chat=Re(r.chat,n),r;if(e.eventType==="session.regenerate_failed")return r.chat.push(jo(e)),r.chat=Re(r.chat,n),r;const o=Jt(e);return o&&(r.activity.push(o),r.activity=Re(r.activity,n)),r}function sn(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,r=typeof i=="string"&&i.trim()?i:null,o=e?.isSystem?Ft(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:${o}`,role:"system",text:`${n}
21
-
22
- ${a}`,...r?{mobileText:`${r}
23
-
24
- ${a}`}:{},time:"",splash:!0}]}const Mc=.7,Pc=30,qi=36,nn=18,rn=18,on=0,qo=3,$t=6,Bs=10,_c=.25,$c=.5,Tt=6,xs=10,zo=.336,an=Tt,ln=xs,cn=$t,un=Bs;function Vt(t,e,s){return Math.max(e,Math.min(s,t))}function Rc(t){return[T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY].includes(t)?t:null}function Oc(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function Nt(t=""){const e=String(t||"").split(`
25
- `).length;return Vt(e,1,qo)}function Yo(t){return Math.max($t,Math.floor(t*_c))}function Xo(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*$c),n=Math.max($t,e-Bs);return Math.max($t,Math.min(n,s))}function Xt(t,e=0,s=1,n=0,i=0,r=null){const o=Oc(t),a=o.width,c=o.height,u=Vt(Number(s)||1,1,qo),p=Rc(r),d=5+u,f=Math.max(18,c-d),g=Math.floor(a*Mc)+(Number(e)||0),h=a-g-on;let y=!1,S=!1;g<=nn&&h>rn?y=!0:h<=rn&&g>nn?S=!0:g<=nn&&h<=rn&&(S=e>=0,y=!S);let E,x;y?(E=0,x=a):S?(E=a,x=0):(E=Vt(g,Pc,a-qi-on),x=Math.max(qi,a-E-on));const b=Yo(f)+(Number(n)||0),I=f-b;let k=!1,P=!1;I<=un&&b>cn?P=!0:b<=cn&&I>un?k=!0:I<=un&&b<=cn&&(P=(Number(n)||0)>=0,k=!P);let M,B;if(k)M=0,B=f;else if(P)M=f,B=0;else{const Pe=Xo(c,f);M=Vt(b,$t,Pe),B=Math.max(Bs,f-M)}const _=Math.max(Tt,Math.floor(f*zo))+(Number(i)||0),L=f-_;let W=!1,Y=!1;L<=ln&&_>an?W=!0:_<=an&&L>ln?Y=!0:L<=ln&&_<=an&&(W=(Number(i)||0)>=0,Y=!W);let te,ne;return W?(te=f,ne=0):Y?(ne=f,te=0):(te=Vt(_,Tt,Math.max(Tt,f-xs)),ne=Math.max(xs,f-te)),{viewport:o,totalWidth:a,totalHeight:c,reservedRows:d,bodyHeight:f,promptRows:u,fullscreenPane:p,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(i)||0,leftHidden:y,rightHidden:S,inspectorHidden:W,activityHidden:Y,sessionHidden:k,chatHidden:P,leftWidth:E,rightWidth:x,sessionPaneHeight:M,chatPaneHeight:B,activityPaneHeight:te,inspectorPaneHeight:ne}}function Nn(t){if(t?.fullscreenPane)return[t.fullscreenPane,T.PROMPT];if(t?.leftHidden)return[T.INSPECTOR,T.ACTIVITY,T.PROMPT];if(t?.rightHidden)return[...t?.sessionHidden?[T.CHAT]:t?.chatHidden?[T.SESSIONS]:[T.SESSIONS,T.CHAT],T.PROMPT];if(t?.sessionHidden){const e=t?.inspectorHidden?[T.ACTIVITY]:t?.activityHidden?[T.INSPECTOR]:[T.INSPECTOR,T.ACTIVITY];return[T.CHAT,...e,T.PROMPT]}if(t?.chatHidden){const e=t?.inspectorHidden?[T.ACTIVITY]:t?.activityHidden?[T.INSPECTOR]:[T.INSPECTOR,T.ACTIVITY];return[T.SESSIONS,...e,T.PROMPT]}return t?.inspectorHidden?[T.SESSIONS,T.CHAT,T.ACTIVITY,T.PROMPT]:t?.activityHidden?[T.SESSIONS,T.CHAT,T.INSPECTOR,T.PROMPT]:[T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY,T.PROMPT]}function Ye(t,e){const s=Nn(e);return s.includes(t)?t:s[0]||T.PROMPT}function Lc(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[T.PROMPT]:T.PROMPT,[T.ACTIVITY]:T.INSPECTOR,[T.INSPECTOR]:T.INSPECTOR}[t]||T.INSPECTOR:e?.rightHidden?{[T.PROMPT]:T.PROMPT,[T.CHAT]:e?.sessionHidden?T.CHAT:T.SESSIONS,[T.SESSIONS]:T.SESSIONS}[t]||(e?.sessionHidden?T.CHAT:T.SESSIONS):{[T.PROMPT]:e?.sessionHidden?T.CHAT:T.SESSIONS,[T.ACTIVITY]:e?.chatHidden?T.SESSIONS:T.CHAT,[T.INSPECTOR]:e?.chatHidden?T.SESSIONS:T.CHAT,[T.CHAT]:e?.sessionHidden?T.CHAT:T.SESSIONS,[T.SESSIONS]:T.SESSIONS}[t]||(e?.sessionHidden?T.CHAT:T.SESSIONS)}function Fc(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[T.PROMPT]:T.PROMPT,[T.INSPECTOR]:T.ACTIVITY,[T.ACTIVITY]:T.ACTIVITY}[t]||T.INSPECTOR:e?.rightHidden?{[T.PROMPT]:T.PROMPT,[T.SESSIONS]:e?.chatHidden?T.SESSIONS:T.CHAT,[T.CHAT]:T.CHAT}[t]||(e?.chatHidden?T.SESSIONS:T.CHAT):e?.inspectorHidden?{[T.PROMPT]:T.PROMPT,[T.SESSIONS]:T.CHAT,[T.CHAT]:T.ACTIVITY,[T.ACTIVITY]:T.ACTIVITY}[t]||T.CHAT:e?.activityHidden?{[T.PROMPT]:T.PROMPT,[T.SESSIONS]:T.CHAT,[T.CHAT]:T.INSPECTOR,[T.INSPECTOR]:T.INSPECTOR}[t]||T.CHAT:{[T.PROMPT]:T.PROMPT,[T.SESSIONS]:T.CHAT,[T.CHAT]:T.INSPECTOR,[T.INSPECTOR]:T.ACTIVITY,[T.ACTIVITY]:T.ACTIVITY}[t]||T.CHAT}function Qo(t){const e=String(t||"").trim();if(!e)return{error:"Paste a link to plugin.json or the folder that contains it."};let s;try{s=new URL(e)}catch{return{error:"That does not look like a URL — paste the browser link to plugin.json or its folder."}}const n=s.hostname.toLowerCase();if(n==="github.com"||n==="www.github.com"){const r=s.pathname.split("/").filter(Boolean);if(r.length<2)return{error:"GitHub links need at least github.com/org/repo."};const[o,a,c,u,...p]=r,d=a.replace(/\.git$/u,""),f=`https://github.com/${o}/${d}`;return c?c!=="blob"&&c!=="tree"?{error:`Unrecognized GitHub link shape (…/${c}/…) — use a /blob/ or /tree/ link, or the bare repo URL.`}:u?{kind:"github",repoUrl:f,ref:u,path:p.length?`/${p.join("/")}`:null}:{error:"That GitHub link is missing the branch segment."}:{kind:"github",repoUrl:f,ref:null,path:null}}if(n==="dev.azure.com"||n.endsWith(".visualstudio.com")){if(!s.pathname.includes("/_git/"))return{error:"Azure DevOps links must point at a repo (…/_git/<repo>…)."};const r=`${s.origin}${s.pathname.split("?")[0]}`.replace(/\/$/u,""),o=s.searchParams.get("path"),a=s.searchParams.get("version"),c=a&&/^G[BT]/u.test(a)?a.slice(2):a||null;return{kind:"ado",repoUrl:r,ref:c,path:o||null}}return{error:"Only GitHub and Azure DevOps links are recognized here — for a tarball use the URL tab."}}const Es=2*1024*1024,Bc=new Set(["node_modules",".git"]);function Mn(t){const e=t instanceof Uint8Array?t:new Uint8Array(t);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let s="";const n=32768;for(let i=0;i<e.length;i+=n)s+=String.fromCharCode.apply(null,e.subarray(i,i+n));return btoa(s)}function Jo(t){const e=String(t||"").replace(/\s+/gu,"");if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const s=atob(e),n=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)n[i]=s.charCodeAt(i);return n}function Zo(t){return t.split("/").some(e=>Bc.has(e))}function ea(t){const e=String(t||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.endsWith("/plugin.json")?e.slice(0,-12):e==="plugin.json"?"":e:""}function Dc(t,e){return t?`${t}/${e}`:e}function ta(t,e){const s=String(e?.message||e||"");return new Error(`could not reach ${t} from the browser (${s||"network error"}) — the host may block cross-origin reads from this portal; use Upload folder instead`)}async function vs(t,e,s,n){let i;try{i=await t(e,{headers:{accept:"application/json",...s}})}catch(r){throw ta(n,r)}if(!i.ok){const r=await i.text().catch(()=>"");throw new Error(`${n} returned HTTP ${i.status}${r?`: ${r.slice(0,200)}`:""}`)}return i.json()}async function sa(t,e,s,n){let i;try{i=await t(e,{headers:s})}catch(o){throw ta(n,o)}if(!i.ok)throw new Error(`${n} returned HTTP ${i.status} for ${e}`);const r=await i.arrayBuffer();return new Uint8Array(r)}function Hc(t){const e=new URL(t).pathname.split("/").filter(Boolean);if(e.length<2)throw new Error(`not a GitHub repository URL: ${t}`);return{owner:e[0],repo:e[1].replace(/\.git$/u,"")}}async function Gc({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:i,onProgress:r}){const{owner:o,repo:a}=Hc(t),c="https://api.github.com",u={"x-github-api-version":"2022-11-28",...i?{authorization:`Bearer ${i}`}:{}};let p=e;p||(r("resolving the default branch…"),p=(await vs(n,`${c}/repos/${o}/${a}`,u,"api.github.com"))?.default_branch||"main"),r(`reading the file tree of ${o}/${a}@${p}…`);const d=await vs(n,`${c}/repos/${o}/${a}/git/trees/${encodeURIComponent(p)}?recursive=1`,u,"api.github.com");if(d?.truncated)throw new Error("this repository's file tree is too large for the API listing — point the link at the package folder");const f=Array.isArray(d?.tree)?d.tree:[],m=ea(s),g=Dc(m,"plugin.json");if(!f.some(w=>w.type==="blob"&&w.path===g))throw new Error(`no plugin.json at ${g||"the repository root"} on ${p} — link to the folder that contains the manifest`);const h=m?`${m}/`:"",y=f.filter(w=>w.type==="blob"&&(!h||w.path.startsWith(h))&&!Zo(w.path.slice(h.length))),S=[];let E=0,x=0;for(const w of y){x+=1;const b=w.path.slice(h.length);r(`fetching ${x}/${y.length}: ${b}`);const I=i?await jc(n,c,o,a,w.sha,u):await sa(n,`https://raw.githubusercontent.com/${o}/${a}/${encodeURIComponent(p)}/${w.path.split("/").map(encodeURIComponent).join("/")}`,{},"raw.githubusercontent.com");if(E+=I.length,E>Es)throw new Error(`package exceeds the ${Math.round(Es/1024)} KB upload limit at ${b}`);S.push({path:b,contentBase64:Mn(I)})}return S}async function jc(t,e,s,n,i,r){const o=await vs(t,`${e}/repos/${s}/${n}/git/blobs/${i}`,r,"api.github.com"),a=String(o?.content||"").replace(/\s+/gu,"");if(o?.encoding&&o.encoding!=="base64")throw new Error(`unexpected blob encoding "${o.encoding}" from api.github.com`);return Jo(a)}function Uc(t){const e=new URL(t),s=e.pathname.split("/").filter(Boolean),n=s.indexOf("_git");if(n<0||n===s.length-1)throw new Error(`not an Azure DevOps repository URL: ${t}`);const i=decodeURIComponent(s[n+1]),r=s.slice(0,n).map(decodeURIComponent),o=e.hostname.toLowerCase(),a=o.endsWith(".visualstudio.com")?o.split(".")[0]:r[0],c=o.endsWith(".visualstudio.com")?r[0]:r[1];if(!a||!c)throw new Error(`could not read org/project from ${t}`);return{org:a,project:c,repo:i}}async function Wc({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:i,tokenKind:r,onProgress:o}){if(!i)throw new Error("Azure DevOps needs a credential — sign-in did not yield a token; paste a PAT with Code (read)");const{org:a,project:c,repo:u}=Uc(t),p=`https://dev.azure.com/${encodeURIComponent(a)}/${encodeURIComponent(c)}/_apis/git/repositories/${encodeURIComponent(u)}`,f={authorization:r==="pat"?`Basic ${Mn(new TextEncoder().encode(`:${i}`))}`:`Bearer ${i}`},m=ea(s),g=`/${m}`,h=e?`&versionDescriptor.version=${encodeURIComponent(e)}&versionDescriptor.versionType=branch`:"";o(`reading ${u}${m?`/${m}`:""}…`);const y=await vs(n,`${p}/items?scopePath=${encodeURIComponent(g)}&recursionLevel=Full${h}&api-version=7.1`,f,"dev.azure.com"),E=(Array.isArray(y?.value)?y.value:[]).filter(P=>P?.gitObjectType==="blob"&&!P?.isFolder),x=m?`/${m}/`:"/";if(!E.find(P=>P.path===`${x}plugin.json`.replace("//","/")))throw new Error(`no plugin.json under ${g} — link to the folder that contains the manifest`);const b=[];let I=0,k=0;for(const P of E){const M=String(P.path||"").slice(x.length);if(!M||Zo(M))continue;k+=1,o(`fetching ${k}/${E.length}: ${M}`);const B=await sa(n,`${p}/blobs/${encodeURIComponent(P.objectId)}?api-version=7.1&$format=octetStream`,{...f,accept:"application/octet-stream"},"dev.azure.com");if(I+=B.length,I>Es)throw new Error(`package exceeds the ${Math.round(Es/1024)} KB upload limit at ${M}`);b.push({path:M,contentBase64:Mn(B)})}return b}async function Kc(t,{fetchImpl:e=typeof fetch=="function"?fetch:null,token:s=null,tokenKind:n="bearer",onProgress:i=()=>{}}={}){if(typeof e!="function")throw new Error("no fetch implementation available");const r=Qo(t);if(r.error)throw new Error(r.error);const o={fetchImpl:e,token:s,tokenKind:n,onProgress:i},a=r.kind==="github"?await Gc(r,o):await Wc(r,o);if(a.length===0)throw new Error("the package folder is empty");return{kind:r.kind,files:a}}function Vc(t=[]){const e=(Array.isArray(t)?t:[]).find(s=>s?.path==="plugin.json");if(!e?.contentBase64)return null;try{const s=Jo(e.contentBase64),n=JSON.parse(new TextDecoder().decode(s));return String(n?.name||"").trim()||null}catch{return null}}function zi(t){return t?.isSystem?Do(t):Number.MAX_SAFE_INTEGER}function qc(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 zc(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return qc(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 Yc(t){if(t instanceof Map)return t;const e=new Map;if(!Array.isArray(t))return e;for(let s=0;s<t.length;s+=1){const n=t[s];typeof n!="string"||!n||e.has(n)||e.set(n,s)}return e}function Rt(t){return!!(t&&!t.isSystem&&!t.parentSessionId)}function Xc(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Yi(t,e){return!!(Xc(t)&&e&&e.has(t.sessionId))}function Xi(t,e){return t.isSystem?0:t.isGroup&&Yi(t,e)?1:Yi(t,e)?2:t.isGroup?3:4}function Qi(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function Ji(t,e,s,n,i){const r=Xi(t,n),o=Xi(e,n);if(r!==o)return r-o;const a=zi(t),c=zi(e);if(a!==c)return a-c;if(i&&i.size>0&&Rt(t)&&Rt(e)){const S=i.has(t.sessionId)?i.get(t.sessionId):1/0,E=i.has(e.sessionId)?i.get(e.sessionId):1/0;if(S!==E)return S-E}const u=s.get(t.sessionId),p=s.get(e.sessionId);if(typeof u=="number"&&typeof p=="number"&&u!==p)return u-p;const d=Qi(t),f=Qi(e);if(d>0&&f>0&&d!==f)return d-f;const m=(t.createdAt||0)-(e.createdAt||0);if(m!==0)return m;const g=String(t.title||""),h=String(e.title||""),y=g.localeCompare(h);return y!==0?y:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function je(t=[],e=new Set,s=[],n=null,i=null){const r=new Map,o=new Map,a=zc(s),c=Yc(i),u=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const h of t)r.set(h.sessionId,h);const p=[];for(const h of t){if(h.isGroup||!h.groupId||h.parentSessionId)continue;const y=`group:${h.groupId}`;if(r.has(y))continue;const S={sessionId:y,groupId:h.groupId,isGroup:!0,title:"Group",status:"group",shortSummary:"reconnecting…",createdAt:0,updatedAt:0};r.set(y,S),p.push(S)}const d=new Set(p.map(h=>h.sessionId));p.length>0&&(t=[...t,...p]);for(const h of t){const y=!h.isGroup&&h.groupId&&!h.parentSessionId&&r.has(`group:${h.groupId}`)?`group:${h.groupId}`:null,S=h.parentSessionId||y;!S||!r.has(S)||(o.has(S)||o.set(S,[]),o.get(S).push(h))}for(const h of o.values())h.sort((y,S)=>Ji(y,S,a,u,c));const f=t.filter(h=>!(h.parentSessionId||!h.isGroup&&h.groupId)).sort((h,y)=>Ji(h,y,a,u,c)),m=[];function g(h,y){const S=o.get(h.sessionId)||[];if(m.push({sessionId:h.sessionId,depth:y,hasChildren:S.length>0,collapsed:e.has(h.sessionId),...d.has(h.sessionId)?{standIn:h}:{}}),!e.has(h.sessionId))for(const E of S)g(E,y+1)}for(const h of f)g(h,0);return m}function Qc(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function dn(t){return Number.parseInt(t,16)/255}function Jc(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 pn(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Zc(t){const e=Jc(t);if(!e)return 0;const s=pn(dn(e.slice(1,3))),n=pn(dn(e.slice(3,5))),i=pn(dn(e.slice(5,7)));return .2126*s+.7152*n+.0722*i}function eu(t){const e=t?.page?.background||t?.tui?.background||t?.terminal?.background;return Zc(e)>=.5}function we({id:t,label:e,description:s,page:n,terminal:i,tui:r={},richChat:o=!1}){const a={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 Qc({id:t,label:e,description:s,richChat:!!o,page:n,terminal:i,tui:{...a,...r}})}const tu=we({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"}}),su=we({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",page:{background:"#f6f8fa",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"}}),nu=we({id:"workspace-dark",label:"Workspace Dark",description:"Flat workspace chrome: tone surfaces and hairlines instead of panel borders.",page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#272e37",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:"#161b22",border:"#272e37",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),iu=we({id:"workspace-dark-rich",label:"Workspace Dark — Rich Text",description:"Workspace Dark with the rich desktop-style chat transcript (portal only).",richChat:!0,page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#272e37",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:"#161b22",border:"#272e37",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),ru=we({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"}}),ou=we({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"}}),au=we({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"}}),lu=we({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"}}),cu=we({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"}}),uu=we({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"}}),du=we({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"}}),na=we({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"}}),pu=we({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"}}),fu=we({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"}}),hu=we({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"}}),mu=we({id:"win95",label:"Windows 95",description:"Authentic 3D-bevelled grey, navy title bars, teal desktop, and the 16-colour VGA terminal set.",page:{background:"#008080",foreground:"#000000",overlayBackground:"#c0c0c0",overlayForeground:"#000000",hintColor:"#5a5a5a",modalBackdrop:"rgba(0, 0, 0, 0.45)",modalBackground:"#c0c0c0",modalBorder:"#808080",modalForeground:"#000000",modalMuted:"#5a5a5a",modalSelectedBackground:"#000080",modalSelectedBorder:"#000080",modalSelectedForeground:"#ffffff"},terminal:{background:"#c0c0c0",foreground:"#000000",cursor:"#000080",cursorAccent:"#c0c0c0",selectionBackground:"#000080",black:"#000000",red:"#800000",green:"#008000",yellow:"#808000",blue:"#000080",magenta:"#800080",cyan:"#008080",white:"#c0c0c0",brightBlack:"#5a5a5a",brightRed:"#c00000",brightGreen:"#006000",brightYellow:"#7a5c00",brightBlue:"#0000c0",brightMagenta:"#a000a0",brightCyan:"#006a6a",brightWhite:"#000000"},tui:{surface:"#c0c0c0",border:"#808080",userChat:"#000080",userChatLabel:"#000080",activeHighlightBackground:"#000080",activeHighlightForeground:"#ffffff",selectionBackground:"#000080",selectionForeground:"#ffffff",promptCursorBackground:"#000080",promptCursorForeground:"#ffffff"}}),gu=we({id:"ms-dos",label:"MS-DOS 2.0",description:"CGA light-grey on black, the 16-colour CGA palette with brown, and CP437 box framing.",page:{background:"#000000",foreground:"#aaaaaa",overlayBackground:"#000000",overlayForeground:"#aaaaaa",hintColor:"#8f8f8f",modalBackdrop:"rgba(0, 0, 0, 0.78)",modalBackground:"#000000",modalBorder:"#aaaaaa",modalForeground:"#aaaaaa",modalMuted:"#8f8f8f",modalSelectedBackground:"#aaaaaa",modalSelectedBorder:"#ffffff",modalSelectedForeground:"#000000"},terminal:{background:"#000000",foreground:"#aaaaaa",cursor:"#aaaaaa",cursorAccent:"#000000",selectionBackground:"#aaaaaa",black:"#000000",red:"#aa0000",green:"#00aa00",yellow:"#aa5500",blue:"#0000aa",magenta:"#aa00aa",cyan:"#00aaaa",white:"#aaaaaa",brightBlack:"#8f8f8f",brightRed:"#ff5555",brightGreen:"#55ff55",brightYellow:"#ffff55",brightBlue:"#5555ff",brightMagenta:"#ff55ff",brightCyan:"#55ffff",brightWhite:"#ffffff"},tui:{surface:"#000000",border:"#aaaaaa",userChat:"#ffffff",userChatLabel:"#ffffff",activeHighlightBackground:"#aaaaaa",activeHighlightForeground:"#000000",selectionBackground:"#aaaaaa",selectionForeground:"#000000",promptCursorBackground:"#aaaaaa",promptCursorForeground:"#000000"}}),ia=Object.freeze([nu,iu,ou,tu,su,ru,cu,lu,au,uu,du,na,pu,fu,hu,mu,gu].sort((t,e)=>t.label.localeCompare(e.label,void 0,{sensitivity:"base"}))),yu=new Map(ia.map(t=>[t.id,t])),Su=na.id;function bu(){return ia}function Be(t){return t?yu.get(t)??null:null}const wu=new Set(["agent","user","system"]);function ks(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 Iu(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:wu.has(t.source)?t.source:"agent"}}function As(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const i of e){const r=Iu(i);!r||n.has(r.filename)||(n.add(r.filename),s.push(r))}return s}function xu(t,e){const s=String(e||"").trim();return s&&As(t).find(n=>n.filename===s)||null}function ti(t){const e=t&&typeof t=="object"?t:{},s=Number(e.paneAdjust),n=Number(e.sessionPaneAdjust),i=Number(e.portalSessionColumnAdjust),r=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(r)?Math.trunc(r):0}}function Cs(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 si(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 Pn(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 ra(t){if(t==null)return null;const e=String(t).trim();return e||null}function _n({mode:t="local",branding:e=null,docs:s=null,themeId:n=null,chatViewMode:i=null,sessionOwnerFilter:r=null,layoutAdjustments:o=null,pinnedSessionIds:a=null,collapsedSessionIds:c=null,activeSessionId:u=null,sessionOrder:p=null}={}){const d=r!=null,f=c!=null,m=ti(o);return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},docs:{agentPackageGuideUrl:s?.agentPackageGuideUrl||"https://github.com/affandar/PilotSwarm/blob/main/docs/building-agent-packages.md"},auth:{principal:null,authorization:null},ui:{focusRegion:T.SESSIONS,inspectorTab:We[0],nodeMapSelectedNode:null,sequenceExpandedTurns:[],sequenceSelectedTurn:null,chatViewMode:i==="summary"?"summary":"transcript",statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:Be(n)?.id||Su,modal:null,fullscreenPane:null,layout:{...m,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:{},groupRows:[],flat:[],activeSessionId:ra(u),collapsedIds:Pn(c),collapsedIdsExplicit:f,pinnedIds:Cs(a),manualOrder:si(p),listingSeen:!1,groupsListingSeen:!1,selectedIds:[],selectMode:!1,listDeselected:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:d,ownerFilter:ks(r),navigationIntent:null,filterExceptionId:null},history:{bySessionId:new Map},outbox:{bySessionId:{}},orchestration:{bySessionId:{}},executionHistory:{bySessionId:{},format:"pretty"},files:{bySessionId:{},fullscreen:!1,selectedArtifactId:null,markedIds:[],previewOrigin:null,restoreArtifactId: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},section:"ghcp",packages:{loading:!1,error:null,list:[],workerState:[],fetchedAt:0,selectedName:null,detail:null,detailLoading:!1,detailError:null,workspace:{tree:null,treeLoading:!1,treeError:null,expandedDirs:[],selectedPath:null,file:null,fileLoading:!1,fileError:null},action:{pending:null,error:null},addDialog:{open:!1,kind:"repo",scope:"user",updateName:null,repoUrl:"",ref:"",path:"",url:"",authToken:"",submitting:!1,progress:null,error:null}},workers:{loading:!1,error:null,list:[],fetchedAt:0,attempts:0,lastAttemptAt:0,lastSkip:null}}}}function oa(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function Eu(t,e){return!(!oa(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const aa="activeHighlightBackground",ni="activeHighlightForeground",fn="userChat",vu="userChatLabel",ku="otherUserChatLabel",Zi=new WeakMap,er=new WeakMap;function Au(t){return t||ni}function la(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Au(s?.color):ni,backgroundColor:aa,bold:s?.bold??!0}))}function Ke(t,{color:e=ni,bold:s=!0}={}){return{text:t,color:e,backgroundColor:aa,bold:s}}function Ue(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Cu=72;function ca(t){const e=Number(t)||0;return e>0&&e<=Cu}function ii(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function Tu(t){const e=ii(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function Nu(t){const e=ua(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function ua(t){return t?.rowVisualStatus||ii(t)}function da(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function ri(t){const e=ii(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&oa(t?.error)&&!da(t?.orchestrationStatus)?"warning":null}function pa(t,e="local"){const s=ri(t);if(s)return s;const n=ua(t);if(e==="remote"&&da(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 Mt(t,e="local"){switch(pa(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 fa(t,e="local"){switch(pa(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 de(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function Ds(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Mu=de({provider:"system",subject:"system"});function tr(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]}`.toUpperCase():(s[0]||e).replace(/[^A-Za-z0-9]/gu,"").slice(0,2).toUpperCase()}function $n(t){return tr(t?.displayName)||tr(t?.email)||"?"}function Pu(t,e=!1){return Rt(t)?e?"pinned":t.isGroup?"folders":t.groupId?`g:${t.groupId}`:"":null}function ha(t,{isMine:e=!1}={}){if(!t)return null;const s=Ds(t,t?.email||"");return{initials:$n(t),hue:Ou(Lu(t,t?.email)),name:s||"unknown user",isMine:!!e}}function _u(t){const e=new Map;for(const s of Object.values(t||{})){const n=s?.owner;if(!n?.subject||!n.displayName&&!n.email)continue;const i=de(n);i&&!e.has(i)&&e.set(i,n)}return e}function $u(t,e){if(t?.owner?.displayName||t?.owner?.email)return t.owner;const s=e?.get?.(de(t?.owner))||null;return s||(t?.createdBy?{email:t.createdBy}:null)}const Ru=8;function Ou(t){const e=String(t||"").trim().toLowerCase();if(!e)return 0;let s=2166136261;for(let n=0;n<e.length;n+=1)s^=e.charCodeAt(n),s=Math.imul(s,16777619)>>>0;return s%Ru}function Lu(t,e){return String(e||t?.email||t?.displayName||(t?.provider&&t?.subject?`${t.provider}:${t.subject}`:"")||"").trim().toLowerCase()}function Rn(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=de(n.owner);if(i&&(s.add(i),s.size>1))return!0}return!1}function ma(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function It(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of ma(t,e)){const i=de(n?.owner);i&&!s.has(i)&&s.set(i,n.owner)}return s.size===1?s.values().next().value:null}function sr(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function nr(t,e){const s=sr(t),n=sr(e?.agentId);return!!(s&&n&&s===n)}function Fu(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 o=e.slice(0,n).trim(),a=e.slice(n+s.length).trim();if(o&&nr(a,t))return{displayTitle:o,agentTitle:a}}const i=/^(.+?)\s+[–—-]\s+(.+)$/u.exec(e);if(i){const o=i[1].trim(),a=i[2].trim();if(o&&a)return{displayTitle:a,agentTitle:o}}const r=e.indexOf(": ");if(r>0){const o=e.slice(0,r).trim(),a=e.slice(r+2).trim();if(a&&nr(o,t))return{displayTitle:a,agentTitle:o}}return null}function Bu(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}}const Du=[[/&lt;/g,"<"],[/&gt;/g,">"],[/&quot;/g,'"'],[/&#0?39;/g,"'"],[/&apos;/g,"'"],[/&nbsp;/g," "],[/&amp;/g,"&"]];function Hu(t){let e=String(t??"");if(!e.includes("&"))return e;for(const[s,n]of Du)e=e.replace(s,n);return e}function Hs(t){return Hu(Gu(t))}function Gu(t){const e=String(t?.title||"").trim(),s=Fu(t);if(!s)return e;const n=Bu(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function ga(t,e){const s=ce(t?.sessionId);if(t?.isSystem)return`${Ft(t,e)} (${s})`;const n=Hs(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function ir(t,e={},s={},n=void 0){if(!e||e.all===!0||t?.isGroup)return!0;if(t?.isSystem)return e.includeSystem===!0;const i=de(n!==void 0?n:t?.owner);if(!i)return e.includeUnowned===!0;if(i===Mu)return e.includeSystem===!0;const r=de(s?.principal);return e.includeMe&&r&&i===r||e.includeShared===!0&&i!==r?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(i)}function ya(t,e={},s={},n=null){const i=It(t,n||{});if(ir(t,e,s,i))return!0;if(!n)return!1;if(t?.isGroup)return ma(t,n).some(a=>ya(a,e,s,n));let r=t,o=0;for(;r?.parentSessionId&&o<16;){const a=n[r.parentSessionId];if(!a)return!1;if(ir(a,e,s))return!0;r=a,o+=1}return!1}function ju(t){return(t||[]).map(e=>e?.text||"").join("")}function oi(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 rr(t){const{childMap:e}=oi(t),s=new Map;function n(i){if(s.has(i))return s.get(i);const o=(e.get(i)||[]).reduce((a,c)=>a+1+n(c),0);return s.set(i,o),o}for(const i of Object.keys(t||{}))n(i);return s}function or(t=[],e={}){const{parentMap:s}=oi(e),n=new Map;for(const i of t){let r=s.get(i.sessionId);for(;r;)n.set(r,(n.get(r)||0)+1),r=s.get(r)}return n}function ai(t={}){if(!t||typeof t!="object")return rr(t);const e=Zi.get(t);if(e)return e;const s=rr(t);return Zi.set(t,s),s}function li(t=[],e={}){if(!Array.isArray(t))return or(t,e);const s=er.get(t);if(s)return s;const n=or(t,e);return er.set(t,n),n}function Sa(t,e,s,n){const i=s.get(t)||0,r=n.get(t)||0,o=Math.max(0,i-r),a=e?.collapsed?i:o;return a?{text:`[+${a}]`,color:"cyan"}:null}function Ts(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 Uu(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${Ts(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${Et(t.cronInterval)}]`,color:"magenta"}:null}function ba(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Wu(t,e){const s=[];typeof t?.regenStage=="string"&&t.regenStage&&s.push({text:`↻ regen:${t.regenStage}`,color:"magenta"});const n=Nu(t);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:Mt(t,e)}));const i=hi(t?.model,t?.reasoningEffort);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i,color:"cyan"}));const r=Dl(t?.contextUsage);r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r.text,color:r.color}));const o=Hl(t?.contextUsage);return o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color})),s}function Ku(t,e,s,n,i){const r=[],o=s.connection?.mode||"local",a=t.depth>0?`${" ".repeat(Math.max(0,t.depth-1))}└ `:"";a&&r.push({text:a,color:"gray",role:"depth"});const c=new Set(Array.isArray(s.sessions?.pinnedIds)?s.sessions.pinnedIds:[]),u=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),p=!!s.sessions?.selectMode,d=u.has(t.sessionId),f=c.has(t.sessionId);if(d&&r.push({text:"▌",color:"cyan",bold:!0}),t.depth===0&&ba(e)&&c.size>0&&(f&&!e?.isSystem?r.push({text:"📌 ",color:"yellow"}):r.push({text:" ",color:"gray"})),e?.isGroup)r.push({text:"🗂 ",color:"cyan",bold:!0});else if(e?.isSystem)r.push({text:"⚙ ",color:"yellow",bold:!0});else if(e?.serviceKind)r.push({text:"⚗ ",color:"magenta",bold:!0});else{const Y=fa(e,o);r.push({text:Y?`${Y} `:" ",color:Mt(e,o),role:"status"})}const m=e?.isGroup?"cyan":e?.isSystem?"yellow":Mt(e,o),g=It(e,s.sessions?.byId||{}),h=ce(e?.sessionId),y=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,S=y?_p(y):"",E=hi(e?.model,e?.reasoningEffort),x=e?.isSystem?Ft(e,s.branding?.title||"PilotSwarm"):Hs(e),w=!!(e?.isSystem||e?.isGroup||x&&x.trim()),b=[...r];if(Rn(s)&&!e?.isSystem&&!e?.isGroup){const Y=de(s?.auth?.principal),te=!!(Y&&de(g)===Y),ne=g?$n(g):"?";b.push({text:`[${ne}] `,color:te?"green":"cyan",bold:!0,ownerChip:!0})}w?b.push({text:x,color:m,bold:!!(e?.isSystem||e?.isGroup)}):(b.push({text:h,color:m}),S&&(b.push({text:" · ",color:"gray"}),b.push({text:S,color:"gray"})),E&&(b.push({text:" · ",color:"gray"}),b.push({text:E,color:"green"})));const I=Sa(e?.sessionId,t,n,i);I&&b.push({text:` ${I.text}`,color:I.color,bold:I.bold});const k=Uu(e);k&&b.push({text:" ⏱",color:"magenta"});const P=[],M=e?.contextUsage?.compaction?.state,B=Yn(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&P.push({text:`${e.memberCount}`,color:"gray"}):M==="running"?P.push({text:"⇊",color:"magenta"}):M==="failed"?P.push({text:"!",color:"red"}):B!=null?P.push({text:`${B}%`,color:B>=85?"red":B>=70?"yellow":"green"}):P.push({text:"—",color:"gray"});const O=[];e?.isGroup&&e?.memberCount!=null&&(O.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),S&&(O.push({text:" · ",color:"gray"}),O.push({text:S,color:"gray"})));const _=[],L=()=>{_.length&&_.push({text:" · ",color:"gray"})};if(e?.isGroup)_.push(...O);else{w&&(_.push({text:h,color:"cyan"}),S&&(L(),_.push({text:S,color:"gray"})),E&&(L(),_.push({text:E,color:"green"})));const Y=e?.contextUsage;Y&&Number.isFinite(Y.currentTokens)&&Number.isFinite(Y.tokenLimit)&&Y.tokenLimit>0&&(L(),_.push({text:`ctx ${X(Y.currentTokens)}/${X(Y.tokenLimit)}`,color:"gray"}));const te=n?.[e?.sessionId];te&&(L(),_.push({text:`${te} child${te===1?"":"ren"}`,color:"gray"})),k&&(L(),_.push({text:k.text,color:k.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(L(),_.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...b,...w&&S&&!e?.isGroup?[{text:" ",color:"gray"},{text:S,color:"gray"}]:[],...P.length&&!e?.isGroup?[{text:" · ",color:"gray"},...P]:[],...e?.isGroup&&O.length?[{text:" ",color:"gray"},...O]:[]],titleRuns:b,ctxRuns:P,metaRuns:O,badgeRuns:[],selectedMetaRuns:_,detailRuns:_,childCount:n?.get?.(e?.sessionId)||0,chrome:{kind:e?.isGroup?"group":e?.isSystem?"system":e?.serviceKind?"service":"session",title:w?x:h,untitled:!w,statusColor:Mt(e,o),accentColor:m,pinned:f,selectMode:p,checked:d,owner:Rn(s)&&!e?.isSystem&&!e?.isGroup?{initials:g?$n(g):"?",isMine:!!(de(s?.auth?.principal)&&de(g)===de(s?.auth?.principal))}:null,childBadge:I?{text:I.text,color:I.color}:null,cron:!!k,age:S||null,model:E||null,shortId:h,ctx:P.length>0?{text:P[0].text,color:P[0].color}:null}}}function wa(t){return String(t||"").trim().toLowerCase()}function lt(t,e){const s=wa(e);return s?String(t||"").toLowerCase().includes(s):!0}function Vu(t){const e=t?.filterExceptionId||null,s=t?.byId||{};if(!e||!s[e])return null;const n=new Set([e]);let i=s[e],r=0;for(;i&&r<16;){let o=null;if(i.parentSessionId&&s[i.parentSessionId]?o=i.parentSessionId:!i.isGroup&&i.groupId&&s[`group:${i.groupId}`]&&(o=`group:${i.groupId}`),!o||n.has(o))break;n.add(o),i=s[o],r+=1}return n}const ar=new WeakMap;function qu(t,e){if(!t||t.length!==e.length)return!1;for(let s=0;s<t.length;s+=1)if(t[s]!==e[s])return!1;return!0}function Ot(t){const e=ai(t.sessions.byId),s=li(t.sessions.flat,t.sessions.byId),n=wa(t.sessions?.filterQuery||""),i=t.sessions?.ownerFilter||{all:!0},r=t.auth||{},o=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),a=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]),c=Vu(t.sessions);let u=ar.get(t.sessions.flat);return u||(u=new Map,ar.set(t.sessions.flat,u)),t.sessions.flat.filter(p=>!!(t.sessions.byId[p.sessionId]||p.standIn)).map(p=>{const d=t.sessions.byId[p.sessionId]||p.standIn,f=p.sessionId===t.sessions.activeSessionId&&!t.sessions.listDeselected,m=o.has(p.sessionId),g=a.has(p.sessionId),h=[p,d,f,m,g,n,i,r,t.connection?.mode,t.sessions.selectMode,e,s,t.branding?.title],y=u.get(p.sessionId);if(y&&qu(y.deps,h))return y.row;const S=Ku(p,d,t,e,s),E={sessionId:p.sessionId,text:ju(S.runs),...S,depth:p.depth,status:d?.status,statusColor:Mt(d,t.connection?.mode||"local"),active:f,groupId:d?.groupId||p?.groupId||null,isSystem:!!d?.isSystem,isGroup:!!d?.isGroup,hasChildren:p.hasChildren,collapsed:p.collapsed,pinned:m,selected:g,canPin:ba(d),ownerBadge:Rn(t)&&!d?.isSystem&&!d?.isGroup&&It(d,t.sessions.byId)?ha(It(d,t.sessions.byId),{isMine:!!(de(t?.auth?.principal)&&de(It(d,t.sessions.byId))===de(t?.auth?.principal))}):null,orderable:Rt(d),orderContainer:Pu(d,m)};return u.set(p.sessionId,{deps:h,row:E}),E}).filter(p=>{if(c?.has(p.sessionId))return!0;const d=t.sessions.byId[p.sessionId];if(!ya(d,i,r,t.sessions.byId))return!1;const f=It(d,t.sessions.byId),m=f?`${Ds(f,"")} ${f.email||""}`:"",g=`${d?.shortSummary||""} ${d?.summaryState?.intent||""} ${d?.summaryState?.summary||""}`;return lt(p.text,n)||lt(p.sessionId,n)||lt(m,n)||lt(g,n)})}function On(t,e=8){const s=Ot(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)),r=i.findIndex(d=>d.sessionId===t.sessions.activeSessionId),o=Math.max(0,r);if(i.length<=e)return s;const a=Math.floor(e/2);let c=Math.max(0,o-a),u=Math.min(i.length,c+e);u>i.length&&(u=i.length,c=Math.max(0,u-e));const p=i.slice(c,u);return ai(t.sessions.byId),li(i,t.sessions.byId),s.filter(d=>p.some(f=>f.sessionId===d.sessionId))}function De(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function zu(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 Lg(t){const e=t.sessions?.filterExceptionId||null;return!e||!t.sessions?.byId?.[e]?null:"Showing linked session outside your current filters."}function Ia(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function Yu(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 Xu(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),i=String(s?.answer||"").trim();if(!n||!i||xa(e,n))return null;const r=s.pendingPhase==="queued"?"queued":"pending",o=Number(s.answeredAt||0)||t.updatedAt||Date.now();return{id:`answered-question:${t.sessionId}:${n}:${o}`,role:"user",text:`The user was asked: "${n}"
27
- The user responded: "${i}"`,time:"",createdAt:o,optimistic:!0,pendingPhase:r}}function Qu(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 xa(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>Fs(n?.text||"")?.question?.trim()===s):!1}function Ju(t){const e=String(t?.error||"").trim();if(!e)return null;const s=ri(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 lr(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 Zu(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function ed(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 r=s[i];if(!r||n.has(r.eventType)||Number(r?.seq||0)<=e)continue;const o=Zu(r.text);if(o)return{...r,summaryText:o}}return null}function td(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 r=(s||[]).filter(b=>b?.role==="user"||b?.role==="assistant"),o=r[r.length-1]||null,a=o?.role==="user",c=a&&o?.optimistic===!0,u=(n||[]).filter(b=>b?.phase==="pending").length,p=(n||[]).filter(b=>b?.phase==="queued").length,d=(n||[]).filter(b=>b?.phase==="cancelling").length,f=Array.isArray(e?.events)?e.events:[],m=lr(f,"user.message"),g=lr(f,"assistant.message"),h=m>g;if(i==="waiting"||i==="input_required"||!a&&!h&&i!=="running"&&!c)return null;const y=Math.max(m,g),S=f.filter(b=>b?.eventType==="assistant.reasoning"&&Number(b?.seq||0)>y),E=S[S.length-1]||null,x=String(E?.data?.content||E?.data?.text||E?.data?.message||"").trim();if(x)return{kind:"thinking",label:"Thinking",text:x,createdAt:E?.createdAt||t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:g,tokenSeq:E?.seq||0};const w=ed(e,y);return w?.summaryText?{kind:i==="running"?"working":"sending",label:i==="running"?"Working":"Sending",text:w.summaryText,createdAt:w.createdAt||t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:g,tokenSeq:w.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:m,lastAssistantSeq:g,tokenSeq:0}:p>0?{kind:"queued",label:p===1?"Queued":`Queued ${p}`,text:p===1?"One prompt is durably queued, waiting for the LLM to receive it.":`${p} prompts are durably queued, waiting for the LLM to receive them.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:g,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:m,lastAssistantSeq:g,tokenSeq:0}:c?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:o?.createdAt||t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:g,tokenSeq:0}:i==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:g,tokenSeq:0}:null}function Gs(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return sn(t.branding);if(s?.isGroup){const u=Object.values(t.sessions.byId||{}).filter(m=>m&&!m.isGroup&&m.groupId===s.groupId&&!m.parentSessionId),p=m=>String(m??"").replace(/\|/g,"\\|").replace(/[\r\n]+/g," ").trim()||" ",d=u.map(m=>`| ${p(m.title||m.sessionId)} | ${p(m.status||"unknown")} | ${p(m.shortSummary||"")} |`),f=[`# ${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:f.filter((m,g)=>g===1||String(m||"").length>0).join(`
30
- `),createdAt:s.updatedAt||Date.now()}]}if(t.ui?.chatViewMode==="summary")return sd(s);const n=t.history.bySessionId.get(e),i=n?.chat||[],r=s?.pendingQuestion?.question&&!xa(i,s.pendingQuestion.question)?Yu(s):null,o=Xu(s,i),a=Ju(s);if((!n||i.length===0)&&!r&&!o&&!a)return sn(t.branding,s);const c=i.length>0?[...i]:sn(t.branding,s);return r&&c.push(r),o&&c.push(o),a&&c.push(a),c}function sd(t){const e=u=>{const p=String(u||"");return p.includes("\\n")?p.replace(/\\\\n/g,`
31
- `).replace(/\\n/g,`
32
- `):p},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=Hs(t)||t?.title||t?.sessionId||"Session",r=[];r.push(`# ${i}`),r.push("");const o=[],a=Tu(t);if(a&&o.push(["Status",a]),s?.intent&&o.push(["Intent",String(s.intent)]),t?.summaryUpdatedAt){const u=Ne(t.summaryUpdatedAt);u&&o.push(["Updated",u])}for(const[u,p]of o)r.push(`**${u}:** ${p}`);o.length>0&&r.push("");const c=e(s?.summary||t?.shortSummary||"").trim();if(c&&(r.push(c),r.push("")),n){const u=Object.entries(n).filter(([,p])=>p!=null&&!(typeof p=="string"&&!p.trim()));if(u.length>0){r.push("## State");for(const[p,d]of u)if(Array.isArray(d))if(d.length===0)r.push(`- **${p}:** _(empty)_`);else{r.push(`- **${p}:**`);for(const f of d.slice(0,16)){const m=typeof f=="string"?e(f):JSON.stringify(f);r.push(` - ${m}`)}}else if(d&&typeof d=="object"){r.push(`- **${p}:**`);for(const[f,m]of Object.entries(d).slice(0,16)){const g=typeof m=="string"?e(m):JSON.stringify(m);r.push(` - **${f}:** ${g}`)}}else r.push(`- **${p}:** ${e(String(d))}`);r.push("")}}for(const[u,p]of[["Blockers","blockers"],["Open Questions","openQuestions"],["Next Actions","nextActions"]]){const d=Array.isArray(s?.[p])?s[p].filter(Boolean).slice(0,12):[];if(d.length!==0){r.push(`## ${u}`);for(const f of d)r.push(`- ${typeof f=="string"?e(f):JSON.stringify(f)}`);r.push("")}}for(!s&&!c&&r.push("_No summary has been written yet for this session._");r.length>0&&r[r.length-1]==="";)r.pop();return[{id:`summary:${t?.sessionId||"none"}`,role:"system",noChrome:!0,text:r.join(`
33
- `),createdAt:t?.summaryUpdatedAt||t?.updatedAt||Date.now()}]}function nd(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>Qu(e,s)).filter(Boolean):[]:[]}function hn(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function Ea(t,e={}){const s=Ne(t?.createdAt||t?.time),n=t?.sender,i=n?.kind==="user"?de(n):null,r=e?.viewerKey||null,o=e?.ownerKey||null,a=e?.sharedContext===!0,c=t?.role==="user",p=a&&c&&i&&!(c&&i&&r&&i===r),f=a&&c&&o&&(i&&i===o||!i&&r&&r===o)?" (owner)":"",m=c?(p?n.display||n.subject||"User":"You")+f:t?.role==="assistant"?"Agent":t?.role==="system"?"System":"PilotSwarm";let g=null,h=null;t?.pendingPhase==="pending"?(g="○",h="yellow"):t?.pendingPhase==="queued"?(g="✓",h="cyan"):t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?(g="x",h="red"):t?.role==="user"&&!t?.optimistic&&!t?.pendingPhase&&(t?.stopped?(g="⊘",h="yellow"):t?.redelivered?(g="✓✓↻",h="yellow"):(g="✓✓",h="green"));const y=t?.pendingPhase==="pending"?"yellow":t?.pendingPhase==="queued"?"cyan":t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?"red":p?ku:t?.role==="user"?vu:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white";return{time:s,glyph:g,glyphColor:h,roleLabel:m,roleColor:y,fromOtherPerson:p}}function id(t,e={}){const{time:s,glyph:n,glyphColor:i,roleLabel:r,roleColor:o}=Ea(t,e),a=s?`[${s}] `:"",c=[...hn(a,"gray")];return n&&c.push(...hn(`${n} `,i)),c.push(...hn(`${r}: `,o,{bold:!0})),c}function nt(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function va(){return[{text:"",color:null}]}function rd(t){const e=(t||[]).find(n=>nt(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=nt(e).trimStart();return/^[┌│└]/.test(s)}function Ns(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(nt(s).trim().length>0)break;e.shift()}return e}function od(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(),r=e.slice(n+2).trim();if(r.startsWith("[SYSTEM:"))return{leadingText:i,systemText:r.slice(8,-1).trim()}}return ad.test(s)?{leadingText:"",systemText:s}:null}const ad=/^(?: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 ci(t){const e=od(t);if(e){const o=[];e.leadingText&&o.push({kind:"text",text:e.leadingText});const a=st(e.systemText);return a&&o.push({kind:"system",text:a}),o}const s=String(t||"").replace(/\r\n/g,`
37
- `).split(`
38
- `),n=[];let i=[];function r(){i.length!==0&&(n.push({kind:"text",text:i.join(`
39
- `)}),i=[])}for(let o=0;o<s.length;){const a=s[o];if(!/^\s*\[SYSTEM:/i.test(a)){i.push(a),o+=1;continue}const c=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(a);if(c){r();const f=st(c[1].trim());if(!f){o+=1;continue}n.push({kind:"system",text:f}),o+=1;continue}const u=[a.replace(/^\s*\[SYSTEM:\s*/i,"")];let p=-1;for(let f=o+1;f<s.length;f+=1){const m=s[f];if(m.trim()==="]"){p=f;break}if(/\]\s*$/.test(m.trim())){const g=m.replace(/\]\s*$/,"");g.trim()&&u.push(g),p=f;break}u.push(m)}if(p===-1){i.push(a),o+=1;continue}r();const d=st(u.join(`
40
- `).trim());if(!d){o=p+1;continue}n.push({kind:"system",text:d}),o=p+1}return r(),n}function ld(t){return t?t?.role==="system"?!Jn(t?.text||"")||!!st(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:ci(t?.text||"").some(e=>e.kind==="system"):!1}function cr(t){return ld(t)?"system":t?.role||"other"}function ka(t,e){return!t||!e?!1:cr(t)!==cr(e)}function cd(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 ud(t,e=""){const s=cd(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:ut(t),color:"gray"}}function ur({title:t,summary:e,body:s,timestamp:n="",color:i="gray"}){const r=String(t||"System").trim()||"System",o=String(e||"").replace(/\s+/g," ").trim();return{kind:"systemNotice",text:`${n?`[${n}] `:""}${r}${o?`: ${o}`:""}`,summary:o,body:ut(s||o),color:i}}function dd(t){return t?.label?[{text:t.label,color:t.kind==="working"?"yellow":"cyan",bold:!0}]:null}function pd(t,e){return e?(t||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||e})):s):t}function fd(t){const e=(t||[]).find(s=>nt(s).trim().length>0);return e?nt(e).trimStart().startsWith("┌"):!1}function Ms(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&fd(e)&&nt(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function hd(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=[],r=/(?:^|\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 o;for(;(o=r.exec(e))!==null;)i.push({agentId:o[1],task:o[2],status:o[3],result:o[4].trim()});return i.length===0?null:s||i.length===1?{kind:"subAgentSingle",...i[0]}:{kind:"subAgentMulti",agents:i}}function md(t,e,s){const n=Math.max(20,Number(s)||20),i=Ne(e?.createdAt||e?.time),r=hd(t),o=a=>{const c=String(a||"").replace(/^session-/i,"");return ce(c)||c||String(a||"")};if(r?.kind==="subAgentSingle"){const a=o(r.agentId),c=[r.task?`**Task:** ${r.task}`:"",r.status?`**Status:** ${r.status}`:"","",r.result||"_(no result)_"].filter((u,p)=>p===2||u).join(`
41
- `);return[ur({title:`Sub-agent Response — ${a}`,summary:r.status||"completed",timestamp:i,body:c,color:"cyan"})]}if(r?.kind==="subAgentMulti"){const a=r.agents.map(u=>{const p=o(u.agentId),d=u.task?`**Task:** ${u.task}`:"",f=u.status?`**Status:** ${u.status}`:"";return`${[`### ${p}`,d,f].filter(Boolean).join(`
42
- `)}
43
-
44
- ${u.result||"_(no result)_"}`}),c=r.agents.map(u=>`${o(u.agentId)} ${u.status||"completed"}`).join(" · ");return[ur({title:`Sub-agent Responses (${r.agents.length})`,summary:c,timestamp:i,body:a.join(`
45
-
46
- ---
47
-
48
- `),color:"cyan"})]}return me({title:"System",timestamp:i,body:t,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function gd(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),i=Ne(t?.createdAt||t?.time),r=String(t?.thinkingLabel||"Thinking…").trim()||"Thinking…",o=t?.progressKind==="working"?"yellow":(t?.progressKind==="sending","cyan"),a=oe([{text:` ⠋ ${r} `,color:o,bold:!0},...i?[{text:` ${i} `,color:"gray"}]:[]],Math.max(1,s-3)),c=a.reduce((f,m)=>f+String(m?.text||"").length,0),u=Math.max(0,s-c-3),p=String(t?.text||"").trim()?Ns(_t(ut(t.text),{width:n})).flatMap(f=>Oo(f,n)):[],d=[[{text:"┌─",color:"gray"},...a,{text:`${"─".repeat(u)}┐`,color:"gray"}]];for(const f of p)d.push([{text:"│ ",color:"gray"},...Ro(f.map(m=>({...m,color:m?.color&&m.color!=="white"?m.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 yd(t){return String(t||"").split(`
49
- `).reduce((e,s)=>Math.max(e,Xn(s).length),0)}function Lt(t,e,s={}){if(t?.splash){const u=t.mobileText&&yd(t.text)>e;return[{kind:"markup",value:u?t.mobileText:t.text,splashAlt:!u&&t.mobileText?t.mobileText:null}]}if(t?.thinking)return gd(t,e);if(t?.noChrome)return Ns(_t(ut(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const u=Fs(t?.text||"");if(u)return[...me({title:"Question",timestamp:Ne(t?.createdAt||t?.time),body:u.question,width:Math.max(20,e),titleColor:fn,borderColor:fn,tableMode:s.tableMode}),...Lt({...t,text:u.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const u=ci(t?.text||"");if(u.some(p=>p.kind==="system")){const p=[];let d=!1;for(const m of u)m.kind!=="system"&&m.text.trim()&&(Ms(p,Lt({...t,text:m.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:d})),d=!0);if(p.length>0)return p;const f=[];for(const m of u)m.kind!=="system"||!m.text.trim()||Ms(f,md(m.text,t,e));if(f.length>0)return f}}if(t?.role!=="user"&&t?.role!=="assistant"){const u=st(t?.text||"");if(t?.role==="system"&&!u)return[];const p=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!p)return[ud(u||t?.text||"",Ne(t?.createdAt||t?.time))];const d=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return me({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:Ne(t?.createdAt||t?.time),body:ut(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=Ns(_t(ut(t?.text||""),{width:e,tableMode:s.tableMode})),i=pd(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?fn:null),r=s.skipPrefix?[]:id(t,s),o=Aa(t,s);if(i.length===0){const u=r.length>0?[r]:[];return o.length>0?[...u,...o]:u}if(rd(i)){const u=r.length>0?[r,...i]:i;return o.length>0?[...u,...o]:u}const a=[];let c=r.length===0;for(const u of i){if(!Array.isArray(u)){c||(a.push(r),c=!0),a.push(u);continue}c?a.push(u):(a.push([...r,...u]),c=!0)}return a.push(...o),a}function Aa(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,r=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?` · ${r}`:""}]`,color:"cyan"}]})}const Sd=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 bd(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),r=s%60;return`${i}h ${String(r).padStart(2,"0")}m`}const wd=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),Id=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function xd(t,e){const s=String(t||"").toLowerCase();return s==="search_skills"||s.includes("skill")?e?"loading skills…":"loaded skills":wd.has(s)?e?"reading facts…":"read facts":Id.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 Ed(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=xd(n,e==="tool.execution_start");if(i)return i;const r=n.length>28?`${n.slice(0,27)}…`:n;return e==="tool.execution_start"?`running tool: ${r}…`:`finished tool: ${r}`}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 ui(t,e={}){if(t?.ui?.chatViewMode==="summary")return[];const s=De(t);if(!s||s.isGroup)return[];if(String(s?.status||"").toLowerCase()!=="running")return[];const i=t.history?.bySessionId?.get(s.sessionId)||null,r=Array.isArray(i?.chat)?i.chat:[];let o=0;for(let E=r.length-1;E>=0;E-=1)if(r[E]?.role==="user"){o=Number(r[E]?.createdAt||0);break}const a=Array.isArray(i?.activity)?i.activity:[];let c=0,u=0;for(let E=a.length-1;E>=0;E-=1){const x=a[E],w=x?.eventType,b=Number(x?.createdAt||0);if(!c&&w==="assistant.turn_start"&&(c=b),!u&&(w==="assistant.turn_end"||w==="session.turn_completed")&&(u=b),c&&u)break}let p=0;o>u?p=o:c>u&&(p=c);let d=null;for(let E=a.length-1;E>=0;E-=1){const x=a[E];if(!(!x||Sd.has(x.eventType))){if(Number(x.createdAt||0)<=u)break;d=x;break}}const f=Number.isFinite(e.now)?e.now:Date.now(),m=p>0?bd(f-p):"",g=String(e.spinnerFrame||"").trim()||"●",h=d?Ed(d):"",y=[{text:`${g} `,color:"cyan"},{text:"Working",color:"cyan"},...m?[{text:` · ${m}`,color:"gray"}]:[],...h?[{text:` — ${h}`,color:"gray"}]:[]],S=Math.max(24,Math.min(120,Math.floor(Number(e.maxWidth)||80)));return[oe(y,S)]}const dr=4;let as=[];function di(t,e=80,s={}){const n=t?.sessions?.activeSessionId??null,i={sessionId:n,session:n?t?.sessions?.byId?.[n]??null:null,byId:t?.sessions?.byId??null,chat:t?.history?.bySessionId?.get?.(n)?.chat??null,viewMode:t?.ui?.chatViewMode??null,branding:t?.branding??null,principal:t?.auth?.principal??null,maxWidth:e,tableMode:s?.tableMode??null};for(const g of as)if(g.sessionId===i.sessionId&&g.session===i.session&&g.byId===i.byId&&g.chat===i.chat&&g.viewMode===i.viewMode&&g.branding===i.branding&&g.principal===i.principal&&Object.is(g.maxWidth,i.maxWidth)&&g.tableMode===i.tableMode)return g.lines;const r=g=>(as.unshift({...i,lines:g}),as.length>dr&&(as.length=dr),g),o=Gs(t);if(!o||o.length===0)return r([{text:"No messages yet.",color:"gray"}]);const a=de(t?.auth?.principal),c=t?.sessions?.activeSessionId,u=c?t?.sessions?.byId?.[c]:null,p=de(u?.owner),d=!!(u&&(u.visibility&&u.visibility!=="private"||p&&a&&p!==a)),f={...s?.tableMode?{tableMode:s.tableMode}:{},...a?{viewerKey:a}:{},...p?{ownerKey:p}:{},...d?{sharedContext:!0}:{}},m=[];for(const[g,h]of o.entries()){if(h?.kind==="epoch-divider")m.push(Ca(h,e));else if(h?.kind==="regen-refused")m.push(Ta(h,e));else if(h?.kind==="regen-failed")m.push(Na(h,e));else{const S=Lt(h,e,f);Ms(m,S)}const y=o[g+1];y&&ka(h,y)&&nt(m[m.length-1]).trim().length>0&&m.push(va())}return r(m.length>0?m:[{text:"No messages yet.",color:"gray"}])}function vd(t){return!(!t||t.kind==="epoch-divider"||t.kind==="regen-refused"||t.kind==="regen-failed"||t.splash||t.thinking||t.noChrome||t.role!=="user"&&t.role!=="assistant"||t.role==="user"&&Fs(t?.text||"")||ci(t?.text||"").some(s=>s.kind==="system"))}const pr=new WeakMap;function kd(t,e=80,s={}){const n=Gs(t);if(!n||n.length===0)return[];const i=de(t?.auth?.principal),r=t?.sessions?.activeSessionId,o=r?t?.sessions?.byId?.[r]:null,a=de(o?.owner),c=!!(o&&(o.visibility&&o.visibility!=="private"||a&&i&&a!==i)),u={...s?.tableMode?{tableMode:s.tableMode}:{},...i?{viewerKey:i}:{},...a?{ownerKey:a}:{},...c?{sharedContext:!0}:{}},p=[];for(const d of n){const f=d?pr.get(d):null;if(f&&Object.is(f.text,d.text)&&Object.is(f.kind,d.kind)&&Object.is(f.role,d.role)&&Object.is(f.id,d.id)&&Object.is(f.pendingPhase,d.pendingPhase)&&Object.is(f.stopped,d.stopped)&&Object.is(f.createdAt,d.createdAt)&&Object.is(f.time,d.time)&&Object.is(f.sender,d.sender)&&Object.is(f.attachments,d.attachments)&&Object.is(f.tableMode,u.tableMode)&&Object.is(f.viewerKey,u.viewerKey)&&Object.is(f.ownerKey,u.ownerKey)&&Object.is(f.sharedContext,u.sharedContext)){p.push(f.block);continue}if(d?.kind==="epoch-divider"){p.push({kind:"lines",variant:"divider",lines:[Ca(d,e)]});continue}if(d?.kind==="regen-failed"){p.push({kind:"lines",variant:"divider",lines:[Na(d,e)]});continue}if(d?.kind==="regen-refused"){p.push({kind:"lines",variant:"divider",lines:[Ta(d,e)]});continue}if(vd(d)){const h=Aa(d,{tableMode:"sentinel"}).find(S=>S?.kind==="imageAttachments")||null,y={kind:"message",id:d?.id??null,role:d.role,header:Ea(d,u),text:ut(d?.text||""),pendingPhase:d?.pendingPhase||null,attachments:h?{sessionId:h.sessionId,attachments:h.attachments}:null};pr.set(d,{block:y,text:d.text,kind:d.kind,createdAt:d.createdAt,time:d.time,sender:d.sender,attachments:d.attachments,role:d.role,id:d.id,pendingPhase:d.pendingPhase,stopped:d.stopped,tableMode:u.tableMode,viewerKey:u.viewerKey,ownerKey:u.ownerKey,sharedContext:u.sharedContext}),p.push(y);continue}const m=Ad(d,e,u);m&&p.push(m)}return p}const fr=new WeakMap;function Ad(t,e,s){if(!t||typeof t!="object"){const o=Lt(t,e,s);return o.length>0?{kind:"lines",variant:"event",lines:o}:null}const n=fr.get(t);if(n&&Object.is(n.maxWidth,e)&&Object.is(n.text,t.text)&&Object.is(n.mobileText,t.mobileText)&&Object.is(n.role,t.role)&&Object.is(n.time,t.time)&&Object.is(n.createdAt,t.createdAt)&&Object.is(n.splash,t.splash)&&Object.is(n.thinking,t.thinking)&&Object.is(n.thinkingLabel,t.thinkingLabel)&&Object.is(n.progressKind,t.progressKind)&&Object.is(n.noChrome,t.noChrome)&&Object.is(n.cardTitle,t.cardTitle)&&Object.is(n.cardTitleColor,t.cardTitleColor)&&Object.is(n.cardBorderColor,t.cardBorderColor)&&Object.is(n.stopped,t.stopped)&&Object.is(n.tableMode,s.tableMode)&&Object.is(n.viewerKey,s.viewerKey)&&Object.is(n.ownerKey,s.ownerKey)&&Object.is(n.sharedContext,s.sharedContext))return n.block;const i=Lt(t,e,s),r=i.length>0?{kind:"lines",variant:"event",lines:i}:null;return fr.set(t,{block:r,maxWidth:e,text:t.text,mobileText:t.mobileText,role:t.role,time:t.time,createdAt:t.createdAt,splash:t.splash,thinking:t.thinking,thinkingLabel:t.thinkingLabel,progressKind:t.progressKind,noChrome:t.noChrome,cardTitle:t.cardTitle,cardTitleColor:t.cardTitleColor,cardBorderColor:t.cardBorderColor,stopped:t.stopped,tableMode:s.tableMode,viewerKey:s.viewerKey,ownerKey:s.ownerKey,sharedContext:s.sharedContext}),r}function pi(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 r=Math.min(6,Math.floor(i/2));return r<1?[{text:t.trim(),color:e,bold:!0}]:[{text:"─".repeat(r),color:e},{text:t,color:e,bold:!0},{text:"─".repeat(r),color:e}]}function Ca(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 pi(n,"magenta",e)}const Cd={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 Ta(t,e){const s=String(t?.reason||"unknown"),i=` ↻ regeneration refused · ${Cd[s]||s.replace(/_/g," ")} `;return pi(i,"yellow",e)}function Na(t,e){const s=String(t?.stage||"unknown"),n=String(t?.error||"").split(`
50
- `)[0],i=n.length>120?`${n.slice(0,117)}…`:n,r=` ✕ regeneration failed at ${s}${i?` · ${i}`:""} `;return pi(r,"red",e)}function fi(t,e=80,s={}){const n=nd(t);if(!n||n.length===0)return[];const i=Math.max(20,Number(e)||80),r=n.filter(g=>g.pendingPhase==="queued").length,o=n.filter(g=>g.pendingPhase==="pending").length,a=n.filter(g=>g.pendingPhase==="cancelling").length,c=n.filter(g=>g.pendingPhase==="rejected").length,u=[];o>0&&u.push(`${o} pending`),r>0&&u.push(`${r} queued`),a>0&&u.push(`${a} cancelling`),c>0&&u.push(`${c} rejected`);const f=[[{text:` queued prompts: ${u.length>0?u.join(" · "):"queued prompts"} `,color:"gray",trailingRule:!0}]],m=s?.tableMode?{tableMode:s.tableMode}:{};for(const[g,h]of n.entries()){Ms(f,Lt(h,i,m));const y=n[g+1];y&&ka(h,y)&&nt(f[f.length-1]).trim().length>0&&f.push(va())}return f}function Td(t){const e=Gs(t),s=[],n=new Set;for(const i of e||[])for(const r of tc(i?.text||"")){const o=`${r.sessionId}/${r.filename}`;n.has(o)||(n.add(o),s.push(r))}return s}function Nd(t){const e=Gs(t),s=[],n=new Set;for(const i of e||[])for(const r of sc(i?.text||"")){const o=String(r.href||"").trim();!o||n.has(o)||(n.add(o),s.push({href:o,text:String(r.text||o).trim()||o}))}return s}function hi(t,e){const s=Mo(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function Md(t){return Mo(t)||"(unknown)"}function Ma(t,e={}){const s=De(t),n=t.sessions?.byId||{},i=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],r=ai(n),o=li(i,n),a=ca(e?.width);if(!s)return{color:"cyan",title:Ue("Chat","cyan"),titleRight:null,animateTitleRight:!1};const c=ce(s.sessionId),u=s.isSystem?"yellow":"cyan",p=Ue(s.isSystem?`⚙ ${Ft(s,t.branding?.title||"PilotSwarm")}`:Hs(s)||"Chat",u),d=i.find(w=>w.sessionId===s.sessionId),f=Sa(s.sessionId,d,r,o);f&&p.push({text:` ${f.text}`,color:f.color}),a||p.push({text:` [${c}]`,color:"gray"});const m=t.history?.bySessionId?.get(s.sessionId)||null,g=Array.isArray(t.outbox?.bySessionId?.[s.sessionId])?t.outbox.bySessionId[s.sessionId]:[],h=t.ui?.chatViewMode==="summary"?null:td(s,m,m?.chat||[],g),y=t.connection?.mode||"local",S=Wu(s,y),E=dd(h),x=E?[...S,...S.length?[{text:" · ",color:"gray"}]:[],...E]:S;return{color:s.isSystem?"yellow":"cyan",title:p,titleRight:x.length?x:null,animateTitleRight:!!h}}function Pd(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function Pa(t){const e=Da(t),s=e.selected?e.nodes.find(o=>o.label===e.selected):null,n=Ue("Worker","gray");if(!s)return n.push({text:" none",color:"gray"}),{title:n,lines:[{text:e.degraded&&e.registryError?`No worker selected — ${e.registryError}`:"No workers to show yet.",color:"gray"}]};n.push({text:` ${s.label}`,color:"cyan"});const i=[],r=(o,a,c="white")=>{a==null||a===""||i.push([{text:`${o.padEnd(10)} `,color:"gray"},{text:String(a),color:c}])};if(s.registered){if(r("Node",s.workerNodeId),r("Phase",s.phase,s.phase==="draining"?"red":s.phase==="starting"?"yellow":"green"),r("Pool",s.pool),s.owner&&r("Owner",s.owner),r("Heartbeat",s.live?`${s.agoText??"now"} · live`:`${s.agoText??"unknown"} · stale`,s.live?"green":"red"),r("Uptime",s.uptimeText),r("Memory",[s.rssText?`rss ${s.rssText}`:null,s.heapText?`heap ${s.heapText}`:null].filter(Boolean).join(" · ")||null),r("Loop p99",s.eventLoopText),r("SDK",s.sdkVersion),r("Runtime",s.substrate),s.capabilities.length&&r("Caps",s.capabilities.join(", ")),s.consumes.length&&r("Consumes",s.consumes.join(", ")),s.pkgEpoch!==null){const o=s.pkgInstalled.filter(c=>c.status==="ok").length,a=s.pkgInstalled.length-o;r("Packages",`epoch ${s.pkgEpoch} · ${o} ok${a?` · ${a} error`:""}`,a?"red":"white");for(const c of s.pkgInstalled)i.push([{text:" ",color:"gray"},{text:`${c.status==="error"?"✗":"✓"} `,color:c.status==="error"?"red":"green"},{text:`${c.name}${c.semver?`@${c.semver}`:""}`,color:c.status==="error"?"red":"white"}]),c.error&&i.push([{text:` ${c.error}`,color:"red"}]);s.pkgLastError&&i.push([{text:` last refresh error: ${s.pkgLastError}`,color:"red"}])}}else i.push({text:"Not in the worker registry — derived from recent activity only.",color:"gray"});i.push({text:"",color:"gray"}),i.push([{text:`EXECUTING (${s.executing.length})`,color:"cyan",bold:!0}]);for(const o of s.executing)i.push(o.active?Ke(o.text):{text:o.text,color:o.color,bold:o.bold});return s.executing.length===0&&i.push({text:`Nothing executing in the ${e.windowLabel} window.`,color:"gray"}),{title:n,lines:i}}function mi(t,e=12){const s=Pd(t),n=De(t),i=Ue("Activity","gray");return n?.isGroup?{title:i,disabled:!0,lines:[{text:Ua,color:"gray"}]}:(n?.statusVersion!=null&&i.push({text:` [current session v${n.statusVersion}]`,color:"gray"}),{title:i,lines:s.length>0?s.map(r=>r.line||[{text:r.text,color:"white"}]):[{text:"No activity yet",color:"gray"}]})}function _a(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 $a(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":_a(e)}function _d(t){return t==="raw"?"raw summary":"pretty text"}function $d(t){return t?.sessionId?`session-${t.sessionId}`:null}function Rd(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},i=$d(e);return s.filter(r=>!(!r||n.source==="currentOrchestration"&&i&&r.orchId!==i||n.level&&n.level!=="all"&&String(r.level||"").toLowerCase()!==n.level))}function Od(t){const e=ss(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:$a(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${ce(s)}] `,color:"gray"}]:[],{text:`${n} `,color:_a(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function Ld(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${ce(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:$a(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function Fd(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:_d(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 r=Rd(t,e);return r.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"},...r.map(o=>n.format==="raw"?Od(o):Ld(o))]}function hr(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function Bd(t){return/\.(json|jsonl)$/i.test(String(t||""))}function Dd(t){return We.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function Hd(t=""){const e=String(t||"").split(`
51
- `);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function mr(t,{selected:e=!1,width:s=24,label:n=null}={}){const i=Math.max(8,s),r=hr(t)?"# ":Bd(t)?"{ ":"• ",o=Ra(`${r}${n||t}`,i).padEnd(i," ");return e?Ke(o):{text:o,color:hr(t)?"cyan":"white",bold:!1}}function Le(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function Gd(t,e={}){if(!t)return new Set;const{childMap:s}=oi(e),n=new Set([t]),i=[t];for(;i.length>0;){const r=i.shift(),o=s.get(r)||[];for(const a of o)!a||n.has(a)||(n.add(a),i.push(a))}return n}function Ps(t,e=Le(t)){const s=De(t)?.sessionId||null,n=Array.isArray(t.sessions?.flat)?t.sessions.flat.map(c=>c?.sessionId||c).filter(Boolean):[],i=Object.keys(t.files?.bySessionId||{}).filter(Boolean);if(e==="allSessions")return[...new Set([...n,...i])];const r=Gd(s,t.sessions?.byId||{});if(r.size===0)return[];const o=[],a=new Set;for(const c of[s,...n,...Object.keys(t.sessions?.byId||{}),...i])!c||a.has(c)||!r.has(c)||(o.push(c),a.add(c));for(const c of r)a.has(c)||o.push(c);return o}function gr(t){const s=De(t)?.sessionId;if(!s)return[];const i=t.history?.bySessionId?.get?.(s)?.events||[],r=new Set,o=[],a=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{})\]]+)/g;for(const c of i){const u=typeof c?.data?.content=="string"?c.data.content:"";if(!u)continue;a.lastIndex=0;let p;for(;(p=a.exec(u))!==null;){const d=`${p[1]}/${p[2]}`;r.has(d)||(r.add(d),o.push(d))}}return o}function ct(t){const e=Le(t);De(t)?.sessionId;const s=t.files?.filter?.query||"",n=Ps(t,e),i=e==="allSessions"||n.length>1,r=[];for(const o of n){const a=As(t.files?.bySessionId?.[o]?.entries);for(const c of a){const u=c.filename;r.push({id:`${o}/${u}`,sessionId:o,filename:u,entry:c,label:i?`[${ce(o)}] ${u}`:u})}}return r.filter(o=>lt(o.filename,s)||lt(o.sessionId,s)||lt(o.label,s))}function et(t){const e=ct(t);if(e.length===0)return null;const s=t.files?.selectedArtifactId||null;if(s){const o=e.find(a=>a.id===s);if(o)return o}if(Le(t)==="allSessions"){const o=De(t)?.sessionId||null,a=o&&t.files?.bySessionId?.[o]?.selectedFilename||null;if(o&&a){const c=e.find(u=>u.sessionId===o&&u.filename===a);if(c)return c}return e[0]}const i=De(t)?.sessionId||null,r=i&&t.files?.bySessionId?.[i]?.selectedFilename||null;return e.find(o=>o.sessionId===i&&o.filename===r)||e[0]}function gi(t,e={}){const s=De(t),n=Math.max(12,Number(e?.listWidth)||Number(e?.width)||24),i=Math.max(18,Number(e?.previewWidth)||Number(e?.width)||36),r=e?.showHints!==!1,o=s?.sessionId||null,a=Le(t),c=t.files?.filter?.query||"",u=ct(t),p=et(t),d=p?.filename||null,f=Math.max(0,u.findIndex(_=>_.id===p?.id)),m=p?.sessionId&&d&&t.files?.bySessionId?.[p.sessionId]?.previews?.[d]||null,g=m||p?.entry||null,h=s?ce(s.sessionId):"",y=Ps(t,a),S=a!=="allSessions"&&y.some(_=>_&&_!==o),E=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(_=>_?.sessionId||_):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),x=a==="allSessions"&&E.some(_=>!t.files?.bySessionId?.[_]?.loaded||t.files?.bySessionId?.[_]?.loading),w=a==="allSessions"&&E.map(_=>t.files?.bySessionId?.[_]?.error).find(Boolean)||null,b=[Dd("files"),...s||a==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(a==="allSessions")x&&u.length===0?b.push({text:"Loading exported files across all sessions…",color:"gray"}):w&&u.length===0?b.push({text:w,color:"red"}):u.length===0?(b.push({text:c?`No artifacts matched "${c}" across any session.`:"No exported files across any session yet.",color:"gray"}),b.push({text:c?"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"})):b.push(...u.map((_,L)=>mr(_.filename,{selected:L===f,width:n,label:_.label})));else if(s){const _=o?t.files?.bySessionId?.[o]:null;Array.isArray(_?.entries)&&_.entries;const L=u.filter(W=>y.includes(W.sessionId));_?.loading?b.push({text:"Loading exported files…",color:"gray"}):_?.error?b.push({text:_.error,color:"red"}):L.length===0&&y.every(W=>{const Y=t.files?.bySessionId?.[W]?.entries;return!Array.isArray(Y)||Y.length===0})?(b.push({text:c?`No artifacts matched "${c}" for this ${S?"session tree":"session"}.`:`No exported files for this ${S?"session tree":"session"} yet.`,color:"gray"}),b.push({text:c?"Clear the query or upload an artifact to this session.":S?"Artifacts exported by this session or any child session will appear here.":"Agents must write/export artifacts before they appear here.",color:"gray"})):b.push(...L.map((W,Y)=>mr(W.filename,{selected:Y===f,width:n,label:W.label})))}let I,k;!s&&a!=="allSessions"?(k=[{text:"Preview",color:"cyan",bold:!0}],I=[{text:"No session selected.",color:"gray"}]):d?m?.loading?(k=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||p?.sessionId&&p.sessionId!==o)&&p?.sessionId?[{text:` · ${ce(p.sessionId)}`,color:"gray"}]:[]],I=[{text:"Loading file preview…",color:"gray"}]):m?.error?(k=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||p?.sessionId&&p.sessionId!==o)&&p?.sessionId?[{text:` · ${ce(p.sessionId)}`,color:"gray"}]:[]],I=[{text:m.error,color:"red"}]):(k=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||p?.sessionId&&p.sessionId!==o)&&p?.sessionId?[{text:` · ${ce(p.sessionId)}`,color:"gray"}]:[],...m?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:m?.isBinary===!0?[{text:" [file]",color:"gray"}]:m?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],I=m?.renderMode==="markdown"?Ns(_t(m?.content||"",{width:i})):Hd(m?.content||"")):(k=[{text:"Preview",color:"cyan",bold:!0}],I=[{text:"Select a file to preview it here.",color:"gray"}]);const P=a==="allSessions"?"Files: all sessions":s?`Files: ${h}${S?" tree":""}`:"Files",M=a==="allSessions"?"all sessions":s?`${h}${S?" tree":""}`:"Files",B=a==="allSessions"?`Artifacts${u.length>0?` [${u.length}]`:""}`:`Artifacts${S?" tree":""}${u.length>0?` [${u.length}]`:""}`,O=c?` · @${c}`:"";return{panelTitle:[{text:`${P}${O}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${M}${O}`,color:"magenta",bold:!0}],listTitle:[{text:`${B}${O}`,color:"cyan",bold:!0}],listLines:b,listBodyLines:b.slice(1),selectedIndex:f,selectedFilename:d,selectedSessionId:p?.sessionId||null,scope:a,previewTitle:k,previewLines:I,previewContent:m?.content||"",previewContentType:m?.contentType||"",previewRenderMode:m?.renderMode||null,previewIsBinary:g?.isBinary===!0,previewSizeBytes:g?.sizeBytes??null,previewUploadedAt:g?.uploadedAt||"",previewSource:g?.source||null,previewError:m?.error||null,previewLoading:!!m?.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}]:[],...r?[{text:" [f filter] [u upload] [a download] [x delete] [o open] [v/esc close fullscreen]",color:"gray"}]:[]]}}function yr(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);return Number.isNaN(e.getTime())?"—":e.toISOString().slice(0,10)}function xt(t){const e=Number(t)||0;return e<=0?"0 B":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function jd(t){const e=String(t||"").toLowerCase();return e.endsWith(".md")?"markdown":e.endsWith(".json")?"json":/\.(mjs|cjs|js)$/.test(e)?"javascript":"text"}function Ud(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,r=e.systemGhcpKey||{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null},o=!!s?.isAdmin,a=o&&!!n.storeAsSystem,c=a?!!r.configured:!!s?.githubCopilotKeySet,u=a?"System key":"key",p=r.configured&&r.changedBy?` (set by ${r.changedBy})`:"",d=n.saving?"Saving...":n.editing?"Editing — Enter to save, Esc to cancel":a?r.configured?`System key configured — ownerless system sessions use it for GitHub Copilot models${p}`:"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)",f=e.packages||{},m=Array.isArray(f.list)?f.list:[],g=C=>!!(o||C?.owner&&i&&C.owner.provider===i.provider&&C.owner.subject===i.subject),h=_u(t?.sessions?.byId),y=C=>({name:C.name,scope:C.scope==="shared"?"shared":"user",enabled:!!C.enabled,semver:C.active?.semver||null,sha7:C.active?.sha256?String(C.active.sha256).slice(0,7):null,agentCount:Array.isArray(C.active?.manifest?.agents)?C.active.manifest.agents.length:0,canManage:g(C),ownerBadge:C.scope==="shared"?null:ha($u(C,h)),selected:e.section==="packages"&&f.selectedName===C.name}),S=C=>!!(C?.owner&&i&&C.owner.provider===i.provider&&C.owner.subject===i.subject),E=t.sessions?.ownerFilter,x=C=>{if(!E||E.all===!0)return!0;const N=de(C?.owner);return N?Array.isArray(E.ownerKeys)&&E.ownerKeys.includes(N):E.includeUnowned===!0},w=m.filter(C=>C.scope==="shared").map(y),b=m.filter(C=>C.scope!=="shared"&&S(C)).map(y),I=m.filter(C=>C.scope!=="shared"&&!S(C)&&x(C)).map(C=>({...y(C),ownerLabel:C?.createdBy||C?.owner?.subject||"another user"})),k=["packages","workers"].includes(e.section)?e.section:"ghcp",P=[{id:"ghcp",kind:"section",depth:0,label:"GitHub Keys",selected:k==="ghcp"},{id:"agents",kind:"section",depth:0,label:"Agents",selected:k==="packages"&&!f.selectedName},{id:"group:shared",kind:"group",depth:1,label:"Shared",count:w.length},...w.map(C=>({id:`pkg:${C.name}`,kind:"package",depth:2,label:C.name,...C})),{id:"group:user",kind:"group",depth:1,label:"User",count:b.length},...b.map(C=>({id:`pkg:${C.name}`,kind:"package",depth:2,label:C.name,...C})),...I.length>0?[{id:"group:others",kind:"group",depth:1,label:"Other users",count:I.length},...I.map(C=>({id:`pkg:${C.name}`,kind:"package",depth:2,label:C.name,...C}))]:[],...o?[{id:"workers",kind:"section",depth:0,label:"Workers",selected:k==="workers"}]:[]],M=f.detail||null;let B=null;if(f.selectedName){const C=m.find(K=>K.name===f.selectedName)||null,N=M?.versions?.find(K=>K.versionId===M.activeVersionId)||null,F=N?.manifest||C?.active?.manifest||{},z=Date.now()-9e4,Q=(Array.isArray(f.workerState)?f.workerState:[]).filter(K=>{const xe=K?.updatedAt instanceof Date?K.updatedAt:new Date(K?.updatedAt??0);return!Number.isNaN(xe.getTime())&&xe.getTime()>=z}),pe=Q.length,Se=N?Q.filter(K=>K.installed?.[f.selectedName]?.semver===N.semver&&K.installed?.[f.selectedName]?.status==="ok").length:0,$e=M?g(M):C?g(C):!1;B={name:f.selectedName,loading:!!f.detailLoading,error:f.detailError||null,scope:(M?.scope||C?.scope)==="shared"?"shared":"user",enabled:M?!!M.enabled:!!C?.enabled,canManage:$e,createdBy:M?.createdBy||C?.createdBy||null,createdAtText:yr(M?.createdAt||C?.createdAt),description:typeof F.description=="string"?F.description:"",activeSemver:N?.semver||C?.active?.semver||null,activeSha12:N?.sha256?String(N.sha256).slice(0,12):null,sizeText:xt(N?.sizeBytes??C?.active?.sizeBytes),agents:Array.isArray(F.agents)?F.agents.map(K=>({name:K.name,description:K.description||"",toolCount:Array.isArray(K.tools)?K.tools.length:0,skillCount:Array.isArray(K.skills)?K.skills.length:0})):[],versions:(M?.versions||[]).map(K=>({semver:K.semver,sha12:String(K.sha256||"").slice(0,12),dateText:yr(K.createdAt),active:K.versionId===M?.activeVersionId})),fleet:pe>0&&N?{current:Se,total:pe,text:`${Se}/${pe} workers current`}:null,actionPending:f.action?.pending||null,actionError:f.action?.error||null}}const O=f.workspace||{};let _=null;if(f.selectedName){const C=O.tree,N=new Set(O.expandedDirs||[]),F=[];if(C){const z=K=>{const xe=K.split("/");for(let Ve=1;Ve<xe.length;Ve++)if(!N.has(xe.slice(0,Ve).join("/")))return!1;return!0},Q=Array.isArray(C.dirs)?C.dirs:[],pe=Array.isArray(C.files)?C.files:[],Se=K=>String(K).split("/").join("\0"),$e=[...Q.map(K=>({type:"dir",path:K})),...pe.map(K=>({type:"file",path:K.path,size:K.size}))].sort((K,xe)=>Se(K.path)<Se(xe.path)?-1:1);for(const K of $e){if(!z(K.path))continue;const xe=K.path.split("/").length-1;F.push({type:K.type,path:K.path,label:K.path.split("/").pop()+(K.type==="dir"?"/":""),depth:xe,expanded:K.type==="dir"?N.has(K.path):void 0,sizeText:K.type==="file"?xt(K.size):null,selected:O.selectedPath===K.path})}}const U=O.file;_={loading:!!O.treeLoading,error:O.treeError||null,semver:O.tree?.semver||null,treeRows:F,file:U?{path:U.path,sizeText:xt(U.size),truncated:!!U.truncated,isBinary:U.encoding==="base64",text:U.encoding==="base64"?null:String(U.content||""),language:jd(U.path)}:null,fileLoading:!!O.fileLoading,fileError:O.fileError||null,selectedPath:O.selectedPath||null}}const L=e.workers||{},W=Array.isArray(L.list)?L.list:[],Y=9e4,te=Date.now(),ne=C=>!Number.isFinite(C)||C<0?"—":C<6e4?`${Math.round(C/1e3)}s ago`:C<36e5?`${Math.round(C/6e4)}m ago`:`${Math.round(C/36e5)}h ago`,Pe=C=>{if(!Number.isFinite(C)||C<0)return null;if(C<60)return`${Math.round(C)}s`;if(C<3600)return`${Math.floor(C/60)}m`;const N=Math.floor(C/3600);return N<48?`${N}h ${Math.floor(C%3600/60)}m`:`${Math.floor(N/24)}d ${N%24}h`},ee=W.map(C=>{const N=C?.updatedAt instanceof Date?C.updatedAt:new Date(C?.updatedAt??0),F=Number.isNaN(N.getTime())?Number.NaN:te-N.getTime(),U=C?.health||{},z=C?.info||{},Q=C?.state?.["agent-packages"]||null,pe=Q?.installed&&typeof Q.installed=="object"?Object.values(Q.installed):[],Se=pe.filter($e=>$e?.status==="error").length;return{id:String(C?.workerNodeId??""),pool:String(C?.pool??"default"),phase:["starting","ready","draining"].includes(C?.phase)?C.phase:"ready",live:Number.isFinite(F)&&F<=Y,agoText:ne(F),uptimeText:Pe(U.uptimeS),rssText:xt(U.rssBytes),sessions:Number.isFinite(U.activeSessions)?U.activeSessions:null,eventLoopText:Number.isFinite(U.eventLoopDelayP99Ms)?`${U.eventLoopDelayP99Ms}ms`:null,sdkVersion:typeof z.sdkVersion=="string"?z.sdkVersion:null,substrate:typeof z.runtime?.substrate=="string"?z.runtime.substrate:null,consumes:Array.isArray(z.consumes)?z.consumes:[],owner:C?.owner?.subject?String(C.owner.subject):null,pkgEpoch:Number.isFinite(Q?.epoch)?Q.epoch:null,pkgText:Q?`${pe.length-Se} ok${Se?` · ${Se} error`:""}`:null}}).sort((C,N)=>C.pool===N.pool?C.id<N.id?-1:1:C.pool<N.pool?-1:1),ye=ee.filter(C=>C.live),v={loading:!!L.loading,error:L.error||null,empty:ee.length===0&&!L.loading,rows:ee,counts:{registered:ee.length,live:ye.length,ready:ye.filter(C=>C.phase==="ready").length,starting:ye.filter(C=>C.phase==="starting").length,draining:ye.filter(C=>C.phase==="draining").length,pools:[...new Set(ye.map(C=>C.pool))].length},summaryText:ee.length?`${ye.length} live / ${ee.length} registered`:null},$={loading:!!f.loading,error:f.error||null,empty:m.length===0&&!f.loading,sharedCount:w.length,userCount:b.length,selectedName:f.selectedName||null,detail:B,workspace:_,addDialog:{open:!!f.addDialog?.open,kind:f.addDialog?.kind||"repo",scope:f.addDialog?.scope||"user",repoUrl:f.addDialog?.repoUrl||"",ref:f.addDialog?.ref||"",path:f.addDialog?.path||"",url:f.addDialog?.url||"",authToken:f.addDialog?.authToken||"",submitting:!!f.addDialog?.submitting,progress:f.addDialog?.progress||null,error:f.addDialog?.error||null}},H=[];return k==="workers"?(H.push({id:"workersRefresh",label:"Refresh workers",key:"r"}),H.push({id:"showPackages",label:"Agents",key:"a"}),H.push({id:"showGhcp",label:"GitHub Keys",key:"g"}),H.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:o,section:k,settingsTree:P,packages:$,workers:v,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:c,storeAsSystem:a,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:d},systemGhcpKey:{supported:!!r.supported,loading:!!r.loading,configured:!!r.configured,changedBy:r.changedBy||null,changedAt:r.changedAt||null,error:r.error||null},actions:H}):k==="packages"?(H.push({id:"packagesRefresh",label:"Refresh packages",key:"r"}),H.push({id:"packagesNext",label:"Next package",key:"j"}),H.push({id:"packagesPrev",label:"Previous package",key:"k"}),H.push({id:"showGhcp",label:"GitHub Keys",key:"g"}),H.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:o,section:k,settingsTree:P,packages:$,workers:v,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:c,storeAsSystem:a,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:d},systemGhcpKey:{supported:!!r.supported,loading:!!r.loading,configured:!!r.configured,changedBy:r.changedBy||null,changedAt:r.changedAt||null,error:r.error||null},actions:H}):(n.editing?(H.push({id:"save",label:"Save",key:"Enter"}),H.push({id:"cancel",label:"Cancel",key:"Esc"})):(H.push({id:"edit",label:c?`Replace ${u}`:`Set ${u}`,key:"e"}),c&&H.push({id:"clear",label:`Clear ${u}`,key:"c"}),H.push({id:"refresh",label:"Refresh",key:"r"})),H.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),k==="ghcp"&&H.splice(H.length-1,0,{id:"showPackages",label:"Agents",key:"a"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:o,section:k,settingsTree:P,packages:$,workers:v,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:c,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:!!r.supported,loading:!!r.loading,configured:!!r.configured,changedBy:r.changedBy||null,changedAt:r.changedAt||null,error:r.error||null},actions:H})}function Wd(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=De(t),i=!!n?.pendingQuestion?.question,r=n?.sessionId&&Array.isArray(t.outbox?.bySessionId?.[n.sessionId])?t.outbox.bySessionId[n.sessionId]:[],o=r.length>0,a=r.some(E=>E?.phase==="pending"),c=t.ui.promptEdit?.sessionId===n?.sessionId,u=c&&t.ui.promptEdit?.phase==="queued",p=c&&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 f=!!t.sessions?.selectMode,m=Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds.length:0;if(f&&e===T.SESSIONS)return{left:`Select mode · ${m} selected`,right:"up/down move · space toggle · ctrl-g group · c cancel · d complete · D hard delete · V/esc exit"};const h=(t.ui?.chatViewMode==="summary"?"summary":"transcript")==="summary"?"s transcript":"s summary",y={[T.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",[T.CHAT]:`${h} · 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`,[T.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`,[T.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`,[T.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"}`:c?u?`queued prompt selected · d delete · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:p?`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"}`:o?`type message · enter queues behind durable items · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:`type message · enter send · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`};let S=y[e]||y[T.SESSIONS];return Ia(De(t))&&(S=`ctrl-x stop · ${S}`),{left:t.ui.statusText,right:S}}function ft(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function oe(t,e){if(e<=0)return[];const s=[];let n=e;for(const i of t||[]){if(n<=0)break;const r=String(i?.text||"");if(!r)continue;const o=r.length>n&&n>1?`${r.slice(0,n-1)}…`:r.slice(0,n);o&&(s.push({...i,text:o}),n-=o.length)}return s}function Me(t){return Array.from(String(t||"")).length}function Ra(t,e){const s=String(t||"");return e<=0?"":Me(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function Pt(t,e){const s=Ra(t,e),n=Math.max(0,e-Me(s));return s+" ".repeat(n)}function J(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function be(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 Sr(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 Oa(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?Me(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function Kd(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 La(t=[]){const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();if(!i)continue;const r=i.toLowerCase();e.has(r)||(e.add(r),s.push(i))}return s.join(" | ")}function Vd(t,e=""){return La([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function qd(t,e=""){return La([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function ss(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 zd=300*1e3,Yd="last 5m";function yi(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-zd,endMs:e,label:Yd}}function Xd(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 Fa(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 Qd=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done"]);function Jd(t){return Qd.has(t)}function Zd(t){const e=_o(t?.createdAt),s=ss(t?.workerNodeId),n=Kd(t),i=Oa(n,20),r=t?.createdAt instanceof Date?t.createdAt.getTime():new Date(t?.createdAt||0).getTime(),o={time:e,createdAtMs:Number.isFinite(r)?r:0,nodeLabel:s,color:"white",detail:"",type:"other"};switch(t?.eventType){case"session.turn_started":return{...o,type:"turn_start",color:"gray",detail:`turn ${t?.data?.iteration??"?"}`};case"session.turn_completed":{const a=Number(t?.data?.turnIndex??t?.data?.iteration);return{...o,type:"turn_end",color:"gray",detail:`turn ${t?.data?.iteration??"?"} done`,...Number.isFinite(a)?{completedTurn:a}:{}}}case"user.message":return{...o,type:"user_msg",color:"white",detail:i?`>> ${i}`:">> user"};case"assistant.message":return{...o,type:"response",color:"green",detail:i?`< ${i}`:"< response"};case"system.message":return{...o,type:"system",color:"yellow",detail:i||"system"};case"session.wait_started":return{...o,type:"wait",color:"yellow",detail:`wait ${Et(t?.data?.seconds??0)}`};case"session.wait_completed":return{...o,type:"timer",color:"yellow",detail:`${Et(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const a=qd(t,i);return{...o,type:"dehydrate",color:"yellow",detail:a?`lossy ${a}`:"lossy handoff"}}case"session.dehydrated":return{...o,type:"dehydrate",color:"cyan",detail:`ZZ ${Vd(t,i)}`.trim()};case"session.rehydrated":case"session.hydrated":return{...o,type:"hydrate",color:"green",detail:"rehydrated"};case"session.agent_spawned":return{...o,type:"spawn",color:"cyan",detail:`spawn ${t?.data?.agentId||ce(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${Et(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${Ts(t?.data?.nextFireAtMs??t?.data?.nextFireAt)}`};case"session.cron_fired":return{...o,type:"cron_fire",color:"magenta",detail:"cron fired"};case"session.cron_at_fired":return{...o,type:"cron_fire",color:"magenta",detail:`cron fired ${Ts(t?.data?.scheduledAt)}`};case"session.cron_cancelled":case"session.cron_at_cancelled":return{...o,type:"cron_cancel",color:"magenta",detail:"cron off"};case"session.cron_at_completed":return{...o,type:"cron_cancel",color:"magenta",detail:"cron done"};case"session.command_received":return{...o,type:"cmd_recv",color:"magenta",detail:`/${t?.data?.cmd||"?"}`};case"session.command_completed":return{...o,type:"cmd_done",color:"magenta",detail:`/${t?.data?.cmd||"?"} ok`};case"session.compaction_start":return{...o,type:"compaction",color:"gray",detail:"compaction…"};case"session.compaction_complete":return{...o,type:"compaction",color:"gray",detail:"compacted"};case"session.error":return{...o,type:"error",color:"red",detail:i||"error"};default:return null}}function Ba(t=[]){const e=[];for(const s of t||[]){const n=Zd(s);n&&e.push({...n,nodeLabel:Jd(n.type)?"orch":n.nodeLabel||"orch"})}return e}function ep(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 r=t[s+i];if(r?.type!=="spawn"||r?.nodeLabel!=="orch"||r?.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 tp(t){const e=String(t?.error||"").trim();if(!e)return null;const s=ri(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),i=Number.isFinite(n)?n:Date.now();return{time:_o(i),createdAtMs:i,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${Oa(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function sp(t,e){const s=tp(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 np(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 r=Ba(i?.events||[]);for(const o of r){if(!o?.nodeLabel||o.nodeLabel==="orch")continue;const a=Number(o.createdAtMs||0);Number.isFinite(a)&&(a<e||a>s||n.add(o.nodeLabel))}}return Array.from(n).sort((i,r)=>i.localeCompare(r))}function ip(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const i of n?.events||[]){if(!Fa(i,e))continue;const r=ss(i?.workerNodeId);r&&s.add(r)}return Array.from(s).sort((n,i)=>n.localeCompare(i))}function Si(t){const e=t.slice();for(;e.length>0;){const s=e[e.length-1],n=String(s.text??"").replace(/\s+$/,"");if(n===""){e.pop();continue}e[e.length-1]={...s,text:n};break}return e}function br(t){return Array.isArray(t?.runs)?t.runs.reduce((e,s)=>e+Me(String(s.text??"")),0):Array.isArray(t)?t.reduce((e,s)=>e+Me(String(s.text??"")),0):Me(String(t?.text??""))}function rp(t,e,s){const n=[{text:Pt("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((i,r)=>{r>0&&n.push({text:" ",color:null}),n.push({text:Pt(i,s),color:"white",bold:!0})}),Si(n)}function op(t,e,s,n=1/0){const i=`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`;return J(Number.isFinite(n)?i.slice(0,Math.max(e,n)):i,"gray")}function ap(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 r=n.stats,o=[],a=[];if(typeof r.orchestrationVersion=="string"&&r.orchestrationVersion&&(o.push(`v ${r.orchestrationVersion}`),a.push(`v${r.orchestrationVersion}`)),r.historyEventCount!=null&&(o.push(`hist ${Number(r.historyEventCount)||0} ev`),a.push(`h${Number(r.historyEventCount)||0}`)),r.historySizeBytes!=null){const c=be(r.historySizeBytes);o.push(c),a.push(c)}r.queuePendingCount!=null&&(o.push(`q ${Number(r.queuePendingCount)||0}`),a.push(`q${Number(r.queuePendingCount)||0}`)),r.kvUserKeyCount!=null&&(o.push(`kv ${Number(r.kvUserKeyCount)||0} keys`),a.push(`kv${Number(r.kvUserKeyCount)||0}`)),r.kvTotalValueBytes!=null&&o.push(be(r.kvTotalValueBytes)),i=s<=40?a.join(" · "):o.join(" | "),i||(i="orchestration stats unavailable")}return s<=52?[oe([{text:"Stats ",color:"cyan",bold:!0},{text:i,color:"white"}],Math.max(18,s))]:me({title:"Stats",body:i,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function lp(t,e,s,n){const i=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],r=[{text:Pt(t.time||"",s),color:"white"},{text:" ",color:null}];return e.forEach((o,a)=>{a>0&&r.push({text:" ",color:null}),o===i?r.push({text:Pt(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):r.push({text:Pt("│",n),color:"gray"})}),Si(r)}const cp=new Set(["none","minimal","low","medium","high","xhigh","max"]);function up(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&&cp.has(n)?s.length-2:s.length-1;return s[Math.max(0,i)]||s[0]||"unknown"}function wr(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 rt(t){return Number(t||0).toLocaleString("en-US")}function dp(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 pp(t,{expanded:e,selected:s,maxWidth:n}){const i=e?"v":">",r=up(t?.model),o=t?.durationMs!=null?`${(Number(t.durationMs)/1e3).toFixed(1)}s`:"n/a",a=`${i} Mod: ${r} tok ${wr(t?.tokensInput)}/${wr(t?.tokensOutput)} dur ${o}`,c=[];if(s?c.push(Ke(Pt(a,Math.max(18,n)))):c.push([{text:a,color:"magenta"}]),e){const u=[["model",t?.reasoningEffort?`${t?.model||"(unknown)"}:${t.reasoningEffort}`:t?.model||"(unknown)"],["duration",t?.durationMs!=null?`${rt(t.durationMs)} ms`:null],["tokens",`${rt(t?.tokensInput)} in / ${rt(t?.tokensOutput)} out`],["cache",`${rt(t?.tokensCacheRead)} read / ${rt(t?.tokensCacheWrite)} write`],["tools",`${rt(t?.toolCalls)} calls / ${rt(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(([,p])=>p!=null&&p!=="");for(const[p,d]of u)c.push([{text:` ${p}: `,color:"gray"},{text:String(d),color:"white"}])}return c}function fp(t,e,s,n={}){const i=!!n?.allowWideColumns,r=ap(t,e,s),o=t.history.bySessionId.get(e.sessionId),a=sp(ep(Ba(o?.events||[])),e);if(a.length===0)return{stickyLines:r,lines:[J("No events yet - interact with this session to populate the sequence diagram.")]};const c=yi(t),u=a.filter(O=>Xd(O,c)),p=(u.length>0?u:a).slice(-48),d=np(t,c.startMs,c.endMs),f=Array.from(new Set(p.map(O=>O.nodeLabel).filter(O=>O&&O!=="orch"))).sort((O,_)=>O.localeCompare(_)),m=d.length>0?d:f,g=Math.min(13,Math.max(8,...p.map(O=>Me(String(O.time||""))))),h=Math.max(18,s),y=Math.max(1,Math.floor((h-g-1)/6));let S=["orch",...m];if(!i&&S.length>y){const O=Math.max(1,y-1);S=[...S.slice(0,O),"…"]}const E=Math.max(0,S.length-1),x=Math.max(4,Math.floor((h-g-1-E)/Math.max(1,S.length))),w=n?.sequenceExpansion||null,b=w?dp(o?.events||[]):null,I=w?new Set((w.expandedTurns||[]).map(Number)):null,k=w&&w.selectedTurn!=null?Number(w.selectedTurn):null,P=[];for(const O of p)if(P.push(lp(O,S,g,x)),w&&O.completedTurn!=null){const _=Number(O.completedTurn),L=b.get(_);if(L)for(const W of pp(L,{expanded:I.has(_),selected:k===_,maxWidth:h}))P.push(W)}const M=rp(S,g,x),B=P.reduce((O,_)=>Math.max(O,br(_)),br(M));return{stickyLines:[...r,J(`Window: ${c.label}`,"gray"),M,op(S,g,x,B)],lines:P}}function hp(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 mp(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!Fa(s[n],e))continue;const i=ss(s[n]?.workerNodeId);if(i)return i}return null}function gp(t){return!Number.isFinite(t)||t<0?null:t<6e4?`${Math.round(t/1e3)}s ago`:t<36e5?`${Math.round(t/6e4)}m ago`:`${Math.round(t/36e5)}h ago`}function yp(t){if(!Number.isFinite(t)||t<0)return null;if(t<60)return`${Math.round(t)}s`;if(t<3600)return`${Math.floor(t/60)}m`;const e=Math.floor(t/3600);return e<48?`${e}h ${Math.floor(t%3600/60)}m`:`${Math.floor(e/24)}d ${e%24}h`}function Sp(t,e,s){const n=t?.isSystem?Ft(t,e):t?.title||ce(t?.sessionId),i=t?.isSystem?"⚙ ":t?.serviceKind?"⚗ ":`${fa(t)||"."} `;return{sessionId:t?.sessionId||null,text:`${i}${n}`,color:t?.isSystem?"yellow":Mt(t),bold:!!t?.isSystem,active:!!s}}function Da(t){const e=yi(t),s=t.branding?.title||"PilotSwarm",n=t.sessions.activeSessionId,i=Array.isArray(t.admin?.workers?.list)?t.admin.workers.list:[],r=Date.now(),o=9e4,a=new Map;for(const m of i){const g=ss(m?.workerNodeId);if(!g)continue;const h=m?.updatedAt instanceof Date?m.updatedAt.getTime():new Date(m?.updatedAt??0).getTime(),y=Number.isFinite(h)?r-h:Number.NaN,S=m?.health||{};a.set(g,{label:g,workerNodeId:String(m?.workerNodeId??""),registered:!0,live:Number.isFinite(y)&&y<=o,phase:["starting","ready","draining"].includes(m?.phase)?m.phase:"ready",pool:String(m?.pool??"default"),agoText:gp(y),uptimeText:yp(S.uptimeS),rssText:Number.isFinite(S.rssBytes)?xt(S.rssBytes):null,heapText:Number.isFinite(S.heapUsedBytes)?xt(S.heapUsedBytes):null,eventLoopText:Number.isFinite(S.eventLoopDelayP99Ms)?`${S.eventLoopDelayP99Ms}ms`:null,sessions:Number.isFinite(S.activeSessions)?S.activeSessions:null,sdkVersion:typeof m?.info?.sdkVersion=="string"?m.info.sdkVersion:null,substrate:typeof m?.info?.runtime?.substrate=="string"?m.info.runtime.substrate:null,capabilities:m?.info?.capabilities&&typeof m.info.capabilities=="object"?Object.entries(m.info.capabilities).filter(([,E])=>!!E).map(([E])=>E).sort():[],consumes:Array.isArray(m?.info?.consumes)?m.info.consumes:[],owner:m?.owner?.subject?String(m.owner.subject):null,pkgEpoch:Number.isFinite(m?.state?.["agent-packages"]?.epoch)?m.state["agent-packages"].epoch:null,pkgInstalled:m?.state?.["agent-packages"]?.installed&&typeof m.state["agent-packages"].installed=="object"?Object.entries(m.state["agent-packages"].installed).map(([E,x])=>({name:E,semver:x?.semver??null,status:x?.status==="error"?"error":"ok",error:x?.error?String(x.error):null})):[],pkgLastError:m?.state?.["agent-packages"]?.lastError?String(m.state["agent-packages"].lastError):null,executing:[]})}for(const m of ip(t,e))a.has(m)||a.set(m,{label:m,workerNodeId:null,registered:!1,live:!0,phase:null,pool:null,agoText:null,uptimeText:null,rssText:null,heapText:null,eventLoopText:null,sessions:null,sdkVersion:null,substrate:null,capabilities:[],consumes:[],owner:null,pkgEpoch:null,pkgInstalled:[],pkgLastError:null,executing:[]});let c=0;for(const m of hp(t)){const g=t.sessions.byId[m];if(!g)continue;const h=t.history.bySessionId.get(m);h?.events||(c+=1);const y=mp(h,e),S=y?a.get(y):null;S&&S.executing.push(Sp(g,s,m===n))}const u=Array.from(a.values()).sort((m,g)=>{if(m.registered!==g.registered)return m.registered?-1:1;if(m.live!==g.live)return m.live?-1:1;const h=String(m.pool??"~").localeCompare(String(g.pool??"~"));return h!==0?h:m.label.localeCompare(g.label)});u.forEach((m,g)=>{m.ordinal=g+1});const p=u.filter(m=>m.registered),d=t.ui?.nodeMapSelectedNode,f=d&&u.some(m=>m.label===d)?d:u[0]?.label??null;return{windowLabel:e.label,degraded:p.length===0,registryError:t.admin?.workers?.error||null,registryFetchedAt:t.admin?.workers?.fetchedAt||0,registryLoading:!!t.admin?.workers?.loading,registryAttempts:t.admin?.workers?.attempts||0,registryLastAttemptAt:t.admin?.workers?.lastAttemptAt||0,registryLastSkip:t.admin?.workers?.lastSkip||null,registered:p.length,liveCount:p.filter(m=>m.live).length,executingTotal:u.reduce((m,g)=>m+g.executing.length,0),missingHistoryCount:c,selected:f,nodes:u}}function bp(t,e,s={}){const n=Da(t);if(n.nodes.length===0)return[J(n.degraded?`No workers registered and no worker activity in the ${n.windowLabel} window.`:`No worker activity in the ${n.windowLabel} window.`,"gray")];const i=[];if(i.push([{text:n.degraded?`Nodes (activity-derived) · window ${n.windowLabel}`:`Nodes · ${n.liveCount} live / ${n.registered} registered · window ${n.windowLabel}`,color:"gray"}]),n.degraded)if(n.registryError)i.push([{text:`! worker registry unavailable: ${n.registryError}`,color:"red"}]);else if(n.registryFetchedAt)i.push([{text:"registry reachable but EMPTY — no worker has heartbeated in the last hour",color:"yellow"}]);else if(n.registryLoading)i.push([{text:"registry request in flight… (times out red after 10s)",color:"yellow"}]);else if(n.registryAttempts===0)i.push([{text:"registry refresh has NEVER been attempted in this tab — reload; if it persists the refresh call is not reaching the controller",color:"red"}]);else{const r=n.registryLastAttemptAt?Math.round((Date.now()-n.registryLastAttemptAt)/1e3):null;i.push([{text:`registry attempted ${n.registryAttempts}× (last ${r===null?"?":`${r}s`} ago${n.registryLastSkip?`, skipped: ${n.registryLastSkip}`:""}) but no rows and no error — reload if this persists`,color:"yellow"}])}i.push(J("","gray"));for(const r of n.nodes){const o=r.label===n.selected,a=r.live?"●":"○",c=r.live?r.phase==="draining"?"red":r.phase==="starting"?"yellow":"green":"gray",u=[{text:o?"› ":" ",color:"green",bold:o,nodeSelect:r.label,nodeSelected:o},{text:r.ordinal<=9?`${r.ordinal} `:" ",color:"gray",nodeSelect:r.label},{text:`${a} `,color:c,nodeSelect:r.label},{text:r.label.padEnd(7),color:o||r.live?"white":"gray",bold:o,nodeSelect:r.label}];if(r.registered){u.push({text:` ${(r.phase||"").padEnd(8)}`,color:c,nodeSelect:r.label}),u.push({text:` ${r.pool}`,color:"gray",nodeSelect:r.label});const p=[r.executing.length?`${r.executing.length} sess`:null,r.rssText,r.uptimeText?`up ${r.uptimeText}`:null,r.agoText].filter(Boolean).join(" · ");p&&u.push({text:` ${p}`,color:"gray",nodeSelect:r.label})}else u.push({text:" activity only",color:"gray",nodeSelect:r.label}),r.executing.length&&u.push({text:` · ${r.executing.length} sess`,color:"gray",nodeSelect:r.label});i.push(Si(u))}return i.push(J("","gray")),i.push(J("Click a node (or press 1-9) — its details fill the pane below.","gray")),n.missingHistoryCount>0&&i.push(J(`Loading worker history for ${n.missingHistoryCount} session(s)…`,"gray")),i}function wp(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),r=Math.max(24,e-4),o=[],a=[];let c=0;for(const m of n){const g=oe([{text:`${m.providerId}`,color:"cyan",bold:!0},{text:` (${m.providerType||"provider"})`,color:"gray"}],r);o.push(g),a.push(null);for(const h of m.models||[]){const y=Array.isArray(s.items)?s.items.findIndex(b=>b.id===h.id):-1,S=y===i,E=!!h.disabled,x=oe([{text:"· ",color:"gray"},{text:h.modelName||h.qualifiedName||h.id,color:E?"gray":"white",bold:!!h.isDefault&&!E},...h.cost?[{text:` [${h.cost}]`,color:"gray"}]:[],...E?[{text:" ⊘ needs GitHub key",color:"yellow"}]:[],...h.isDefault?[{text:" ← current default",color:"gray"}]:[]],r),w=S?Ke(x.map(b=>b.text).join("").padEnd(r," ")):x;S&&(c=o.length),o.push(w),a.push(y>=0?y:null)}}const u=Array.isArray(s.items)&&s.items[i]||null,p=Array.isArray(u?.supportedReasoningEfforts)?u.supportedReasoningEfforts.filter(Boolean):[],d=typeof u?.defaultReasoningEffort=="string"?u.defaultReasoningEffort:null,f=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"}]]:[],...p.length>0?[[{text:`Reasoning: ${p.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:o,rowItemIndexes:a,selectedRowIndex:c,detailsTitle:"Model Details",detailsLines:f,idealWidth:Math.min(Math.max(46,o.reduce((m,g)=>Array.isArray(g)?Math.max(m,ft(g)):Math.max(m,String(g?.text||"").length),0)+4),e)}}function Ip(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),r=Math.max(24,e-4),o={shared:"Shared",mine:"My agents",generic:""},a=n.some(y=>y?.packageName),c=[],u=[];let p=null;n.forEach((y,S)=>{const E=y?.group||"shared";if(a&&E!==p){const I=o[E]??"";c.push([{text:I?`── ${I} ──`:"──",color:"gray"}]),u.push(null),p=E}const x=S===i,w=y?.kind==="generic"?" [generic]":y?.packageName?` ${y.packageName} ${y.packageSemver||""}`.trimEnd():` (${y?.agentName||y?.id||"agent"})`,b=oe([{text:y?.kind==="generic"?"○ ":"· ",color:"gray"},{text:y?.title||y?.agentName||y?.id||"Agent",color:"white",bold:!0},{text:w,color:"gray"}],r);c.push(x?Ke(b.map(I=>I.text).join("").padEnd(r," ")):b),u.push(S)});const d=n[i]||null,f=s.sessionOptions?.model||null,m=s.sessionOptions?.reasoningEffort||null,g=d?[[{text:d.title||d.agentName||d.id||"Agent",color:"white",bold:!0}],...d.kind==="generic"?[[{text:"Open-ended session",color:"gray"}]]:[[{text:d.agentName||d.id||"agent",color:"gray"}]],...d.packageName?[[{text:`Package: ${d.packageName}@${d.packageSemver||"?"} · ${d.packageScope||"shared"}`,color:"gray"}]]:d.kind==="agent"?[[{text:"Built-in agent",color:"gray"}]]:[],...f?[[{text:`Model: ${f}`,color:"gray"}]]:[],...m?[[{text:`Reasoning: ${m}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:d.description||(d.kind==="generic"?"Create a general-purpose session without a specialized named agent.":"No description available for this agent."),color:d.description?"white":"gray"}],[{text:"",color:"gray"}],[{text:d.tools?.length?`Tools: ${d.tools.join(", ")}`:"Tools: system defaults only",color:"gray"}]]:[[{text:"No agent selected.",color:"gray"}]],h=u.indexOf(i);return{title:s.title||"Select agent for new session",rows:c,rowItemIndexes:u,selectedRowIndex:h>=0?h:0,detailsTitle:"Agent Details",detailsLines:g,idealWidth:Math.min(Math.max(52,c.reduce((y,S)=>Array.isArray(S)?Math.max(y,ft(S)):Math.max(y,String(S?.text||"").length),0)+4),e)}}function xp(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),r=Math.max(24,e-4),o=n.map((p,d)=>{const f=d===i,m=oe([{text:"· ",color:"gray"},{text:String(p?.label||p?.id||"effort"),color:"white",bold:!0},...p?.isDefault?[{text:" ← model default",color:"gray"}]:[]],r);return f?Ke(m.map(g=>g.text).join("").padEnd(r," ")):m}),a=n[i]||null,c=s.modelItem||null,u=[[{text:c?.modelName||c?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${c?.providerId||"provider"} (${c?.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:o,selectedRowIndex:i,detailsTitle:"Reasoning Details",detailsLines:u,idealWidth:Math.min(Math.max(46,o.reduce((p,d)=>Array.isArray(d)?Math.max(p,ft(d)):Math.max(p,String(d?.text||"").length),0)+4),e)}}function Ep(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),r=Math.max(24,e-4),o=n.map((d,f)=>{const m=f===i,g=oe([{text:"· ",color:"gray"},{text:String(d?.label||d?.id||"tier"),color:"white",bold:!0},...d?.isDefault?[{text:" ← model default",color:"gray"}]:[]],r);return m?Ke(g.map(h=>h.text).join("").padEnd(r," ")):g}),a=n[i]||null,c=s.modelItem||null,u=a?.label||a?.id,p=[[{text:c?.modelName||c?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${c?.providerId||"provider"} (${c?.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:o,selectedRowIndex:i,detailsTitle:"Context Window",detailsLines:p,idealWidth:Math.min(Math.max(46,o.reduce((d,f)=>Array.isArray(f)?Math.max(d,ft(f)):Math.max(d,String(f?.text||"").length),0)+4),e)}}function vp(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),r=Math.max(24,e-4),o=Array.isArray(s.sessionIds)?s.sessionIds.length:0,a=n.map((p,d)=>{const f=d===i,m=p?.kind==="noGroup"?"○ ":p?.kind==="newGroup"?"+ ":"🗂 ",g=oe([{text:m,color:p?.kind==="group"?"cyan":"gray",bold:p?.kind!=="noGroup"},{text:p?.label||p?.groupId||"Group",color:"white",bold:!0},...p?.kind==="group"?[{text:` (${p.memberCount??0})`,color:"gray"}]:[]],r);return f?Ke(g.map(h=>h.text).join("").padEnd(r," ")):g}),c=n[i]||null,u=c?[[{text:c.label||c.groupId||"Group",color:"white",bold:!0}],[{text:`${o} session${o===1?"":"s"} selected`,color:"gray"}],...c.kind==="group"?[[{text:`${c.memberCount??0} current member${c.memberCount===1?"":"s"}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:c.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((p,d)=>Array.isArray(d)?Math.max(p,ft(d)):Math.max(p,String(d?.text||"").length),0)+4),e)}}function kp(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,r=String(s.currentTitle||"").trim(),o=n.trim()?i?`${i}: ${n.trim()}`:n.trim():i?`${i}: …`:"…",a=[[{text:"Current: ",color:"gray"},{text:r||"(untitled session)",color:r?"white":"gray"}],[{text:"Saved as: ",color:"gray"},{text:o,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,Me(r||"(untitled session)")+18,Me(o)+18),e)}}function Ap(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,r=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:r,color:"white",bold:!0}],[{text:"Groups are containers only; session actions remain per-session.",color:"gray"}]],idealWidth:Math.min(Math.max(56,Me(r)+18),e)}}function Cp(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,r=i&&t.sessions?.byId?.[i]||null,o=i?r?ga(r,t.branding?.title):ce(i):"A new session will be created on upload",a=[[{text:"Target: ",color:"gray"},{text:o,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,Me(n||"~/path/to/file.md")+20,Me(o)+20),e)}}function bi(t,e={},s=96,n="Filters",i="Choose how this pane is filtered and rendered."){const r=Array.isArray(t.items)?t.items:[],o=Math.max(0,Number(t.selectedIndex)||0),a=r[o]||null,c=r.map((u,p)=>{const d=e?.[u.id]||u.options?.[0]?.id,f=(u.options||[]).map(m=>m.id===d?Ke(m.label):{text:m.label,color:"white"});return{id:u.id,title:u.label,focused:p===o,description:u.description||"",lines:f.length>0?f:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(u.label||"").length+4,...(u.options||[]).map(m=>String(m?.label||"").length+4))}});return{title:t.title||n,panes:c,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,c.reduce((u,p)=>u+p.idealWidth,0)+Math.max(0,c.length-1)*2+4),s)}}function Ha(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&&!!de(s?.principal):t.kind==="shared"?e?.includeShared===!0:t.kind==="owner"?Array.isArray(e?.ownerKeys)&&e.ownerKeys.includes(t.ownerKey):!1:!1}function Ir(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(i=>i?.kind!=="all"&&Ha(i,e,s)).map(i=>i.kind==="me"?"Me":i.label);return n.length>0?n.join(" + "):"All sessions"}function Tp(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},r=t.auth||{},o=Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1))),a=n[o]||null,c=n.map((p,d)=>{const f=Ha(p,i,r),m=p.kind==="system"?"yellow":p.kind==="unowned"?"gray":p.kind==="all"?"cyan":"white",g=[{text:f?"[x] ":"[ ] ",color:f?"cyan":"gray",bold:f},{text:p.label||p.id,color:m,bold:f}];return d===o?la(g,{preserveColors:!0}):g}),u=[[{text:"Active: ",color:"gray"},{text:Ir(n,i,r),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:c.length>0?c:[{text:"No filter entries available.",color:"gray"}],selectedRowIndex:o,detailsTitle:a?.label||"Session Filter",detailsLines:u,idealWidth:Math.min(Math.max(48,c.reduce((p,d)=>Math.max(p,Array.isArray(d)?ft(d):Me(d?.text||"")),0)+8,Me(Ir(n,i,r))+16),e)}}function Np(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:bi(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function Mp(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:bi(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function Pp(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),r=Math.max(28,e-4),o=n.filter(m=>m.kind==="artifact"),a=n.filter(m=>m.kind==="url"),c=o.reduce((m,g)=>{const h=t.files?.bySessionId?.[g.sessionId]?.downloads?.[g.filename];return m+(h?.localPath?1:0)},0),u=Math.max(0,o.length-c),p=n.map((m,g)=>{let h;if(m.kind==="downloadAll")h=oe([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${u} pending]`,color:"gray"}],r);else if(m.kind==="url")h=oe([{text:"go ",color:"cyan",bold:!0},{text:m.text&&m.text!==m.href?m.text:m.href,color:"white",bold:!0},...m.text&&m.text!==m.href?[{text:` ${m.href}`,color:"gray"}]:[]],r);else{const y=t.files?.bySessionId?.[m.sessionId]?.downloads?.[m.filename];h=oe([{text:y?.localPath?"ok ":"dl ",color:y?.localPath?"green":"cyan",bold:!0},{text:`${ce(m.sessionId)}/`,color:"gray"},{text:m.filename,color:"white"}],r)}return g!==i?h:Ke(h.map(y=>y.text).join("").padEnd(r," "))}),d=n[i]||null;let f=[[{text:"No linked item selected.",color:"gray"}]];if(d?.kind==="downloadAll")f=[[{text:`${o.length} artifacts available`,color:"white",bold:!0}],...a.length>0?[[{text:`${a.length} links available`,color:"gray"}]]:[],[{text:`${c} 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")f=[[{text:d.text||d.href,color:"white",bold:!0}],[{text:d.href,color:"gray"}],[{text:"",color:"gray"}],[{text:"Press Enter to open this link in the browser.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(d?.kind==="artifact"){const m=t.sessions?.byId?.[d.sessionId]||null,g=t.files?.bySessionId?.[d.sessionId]?.downloads?.[d.filename]||null;f=[[{text:d.filename,color:"white",bold:!0}],[{text:m?ga(m,t.branding?.title):ce(d.sessionId),color:"gray"}],...g?.localPath?[[{text:`Saved to: ${g.localPath}`,color:"white"}]]:s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:g?.localPath?"Press Enter to download this artifact again.":"Press Enter to download this artifact.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]]}return{title:s.title||"Linked Items",rows:p.length>0?p:[{text:"No linked items available.",color:"gray"}],selectedRowIndex:i,detailsTitle:"Linked Item Details",detailsLines:f,confirmLabel:a.length>0?o.length>0?"Open / Download":"Open":"Download",idealWidth:Math.min(Math.max(54,p.reduce((m,g)=>Array.isArray(g)?Math.max(m,ft(g)):Math.max(m,String(g?.text||"").length),0)+4),e)}}function X(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 Ga(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 _p(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 ls(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 qt(t){return["session","fleet","users"].includes(t)?t:"session"}function js(t,e){const s=qt(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"}),oe(n,e)}function $p(t,e,s){if(!e)return[J("No session selected.")];const n=t.sessionStats?.bySessionId?.[e.sessionId]||null;if(!n||n.loading&&!n.summary)return[J("Loading session stats...")];const i=n.summary;if(!i)return[J("Session stats unavailable.")];const r=[],o=Math.max(24,s);r.push(js("session",o)),r.push(J("")),r.push(oe([{text:"Session ",color:"cyan",bold:!0},{text:ce(e.sessionId),color:"white"}],o));const a=e.isSystem?"system":e.owner?"user":"unowned",c=e.isSystem?"system":e.owner?Ds(e.owner):"(?) unowned",u=e.owner?.email||"—";r.push(oe([{text:"Owner ",color:"cyan",bold:!0},{text:c,color:e.owner?"white":"gray"}],o)),r.push(oe([{text:"Email ",color:"cyan",bold:!0},{text:u,color:e.owner?.email?"white":"gray"}],o)),r.push(oe([{text:"Type ",color:"cyan",bold:!0},{text:a,color:a==="user"?"white":"gray"}],o)),i.agentId&&r.push(oe([{text:"Agent ",color:"cyan",bold:!0},{text:i.agentId,color:"white"}],o));const p=hi(i.model||e.model,i.reasoningEffort||e.reasoningEffort);p&&r.push(oe([{text:"Model ",color:"cyan",bold:!0},{text:p,color:"white"}],o)),e.createdAt&&r.push(oe([{text:"Created ",color:"cyan",bold:!0},{text:ls(e.createdAt),color:"white"}],o)),e.updatedAt&&r.push(oe([{text:"Updated ",color:"cyan",bold:!0},{text:ls(e.updatedAt),color:"white"}],o)),r.push(J(""));const d=Array.isArray(n.tokensByModel)?n.tokensByModel:[];d.length>1&&(r.push(...me({title:"Models",body:d.map(O=>`${Md(O.model)} · ${O.turnCount||0} turns · ${X(O.totalTokensInput)} in / ${X(O.totalTokensOutput)} out`).join(`
52
- `),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),r.push(J("")));const f=(i.tokensInput||0)+(i.tokensOutput||0),m=i.cacheHitRatio,g=m==null?"—":`${(m*100).toFixed(1)}%`;r.push(...me({title:"Tokens",body:dt([["Input",X(i.tokensInput)],["Output",X(i.tokensOutput)],["Total",X(f)],["Cache Read",X(i.tokensCacheRead)],["Cache Write",X(i.tokensCacheWrite)],["Hit Ratio",g]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0})),r.push(J(""));const h=Number(i.regenCount)||0,y=i.lastRegenStats&&typeof i.lastRegenStats=="object"?i.lastRegenStats:null,S=Number.isFinite(y?.toEpoch)?y.toEpoch:h,E=y?y.distillMode==="deterministic"||!y.distillMode&&!y.distillerModel?"fast":String(y.distillerModel||"llm").replace(/^[^:]*:/,""):null,x=y?`${y.turnsArchived??0} turn${y.turnsArchived===1?"":"s"} · ${(Number(y.totalMs)/1e3).toFixed(1)}s${E?` · ${E}`:""}`:null;r.push(...me({title:"Persistence",body:dt([["Epoch",String(S)],["Regens",h>0?String(h):null],["Last Regen",x],["Snapshot",be(i.snapshotSizeBytes)],["Uncompressed",i.rawSizeBytes?be(i.rawSizeBytes):null],["Compression",Sr(i.rawSizeBytes,i.snapshotSizeBytes)],["Dehydrations",String(i.dehydrationCount)],["Hydrations",String(i.hydrationCount)],["Lossy Handoffs",String(i.lossyHandoffCount)],["Last Dehydrated",i.lastDehydratedAt?ls(i.lastDehydratedAt):null],["Last Hydrated",i.lastHydratedAt?ls(i.lastHydratedAt):null]]),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const w=n.treeStats?.tree;if(w&&w.sessionCount>1){const O=w.cacheHitRatio,_=O==null?"—":`${(O*100).toFixed(1)}%`,L=(w.totalTokensInput||0)+(w.totalTokensOutput||0);r.push(J("")),r.push(...me({title:`Tree (${w.sessionCount} sessions)`,body:dt([["Input",X(w.totalTokensInput)],["Output",X(w.totalTokensOutput)],["Total",X(L)],["Cache Read",X(w.totalTokensCacheRead)],["Cache Write",X(w.totalTokensCacheWrite)],["Hit Ratio",_],["Snapshot",be(w.totalSnapshotSizeBytes)],["Uncompressed",w.totalRawSizeBytes?be(w.totalRawSizeBytes):null],["Compression",Sr(w.totalRawSizeBytes,w.totalSnapshotSizeBytes)],["Dehydrations",String(w.totalDehydrationCount)],["Hydrations",String(w.totalHydrationCount)]]),width:o,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const W=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];W.length>1&&(r.push(J("")),r.push(...me({title:"Tree By Model",body:Dp(W),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const b=Array.isArray(n.skillUsage)?n.skillUsage:[];b.length>0&&(r.push(J("")),r.push(...me({title:`Skills (${b.length})`,body:xr(b,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const I=n.treeSkillUsage,k=Array.isArray(I?.rolledUp)?I.rolledUp:[],P=Array.isArray(I?.perSession)?I.perSession.length:0;k.length>0&&P>1&&(r.push(J("")),r.push(...me({title:`Tree Skills (${k.length})`,body:xr(k,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const M=n.factsStats,B=n.treeFactsStats;if(M&&Array.isArray(M.rows)&&M.rows.length>0){r.push(J(""));const O=ja(M.rows),_=O?O.split(`
53
- `).length:0,L=`${M.totalCount} · ${be(M.totalBytes)}`;let W=O;B&&B.totalCount>M.totalCount&&(W+=`
54
- Tree (${B.sessionIds.length} sessions): ${B.totalCount} · ${be(B.totalBytes)}`),_>0&&r.push(...me({title:`Facts (${L})`,body:W,width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return r}function dt(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,[c])=>Math.max(a,String(c).length),0),r=n.reduce((a,[,c])=>Math.max(a,String(c).length),0),o=" ".repeat(s);return n.map(([a,c])=>`${String(a).padEnd(i)}${o}${String(c).padStart(r)}`).join(`
55
- `)}function Us(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 ns(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,c)=>Math.max(a,c.length),0),r=new Array(i).fill(0);for(const a of n)for(let c=0;c<i;c+=1){const u=a[c]==null?"":String(a[c]);u.length>r[c]&&(r[c]=u.length)}const o=" ".repeat(s);return n.map(a=>a.map((c,u)=>{const p=c==null?"":String(c);return u===0?p.padEnd(r[u]):p.padStart(r[u])}).join(o)).join(`
56
- `)}function xr(t,e){const s=t.slice().sort((d,f)=>(f.invocations||0)-(d.invocations||0)).slice(0,12),n=s.map(d=>`${d.invocations||0} inv`),i=n.reduce((d,f)=>Math.max(d,f.length),0),a=4+2+i,c=Number.isFinite(e)&&e>0?Math.max(8,Math.floor(e)-a):1/0,u=s.map((d,f)=>{const m=d.kind==="learned"?"L":"S",g=String(d.name||"(unknown)");return[Us(`${m} ${g}`,c),n[f]]}),p=ns(u);return t.length>s.length?`${p}
57
- … ${t.length-s.length} more`:p}function ja(t){const s=t.slice().sort((n,i)=>(i.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),be(n.totalValueBytes||0)]);return ns(s)}function Rp(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":Et(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return ns([["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 Op(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 Lp(t,e){const s=t.slice().sort((d,f)=>(Number(f.calls)||0)-(Number(d.calls)||0)).slice(0,12),n=s.map(d=>`${Number(d.calls)||0} calls`),i=s.map(d=>`${Number(d.totalResults)||0} res`),r=n.reduce((d,f)=>Math.max(d,f.length),0),o=i.reduce((d,f)=>Math.max(d,f.length),0),a=6+r+2+o,c=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-a):1/0,u=s.map((d,f)=>{const m=d.namespace?` ${d.namespace}`:"";return[Us(`${Op(d.operation)}${m}`,c),n[f],i[f]]}),p=ns(u);return t.length>s.length?`${p}
58
- … ${t.length-s.length} more`:p}function Fp(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.data)return[J("Loading fleet stats...")];const n=s.data;if(!n)return[J("Fleet stats unavailable.")];const i=[],r=Math.max(24,e);i.push(js("fleet",r)),i.push(J(""));const o=n.windowStart?`Since: ${Ga(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(oe([{text:o,color:"cyan"},{text:a?` ${a}`:"",color:"gray"}],r)),i.push(oe([{text:`Sessions: ${n.totals.sessionCount}`,color:"white"},{text:` Tokens: ${X(n.totals.totalTokensInput)} in / ${X(n.totals.totalTokensOutput)} out`,color:"white"}],r)),i.push(J(""));const c=new Map;for(const h of n.byAgent||[]){const y=h.model||"(default)",S=c.get(y)||{totalTokensInput:0,totalTokensOutput:0,totalTokensCacheRead:0,totalTokensCacheWrite:0,totalSnapshotSizeBytes:0,turnCount:0};S.totalTokensInput+=Number(h.totalTokensInput)||0,S.totalTokensOutput+=Number(h.totalTokensOutput)||0,S.totalTokensCacheRead+=Number(h.totalTokensCacheRead)||0,S.totalTokensCacheWrite+=Number(h.totalTokensCacheWrite)||0,S.totalSnapshotSizeBytes+=Number(h.totalSnapshotSizeBytes)||0,S.turnCount+=Number(h.turnCount)||0,c.set(y,S)}if(c.size>0){const h=[];for(const[y,S]of c.entries()){const E=S.totalTokensInput>0?S.totalTokensCacheRead/S.totalTokensInput:null;h.push(y),h.push(wi(S,E)),h.push("")}i.push(...me({title:"Tokens By Model",body:h.join(`
59
- `).trimEnd(),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(J(""))}const u=n.totals.cacheHitRatio,p=u==null?"—":`${(u*100).toFixed(1)}%`;i.push(...me({title:"Fleet Totals",body:dt([["Sessions",String(n.totals.sessionCount)],["Tokens In",X(n.totals.totalTokensInput)],["Tokens Out",X(n.totals.totalTokensOutput)],["Total Tokens",X(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",X(n.totals.totalTokensCacheRead)],["Cache Write",X(n.totals.totalTokensCacheWrite)],["Hit Ratio",p],["Snapshots",be(n.totals.totalSnapshotSizeBytes)]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0}));const d=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(h=>!(h&&h.agentId==="facts-manager"&&String(h.name||"").startsWith("skills/")));d.length>0&&(i.push(J("")),i.push(...me({title:`Fleet Skills (${d.length})`,body:Bp(d,e),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const f=Array.isArray(s.retrievalUsage?.rows)?s.retrievalUsage.rows:[];if(f.length>0){const h=f.reduce((y,S)=>y+(Number(S.calls)||0),0);i.push(J("")),i.push(...me({title:`Fleet Retrieval (${X(h)})`,body:Lp(f,e),width:r,titleColor:"magenta",borderColor:"gray",fitToContent:!0}))}const m=s.sharedFactsStats;if(m&&Array.isArray(m.rows)&&m.rows.length>0){i.push(J(""));const h=`${m.totalCount} · ${be(m.totalBytes)}`;i.push(...me({title:`Shared Facts (${h})`,body:ja(m.rows),width:r,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const g=s.factsTombstoneStats;return g&&Number(g.pendingTotal)>0&&(i.push(J("")),i.push(...me({title:`Fact Tombstones (${Number(g.pendingTotal)||0})`,body:Rp(g),width:r,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),i}function Bp(t,e){const n=t.slice().sort((g,h)=>{const y=b=>b==="learned"?1:0,S=y(g.kind)-y(h.kind);if(S!==0)return S;const E=g.agentId?0:1,x=h.agentId?0:1;if(E!==x)return E-x;const w=String(g.agentId||"").localeCompare(String(h.agentId||""));return w!==0?w:String(g.name||"").localeCompare(String(h.name||""))}).slice(0,15),i=n.map(g=>`${g.invocations||0} inv`),r=n.map(g=>`${g.sessionCount||0} sess`),o=i.reduce((g,h)=>Math.max(g,h.length),0),a=r.reduce((g,h)=>Math.max(g,h.length),0),c=4,u=2,p=c+u+o+u+a,d=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-p):1/0,f=n.map((g,h)=>{const y=g.kind==="learned"?"L":"S",S=g.agentId||".",E=String(g.name||"(unknown)");return[Us(`${y} ${S}/${E}`,d),i[h],r[h]]}),m=ns(f);return t.length>n.length?`${m}
60
- … ${t.length-n.length} more`:m}function Dp(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(wi(n,i)),s.push("")}return s.join(`
61
- `).trimEnd()}function wi(t,e){const s=e==null?"—":`${(e*100).toFixed(1)}%`,n=(Number(t.totalTokensInput)||0)+(Number(t.totalTokensOutput)||0),i=[["Input",X(t.totalTokensInput||0)],["Output",X(t.totalTokensOutput||0)],["Total",X(n)],["Turns",X(t.turnCount||0)],["Cache Read",X(t.totalTokensCacheRead||0)],["Cache Write",X(t.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",be(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&i.push(["Orch",be(t.totalOrchestrationHistorySizeBytes||0)]),dt(i).split(`
62
- `).map(o=>` ${o}`).join(`
63
- `)}function Ln(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":Ds(t?.owner,"Unknown User")}function Hp(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=Ln(t);return e&&e!==s?e:""}function Gp(t,e){const s=Array.isArray(t?.byModel)?t.byModel:[];if(s.length===0)return"";const n=s.slice().sort((r,o)=>(o.totalTokensInput||0)-(r.totalTokensInput||0)).slice(0,6),i=[];for(const r of n){const o=Us(String(r.model||"(default)"),Math.max(12,e-10));i.push(`${o} · ${r.sessionCount||0} sess · ${r.turnCount||0} turns`),i.push(wi(r,r.cacheHitRatio)),i.push("")}return s.length>n.length&&i.push(`… ${s.length-n.length} more models`),i.join(`
64
- `).trimEnd()}function jp(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.userStats)return[J("Loading user stats...")];const n=s.userStats;if(!n)return[J("User stats unavailable.")];const i=[],r=Math.max(24,e);i.push(js("users",r)),i.push(J(""));const o=n.windowStart?`Since: ${Ga(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(oe([{text:o,color:"cyan"},{text:a?` ${a}`:"",color:"gray"}],r)),i.push(oe([{text:`Users: ${Array.isArray(n.users)?n.users.length:0}`,color:"white"},{text:` Sessions: ${n.totals.sessionCount||0}`,color:"white"}],r)),i.push(J(""));const c=n.totals.cacheHitRatio,u=c==null?"—":`${(c*100).toFixed(1)}%`;i.push(...me({title:"User Totals",body:dt([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",X(n.totals.totalTokensInput||0)],["Tokens Out",X(n.totals.totalTokensOutput||0)],["Total Tokens",X((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",X(n.totals.totalTokensCacheRead||0)],["Cache Write",X(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",u],["Snapshots",be(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",be(n.totals.totalOrchestrationHistorySizeBytes||0)]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0}));const p=Array.isArray(n.users)?n.users:[],d=p.slice().sort((f,m)=>(m.totalTokensInput||0)-(f.totalTokensInput||0)||(m.totalSnapshotSizeBytes||0)-(f.totalSnapshotSizeBytes||0)).slice(0,8);for(const f of d){const m=Hp(f),g=f.cacheHitRatio,h=g==null?"—":`${(g*100).toFixed(1)}%`,y=m?`${Ln(f)} <${m}>`:Ln(f),S=dt([["Sessions",String(f.sessionCount||0)],["Tokens In",X(f.totalTokensInput||0)],["Tokens Out",X(f.totalTokensOutput||0)],["Total Tokens",X((f.totalTokensInput||0)+(f.totalTokensOutput||0))],["Cache Read",X(f.totalTokensCacheRead||0)],["Cache Write",X(f.totalTokensCacheWrite||0)],["Hit Ratio",h],["Snapshots",be(f.totalSnapshotSizeBytes||0)],["Orch Size",be(f.totalOrchestrationHistorySizeBytes||0)]]),E=Gp(f,r);i.push(J("")),i.push(...me({title:`${y} (${f.sessionCount||0})`,body:E?`${S}
65
-
66
- ${E}`:S,width:r,titleColor:f.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return p.length>d.length&&(i.push(J("")),i.push(J(`… ${p.length-d.length} more users`))),i}function it(t,e={}){const s=De(t),n=t.ui.inspectorTab,i=Math.max(18,Number(e?.width)||36),r=!!e?.allowWideColumns,o=ca(i);if(s?.isGroup)return{title:Ue("Inspector","magenta"),activeTab:n,tabs:We,disabled:!0,stickyLines:[],lines:[J(Ua,"gray")]};const a=s?ce(s.sessionId):"",c=n==="sequence"||n==="nodes"?yi(t):null,u=n==="nodes"?[...Ue("Node Map","magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:s?n==="sequence"?[...Ue(o?"Sequence":`Sequence: ${a}`,"magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:n==="logs"?[...Ue(o?"Logs":`Logs: ${a}`,"magenta")]:n==="history"?[...Ue(o?"History":`History: ${a}`,"magenta")]:n==="stats"?[...Ue(o?"Stats":`Stats: ${a}`,"magenta"),{text:` [${qt(t.ui?.statsViewMode)}]`,color:"gray"}]:[...Ue(o?"Files":`Files: ${a}`,"magenta")]:n==="stats"?`Stats: ${qt(t.ui?.statsViewMode).replace(/^./u,f=>f.toUpperCase())}`:"No session selected";let p,d=[];switch(n){case"sequence":{const f=s?fp(t,s,i,{allowWideColumns:r,sequenceExpansion:e?.sequenceExpansion||null}):{stickyLines:[],lines:["No session selected."]};d=f.stickyLines||[],p=f.lines;break}case"logs":p=s?Fd(t,s):["No session selected."];break;case"nodes":p=bp(t,i,{});break;case"files":p=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":p=s?Vp(t,s):["No session selected."];break;case"stats":p=qt(t.ui?.statsViewMode)==="users"?jp(t,i):qt(t.ui?.statsViewMode)==="fleet"?Fp(t,i):s?$p(t,s,i):[js("session",Math.max(24,i)),J(""),J("No session selected. Press f to cycle to fleet or users view.")];break;default:p=["Inspector view is scaffolded in the new architecture."];break}return{title:u,activeTab:n,tabs:We,stickyLines:d,lines:p}}const Up={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"},Ua="Select a session to see details.";function Wp(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=Up[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 r=JSON.parse(t.data);if(typeof r=="object"&&r!==null)for(const[o,a]of Object.entries(r)){const c=typeof a=="string"?a:JSON.stringify(a),u=c.length>100?c.slice(0,97)+"...":c;n.push([{text:` ${o}: `,color:"yellow"},{text:u,color:"white"}])}else n.push({text:` ${String(r).slice(0,120)}`,color:"white"})}catch{const r=t.data.length>120?t.data.slice(0,117)+"...":t.data;n.push({text:` ${r}`,color:"white"})}return n}function Kp(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function Vp(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",r=[];if(r.push({text:`${n.length} event(s) · format: ${i}`,color:"gray"}),r.push(""),i==="raw")for(let o=0;o<n.length;o++){const a=Kp(n[o]).split(`
67
- `);for(const c of a)r.push({text:c,color:"gray"});o<n.length-1&&r.push({text:"────────────────────────────────",color:"gray"})}else for(let o=0;o<n.length;o++){const a=Wp(n[o]);for(const c of a)r.push(c);o<n.length-1&&r.push({text:"────────────────────────────────",color:"gray"})}return r}function qp(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:bi(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function Er(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 zp(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),r=n[i]||null,o=s.currentThemeId||t.ui.themeId||null,a=n.find(f=>f.id===o)||null,c=r&&r.id!==o,u=Math.max(24,e-4),p=n.map((f,m)=>{const g=f.id===o?" [current]":"",h=`${f.label}${g}`.slice(0,u);return m===i?Ke(h.padEnd(u," ")):[{text:h,color:f.id===o?"cyan":"white",bold:f.id===o}]}),d=r?[[{text:`theme: ${r.description||"Shared theme for the portal and native TUI."}`,color:"white"}],{text:"",color:"gray"},[{text:c?`Previewing now. Cancel reverts to ${a?.label||"the previous theme"}.`:"Currently active in this TUI session.",color:c?"yellow":"green"}],Er([{label:"bg",color:r.tui?.background||r.terminal?.background||"#000000"},{label:"surface",color:r.tui?.surface||r.terminal?.background||"#000000"},{label:"fg",color:r.tui?.white||r.terminal?.foreground||"#ffffff"}]),Er([{label:"blue",color:r.tui?.blue||r.terminal?.blue||"#5555ff"},{label:"green",color:r.tui?.green||r.terminal?.green||"#55ff55"},{label:"magenta",color:r.tui?.magenta||r.terminal?.magenta||"#ff55ff"},{label:"yellow",color:r.tui?.yellow||r.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:p,selectedRowIndex:i,detailsTitle:"Theme Details",detailsLines:d}}function Yp(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 vr(t){return new Map(t)}function zt(t){return new Set(t)}function Xp(t){return Array.isArray(t)?[...t]:[]}function Qp(t){return Array.isArray(t)?[...t]:[]}const Jp=5e3;function Fn(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 Wa(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function cs(t,e){return Fn(t,e).filter(s=>Wa(e[s]))}function Ka(t){return zt(t)}function Zp(t,e){const s=[],n=new Set([t]);let i=e?.[t]||null;for(;i;){let r=null;if(i.parentSessionId&&e?.[i.parentSessionId]?r=i.parentSessionId:!i.isGroup&&i.groupId&&e?.[`group:${i.groupId}`]&&(r=`group:${i.groupId}`),!r||n.has(r))break;s.push(r),n.add(r),i=e[r]||null}return s}function kr(t,e,s){const n=Ka(t);if(!s||!e?.[s])return n;for(const i of Zp(s,e))n.delete(i);return n}function Ar(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 ef(t){return{...t||{}}}function qe(t){return{...t||{}}}function Cr(t){return{...t||{}}}function us(t){return{...t||{}}}function mn(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function tf(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function sf(t){return[T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY].includes(t)?t:null}function gn(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(le,Number(e)||le);return s.length>n?s.slice(-n):s}function Bn(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(!Bn(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)||!Bn(t[i],e[i]))return!1;return!0}function Tr(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 nf(t,e){const s=Tr(t),n=Tr(e);return s>0&&n>0&&n<=s}const rf=new Set(["completed","failed","cancelled","error"]);function of(t,e){const s=String(e?.status??"").toLowerCase();if(t?.status!=="running"||s==="running"||rf.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:nf(t,e)}function Nr(t={},e={}){let s=t||{};const n=of(t,e);for(const[i,r]of Object.entries(e||{}))if(r!==void 0&&!(i==="status"&&n)){if(i==="pendingQuestion"&&af(t,r)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}Bn(t?.[i],r)||(s===t&&(s={...t||{}}),s[i]=r)}return s}function Mr(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function Pr(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=Mr(e),i=t?.rowVisualStatus||Mr(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 o=t.rowVisualStatusCandidate===n&&Number(t.rowVisualStatusCandidateSince)||s;return s-o>=Jp?{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0}:e.rowVisualStatus===i&&e.rowVisualStatusCandidate===n&&Number(e.rowVisualStatusCandidateSince)===o?e:{...e,rowVisualStatus:i,rowVisualStatusCandidate:n,rowVisualStatusCandidateSince:o}}function _r(t){return String(t?.question||"").trim()}function af(t,e){const s=_r(t?.answeredPendingQuestion),n=_r(e);return!!(s&&n&&s===n)}function lf(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&Do(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function $r(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 Rr(t={}){const e=String(t?.filterQuery||"").trim(),s=ks(t?.ownerFilter);return!!e||s.all!==!0}function cf(t,e=[]){const s=Ot(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(r=>r.sessionId===n)||t.sessions?.navigationIntent||n&&t.sessions?.byId?.[n]&&!Rr(t.sessions)||n&&!t.sessions?.listingSeen)return n;if(Rr(t.sessions))return s[0]?.sessionId||null;const i=s.length>0?s.map(r=>t.sessions?.byId?.[r.sessionId]||null).filter(Boolean):e;return lf(i)}function uf(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 ot(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 r=s.activeSessionId||null;if(r&&s.byId?.[r]){const d=kr(s.collapsedIds,s.byId,r);Ar(d,s.collapsedIds)||(s={...s,collapsedIds:d,flat:je(Object.values(s.byId||{}),d,s.orderById,s.pinnedIds,s.manualOrder)})}i&&s.filterExceptionId!==i&&(Ot({...t,sessions:s}).some(f=>f.sessionId===i)||(s={...s,filterExceptionId:i}));const o={...t,sessions:s},a=cf(o,Object.values(s.byId||{})),c=kr(s.collapsedIds,s.byId,a);return{sessions:{...!Ar(c,s.collapsedIds)?{...s,collapsedIds:c,flat:je(Object.values(s.byId||{}),c,s.orderById,s.pinnedIds,s.manualOrder)}:s,activeSessionId:a},ui:uf(t,a)}}function yn(t={},e=0,s=[]){const n=ef(t);let i=Number.isFinite(e)?e:0;for(const r of s||[]){const o=r?.sessionId;o&&typeof n[o]!="number"&&(n[o]=i,i+=1)}return{orderById:n,nextOrderOrdinal:i}}function df(t=[],e=[]){const s=je(t,new Set,{},e),n={};let i=0;for(const r of s){const o=r?.sessionId;!o||typeof n[o]=="number"||(n[o]=i,i+=1)}for(const r of t||[]){const o=r?.sessionId;!o||typeof n[o]=="number"||(n[o]=i,i+=1)}return{orderById:n,nextOrderOrdinal:i}}function pf(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 Or(t,e){const s=String(t||"");return(Array.isArray(e)?e.filter(Boolean):[]).filter(i=>{if(i?.kind==="image")return!0;const r=String(i?.token||"").trim();return r&&s.includes(r)})}function ff(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"),r=Object.prototype.hasOwnProperty.call(s,"layoutAdjustments"),o=Object.prototype.hasOwnProperty.call(s,"chatViewMode")&&(s.chatViewMode==="summary"||s.chatViewMode==="transcript"),a=Object.prototype.hasOwnProperty.call(s,"pinnedSessionIds"),c=Object.prototype.hasOwnProperty.call(s,"collapsedSessionIds"),u=Object.prototype.hasOwnProperty.call(s,"sessionOrder"),p=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.status!=="failed"),d=Object.prototype.hasOwnProperty.call(s,"activeSessionId")&&!p,f=Object.keys(t.sessions.byId||{}).length>0,m=r?{...t.ui.layout||{},...ti(s.layoutAdjustments)}:t.ui.layout,g=a?f?cs(Cs(s.pinnedSessionIds),t.sessions.byId):Cs(s.pinnedSessionIds):t.sessions.pinnedIds,h=c?f?Ka(Pn(s.collapsedSessionIds),t.sessions.byId):Pn(s.collapsedSessionIds):t.sessions.collapsedIds,y=u?si(s.sessionOrder):t.sessions.manualOrder,S=d?ra(s.activeSessionId):t.sessions.activeSessionId,E={...t.sessions,...i?{ownerFilter:ks(s.sessionOwnerFilter),ownerFilterExplicit:!0}:{},pinnedIds:g,manualOrder:y,collapsedIds:h,collapsedIdsExplicit:c?!0:t.sessions.collapsedIdsExplicit,activeSessionId:S,flat:a||c||u?je(Object.values(t.sessions.byId),h,t.sessions.orderById,g,y):t.sessions.flat},x=f&&(i||a||c||d)?ot(t,E):{sessions:E,ui:t.ui};return{...t,sessions:x.sessions,ui:{...x.ui,themeId:n?s.themeId.trim():x.ui.themeId,chatViewMode:o?s.chatViewMode:x.ui.chatViewMode,layout:m}}}case"ui/chatViewMode":return e.mode!=="summary"&&e.mode!=="transcript"?t:{...t,ui:{...t.ui,chatViewMode:e.mode,scroll:{...t.ui.scroll,chat:0}}};case"ui/modal":return{...t,ui:{...t.ui,modal:e.modal??null}};case"ui/viewport":{const s=t.ui.layout?.viewportWidth??120,n=t.ui.layout?.viewportHeight??40,i=Math.max(40,e.width??s),r=Math.max(18,e.height??n);return i===s&&r===n?t:{...t,ui:{...t.ui,layout:{...t.ui.layout||{},viewportWidth:i,viewportHeight:r}}}}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=ot(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:ks(e.filter),navigationIntent:null,filterExceptionId:null},n=ot(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=ot(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/nodeMapSelect":return e.label?{...t,ui:{...t.ui,nodeMapSelectedNode:String(e.label)}}:t;case"ui/inspectorTab":return{...t,ui:{...t.ui,inspectorTab:e.inspectorTab,fullscreenPane:e.inspectorTab==="files"&&t.ui.fullscreenPane===T.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:pf(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:Nt(e.prompt),promptAttachments:Or(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:Or(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 r={...t.sessions.byId};delete r[s];const o=Array.isArray(t.sessions.selectedIds)?t.sessions.selectedIds.filter(a=>a!==s):t.sessions.selectedIds;return{...t,sessions:{...t.sessions,byId:r,selectedIds:o,activeSessionId:i?null:t.sessions.activeSessionId}}}case"sessions/loaded":{const s={};let n=!1;const i=Date.now();for(const w of t.sessions.groupRows||[])s[w.sessionId]=t.sessions.byId[w.sessionId]||w;for(const w of e.sessions){const b=t.sessions.byId[w.sessionId],I=Pr(b,Nr(b,w),i);s[w.sessionId]=I,!n&&I!==b&&(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 r=Object.keys(t.sessions.byId),o=Object.keys(s);if(r.length!==o.length&&(n=!0),!n){for(const w of o)if(!t.sessions.byId[w]){n=!0;break}}if(!n)return t;const a=Object.values(s),c=Object.keys(t.sessions.orderById||{}).length>0,u=$r(a),p=!!t.sessions.collapsedIdsExplicit,{orderById:d,nextOrderOrdinal:f}=c?yn(t.sessions.orderById,t.sessions.nextOrderOrdinal,a):df(a,t.sessions.pinnedIds),m=p?zt(t.sessions.collapsedIds):u,g=t.sessions.listingSeen===!0;if(p&&g){const w=$r(Object.values(t.sessions.byId));for(const b of u)w.has(b)||m.add(b)}const h=cs(t.sessions.pinnedIds,s),y=Fn(t.sessions.selectedIds,s),S=je(a,m,d,h,t.sessions.manualOrder),E={...t.sessions,byId:s,collapsedIds:m,collapsedIdsExplicit:p,listingSeen:!0,pinnedIds:h,selectedIds:y,selectMode:t.sessions.selectMode&&y.length>0,flat:S,activeSessionId:t.sessions.activeSessionId,orderById:d,nextOrderOrdinal:f},x=ot(t,E);return{...t,sessions:x.sessions,ui:x.ui}}case"sessions/groupsLoaded":{const s=Array.isArray(e.groups)?e.groups:[],n={...t.sessions.byId},i=Array.isArray(e.sessions)?e.sessions:Object.values(t.sessions.byId),r=new Set(i.filter(g=>g&&!g.isGroup&&g.groupId&&!g.parentSessionId).map(g=>`group:${g.groupId}`)),o=[];for(const g of Object.keys(n))if(n[g]?.isGroup&&!s.some(h=>h.sessionId===g)){if(r.has(g)){o.push(n[g]);continue}delete n[g]}for(const g of s)n[g.sessionId]={...n[g.sessionId]||{},...g};const a=cs(t.sessions.pinnedIds,n),{orderById:c,nextOrderOrdinal:u}=yn(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(n)),p=t.sessions.groupsListingSeen===!0,d=zt(t.sessions.collapsedIds);for(const g of s)p&&(t.sessions.byId[g.sessionId]||d.add(g.sessionId));const f={...t.sessions,groupRows:[...s,...o],byId:n,pinnedIds:a,orderById:c,nextOrderOrdinal:u,collapsedIds:d,groupsListingSeen:!0,flat:je(Object.values(n),d,c,a,t.sessions.manualOrder)},m=ot(t,f);return{...t,sessions:m.sessions,ui:m.ui}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=Pr(s,Nr(s,e.session),Date.now());if(n===s)return t;const i={...t.sessions.byId,[e.session.sessionId]:n},r=cs(t.sessions.pinnedIds,i),{orderById:o,nextOrderOrdinal:a}=yn(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(i)),c={...t.sessions,byId:i,pinnedIds:r,flat:je(Object.values(i),t.sessions.collapsedIds,o,r,t.sessions.manualOrder),activeSessionId:t.sessions.activeSessionId,orderById:o,nextOrderOrdinal:a},u=ot(t,c);return{...t,sessions:u.sessions,ui:u.ui}}case"sessions/selected":{t={...t,sessions:{...t.sessions,listDeselected:!1}};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=sf(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=zt(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:je(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds,t.sessions.manualOrder)}}}case"sessions/expand":{const s=zt(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:je(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds,t.sessions.manualOrder)}}}case"sessions/pinToggle":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=t.sessions.byId[s];if(!Wa(n))return t;const i=Xp(t.sessions.pinnedIds),o=i.indexOf(s)>=0?i.filter(a=>a!==s):[...i,s];return{...t,sessions:{...t.sessions,pinnedIds:o,flat:je(Object.values(t.sessions.byId),t.sessions.collapsedIds,t.sessions.orderById,o,t.sessions.manualOrder)}}}case"sessions/reorder":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=t.sessions.byId[s];if(!Rt(n))return t;const i=e.beforeSessionId==null?null:String(e.beforeSessionId).trim()||null;if(i===s)return t;const o=(Array.isArray(t.sessions.manualOrder)&&t.sessions.manualOrder.length>0?t.sessions.manualOrder:(t.sessions.flat||[]).map(p=>p.sessionId).filter(p=>Rt(t.sessions.byId[p]))).filter(p=>p!==s),a=i?o.indexOf(i):-1,c=a>=0?[...o.slice(0,a),s,...o.slice(a)]:[...o,s];return c.length===(t.sessions.manualOrder||[]).length&&c.every((p,d)=>p===t.sessions.manualOrder[d])?t:{...t,sessions:{...t.sessions,manualOrder:c,flat:je(Object.values(t.sessions.byId),t.sessions.collapsedIds,t.sessions.orderById,t.sessions.pinnedIds,c)}}}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=Qp(t.sessions.selectedIds),o=i.indexOf(s)>=0?i.filter(a=>a!==s):[...i,s];return{...t,sessions:{...t.sessions,selectedIds:o,selectMode:o.length>0?!0:t.sessions.selectMode}}}case"sessions/selectSet":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[],n=Fn(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/listReselect":return t.sessions.listDeselected?{...t,sessions:{...t.sessions,listDeselected:!1}}:t;case"sessions/listDeselect":return{...t,sessions:{...t.sessions,listDeselected:!0,selectedIds:[],selectMode:!1}};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(le,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??le)||le),r=gn(At(e.history?.chat||[]),i),o=n[n.length-1]?.id||null,a=r[r.length-1]?.id||null,c=e.sessionId===t.sessions.activeSessionId&&a!==o,u=vr(t.history.bySessionId);return u.set(e.sessionId,{...e.history||{},chat:r,activity:gn(e.history?.activity||[],i),events:gn(e.history?.events||[],i),loadedEventLimit:i}),{...t,history:{...t.history,bySessionId:u},ui:c?{...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=vr(t.history.bySessionId);for(const o of s)n.delete(o);const i=Cr(t.outbox?.bySessionId);for(const o of s)delete i[o];const r={...t.ui.chatScrollBySession||{}};for(const o of s)delete r[o];return{...t,history:{...t.history,bySessionId:n},outbox:{...t.outbox,bySessionId:i},ui:{...t.ui,chatScrollBySession:r}}}case"outbox/setSessionItems":{const s=e.sessionId;if(!s)return t;const n=Array.isArray(e.items)?e.items.filter(Boolean):[],i=Cr(t.outbox?.bySessionId);return n.length===0?delete i[s]:i[s]=n,{...t,outbox:{...t.outbox,bySessionId:i}}}case"orchestration/statsLoading":{const s=us(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=us(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=us(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=us(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,r=n.length>i?n.slice(-i):n;return s[e.sessionId]={loading:!1,error:null,fetchedAt:e.fetchedAt||Date.now(),events:r},{...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/section":{const s=["packages","workers","ghcp"].includes(e.section)?e.section:"ghcp";return{...t,admin:{...t.admin,section:s}}}case"admin/workers/attempt":{const s=t.admin.workers||{};return{...t,admin:{...t.admin,workers:{...s,attempts:(s.attempts||0)+1,lastAttemptAt:Date.now(),lastSkip:e.skip||null}}}}case"admin/workers/loading":return{...t,admin:{...t.admin,workers:{...t.admin.workers,loading:!0,error:null}}};case"admin/workers/loaded":return{...t,admin:{...t.admin,workers:{loading:!1,error:null,list:Array.isArray(e.list)?e.list:[],fetchedAt:Date.now()}}};case"admin/workers/loadFailed":return{...t,admin:{...t.admin,workers:{...t.admin.workers,loading:!1,error:e.error||"Failed to load workers"}}};case"admin/packages/loading":return{...t,admin:{...t.admin,packages:{...t.admin.packages,loading:!0,error:null}}};case"admin/packages/loaded":{const s=t.admin.packages,n=Array.isArray(e.list)?e.list:[],i=s.selectedName&&n.some(r=>r.name===s.selectedName);return{...t,admin:{...t.admin,packages:{...s,loading:!1,error:null,list:n,workerState:Array.isArray(e.workerState)?e.workerState:[],fetchedAt:Date.now(),selectedName:i?s.selectedName:null,...i?{}:{detail:null,workspace:{...s.workspace,tree:null,selectedPath:null,file:null}}}}}}case"admin/packages/loadFailed":return{...t,admin:{...t.admin,packages:{...t.admin.packages,loading:!1,error:e.error||"Failed to load agent packages"}}};case"admin/packages/select":return{...t,admin:{...t.admin,section:"packages",packages:{...t.admin.packages,selectedName:e.name||null,detail:null,detailLoading:!!e.name,detailError:null,action:{pending:null,error:null},workspace:{tree:null,treeLoading:!!e.name,treeError:null,expandedDirs:[],selectedPath:null,file:null,fileLoading:!1,fileError:null}}}};case"admin/packages/detail/loaded":return t.admin.packages.selectedName!==e.name?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,detail:e.detail,detailLoading:!1,detailError:null}}};case"admin/packages/detail/loadFailed":return t.admin.packages.selectedName!==e.name?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,detail:null,detailLoading:!1,detailError:e.error||"Failed to load package"}}};case"admin/packages/tree/loaded":{if(t.admin.packages.selectedName!==e.name)return t;const s=Array.isArray(e.tree?.dirs)?e.tree.dirs.filter(n=>!n.includes("/")):[];return{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,tree:e.tree,treeLoading:!1,treeError:null,expandedDirs:s}}}}}case"admin/packages/tree/loadFailed":return t.admin.packages.selectedName!==e.name?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,treeLoading:!1,treeError:e.error||"Failed to load package files"}}}};case"admin/packages/toggleDir":{const s=t.admin.packages.workspace,n=new Set(s.expandedDirs);return n.has(e.dir)?n.delete(e.dir):n.add(e.dir),{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...s,expandedDirs:[...n]}}}}}case"admin/packages/file/loading":return{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,selectedPath:e.path,file:null,fileLoading:!0,fileError:null}}}};case"admin/packages/file/loaded":return t.admin.packages.workspace.selectedPath!==e.file?.path?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,file:e.file,fileLoading:!1,fileError:null}}}};case"admin/packages/file/loadFailed":return t.admin.packages.workspace.selectedPath!==e.path?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,fileLoading:!1,fileError:e.error||"Failed to load file"}}}};case"admin/packages/action/pending":return{...t,admin:{...t.admin,packages:{...t.admin.packages,action:{pending:e.action,error:null}}}};case"admin/packages/action/done":return{...t,admin:{...t.admin,packages:{...t.admin.packages,action:{pending:null,error:null}}}};case"admin/packages/action/failed":return{...t,admin:{...t.admin,packages:{...t.admin.packages,action:{pending:null,error:e.error||"Action failed"}}}};case"admin/packages/addDialog/open":{const s={..._n().admin.packages.addDialog,open:!0,updateName:e.updateName||null,scope:e.scope==="shared"?"shared":"user"};return{...t,admin:{...t.admin,section:"packages",packages:{...t.admin.packages,addDialog:s}}}}case"admin/packages/addDialog/close":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{..._n().admin.packages.addDialog,open:!1}}}};case"admin/packages/addDialog/setField":{const s=t.admin.packages.addDialog;return e.field in s?{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...s,[e.field]:e.value,error:null}}}}:t}case"admin/packages/addDialog/submitting":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,submitting:!0,progress:null,error:null}}}};case"admin/packages/addDialog/progress":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,progress:e.message||null}}}};case"admin/packages/addDialog/failed":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,submitting:!1,progress:null,error:e.error||"Failed to import package"}}}};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=qe(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=qe(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=qe(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},i=As(e.entries),r=Number(e.fetchedAt)||0,o=c=>i.some(u=>u.filename===c),a=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:a,loading:!1,loaded:!0,fetchedAt:r,error:null},{...t,files:{...t.files,bySessionId:s}}}case"files/sessionError":{const s=qe(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=qe(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/toggleMark":{const s=String(e.artifactId||"");if(!s)return t;const n=new Set(t.files.markedIds||[]);return n.has(s)?n.delete(s):n.add(s),{...t,files:{...t.files,markedIds:[...n]}}}case"files/setMarks":return{...t,files:{...t.files,markedIds:Array.isArray(e.artifactIds)?[...new Set(e.artifactIds.map(String))]:[]}};case"files/previewOrigin":return{...t,files:{...t.files,previewOrigin:e.origin||null,restoreArtifactId:e.origin==="chat"?e.restoreArtifactId??t.files.restoreArtifactId??null:null}};case"files/clearMarks":return{...t,files:{...t.files,markedIds:[]}};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=qe(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=qe(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=qe(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=qe(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":{t={...t,files:{...t.files,markedIds:(t.files.markedIds||[]).filter(d=>d!==`${e.sessionId}/${e.filename}`)}};const s=qe(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},i=As(n.entries).filter(d=>d.filename!==e.filename),r=n.selectedFilename===e.filename?i[0]?.filename||null:n.selectedFilename,{[e.filename]:o,...a}=n.previews||{},{[e.filename]:c,...u}=n.downloads||{},p=e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:null;return s[e.sessionId]={...n,entries:i,previews:a,downloads:u,selectedFilename:r},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:t.files.selectedArtifactId===p?r?`${e.sessionId}/${r}`: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:{...mn(t.files.filter),...mn(e.filter)},...mn(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:tf(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 hf(t,e){let s=e;const n=new Set;return{getState(){return s},dispatch(i){const r=t(s,i);if(Object.is(r,s))return i;s=r;for(const o of n)o(s,i);return i},subscribe(i){return n.add(i),()=>n.delete(i)}}}const mf=2e4,gf=2e4,yf=3e4,Sf=30,Lr="Session refresh failed",bf=3,wf=200,If=5,xf=new Set([T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY]);function Ef(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 Sn(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 jt(t){return gs(t)!==null}function vf(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 bn(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 Ut(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||s==="NOT_FOUND"}async function kf(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<If;n+=1){const i=await t.listSessionsPage({limit:wf,cursor:s}),r=Array.isArray(i?.sessions)?i.sessions:[];if(e.push(...r),!i?.hasMore||!i?.nextCursor)break;s=i.nextCursor}return e}function Af(t=[]){const e=[],s=new Map;for(const n of t){const i=n?.providerId||"models";let r=s.get(i);r||(r={providerId:i,providerType:n?.providerType||"provider",models:[]},s.set(i,r),e.push(r)),r.models.push(n)}return e}function Dn(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 Fr(t){const e=Dn(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 Hn(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 Cf(t){const e=Hn(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 Va={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function Tf(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 Nf(t,e){const s=Tf(e);return s?t==="long_context"?`Long context (${s} tokens, higher cost)`:`Default (${s} tokens)`:Va[t]||t}function Gn(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 Mf(t){return Gn([t])}function Br(t,e=[]){let s=Co(t);for(const n of e){const i=To(s,n?.eventType,n?.data,{timestamp:n?.createdAt});i&&(s=i)}return s}function _s(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i+=1)if(!_s(t[i],e[i]))return!1;return!0}if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!_s(t[i],e[i]))return!1;return!0}function Dr(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 Ii(t,e){const s=Dr(t?.updatedAt),n=Dr(e?.updatedAt);return s>0&&n>0&&n<=s}function Pf(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function _f(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&Pf(e?.status)&&Ii(t,e)}function $f(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!za(e?.status)&&!qa(e?.orchestrationStatus)&&Ii(t,e)}function Rf(t,e){if(!e?.sessionId)return null;const s={sessionId:e.sessionId};let n=!1;for(const[a,c]of Object.entries(e))a==="sessionId"||c===void 0||_s(t?.[a],c)||(s[a]=c,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&!Ii(t,e)&&(s.pendingQuestion=null,n=!0),_f(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),Eu(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),$f(t,e))for(const a of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[a]!=null&&(_s(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((za(e.status)||qa(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 Hr(t){return String(t||"").replace(/\r\n/g,`
68
- `).trim()}function qa(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function za(t){return t==="completed"||t==="failed"||t==="cancelled"}function Ee(t){return String(t||"").slice(0,8)}function $s(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function ds(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Of=$s({provider:"system",subject:"system"});function Gr(t){const e=t.auth?.principal||null,s=$s(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 r=ds(e,"current user");n.push({id:"me",kind:"me",label:`Me (${r})`,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 r of Object.values(t.sessions?.byId||{})){const o=r?.owner,a=$s(o);!a||a===s||a===Of||i.has(a)||i.set(a,o)}for(const[r,o]of[...i.entries()].sort((a,c)=>ds(a[1]).localeCompare(ds(c[1])))){const a=ds(o),c=String(o?.email||"").trim();n.push({id:`owner:${r}`,kind:"owner",ownerKey:r,label:c&&c!==a?`${a} <${c}>`:a,description:"Show sessions owned by this user."})}return n}function Rs(t){return $s(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,includeShared:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function Lf(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||t?.includeShared||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function Ff(t,e,s){const n=t||Rs(s);if(!e)return n;if(e.kind==="all")return n.all?Rs(s):{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]};const i={...n,all:!1,ownerKeys:Array.isArray(n.ownerKeys)?[...n.ownerKeys]:[]};if(e.kind==="system"&&(i.includeSystem=!i.includeSystem),e.kind==="unowned"&&(i.includeUnowned=!i.includeUnowned),e.kind==="me"&&(i.includeMe=!i.includeMe),e.kind==="shared"&&(i.includeShared=!i.includeShared),e.kind==="owner"&&e.ownerKey){const r=i.ownerKeys.indexOf(e.ownerKey);r>=0?i.ownerKeys.splice(r,1):i.ownerKeys.push(e.ownerKey)}return Lf(i)?i:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function xi(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 Bf(t){const e=xi(t);return e?Math.max(1,60-`${e}: `.length):60}function Df(t){const e=String(t?.title||"").trim();if(!e)return"";const s=xi(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===Ee(t?.sessionId)?"":n}return e===Ee(t?.sessionId)?"":e}function jr(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 Ur(t){return`📎 ${String(t||"").trim()}`}function Wr(t,e){const s=String(t||""),n=fe(s,e,s.length),r=s.slice(0,n).match(/(^|\s)(@@?)([^\s]*)$/u);if(!r)return null;const o=r[2],a=String(r[3]||"");return{kind:o==="@@"?"sessions":"artifacts",query:a,signature:`${o}${a}`,tokenStart:(r.index||0)+String(r[1]||"").length,tokenEnd:n}}function Hf(t,e,s,n){const i=String(t||""),r=fe(i,e),o=fe(i,s),a=String(n||"");return{prompt:`${i.slice(0,r)}${a}${i.slice(o)}`,cursor:r+a.length}}function Gf(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function jf(t){const e=String(t?.sessionId||"").trim(),s=Ee(e)||"session";return`Referenced session: ${Gf(t?.title,s)} — session://${e}`}function Kr(t,e,s){if(!e)return tt(t,String(t||"").length,s);const n=String(t||""),i=n.slice(e.tokenEnd,e.tokenEnd+1),r=!i||/\s/u.test(i);return Hf(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${r?" ":""}`)}function Uf(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,`
69
- `).replace(/\n[ \t]+/g,`
70
- `).replace(/[ \t]{2,}/g," ").trim()}const Vr=new Set(["image/png","image/jpeg","image/gif","image/webp"]),qr=4*1024*1024,wn=4;function Wf(t,e=[]){const s=Array.isArray(e)?e.filter(r=>r?.sessionId&&r?.filename&&r?.kind!=="image"):[];if(s.length===0)return String(t||"");const n=s.map(r=>`[Attached file: ${r.filename} — artifact://${r.sessionId}/${r.filename}]`),i=Uf(t,s);return n.join(`
71
- `)+(i?`
72
-
73
- ${i}`:"")}function St(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function Ya(t){return Array.from(String(t||"")).length}function Kf(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=No(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 Vf(t,e){const s=Math.max(1,Number(e)||1),n=Ya(t);return Math.max(1,Math.ceil(n/s))}function bt(t,e){const s=Math.max(1,Number(e)||1);return Kf(t).reduce((n,i)=>{if(!i)return n+1;if(Array.isArray(i)){const r=i.reduce((o,a)=>o+Ya(a?.text||""),0);return n+Math.max(1,Math.ceil(r/s))}return n+Vf(i.text||"",s)},0)}function fe(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function Xa(t){return String(t||"").split(`
74
- `)}function qf(t,e){const n=String(t||"").slice(0,fe(t,e)).split(`
75
- `),i=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:i.length}}function zf(t,e,s){const n=Xa(t),i=Math.max(0,Math.min(Number(e)||0,Math.max(0,n.length-1))),r=Math.max(0,Math.min(Number(s)||0,n[i]?.length||0));let o=0;for(let a=0;a<i;a+=1)o+=(n[a]?.length||0)+1;return fe(t,o+r)}function tt(t,e,s){const n=String(t||""),i=fe(n,e),r=String(s||"");return{prompt:`${n.slice(0,i)}${r}${n.slice(i)}`,cursor:i+r.length}}function wt(t,e){const s=String(t||""),n=fe(s,e);return n<=0?{prompt:s,cursor:n}:{prompt:`${s.slice(0,n-1)}${s.slice(n)}`,cursor:n-1}}function ps(t){return/\s/u.test(t||"")}function Qa(t,e,s){const n=String(t||"");let i=fe(n,e);if(s<0){for(;i>0&&ps(n[i-1]);)i-=1;for(;i>0&&!ps(n[i-1]);)i-=1;return i}for(;i<n.length&&ps(n[i]);)i+=1;for(;i<n.length&&!ps(n[i]);)i+=1;return i}function Yf(t,e){const s=String(t||""),n=fe(s,e),i=Qa(s,n,-1);return i===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,i)}${s.slice(n)}`,cursor:i}}function Xf(t,e,s){const n=Xa(t);if(n.length<=1)return fe(t,e);const i=qf(t,e),r=Math.max(0,Math.min(i.line+s,n.length-1));return r===i.line?fe(t,e):zf(t,r,i.column)}const jn=3e3,Qf=new Set(["logs","sequence"]),Jf=2e5,Zf=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),eh=new Set([".json",".jsonl"]),th=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function Ja(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function sh(t,e=""){const s=Ja(t),n=String(e||"").toLowerCase();return th.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}function zr(t,e=Jf){const s=String(t??"");return s.length<=e?s:`${s.slice(0,e)}
76
-
77
- [Preview truncated at ${e.toLocaleString()} characters. Open the artifact directly if you need the full file.]`}function nh(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 ih(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${nh(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
78
- `)}function Yr(t,e,s="",n=null){const i=String(s||"").toLowerCase(),r=Ja(t);if(n?.isBinary===!0||sh(t,s))return{content:ih(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 o=zr(e);if(Zf.has(r)||i.includes("markdown"))return{content:o,contentType:s||"text/markdown",renderMode:"markdown",isBinary:!1,sizeBytes:n?.sizeBytes??null,uploadedAt:n?.uploadedAt||"",source:n?.source||"agent"};if(eh.has(r)||i.includes("json"))try{return{content:zr(JSON.stringify(JSON.parse(String(e??"")),null,2)),contentType:s||"application/json",renderMode:"text"}}catch{return{content:o,contentType:s||"application/json",renderMode:"text"}}return{content:o,contentType:s||"text/plain",renderMode:"text"}}const rh=1e4,oh=140,ah=1500;class lh{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(c=>c.id===s);if(!i)return!1;const r=this.getState().ui,o=this.getPromptEditSessionMatch(e),a=o?{...o,itemId:s,phase:i.phase}:{sessionId:e,itemId:s,phase:i.phase,draftPrompt:r.prompt,draftCursor:r.promptCursor};return this.dispatch({type:"ui/promptEdit",promptEdit:a}),this.setPrompt(i.text,i.text.length),this.setFocus(T.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(r=>r.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(r=>r.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(r=>r.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(r=>r.id===e.itemId&&r.phase==="pending"))return!1;const i=s.filter(r=>r.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(o=>o.id===s);if(!i||i.phase==="cancelling")return!1;this.getPromptEditSessionMatch(e)?.itemId===s&&this.exitPendingPromptEdit({restoreDraft:!0});const r=Array.isArray(i.clientMessageIds)&&i.clientMessageIds.length>0?i.clientMessageIds:[i.id];if(i.phase==="queued")if(this.setSessionOutboxItems(e,n.map(o=>o.id===s?{...o,phase:"cancelling"}:o)),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,r),this.dispatch({type:"ui/status",text:"Cancelling queued prompt"})}catch(o){return this.setSessionOutboxItems(e,n),this.dispatch({type:"ui/status",text:o?.message||String(o)}),!1}else this.dispatch({type:"ui/status",text:"Queued prompt marked cancelling (local only — transport has no cancel)"});else{const o=n.filter(a=>a.id!==s);if(this.setSessionOutboxItems(e,o),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,r)}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"),r=[],o=[];for(const a of s){const c=String(a.type||"").toLowerCase();if(!Vr.has(c)){o.push({name:a.name||"image",reason:"unsupported type"});continue}if((Number(a.size)||0)>qr){o.push({name:a.name||"image",reason:"over 4 MB"});continue}if(i.length+r.length>=wn){o.push({name:a.name||"image",reason:`max ${wn} images`});continue}r.push({kind:"image",file:a,filename:String(a.name||"image"),contentType:c,sizeBytes:Number(a.size)||0})}return r.length>0&&this.setPromptAttachments([...n,...r]),o.length>0&&this.dispatch({type:"ui/status",text:`Skipped ${o.map(a=>`${a.name} (${a.reason})`).join(", ")}`}),{accepted:r.length,rejected:o}}stageUploadedImageAttachment(e,s){const n=String(e?.contentType||"").toLowerCase();return!Vr.has(n)||(Number(e?.sizeBytes)||0)>qr||this.getPromptAttachments().filter(r=>r?.kind==="image").length>=wn?!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(r=>r?.kind==="image")[e];i&&this.setPromptAttachments(s.filter(r=>r!==i))}async uploadPendingImageAttachments(e,s,n){const i=[],r=String(n||Date.now()).replace(/[^a-zA-Z0-9_-]/g,"").slice(-24)||"img";let o=0;for(const a of s){if(!a.file){a.uploaded&&a.filename&&i.push({filename:a.filename});continue}o+=1;const c={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[a.contentType]||"png",u=`attach-${r}-${o}.${c}`;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 c=i.findIndex(u=>(u?.phase==="pending"||u?.phase==="queued"||u?.phase==="cancelling")&&Array.isArray(u.clientMessageIds)&&u.clientMessageIds.includes(n));if(c!==-1){const u=i[c];return this.setSessionOutboxItems(e,i.filter((p,d)=>d!==c)),this.getPromptEditSessionMatch(e)?.itemId===u?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const r=Hr(s);if(!r)return!1;const o=i.findIndex(c=>(c?.phase==="pending"||c?.phase==="queued"||c?.phase==="cancelling")&&Hr(c.text)===r);if(o===-1)return!1;const a=i[o];return this.setSessionOutboxItems(e,i.filter((c,u)=>u!==o)),this.getPromptEditSessionMatch(e)?.itemId===a?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}acknowledgeCancelledOutboxPrompt(e,s=[]){if(!e)return!1;const n=new Set((s||[]).filter(c=>typeof c=="string"&&c));if(n.size===0)return!1;const i=this.getSessionOutbox(e),r=i.filter(c=>c?.phase!=="cancelling"?!0:!(Array.isArray(c.clientMessageIds)?c.clientMessageIds:[c.id]).some(p=>n.has(p)));if(r.length===i.length)return!1;const o=new Set(i.filter(c=>!r.some(u=>u.id===c.id)).map(c=>c.id));this.setSessionOutboxItems(e,r);const a=this.getPromptEditSessionMatch(e);return a&&o.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(g=>g?.attempted===!0),r=i?[i]:n.filter(g=>g?.attempted!==!0);if(r.length===0)return!1;const o=r.flatMap(g=>Array.isArray(g.clientMessageIds)&&g.clientMessageIds.length>0?g.clientMessageIds:[g.id]),a=r.map(g=>String(g.text||"")).join(`
79
-
80
- `),c=r.flatMap(g=>Array.isArray(g.attachments)?g.attachments:[]),u={id:r[0].id,text:a,createdAt:r[0].createdAt||Date.now(),phase:"pending",attempted:!0,clientMessageIds:o,...c.length>0?{attachments:c}:{}},p=new Set(r.map(g=>g.id)),d=this.getSessionOutbox(e).filter(g=>!p.has(g.id));this.setSessionOutboxItems(e,[...d,u]);const f=this.getPromptEditSessionMatch(e);f&&p.has(f.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const m=(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 h=this.getSessionOutbox(e).map(y=>y.id===u.id?{...y,phase:"queued"}:y);return this.setSessionOutboxItems(e,h),this.syncSessionEvents(e).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(g=>{const h=g?.code==="FORBIDDEN"||g?.code==="UNAUTHORIZED"||g?.status===403||g?.status===401,y=this.getSessionOutbox(e);if(h){const S=y.map(E=>E.id===u.id?{...E,phase:"rejected"}:E);this.setSessionOutboxItems(e,S),setTimeout(()=>{const E=this.getSessionOutbox(e),x=E.filter(w=>!(w.id===u.id&&w.phase==="rejected"));x.length!==E.length&&this.setSessionOutboxItems(e,x)},6e3)}else{const S=y.map(E=>E.id===u.id?{...u,phase:"pending",attempted:!0}:E);this.setSessionOutboxItems(e,S)}throw this.dispatch({type:"ui/status",text:g?.message||String(g)}),g}).finally(()=>{this.outboxFlushPromises.delete(e),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e)});return this.outboxFlushPromises.set(e,m),await m}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 Wr(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=et(s),i=n?.sessionId||s.sessions.activeSessionId||null,r=n?.filename||null;if(!i||!r)return!1;const o=Ur(r),a=Kr(s.ui.prompt,e,o),c=this.getPromptAttachments(),u=c.findIndex(f=>f?.sessionId===i&&f?.filename===r),p={...u>=0?c[u]:{},id:`${i}/${r}`,sessionId:i,filename:r,resolvedPath:r,token:o},d=u>=0?c.map((f,m)=>m===u?p:f):[...c,p];return this.setPrompt(a.prompt,a.cursor),this.setPromptAttachments(d),this.setFocus(T.PROMPT),this.dispatch({type:"ui/status",text:`Attached ${r}`}),!0}acceptSessionPromptReference(e=this.getPromptReferenceContext()){if(!e||e.kind!=="sessions")return!1;const s=this.getState(),i=Ot(s)[0]||null,r=i?.sessionId&&s.sessions.byId[i.sessionId]||null;if(!r?.sessionId)return!1;const o=jf(r),a=Kr(s.ui.prompt,e,o);return this.setPrompt(a.prompt,a.cursor),this.setFocus(T.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${Ee(r.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}openSessionOwnerFilter(){const e=this.getState(),s=Gr(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),r=n.items?.[i];if(!r)return;const o=Ff(s.sessions.ownerFilter,r,s.auth?.principal);this.dispatch({type:"sessions/ownerFilter",filter:o}),this.dispatch({type:"ui/modalSelection",index:i}),this.dispatch({type:"ui/status",text:`Session filter updated: ${r.label||r.id||"selection"}`})}refreshOpenSessionOwnerFilterModal(){const e=this.getState(),s=e.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return;const n=Gr(e),i=Array.isArray(s.items)?s.items:[];if(i.length===n.length&&i.every((u,p)=>u?.id===n[p]?.id))return;const o=i[Math.max(0,Number(s.selectedIndex)||0)]?.id,a=o!=null?n.findIndex(u=>u.id===o):-1,c=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:c}})}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=Wr(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 r=new Set(Ps(this.getState(),"selectedSession")),a=ct(this.getState()).filter(c=>r.has(c.sessionId))[0]||null;a?.filename&&(this.dispatch({type:"files/select",sessionId:a.sessionId,filename:a.filename}),await this.ensureFilePreview(a.sessionId,a.filename).catch(()=>{}))}).catch(()=>{})}async start({initialSessionId:e=null}={}){await this.transport.start();const s=typeof this.transport.getAuthContext=="function"?this.transport.getAuthContext():null;this.dispatch({type:"auth/context",principal:s?.principal??null,authorization:s?.authorization??null}),this.getState().sessions.ownerFilterExplicit||this.dispatch({type:"sessions/ownerFilter",filter:Rs(s?.principal??null)});const n=typeof this.transport.getLogConfig=="function"?this.transport.getLogConfig():null;n&&this.dispatch({type:"logs/config",available:n.available,availabilityReason:n.availabilityReason}),this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,statusText:"Connected"});const i=String(e||"").trim();i&&this.dispatch({type:"sessions/navigationIntent",sessionId:i}),await this.refreshSessions(),this.catalogTimer=setInterval(()=>{this.refreshSessions().catch(r=>{this.dispatch({type:"connection/error",error:r?.message||String(r),statusText:Lr})})},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&&(jt(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(){this.refreshWorkerRegistryIfStale().catch(()=>{});const e=this.sessionRefreshSeq=(this.sessionRefreshSeq||0)+1,s=this.getState(),n=!s.connection.connected||!!s.connection.error,i=s.ui.statusText===Lr,r=this.getState().sessions.activeSessionId;let o=(await kf(this.transport)).map(Sn),a=null;if(typeof this.transport.listSessionGroups=="function")try{const f=await this.transport.listSessionGroups();a=(Array.isArray(f)?f:[]).map(Ef).filter(Boolean)}catch(f){console.warn(`[PilotSwarmUi] session-group fetch failed, keeping the known folders: ${f?.message||f}`)}const c=s.sessions.navigationIntent;if(c?.status==="pending"&&!o.some(f=>f?.sessionId===c.sessionId)&&typeof this.transport.getSession=="function")try{const f=await this.transport.getSession(c.sessionId);f?.sessionId?o=[...o,Sn(f)]:this.dispatch({type:"sessions/navigationIntentFailed",sessionId:c.sessionId,errorKind:"not_found"})}catch(f){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:c.sessionId,errorKind:bn(f)})}const u=r;if(u&&!jt(u)&&!o.some(f=>f?.sessionId===u)&&typeof this.transport.getSession=="function"){const f=await this.transport.getSession(u).catch(()=>null);f?.sessionId&&(o=[...o,Sn(f)])}if(e!==this.sessionRefreshSeq)return;n&&this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,...i?{statusText:"Connected"}:{}}),a&&this.dispatch({type:"sessions/groupsLoaded",groups:a,sessions:o}),this.dispatch({type:"sessions/loaded",sessions:o}),this.refreshOpenSessionOwnerFilterModal();const p=this.getState().sessions.activeSessionId,d=new Set;if(p){if(p!==r){if(!this.getState().sessions.byId[p]?.isGroup){const h=this.getState().sessions.navigationIntent;if(h&&h.sessionId===p&&h.status!=="failed")try{await this.loadSession(p)}catch(y){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:p,errorKind:bn(y)})}else await this.loadSession(p)}return}if(this.getState().sessions.byId[p]?.isGroup)return;this.getState().history.bySessionId.get(p)?.events?.length||await this.ensureSessionHistory(p,{force:!0}).catch(()=>{}),this.activeSessionSubscriptionId!==p&&this.attachActiveSession(p),await this.syncSessionDetail(p).catch(()=>{}),await this.syncSessionEvents(p).catch(()=>{}),d.add(p);const m=this.getState(),g=m.sessions.byId[p]||null;if(g?.parentSessionId&&typeof this.transport.getSession=="function"){const h=Object.values(m.sessions.byId).filter(y=>y?.parentSessionId===g.parentSessionId).map(y=>y.sessionId).filter(y=>y&&y!==p).slice(0,6);await Promise.all(h.map(y=>this.syncSessionDetail(y).catch(()=>{})));for(const y of h)d.add(y)}}await this.syncVisibleSessionDetails(d).catch(()=>{}),this.ensureInspectorData().catch(()=>{}),this.evictStaleSessionState()}async refreshWorkerRegistryIfStale(){const e=this.getState().admin?.workers;if(e?.loading){this.dispatch({type:"admin/workers/attempt",skip:"already in flight"});return}if(e?.fetchedAt&&Date.now()-e.fetchedAt<2e4){this.dispatch({type:"admin/workers/attempt",skip:"fresh"});return}this.dispatch({type:"admin/workers/attempt",skip:null}),await this.refreshAdminWorkers()}evictStaleSessionState(){const e=this.getState(),s=e.sessions.activeSessionId,n=Date.now(),i=6e4,r=20,o=Object.entries(e.orchestration.bySessionId||{});if(o.length>r){const p=o.filter(([d,f])=>d!==s&&!f?.loading).sort((d,f)=>(d[1]?.fetchedAt||0)-(f[1]?.fetchedAt||0)).slice(0,o.length-r).filter(([,d])=>n-(d?.fetchedAt||0)>i);p.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:p.map(([d])=>d)})}const a=Object.entries(e.executionHistory?.bySessionId||{});if(a.length>r){const p=a.filter(([d,f])=>d!==s&&!f?.loading).sort((d,f)=>(d[1]?.fetchedAt||0)-(f[1]?.fetchedAt||0)).slice(0,a.length-r).filter(([,d])=>n-(d?.fetchedAt||0)>i);p.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:p.map(([d])=>d)})}const c=Object.entries(e.files.bySessionId||{});if(c.length>r){const p=c.filter(([d])=>d!==s).slice(0,c.length-r);p.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:p.map(([d])=>d)})}const u=[...e.history.bySessionId.entries()];if(u.length>r*2){const p=u.filter(([d])=>d!==s).slice(0,u.length-r*2).map(([d])=>d);p.length>0&&this.dispatch({type:"history/evict",sessionIds:p})}}async syncVisibleSessionDetails(e=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=Xt({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??Nt(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),r=On(s,i),o=[...new Set(r.map(a=>a.sessionId).filter(a=>a&&!jt(a)&&!e.has(a)))];o.length!==0&&await Promise.all(o.map(a=>this.syncSessionDetail(a).catch(()=>{})))}async catchUpSessionHistory(e,s,n){let r;try{r=await this.transport.getSessionEvents(e,n,1e3)}catch(p){return Ut(p)&&this.handleSessionGone(e),null}if(!Array.isArray(r)||r.length>=1e3)return null;if(r.length===0)return s;let o=s;for(const p of r)o=Vi(o,p);o={...o,loadedEventLimit:Math.max(Number(s.loadedEventLimit)||0,Array.isArray(o.events)?o.events.length:0)},this.dispatch({type:"history/set",sessionId:e,history:o});for(const p of r)this.reconcileOutboxAgainstEvent(e,p);const a=Gn(r),c=this.getState().sessions.byId[e]||{},u=Br(c.contextUsage,r);return(a||u)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...a||{},...u?{contextUsage:u}:{}}}),o}async ensureSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),i=Math.min(ah,Math.max(le,Number(n?.loadedEventLimit??le)||le));if(!s&&n?.events)return n;if(!s&&this.sessionHistoryLoads.has(e))return this.sessionHistoryLoads.get(e);const r=Number(n?.lastSeq)||0;if(s&&r>0&&Array.isArray(n?.events)&&n.events.length>0){const a=await this.catchUpSessionHistory(e,n,r);if(a)return a}const o=(async()=>{let a;try{a=await this.transport.getSessionEvents(e,void 0,i)}catch(f){if(Ut(f))return this.handleSessionGone(e),null;throw f}const c={...os(a,{requestedLimit:i}),lastSeq:a[a.length-1]?.seq||0};this.dispatch({type:"history/set",sessionId:e,history:c});for(const f of a||[])this.reconcileOutboxAgainstEvent(e,f);const u=Gn(a),p=this.getState().sessions.byId[e]||{},d=Br(p.contextUsage,a);return(u||d)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...u||{},...d?{contextUsage:d}:{}}}),c})().finally(()=>{this.sessionHistoryLoads.delete(e)});return this.sessionHistoryLoads.set(e,o),o}async ensureInspectorData(e=this.getState().ui.inspectorTab){if(e==="sequence"){const s=this.getState().sessions.activeSessionId;if(!s)return;await this.ensureSessionHistory(s).catch(()=>{}),await this.ensureOrchestrationStats(s).catch(()=>{});return}if(e==="nodes"){this.refreshWorkerRegistryIfStale().catch(()=>{});const s=this.getState(),n=Xt({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??Nt(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),r=On(s,i),o=[...new Set(r.map(a=>a.sessionId).filter(Boolean))];if(o.length===0)return;await Promise.allSettled(o.map(a=>this.ensureSessionHistory(a)));return}if(e==="files"&&await this.ensureFilesForScope(Le(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<mf)return n;if(!s&&this.sessionOrchestrationStatsLoads.has(e))return this.sessionOrchestrationStatsLoads.get(e);this.dispatch({type:"orchestration/statsLoading",sessionId:e});const r=(async()=>{try{const o=await this.transport.getOrchestrationStats(e);return this.dispatch({type:"orchestration/statsLoaded",sessionId:e,stats:o,fetchedAt:Date.now()}),this.getState().orchestration.bySessionId?.[e]||null}catch(o){return Ut(o)?(this.handleSessionGone(e),null):(this.dispatch({type:"orchestration/statsError",sessionId:e,error:o?.message||String(o),fetchedAt:Date.now()}),null)}})().finally(()=>{this.sessionOrchestrationStatsLoads.delete(e)});return this.sessionOrchestrationStatsLoads.set(e,r),r}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<gf)){this.dispatch({type:"sessionStats/loading",sessionId:s});try{const[r,o,a,c,u,p,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:r,tokensByModel:o,treeStats:a,skillUsage:c,treeSkillUsage:u,factsStats:p,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<yf)){this.dispatch({type:"fleetStats/loading"});try{const r={since:new Date(Date.now()-Sf*864e5),includeDeleted:!0},[o,a,c,u,p,d]=await Promise.all([this.transport.getFleetStats(r),typeof this.transport.getUserStats=="function"?this.transport.getUserStats(r).catch(()=>null):null,typeof this.transport.getFleetSkillUsage=="function"?this.transport.getFleetSkillUsage(r).catch(()=>null):null,typeof this.transport.getFleetRetrievalUsage=="function"?this.transport.getFleetRetrievalUsage(r).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:o,userStats:a,skillUsage:c,retrievalUsage:u,sharedFactsStats:p,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(()=>{}),this.refreshAdminAgentPackages().catch(()=>{})}closeAdminConsole(){this.dispatch({type:"admin/visibility",visible:!1})}revealCreatedSession(){this.getState().admin?.visible&&this.closeAdminConsole(),this.setFocus(T.PROMPT)}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})}setAdminSection(e){this.dispatch({type:"admin/section",section:e}),e==="packages"&&(this.getState().admin?.packages?.fetchedAt||this.refreshAdminAgentPackages().catch(()=>{})),e==="workers"&&this.refreshAdminWorkers().catch(()=>{})}selectNodeMapNode(e){this.dispatch({type:"ui/nodeMapSelect",label:e?String(e):null})}async refreshAdminWorkers(){if(typeof this.transport.listWorkers!="function"){this.dispatch({type:"admin/workers/loadFailed",error:"The worker registry is not available on this deployment."});return}this.dispatch({type:"admin/workers/loading"});try{const e=await Promise.race([Promise.resolve().then(()=>this.transport.listWorkers()),new Promise((s,n)=>{const i=setTimeout(()=>n(new Error("request timed out after 10s (connection or auth renewal wedged — try a hard refresh)")),1e4);typeof i?.unref=="function"&&i.unref()})]);console.info(`[PilotSwarmUi] worker registry: ${Array.isArray(e)?e.length:0} row(s)`),this.dispatch({type:"admin/workers/loaded",list:e})}catch(e){console.warn(`[PilotSwarmUi] worker-registry fetch failed: ${e?.message||e}`),this.dispatch({type:"admin/workers/loadFailed",error:e?.message||String(e)})}}async refreshAdminAgentPackages(){if(typeof this.transport.listAgentPackages!="function"){this.dispatch({type:"admin/packages/loadFailed",error:"Agent packages are not available on this deployment."});return}this.dispatch({type:"admin/packages/loading"});try{const[e,s]=await Promise.all([this.transport.listAgentPackages(),typeof this.transport.listAgentWorkerState=="function"?this.transport.listAgentWorkerState().catch(()=>[]):[]]);this.dispatch({type:"admin/packages/loaded",list:e,workerState:s})}catch(e){this.dispatch({type:"admin/packages/loadFailed",error:e?.message||String(e)})}}async selectAdminPackage(e){this.dispatch({type:"admin/packages/select",name:e}),e&&await Promise.all([(async()=>{try{const s=await this.transport.getAgentPackage(e);if(!s)throw new Error(`package "${e}" not found`);this.dispatch({type:"admin/packages/detail/loaded",name:e,detail:s})}catch(s){this.dispatch({type:"admin/packages/detail/loadFailed",name:e,error:s?.message||String(s)})}})(),(async()=>{try{const s=await this.transport.getAgentPackageTree(e);if(this.getState().admin?.packages?.selectedName!==e)return;this.dispatch({type:"admin/packages/tree/loaded",name:e,tree:s});const n=s?.files?.find(i=>i.path==="plugin.json")??s?.files?.[0];n&&this.selectAdminPackageFile(n.path)}catch(s){this.dispatch({type:"admin/packages/tree/loadFailed",name:e,error:s?.message||String(s)})}})()])}async stepAdminPackageSelection(e){const s=this.getState().admin?.packages;if(!s?.list?.length)return;const n=[...s.list.filter(o=>o.scope==="shared"),...s.list.filter(o=>o.scope!=="shared")].map(o=>o.name),i=n.indexOf(s.selectedName),r=n[Math.min(n.length-1,Math.max(0,(i<0?e>0?-1:0:i)+e))];r&&r!==s.selectedName&&await this.selectAdminPackage(r)}toggleAdminPackageDir(e){this.dispatch({type:"admin/packages/toggleDir",dir:e})}async selectAdminPackageFile(e){const n=this.getState().admin?.packages?.selectedName;if(!(!n||!e)){this.dispatch({type:"admin/packages/file/loading",path:e});try{const i=await this.transport.getAgentPackageFile(n,null,e);this.dispatch({type:"admin/packages/file/loaded",file:i})}catch(i){this.dispatch({type:"admin/packages/file/loadFailed",path:e,error:i?.message||String(i)})}}}async runAdminPackageAction(e,s=null){const i=this.getState().admin?.packages?.selectedName;if(i){this.dispatch({type:"admin/packages/action/pending",action:e});try{switch(e){case"promote":await this.transport.setAgentPackageScope(i,"shared");break;case"demote":await this.transport.setAgentPackageScope(i,"user");break;case"pin":await this.transport.pinAgentPackageVersion(i,s);break;case"enable":case"disable":await this.transport.setAgentPackageEnabled(i,e==="enable");break;case"delete":await this.transport.deleteAgentPackage(i);break;default:throw new Error(`unknown package action: ${e}`)}this.dispatch({type:"admin/packages/action/done"}),await this.refreshAdminAgentPackages(),e!=="delete"&&await this.selectAdminPackage(i)}catch(r){this.dispatch({type:"admin/packages/action/failed",error:r?.message||String(r)})}}}failAdminAddPackage(e){this.dispatch({type:"admin/packages/addDialog/failed",error:e})}async submitAdminUploadPackage(e,s){const n=this.getState().admin?.packages?.addDialog;if(!(!n?.open||n.submitting)){if(typeof this.transport.uploadAgentPackage!="function"){this.dispatch({type:"admin/packages/addDialog/failed",error:"Folder upload is not available on this deployment."});return}this.dispatch({type:"admin/packages/addDialog/submitting"});try{const i=await this.transport.uploadAgentPackage(e,s==="shared"?"shared":"user");this.dispatch({type:"admin/packages/addDialog/close"}),await this.refreshAdminAgentPackages(),i?.name&&await this.selectAdminPackage(i.name)}catch(i){const r=Array.isArray(i?.validation?.errors)?`
81
- ${i.validation.errors.map(o=>`[${o.code}] ${o.message}`).join(`
82
- `)}`:"";this.dispatch({type:"admin/packages/addDialog/failed",error:`${i?.message||i}${r}`})}}}openAdminAddPackage(){this.dispatch({type:"admin/packages/addDialog/open"})}openAdminUpdatePackage(e,s="user"){const n=String(e||"").trim();n&&this.dispatch({type:"admin/packages/addDialog/open",updateName:n,scope:s})}closeAdminAddPackage(){this.dispatch({type:"admin/packages/addDialog/close"})}setAdminAddPackageField(e,s){this.dispatch({type:"admin/packages/addDialog/setField",field:e,value:s})}async submitAdminAddPackage(){const e=this.getState().admin?.packages?.addDialog;if(!e?.open||e.submitting)return;if(typeof this.transport.uploadAgentPackage!="function"){this.dispatch({type:"admin/packages/addDialog/failed",error:"Package upload is not available on this deployment."});return}const s=String(e.repoUrl||"").trim(),n=Qo(s);if(n.error){this.dispatch({type:"admin/packages/addDialog/failed",error:n.error});return}this.dispatch({type:"admin/packages/addDialog/submitting"});try{let r=String(e.authToken||"").trim()||null,o="pat";!r&&n.kind==="ado"&&(this.dispatch({type:"admin/packages/addDialog/progress",message:"getting an Azure DevOps token for your account…"}),r=typeof this.transport.getRepoAccessToken=="function"?await this.transport.getRepoAccessToken("ado"):null,o="bearer");const{files:a}=await Kc(s,{token:r,tokenKind:o,onProgress:u=>this.dispatch({type:"admin/packages/addDialog/progress",message:u})});if(e.updateName){const u=Vc(a);if(u&&u!==e.updateName){this.dispatch({type:"admin/packages/addDialog/failed",error:`That folder builds "${u}", not "${e.updateName}". Use Add package to publish it as its own package.`});return}}this.dispatch({type:"admin/packages/addDialog/progress",message:`publishing ${a.length} file(s)…`});const c=await this.transport.uploadAgentPackage(a,e.scope==="shared"?"shared":"user");this.dispatch({type:"admin/packages/addDialog/close"}),await this.refreshAdminAgentPackages(),c?.name&&await this.selectAdminPackage(c.name)}catch(i){const r=Array.isArray(i?.validation?.errors)?`
83
- ${i.validation.errors.map(o=>`[${o.code}] ${o.message}`).join(`
84
- `)}`:"";this.dispatch({type:"admin/packages/addDialog/failed",error:`${i?.message||i}${r}`})}}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=tt(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=wt(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,fe(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 r=await this.transport.getExecutionHistory(e);this.dispatch({type:"executionHistory/loaded",sessionId:e,events:r||[],fetchedAt:Date.now()})}catch(r){console.error("[executionHistory] fetch error:",r?.message||r),this.dispatch({type:"executionHistory/error",sessionId:e,error:r?.message||String(r),fetchedAt:Date.now()})}return this.getState().executionHistory?.bySessionId?.[e]||null}async ensureFilesForScope(e=Le(this.getState()),{force:s=!1}={}){const n=Ps(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=et(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;const i=Date.now()-(Number(n?.fetchedAt)||0);if(!s&&n?.loaded&&i<rh)return n.selectedFilename&&await this.ensureFilePreview(e,n.selectedFilename).catch(()=>{}),n;this.dispatch({type:"files/sessionLoading",sessionId:e});try{const r=await this.transport.listArtifacts(e),o=Date.now();this.dispatch({type:"files/sessionLoaded",sessionId:e,entries:r,fetchedAt:o});const a=this.getState().files.bySessionId[e];return a?.selectedFilename&&await this.ensureFilePreview(e,a.selectedFilename).catch(()=>{}),a}catch(r){return this.dispatch({type:"files/sessionError",sessionId:e,error:r?.message||String(r)}),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],r=i?.previews?.[s];let o=xu(i?.entries,s);if(!n&&r?.loading||!n&&r&&(r.content!==void 0||r.error))return r;if(!o&&typeof this.transport.getArtifactMetadata=="function")try{o=await this.transport.getArtifactMetadata(e,s)}catch{o=null}this.dispatch({type:"files/previewLoading",sessionId:e,filename:s});try{const a=o?.isBinary===!0?Yr(s,"",o.contentType||"",o):Yr(s,await this.transport.downloadArtifact(e,s),o?.contentType||"",o);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 r=String(i?.href||"").trim();r&&n.push({id:`url:${r}`,kind:"url",href:r,text:String(i?.text||r).trim()||r})}return(e||[]).length>1&&n.push({id:"__downloadAll__",kind:"downloadAll"}),n}buildArtifactPickerModal({artifactLinks:e,httpLinks:s,previousFocus:n,selectedId:i}={}){const r=this.buildArtifactPickerItems(e,s);if(r.length===0)return null;const o=r.findIndex(a=>a.id===i);return{type:"artifactPicker",title:"Linked Items",previousFocus:n,artifactLinks:e,httpLinks:s,items:r,selectedIndex:o>=0?o: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=et(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||Le(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:i}=s,r=Le(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 o=e.files.bySessionId[n]?.downloads?.[i]?.localPath||null;if(o||(this.dispatch({type:"ui/status",text:`Downloading ${i} to open it...`}),o=(await this.saveArtifactDownload(n,i))?.localPath||null),!o){this.dispatch({type:"ui/status",text:`Open failed: could not save ${i} locally`});return}try{await this.transport.openPathInDefaultApp(o),this.dispatch({type:"ui/status",text:r==="allSessions"?`Opened ${Ee(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=et(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}toggleArtifactMark(e){e?.id&&this.dispatch({type:"files/toggleMark",artifactId:e.id})}markArtifactRange(e){if(!e?.id)return;const s=ct(this.getState()),n=this.getState().files.markedIds||[],i=n.length>0?n[n.length-1]:this.getState().files.selectedArtifactId,r=s.findIndex(p=>p.id===i),o=s.findIndex(p=>p.id===e.id);if(o<0)return;if(r<0){this.dispatch({type:"files/toggleMark",artifactId:e.id});return}const[a,c]=r<=o?[r,o]:[o,r],u=s.slice(a,c+1).map(p=>p.id);this.dispatch({type:"files/setMarks",artifactIds:[...new Set([...n,...u])]})}clearArtifactMarks(){this.dispatch({type:"files/clearMarks"})}async deleteMarkedArtifacts({confirmed:e=!1}={}){const s=this.getState(),n=s.files.markedIds||[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No artifacts marked"}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifacts",message:`Delete ${n.length} artifact${n.length===1?"":"s"}? This action cannot be undone.`,confirmLabel:`Delete ${n.length}`,action:"deleteMarkedArtifacts",previousFocus:s.ui.focusRegion}}),!1;const i=new Set;let r=0;const o=[];for(const a of n){const c=String(a).indexOf("/");if(c<=0)continue;const u=a.slice(0,c),p=a.slice(c+1);try{await this.transport.deleteArtifact(u,p),this.dispatch({type:"files/deleted",sessionId:u,filename:p}),i.add(u),r+=1}catch(d){o.push(`${p}: ${d?.message||String(d)}`)}}for(const a of i)await this.ensureFilesForSession(a,{force:!0}).catch(()=>null);return this.dispatch({type:"files/clearMarks"}),this.dispatch({type:"ui/status",text:o.length>0?`Deleted ${r}, ${o.length} failed — ${o[0]}`:`Deleted ${r} artifact${r===1?"":"s"}`}),o.length===0}async deleteSelectedArtifact({confirmed:e=!1}={}){const s=this.getState(),n=et(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const i=Le(s),r=i==="allSessions"?`${Ee(n.sessionId)} ${n.filename}`:n.filename;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifact",message:`Delete artifact "${r}"? 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 o=et(this.getState());return o?.sessionId&&o?.filename&&await this.ensureFilePreview(o.sessionId,o.filename).catch(()=>null),this.dispatch({type:"ui/status",text:i==="allSessions"?`Deleted ${Ee(n.sessionId)} ${n.filename}`:`Deleted ${n.filename}`}),!0}catch(o){return this.dispatch({type:"ui/status",text:`Delete failed: ${o?.message||String(o)}`}),!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=Td(e),i=Nd(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 r=this.getState().files.bySessionId[s]?.selectedFilename||null,o=r?`${s}/${r}`:null,a=this.buildArtifactPickerModal({artifactLinks:n,httpLinks:i,previousFocus:e.ui.focusRegion,selectedId:o});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(o=>o.kind!=="artifact"?!1:!this.getState().files.bySessionId[o.sessionId]?.downloads?.[o.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 r=0;for(const o of i)(await this.saveArtifactDownload(o.sessionId,o.filename))?.localPath&&(r+=1);this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${r}/${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=Le(this.getState());await this.ensureFilesForScope(s);const n=ct(this.getState());if(n.length===0)return;const i=et(this.getState())||n[0],r=Math.max(0,n.findIndex(c=>c.id===i?.id)),o=Math.max(0,Math.min(n.length-1,r+e)),a=n[o];!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 ${Ee(a.sessionId)} ${a.filename}`:`Previewing ${a.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;this.dispatch({type:"files/previewOrigin",origin:"list"});const s=Le(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 ${Ee(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 r=!i;this.dispatch({type:"files/fullscreen",fullscreen:r}),this.dispatch({type:"ui/status",text:r?`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===T.PROMPT?n:s;if(!xf.has(i)||i===T.INSPECTOR&&e.ui.inspectorTab==="files")return;const r=n===i?null:i;this.dispatch({type:"ui/fullscreenPane",fullscreenPane:r}),this.dispatch({type:"ui/status",text:r?`Fullscreen ${i} pane`:`Closed fullscreen ${i} pane`}),!r&&s===T.PROMPT&&this.setFocus(i)}openFilesFilter(){const e=Le(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:bn(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(r=>typeof r=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];if(i.length>0)for(const r of i)this.acknowledgeOutboxPrompt(e,n,r);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:Vi(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 r=Mf(s),o=this.getState().sessions.byId[e]||{sessionId:e},a=To(o.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(r||a)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...r||{},...a?{contextUsage:a}:{}}}),this.maybeFlushQueuedOutbox(e,this.getState().sessions.byId[e]||o),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(r){if(Ut(r)){this.handleSessionGone(e);return}throw r}if(!(!Array.isArray(i)||i.length===0))for(const r of i)this.mergeSessionEvent(e,r)}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||jt(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||jt(e))return;let s=null;try{s=await this.transport.getSession(e)}catch(r){if(Ut(r)){this.handleSessionGone(e);return}throw r}if(!s)return;const n=this.getState().sessions.byId[e]||null,i=Rf(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.revealCreatedSession(),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.revealCreatedSession(),this.dispatch({type:"ui/status",text:`Created ${jr(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(),s=e.sessions.activeSessionId&&!e.sessions.listDeselected?[e.sessions.activeSessionId]:[];return(Array.isArray(e.sessions.selectedIds)&&e.sessions.selectedIds.length>0?e.sessions.selectedIds:s).map(i=>e.sessions.byId[i]).filter(i=>i&&!i.isSystem&&!i.isGroup&&!i.parentSessionId)}async openMoveToGroupModal(){const e=this.getState(),s=this.getMovableGroupSessionSelection();if(s.length===0)return this.openCreateEmptyGroupModal();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(c=>c.sessionId),r=s.length===1&&s[0].groupId||null,o=[{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(c=>({id:c.groupId,kind:"group",label:c.title||c.groupId,description:c.description||"Move selected session(s) into this group.",groupId:c.groupId,memberCount:c.memberCount??0}))],a=r?Math.max(0,o.findIndex(c=>c.groupId===r)):Math.min(1,o.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(c=>c.title||c.sessionId.slice(0,8)),selectedIndex:a>=0?a:0,items:o}}),this.dispatch({type:"ui/status",text:"Choose a group, [New Group], or [No Group]"}),o}async createSessionGroupFromSelection(){return this.openMoveToGroupModal()}async openCreateEmptyGroupModal(){if(typeof this.transport.createSessionGroup!="function")return this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"}),null;const e=this.getState();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.ui.focusRegion,sessionIds:[],value:"",cursorIndex:0,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"}),null}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 r=null;if(typeof this.transport.placeSessionsInGroup=="function")r=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 o=Array.isArray(r)?r.filter(Boolean):null,a=o?o.filter(d=>d.placed!==!0):[],c=o?o.filter(d=>d.placed===!0).length:i.length;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&c>0&&await this.loadSession(`group:${e}`).catch(()=>{});const u=e?`group ${n||e}`:"No Group",p=a.length>0?` · skipped ${a.length} (${vf(a)})`:"";return this.dispatch({type:"ui/status",text:c>0?`Moved ${c} session${c===1?"":"s"} to ${u}${p}`:`No sessions moved to ${u}${p}`}),c>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=St(e,n.maxLength||80),r=fe(i,s);this.updateSessionGroupNameModal({value:i,cursorIndex:r})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=tt(s.value||"",s.cursorIndex||0,St(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=wt(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||"",fe(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||[]}),r=e.sessionIds||[];r.length===0?(this.dispatch({type:"ui/status",text:`Created group "${i.title||s}"`}),await this.refreshSessions().catch(()=>{})):await this.moveSessionsToGroup(i.groupId,r,{statusTitle:i.title||s})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}applyActiveGroupDefault(e={}){if(e&&Object.prototype.hasOwnProperty.call(e,"groupId"))return e;const s=this.getState(),n=s.sessions?.activeSessionId?s.sessions.byId[s.sessions.activeSessionId]:null,i=n?.isGroup?n.groupId||gs(n.sessionId):n?.groupId;return i?{...e,groupId:i}:e}getActiveSession(e=this.getState()){const s=e.sessions?.activeSessionId;return s&&e.sessions.byId[s]||null}toggleChatViewMode(){if(this.getActiveSession()?.isGroup){this.dispatch({type:"ui/status",text:"Session groups show group details"});return}const s=this.getState().ui?.chatViewMode==="summary"?"transcript":"summary";this.dispatch({type:"ui/chatViewMode",mode:s}),this.dispatch({type:"ui/status",text:s==="summary"?"Showing session summary":"Showing chat transcript"})}setChatViewMode(e){e!=="summary"&&e!=="transcript"||this.getActiveSession()?.isGroup||this.dispatch({type:"ui/chatViewMode",mode:e})}async openSessionAgentPicker(e={}){const s=typeof this.transport.listCreatableAgents=="function"?await this.transport.listCreatableAgents():[],i=(typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0;if(!Array.isArray(s)||s.length===0){if(!i){this.dispatch({type:"ui/status",text:"No user-creatable agents are available for this app"});return}await this.createSession(e);return}const r=[];for(const a of s){const c=String(a?.name||"").trim();c&&r.push({id:c,kind:"agent",agentName:c,title:jr(c,a?.title),description:String(a?.description||"").trim(),tools:Array.isArray(a?.tools)?a.tools.filter(Boolean):[],splash:typeof a?.splash=="string"&&a.splash.trim()?a.splash:null,splashMobile:typeof a?.splashMobile=="string"&&a.splashMobile.trim()?a.splashMobile:null,initialPrompt:typeof a?.initialPrompt=="string"&&a.initialPrompt.trim()?a.initialPrompt:null,group:a?.source==="package"&&a?.scope==="user"&&a?.mine!==!1?"mine":"shared",packageName:a?.packageName||null,packageSemver:a?.packageSemver||null,packageScope:a?.scope||null,builtin:a?.source!=="package"})}const o=[...r.filter(a=>a.group==="shared"),...r.filter(a=>a.group==="mine")];i&&o.push({id:"__generic__",kind:"generic",group:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,splashMobile:null,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=Dn(e?.supportedReasoningEfforts),i=s?.reasoningEffort||Fr(e);if(!n.length||!i){await this.openContextTierPicker(e,s);return}const r=n.map(a=>({id:a,effort:a,label:a,isDefault:i===a})),o=Math.max(0,r.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:r,selectedIndex:o,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=Hn(e?.supportedContextTiers),i=s?.contextTier||Cf(e);if(!n.length||!i){if(s?.mode==="switchModel"){await this.switchSessionModel({...s,model:e?.id});return}await this.openSessionAgentPicker(s);return}const r=n.map(a=>({id:a,tier:a,tokenLimit:e?.contextWindowSizes?.[a]||null,label:Nf(a,e?.contextWindowSizes?.[a]),isDefault:i===a})),o=Math.max(0,r.findIndex(a=>a.id===i));this.dispatch({type:"ui/modal",modal:{type:"contextTierPicker",title:`Context window for ${e?.modelName||e?.qualifiedName||"model"}`,items:r,selectedIndex:o,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():Af(s),r=await this._resolveGhcpUserKeySet(),o=[],a=i.map(p=>({providerId:p.providerId,providerType:p.type||p.providerType,models:(p.models||[]).map(d=>{const f=d.providerType||p.type||p.providerType,m=f==="github"&&d.credentialAvailable===!1&&r===!1,g={id:d.qualifiedName,qualifiedName:d.qualifiedName,modelName:d.modelName||d.qualifiedName,providerId:d.providerId||p.providerId,providerType:f,description:d.description||"",cost:d.cost||null,supportedReasoningEfforts:Dn(d.supportedReasoningEfforts),defaultReasoningEffort:d.defaultReasoningEffort||null,supportedContextTiers:Hn(d.supportedContextTiers),defaultContextTier:d.defaultContextTier||null,contextWindowSizes:d.contextWindowSizes||null,isDefault:n===d.qualifiedName,ghcpKeyMissing:m,disabled:m};return o.push(g),g})})).filter(p=>p.models.length>0),c=e?.model||n;let u=o.findIndex(p=>p.qualifiedName===c&&!p.disabled);u<0&&(u=o.findIndex(p=>!p.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:o,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,r=e.contextTier?` · ${Va[e.contextTier]||e.contextTier}`:"";this.dispatch({type:"ui/status",text:`Next turn will use ${i}${r}`}),await this.refreshSessions();const o=this._onSwitchModelApplied;this._onSwitchModelApplied=null,typeof o=="function"&&o()}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=bu().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 (${Ee(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,""),r=fe(i,s);this.updateArtifactUploadModal({value:i,cursorIndex:r})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=tt(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=wt(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||"",fe(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 revealArtifact(e,s,{force:n=!0,fullscreen:i=!1}={}){const r=e||this.getState().sessions.activeSessionId,o=String(s||"").trim();return!r||!o?!1:(this.dispatch({type:"files/previewOrigin",origin:"chat",restoreArtifactId:this.getState().files.selectedArtifactId||null}),this.getState().sessions.activeSessionId!==r&&await this.loadSession(r).catch(()=>null),this.dispatch({type:"ui/inspectorTab",inspectorTab:"files"}),this.setFocus("inspector"),await this.ensureFilesForSession(r,{force:n}).catch(()=>null),this.dispatch({type:"files/select",sessionId:r,filename:o}),await this.ensureFilePreview(r,o,{force:n}).catch(()=>null),i&&this.dispatch({type:"files/fullscreen",fullscreen:!0}),!0)}async closeArtifactPreview(){const e=this.getState(),s=e.files.previewOrigin;if(this.dispatch({type:"files/fullscreen",fullscreen:!1}),s!=="chat"){this.dispatch({type:"files/previewOrigin",origin:null}),this.setFocus(T.INSPECTOR);return}const n=e.files.restoreArtifactId;if(n){const i=String(n).indexOf("/");i>0&&this.dispatch({type:"files/select",sessionId:n.slice(0,i),filename:n.slice(i+1)})}else this.dispatch({type:"files/select",sessionId:null,filename:null});this.dispatch({type:"files/previewOrigin",origin:null}),this.dispatch({type:"ui/focus",focusRegion:T.CHAT})}async stepArtifactPreview(e){const s=this.getState();if(s.files.previewOrigin!=="chat"){await this.moveFileSelection(e);return}const n=gr(s);if(n.length===0){await this.moveFileSelection(e);return}const i=n.indexOf(s.files.selectedArtifactId),o=(i>=0?i:e>0?-1:n.length)+(e>0?1:-1);if(o<0||o>=n.length)return;const a=n[o],c=a.indexOf("/");if(c<=0)return;const u=a.slice(0,c),p=a.slice(c+1);this.dispatch({type:"files/select",sessionId:u,filename:p}),await this.ensureFilePreview(u,p).catch(()=>{})}canStepArtifactPreview(e){const s=this.getState(),n=s.files.previewOrigin==="chat"?gr(s):ct(s).map(r=>r.id);if(n.length===0)return!1;const i=n.indexOf(s.files.selectedArtifactId);return i<0?!0:e>0?i<n.length-1:i>0}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 r=Ur(e.filename),o=this.getState().ui.prompt,a=this.getState().ui.promptCursor,c=this.getPromptAttachments(),u=c.findIndex(d=>d?.sessionId===i&&d?.filename===e.filename);if(this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),u===-1||!o.includes(c[u]?.token||r)){const d=tt(o,a,`${r} `);this.setPrompt(d.prompt,d.cursor)}const p=u>=0?c.map((d,f)=>f===u?{...d,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:r}:d):[...c,{id:`${i}/${e.filename}`,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:r}];return this.setPromptAttachments(p),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(T.PROMPT),n||this.dispatch({type:"ui/status",text:u>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:i,existingAttachmentIndex:u,token:r}}async uploadArtifactFiles(e=[],{sessionId:s=null}={}){const n=Array.isArray(e)?e.filter(c=>c&&typeof c.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(),r=[];let o=0,a=null;for(const c of n)try{const u=await this.transport.uploadArtifactFromFile(i,c);r.push(u),await this.finalizeArtifactUpload(u,{sessionId:i,suppressStatus:!0})}catch(u){o+=1,a=u}return r.length>0?this.dispatch({type:"ui/status",text:o>0?`Uploaded ${r.length}/${n.length} file(s); last error: ${a?.message||String(a)}`:r.length===1?`Uploaded ${r[0].filename}`:`Uploaded ${r.length} files`}):a&&this.dispatch({type:"ui/status",text:`Upload failed: ${a?.message||String(a)}`}),r}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),r=await this.finalizeArtifactUpload(i,{sessionId:n,suppressStatus:!0});if(this.dispatch({type:"ui/modal",modal:null}),this.stageUploadedImageAttachment(r,n)){this.dispatch({type:"ui/status",text:`Uploaded ${r.filename} — attached to your next message`});return}this.dispatch({type:"ui/status",text:`Uploaded ${r.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=Df(n),r=xi(n),o=Bf(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:`Rename (${Ee(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:i,cursorIndex:i.length,agentTitlePrefix:r,currentTitle:String(n.title||"").trim(),maxLength:o}}),this.dispatch({type:"ui/status",text:r?`Rename title for ${r}; 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 r=this.getBulkSelectedSessionActions(e).eligible;if(r.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:r.length,skippedCount:s.length-r.length,selectedIds:r.map(o=>o.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 r=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:r,state:String(i.state||"").trim(),systemRestart:!0}}),this.dispatch({type:"ui/status",text:"Choose how to restart the system session"});return}if(i.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; manage sessions individually."});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:`Terminate (${Ee(n)})`,sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:String(i.title||"").trim(),state:String(i.state||"").trim(),canRegenerate:!1}})}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(o=>String(o||"").trim()).filter(Boolean))].map(o=>e.sessions.byId[o]).filter(Boolean),r=i.filter(o=>!o.isSystem&&!o.isGroup);return{selected:i,eligible:r,skippedCount:i.length-r.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=St(e,n.maxLength),r=fe(i,s);this.updateRenameSessionModal({value:i,cursorIndex:r})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=tt(s.value||"",s.cursorIndex||0,St(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=wt(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||"",fe(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],r=i?.isGroup?i.groupId||gs(s):null;if(r){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 ${r.slice(0,8)}...`});try{await this.transport.updateSessionGroup(r,{title:n}),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Renamed group ${n}`})}catch(c){this.dispatch({type:"ui/status",text:`Rename failed: ${c?.message||String(c)}`})}return}if(typeof this.transport.renameSession!="function"){this.dispatch({type:"ui/status",text:"Session renaming is not supported by this transport"});return}const o=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),o&&this.setFocus(o),this.dispatch({type:"ui/status",text:`Renaming ${Ee(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${Ee(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=gt(["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(r){this.dispatch({type:"ui/status",text:r?.message||String(r)})}}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(r){this.dispatch({type:"ui/status",text:r?.message||String(r)});return}this.dispatch({type:"ui/modal",modal:{type:"shareSession",title:`Share (${Ee(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=St(e,120),r=fe(i,s);this.updateShareSessionModal({value:i,cursorIndex:r})}insertShareSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=tt(s.value||"",s.cursorIndex||0,St(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=wt(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||"",fe(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 r=n.startsWith("-")?n.slice(1).trim():n.toLowerCase().startsWith("revoke ")?n.slice(7).trim():null;if(r!==null){const m=r.toLowerCase(),g=(e.shares||[]).find(h=>h.subject&&String(h.subject).toLowerCase()===m||h.email&&String(h.email).toLowerCase()===m||h.displayName&&String(h.displayName).toLowerCase()===m);if(!g){this.dispatch({type:"ui/status",text:`No grant matching "${r}"`});return}this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.revokeSessionShare(s,{provider:g.provider,subject:g.subject}),this.dispatch({type:"ui/status",text:`Revoked ${r}`})}catch(h){this.dispatch({type:"ui/status",text:h?.message||String(h)})}return}const o=n.split(/\s+/),a={r:"read",read:"read",w:"write",write:"write"},c=o.length>1?o[o.length-1].toLowerCase():null,u=c&&a[c]?a[c]:"read",p=c&&a[c]?o.slice(0,-1).join(" "):n,d=p.toLowerCase();let f=null;if(typeof this.transport.listKnownUsers=="function"){let m=[];try{m=await this.transport.listKnownUsers({limit:500})}catch{m=[]}const g=Array.isArray(m)?m:[];if(f=g.find(h=>h.displayName&&h.displayName.toLowerCase()===d||h.email&&h.email.toLowerCase()===d||h.subject&&h.subject.toLowerCase()===d)||null,!f){const h=g.filter(y=>y.displayName&&y.displayName.toLowerCase().includes(d)||y.email&&y.email.toLowerCase().includes(d)||y.subject&&y.subject.toLowerCase().includes(d));if(h.length===1)f=h[0];else if(h.length>1){this.dispatch({type:"ui/status",text:`"${p}" is ambiguous (${h.length} matches)`});return}}}f||(f={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:p,email:null,displayName:null}),this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.grantSessionShare(s,{provider:f.provider,subject:f.subject,email:f.email??null,displayName:f.displayName??null},u),this.dispatch({type:"ui/status",text:`Granted ${u} to ${p}`})}catch(m){this.dispatch({type:"ui/status",text:m?.message||String(m)})}}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 r=Math.max(0,Number(s.selectedIndex)||0);this.dispatch({type:"ui/modalSelection",index:Math.max(0,r+e)});return}if(!Array.isArray(s.items)||s.items.length===0)return;if(s.type==="logFilter"||s.type==="filesFilter"||s.type==="historyFormat"){const r=Math.max(0,Math.min(Number(s.selectedIndex)||0,s.items.length-1)),o=s.items[r];if(!o||!Array.isArray(o.options)||o.options.length===0)return;const a=o.options.map(d=>d.id).filter(Boolean);if(a.length===0)return;const c=s.type==="filesFilter"?this.getState().files.filter?.[o.id]||a[0]:s.type==="historyFormat"?this.getState().executionHistory?.format||a[0]:this.getState().logs.filter?.[o.id]||a[0],u=gt(a,c,e),p=o.options.find(d=>d.id===u)||o.options[0];this.dispatch({type:s.type==="filesFilter"?"files/filter":s.type==="historyFormat"?"executionHistory/format":"logs/filter",filter:s.type==="historyFormat"?void 0:{[o.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: ${o.label} = ${p?.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,r=s.items[i],o=s.type==="filesFilter"?this.getState().files.filter?.[r.id]||r.options?.[0]?.id:s.type==="historyFormat"?this.getState().executionHistory?.format||r.options?.[0]?.id:this.getState().logs.filter?.[r.id]||r.options?.[0]?.id,a=r.options?.find(c=>c.id===o)||r.options?.[0];this.dispatch({type:"ui/modalSelection",index:i}),this.dispatch({type:"ui/status",text:`Editing ${r.label}: ${a?.label||o||""}`})}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}):e.action==="deleteMarkedArtifacts"&&await this.deleteMarkedArtifacts({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=Be(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=Fr(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 r={...i,...s?.id?{contextTier:s.id}:{}};if(i?.mode==="switchModel"){await this.switchSessionModel({...r,model:e.modelItem?.id||i.model});return}await this.openSessionAgentPicker(r);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,r=Wf(s,n);let o=e.sessions.activeSessionId;i&&(o=i,e.sessions.activeSessionId!==i&&await this.loadSession(i));let a=o&&e.sessions.byId[o]||null;if(o&&!a&&(a=this.getState().sessions.byId[o]||null),!o){const h=await this.createSession({});if(!h?.sessionId)return;o=h.sessionId,a=this.getState().sessions.byId[o]||null}const c=n.some(h=>h?.kind==="image");if(!r.trim()&&!c){o&&this.getPendingOutboxItems(o).length>0&&await this.dispatchPendingOutbox(o).catch(()=>{});return}const u=a?.pendingQuestion||null,p=!!u?.question,d=this.getPromptEditSessionMatch(o);if(d){const h=this.getSessionOutbox(o).find(y=>y.id===d.itemId);if(h?.phase==="queued"||h?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(o).catch(()=>{});return}if(p&&typeof this.transport.sendAnswer=="function"){const h=Date.now(),y={...u,answer:r,answeredAt:h,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:null,answeredPendingQuestion:y}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(o,r),this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:{...y,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(o,100),this.syncSessionEvents(o).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(S){this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:u}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(r,String(r||"").length),this.dispatch({type:"ui/status",text:S?.message||String(S)})}return}const f=n.filter(h=>h?.kind==="image");let m=null;if(f.length>0){if(f.some(S=>S.file)&&typeof this.transport.uploadArtifactFromFile!="function"){this.dispatch({type:"ui/status",text:"This transport does not support image attachments."});return}const y=this.buildOutboxItem("","pending");this.dispatch({type:"ui/status",text:`Uploading ${f.length} image${f.length>1?"s":""}...`});try{m=await this.uploadPendingImageAttachments(o,f,y.id),this.dispatch({type:"ui/status",text:""})}catch(S){this.dispatch({type:"ui/status",text:`Image upload failed: ${S?.message||S}`});return}}const g=r.trim()?r:m&&m.length>0?"See the attached image(s).":r;this.queuePromptInOutbox(o,g,m?{attachments:m}:null),this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(o).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)),r=this.getState().ui;if(!(r.prompt===n&&r.promptCursor===i)){if(r.promptEdit?.sessionId&&r.promptEdit?.itemId){const a=this.getSessionOutbox(r.promptEdit.sessionId).map(c=>c.id===r.promptEdit.itemId&&c.phase==="pending"&&c.attempted!==!0?{...c,text:n}:c);this.setSessionOutboxItems(r.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=tt(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=wt(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=Yf(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,fe(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,Qa(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=Xf(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 Xt({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??Nt(i),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===T.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 r=this.getCurrentLayout({width:s,height:n}),o=this.getState().ui.focusRegion,a=Ye(o,r);a!==o&&this.setFocus(a)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:Ye(e,this.getCurrentLayout())})}focusNext(){const e=this.getCurrentLayout(),s=Ye(this.getState().ui.focusRegion,e),n=Nn(e);this.setFocus(gt(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=Ye(this.getState().ui.focusRegion,e),n=Nn(e);this.setFocus(gt(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=Ye(this.getState().ui.focusRegion,e);this.setFocus(Lc(s,e))}focusRight(){const e=this.getCurrentLayout(),s=Ye(this.getState().ui.focusRegion,e);this.setFocus(Fc(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 r=this.getCurrentLayout({paneAdjust:i}),o=this.getState().ui.focusRegion,a=Ye(o,r);a!==o&&this.setFocus(a)}adjustSessionPaneSplit(e){const s=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,r=Math.max(-i,Math.min(i,(s.sessionPaneAdjust||0)+e));this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:r});const o=this.getCurrentLayout({sessionPaneAdjust:r}),a=this.getState().ui.focusRegion,c=Ye(a,o);c!==a&&this.setFocus(c)}adjustActivityPaneSplit(e){const s=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,r=Math.max(-i,Math.min(i,(s.activityPaneAdjust||0)+e));this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:r});const o=this.getCurrentLayout({activityPaneAdjust:r}),a=this.getState().ui.focusRegion,c=Ye(a,o);c!==a&&this.setFocus(c)}resizeFocusedPane(e){const s=this.getState().ui.focusRegion,n=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??n.viewportHeight??40,r=n.viewportHeight??40,o=(a,c,u,p)=>{const d=Math.max(u,p);return Math.max(u,Math.min(d,(a||0)+c))};if(s===T.SESSIONS||s===T.CHAT){const a=Yo(i),c=$t+1,u=Math.min(Xo(r,i),i-Bs-1),p=s===T.CHAT?-e:e,d=o(n.sessionPaneAdjust,p,c-a,u-a);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:d})}else if(s===T.INSPECTOR||s===T.ACTIVITY){const a=Math.max(Tt,Math.floor(i*zo)),c=Tt+1,u=i-xs-1,p=s===T.INSPECTOR?-e:e,d=o(n.activityPaneAdjust,p,c-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=[],r=new Set;for(const o of n?.events||[]){if(o?.eventType!=="session.turn_completed")continue;const a=Number(o?.data?.turnIndex??o?.data?.iteration);!Number.isFinite(a)||r.has(a)||(r.add(a),i.push(a))}return i.sort((o,a)=>o-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(r=>r!==s):[...n,s];this.dispatch({type:"ui/sequenceExpandedTurns",turns:i})}nextInspectorTab(){const e=this.getState().ui.inspectorTab,s=gt(We,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=gt(We,this.getState().ui.inspectorTab,-1);this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),this.ensureInspectorData(e).catch(()=>{})}cycleInspectorTab(){this.nextInspectorTab()}toggleStatsView(){const e=["session","fleet","users"],s=this.getState().ui.statsViewMode,n=e.includes(s)?e.indexOf(s):0,i=e[(n+1)%e.length];this.setStatsViewMode(i)}setStatsViewMode(e){this.dispatch({type:"ui/statsViewMode",statsViewMode:e}),this.getState().ui.inspectorTab==="stats"&&this.ensureInspectorData("stats").catch(()=>{})}async selectInspectorTab(e){We.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=Ot(s);if(n.length===0)return;const i=s.sessions.activeSessionId||n[0].sessionId,r=Math.max(0,n.findIndex(c=>c.sessionId===i)),o=Math.max(0,Math.min(n.length-1,r+e)),a=n[o].sessionId;this.navigateToSession(a)}navigateToSession(e){e&&(this.getState().sessions.activeSessionId!==e&&(this.dispatch({type:"sessions/selected",sessionId:e}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.sessionNavSettleTimer&&clearTimeout(this.sessionNavSettleTimer),this.sessionNavSettleTimer=setTimeout(()=>{this.sessionNavSettleTimer=null,this.loadSession(e).catch(()=>{})},oh))}getSessionPageSize(){const e=this.getCurrentLayout(),s=e.fullscreenPane===T.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 Qf.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 r=this.getPaneMaxScrollOffset(e,i),o=Math.max(0,Math.min(Number(s)||0,r));if(this.paneUsesStickyBottomFollow(e,i)){const a=n.followBottom!==void 0?!!n.followBottom:n.atBottom!==void 0?!!n.atBottom:o>=r;return this.dispatch({type:"ui/followBottom",pane:e,followBottom:a}),this.dispatch({type:"ui/scroll",pane:e,offset:a?0:o}),o}return this.dispatch({type:"ui/scroll",pane:e,offset:o}),o}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),c=Math.max(0,Math.min(a-s,i));this.applyPaneVisualScrollOffset(e,c,{followBottom:c>=i},n);return}const r=Math.max(0,Math.min(Number(n.ui.scroll?.[e])||0,i)),o=Math.max(0,Math.min(r+s,i));this.dispatch({type:"ui/scroll",pane:e,offset:o}),e==="chat"&&s>0?r>=i?this.handleChatTopHistoryScrollIntent(o).catch(()=>{}):o>=i&&this.armChatTopHistoryLoad():e==="chat"&&s<0&&this.disarmChatTopHistoryLoad()}scrollPaneTo(e,s){const n=this.getState(),i=this.getPaneMaxScrollOffset(e,n),r=Math.max(0,Math.min(Number(s)||0,i));if(this.paneUsesStickyBottomFollow(e,n)){this.applyPaneVisualScrollOffset(e,r,{followBottom:r>=i},n);return}this.dispatch({type:"ui/scroll",pane:e,offset:r}),e==="chat"&&(i>0&&r>=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:bf,force:!0})}}artifactPreviewOwnsActivitySlot(e=this.getState()){return e.ui.inspectorTab==="files"&&!!e.files?.selectedArtifactId}focusIsArtifactList(e=this.getState()){return e.ui.focusRegion===T.INSPECTOR&&e.ui.inspectorTab==="files"}getScrollablePaneForFocus(){const e=this.getState(),s=e.ui.focusRegion;return s===T.CHAT?"chat":s===T.ACTIVITY?this.artifactPreviewOwnsActivitySlot(e)?"filePreview":"activity":s===T.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),r=di(e,n),o=[...fi(e,n),...ui(e)],a=Math.min(Math.max(0,Math.floor(i*.34)),bt(o,n)),c=bt(r,n);return{contentWidth:n,contentHeight:Math.max(1,i-a),totalLines:c}}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),r=e.sessions.activeSessionId,o={sessions:{activeSessionId:r,byId:r?{[r]:e.sessions.byId[r]||null}:{}},history:{bySessionId:r?new Map([[r,e.history.bySessionId.get(r)||null]]):new Map}},a=mi(o);return{contentWidth:n,contentHeight:i,totalLines:bt(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,r=i&&e.orchestration.bySessionId?.[i]||null,o={branding:e.branding,sessions:{activeSessionId:i,byId:e.sessions.byId,flat:e.sessions.flat},history:{bySessionId:e.history.bySessionId},orchestration:{bySessionId:i&&r?{[i]:r}:{}},logs:e.logs,sessionStats:e.sessionStats,fleetStats:e.fleetStats,ui:{inspectorTab:e.ui.inspectorTab,statsViewMode:e.ui.statsViewMode},executionHistory:e.executionHistory},a=it(o,{width:n}),c=a.tabs.map(f=>({text:f===a.activeTab?`[${f}] `:`${f} `,color:f===a.activeTab?"magenta":"gray",bold:f===a.activeTab})),u=(a.lines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f),p=a.activeTab==="sequence"?[c,...(a.stickyLines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f)]:[],d=a.activeTab==="sequence"?u:[c,...u];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:bt(p,n),totalLines:bt(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,r=n?Math.max(10,s.bodyHeight):s.inspectorPaneHeight,o=Math.max(20,i-4),a=Math.max(8,o-4),c=e.sessions.activeSessionId,u=c&&e.sessions.byId[c]||null,p={sessions:{activeSessionId:c,byId:c&&u?{[c]: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=gi(p,{listWidth:a,previewWidth:a}),f=Math.max(9,r-4),m=Math.max(5,Math.min(10,Math.floor(f*.35)));let g=Math.max(5,Math.min(m,(d.listBodyLines||[]).length+2)),h=Math.max(5,f-g-1);const y=8;if(h<y){const S=y-h;g=Math.max(5,g-S),h=Math.max(5,f-g-1)}return{contentWidth:a,contentHeight:Math.max(1,h-2),totalLines:bt(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),r=Math.max(0,n.contentHeight-i);return Math.max(0,n.totalLines-r)}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 r=n.history.bySessionId.get(i);if(!r?.hasOlderEvents||this.sessionHistoryExpansionLoads.has(i))return;if(Number(r.loadedEventCount||0)>=jn){this.dispatch({type:"ui/status",text:"Reached automatic history limit. Press e to load more older CMS events."});return}const o=Array.isArray(r?.chat)&&r.chat.length>0;if(!s.force&&o){const{contentHeight:a,totalLines:c}=this.getActiveChatRenderMetrics(n),u=Math.max(0,c-a);if(e<u)return}await this.expandSessionHistory(i,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages,eventTypes:cc})}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),r=Math.max(le,Number(i?.loadedEventLimit??le)||le),o=le,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 c=e===n.sessions.activeSessionId,u=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),p=c?this.getActiveChatRenderMetrics(n).totalLines:0,d=(async()=>{let f;const m=Math.max(1,Math.floor(Number(s.pages)||1)),g=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&a>0){f=i||os([],{requestedLimit:r});for(let S=0;S<m;S+=1){const E=Array.isArray(f?.events)&&f.events.length>0?Number(f.events[0]?.seq||0):0;if(!f?.hasOlderEvents||E<=1){f={...f,hasOlderEvents:!1};break}if(Number(f.loadedEventCount||0)>=jn)break;const x=await this.transport.getSessionEventsBefore(e,E,o,g);if(!Array.isArray(x)||x.length===0){f={...f,hasOlderEvents:!1};break}const w=os(x,{requestedLimit:o}),b=[...w.events||[],...f?.events||[]];if(f={chat:At([...w.chat||[],...f?.chat||[]]),activity:[...w.activity||[],...f?.activity||[]],events:b,lastSeq:f?.lastSeq||f?.events?.[f?.events?.length-1]?.seq||x[x.length-1]?.seq||0,loadedEventLimit:b.length,loadedEventCount:b.length,hasOlderEvents:x.length>=o&&Number(x[0]?.seq||0)>1},!f.hasOlderEvents)break}}else{const S=Nc(r);if(S<=r){this.dispatch({type:"ui/status",text:i?.hasOlderEvents?`Already showing a large recent history window (${r} events)`:"Already showing the oldest loaded history"});return}const E=await this.transport.getSessionEvents(e,void 0,S);f={...os(E,{requestedLimit:S}),lastSeq:E[E.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:f});for(const S of f?.events||[])this.reconcileOutboxAgainstEvent(e,S);const h=Array.isArray(i?.chat)&&i.chat.length>0;if(c&&!h)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(c&&u>0){const S=this.getState(),E=this.getActiveChatRenderMetrics(S).totalLines,x=Math.max(0,E-p);x>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:u+x})}const y=f.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${f.loadedEventCount} events loaded)`:`Loaded older history page (${f.loadedEventCount} events loaded)`:`Loaded full available history (${f.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:y}),f.hasOlderEvents?s.autoTriggered&&c&&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:o,skippedCount:a}=this.getBulkSelectedSessionActions(s);if(o.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 ${o.length} selected session${o.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 c=0;const u=[];for(const d of o)try{await this.transport.cancelSession(d.sessionId),c+=1}catch(f){u.push(`${d.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const p=u.length===0?`Cancelled ${c} session${c===1?"":"s"}`:`Cancelled ${c}/${o.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:p}),await this.refreshSessions();return}const i=s.sessions.activeSessionId;if(!i)return;const r=s.sessions.byId[i];if(r?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; cancel 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(!e){const o=r.title||r.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Terminate & Restart System Session",message:`Terminate system session "${o}" and start a fresh one?`,confirmLabel:"Terminate & Restart",action:"cancelSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(r.agentId||i,{disposition:"terminate",reason:"Terminated by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${r.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const a=r?.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",distillerModel:i="",distillerEffort:r="",distillerContextTier:o=""}={}){const a=this.getState(),c=a.sessions.activeSessionId;if(!c)return;if(typeof this.transport.regenerateSession!="function"){this.dispatch({type:"ui/status",text:"Session regeneration is not supported by this deployment"});return}const u=a.sessions.byId[c];if(u?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; regenerate sessions individually."});return}if(u?.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be regenerated."});return}if(u?.serviceKind){this.dispatch({type:"ui/status",text:"Service sessions are runtime machinery and cannot be regenerated."});return}if(!e){const p=u?.title||c.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Regenerate Session",message:`Regenerate context for "${p}"? 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:c,previousFocus:a.ui.focusRegion,extras:{instructions:"",distillMode:"llm",distillerModel:"",distillerEffort:"",distillerContextTier:"",distillerModelOptions:await this._loadDistillerModelOptions()}}});return}try{const p=String(s||"").trim();await this.transport.regenerateSession(c,{force:!0,...p?{instructions:p.slice(0,4e3)}:{},...n==="deterministic"?{distillMode:"deterministic"}:{},...i?{distillerModel:i}:{},...r?{distillerReasoningEffort:r}:{},...o?{distillerContextTier:o}:{}}),this.dispatch({type:"ui/status",text:`Regeneration requested for ${c.slice(0,8)} — rebuilding at the next boundary`})}catch(p){this.dispatch({type:"ui/status",text:`Regenerate failed: ${p?.message||String(p)}`});return}await this.refreshSessions()}async _loadDistillerModelOptions(){if(typeof this.transport.listModels!="function")return[];try{const e=await this.transport.listModels({groupByProvider:!0});return(Array.isArray(e)?e:Array.isArray(e?.providers)?e.providers:Array.isArray(e?.models)?e.models:[]).flatMap(i=>Array.isArray(i?.models)?i.models.map(r=>({...r,providerId:r.providerId||i.providerId})):[i]).filter(i=>i&&(i.qualifiedName||i.modelName)).map(i=>({qualifiedName:i.qualifiedName||i.modelName,modelName:i.modelName||i.qualifiedName,providerId:i.providerId||"",supportedReasoningEfforts:Array.isArray(i.supportedReasoningEfforts)?i.supportedReasoningEfforts:[],supportedContextTiers:Array.isArray(i.supportedContextTiers)?i.supportedContextTiers:[]}))}catch(e){return this.dispatch({type:"ui/status",text:`Could not load distiller models: ${e?.message||String(e)}`}),[]}}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 r=(await this.transport.stopSessionTurn(s,{reason:"Stopped by user"}))?.outcome||"stopped";r==="no_active_turn"?this.dispatch({type:"ui/status",text:"No active turn to stop"}):r==="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:c}=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.${c>0?` (${c} selected row${c===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Complete Sessions",action:"completeSession",previousFocus:n.ui.focusRegion}});return}let u=0;const p=[];for(const f of a)try{await this.transport.completeSession(f.sessionId,e),u+=1}catch(m){p.push(`${f.sessionId.slice(0,8)}: ${m?.message||String(m)}`)}this.dispatch({type:"sessions/selectClear"});const d=p.length===0?`Completed ${u} session${u===1?"":"s"}`:`Completed ${u}/${a.length}; ${p.length} failed: ${p.slice(0,2).join(", ")}${p.length>2?"…":""}`;this.dispatch({type:"ui/status",text:d}),await this.refreshSessions();return}const r=this.getState().sessions.activeSessionId;if(!r)return;const o=this.getState().sessions.byId[r];if(o?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; complete 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(!s){const a=o.title||o.agentId||r.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:r,previousFocus:this.getState().ui.focusRegion}});return}await this.transport.restartSystemSession(o.agentId||r,{disposition:"complete",reason:e}),this.dispatch({type:"ui/status",text:`Restarted system session ${o.agentId||r.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(o?.status==="completed"&&!o?.cronActive&&!o?.cronInterval){this.dispatch({type:"ui/status",text:`${r.slice(0,8)} is already completed`});return}if(!s){const a=o?.title||r.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:r,previousFocus:this.getState().ui.focusRegion}});return}this.dispatch({type:"ui/status",text:`Completing ${r.slice(0,8)} (cascading to sub-agents)...`});try{await this.transport.completeSession(r,e),await this.refreshSessions(),this.scheduleSessionDetailSync(r,100),this.scheduleSessionsRefresh(900)}catch(a){await this.loadSession(r).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:o,skippedCount:a}=this.getBulkSelectedSessionActions(s);if(o.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 ${o.length} selected session${o.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 c=0;const u=[];for(const d of o)try{await this.transport.deleteSession(d.sessionId),this.handleSessionGone(d.sessionId),c+=1}catch(f){u.push(`${d.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const p=u.length===0?`Deleted ${c} session${c===1?"":"s"}`:`Deleted ${c}/${o.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:p}),await this.refreshSessions();return}const i=s.sessions.activeSessionId;if(!i)return;const r=s.sessions.byId[i];if(r?.isGroup){const o=r.groupId||gs(i);if(!o||typeof this.transport.deleteSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group deletion is not supported by this transport"});return}if(Number(r.memberCount||0)>0){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Group Not Empty",message:`Group "${r.title||o}" 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 "${r.title||o}"? This action cannot be undone.`,confirmLabel:"Delete Group",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSessionGroup(o),this.dispatch({type:"ui/status",text:`Deleted group ${r.title||o}`}),await this.refreshSessions();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(!e){const o=r.title||r.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete & Restart System Session",message:`Hard delete system session "${o}" 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(r.agentId||i,{disposition:"hard_delete",reason:"Hard-deleted by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${r.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const a=r?.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 A.REFRESH:await this.refreshSessions();return;case A.NEW_SESSION:await this.openNewSessionFlow();return;case A.OPEN_MODEL_PICKER:await this.openModelPicker();return;case A.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case A.OPEN_THEME_PICKER:this.openThemePicker();return;case A.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case A.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case A.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case A.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case A.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case A.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case A.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case A.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case A.TOGGLE_CHAT_VIEW:this.toggleChatViewMode();return;case A.CLOSE_MODAL:this.closeModal();return;case A.MODAL_PREV:this.moveModalSelection(-1);return;case A.MODAL_NEXT:this.moveModalSelection(1);return;case A.MODAL_PANE_PREV:this.moveModalPane(-1);return;case A.MODAL_PANE_NEXT:this.moveModalPane(1);return;case A.MODAL_CONFIRM:await this.confirmModal();return;case A.SEND_PROMPT:await this.sendPrompt();return;case A.FOCUS_NEXT:this.focusNext();return;case A.FOCUS_PREV:this.focusPrev();return;case A.FOCUS_LEFT:this.focusLeft();return;case A.FOCUS_RIGHT:this.focusRight();return;case A.FOCUS_PROMPT:this.setFocus(T.PROMPT);return;case A.FOCUS_SESSIONS:this.setFocus(T.SESSIONS);return;case A.MOVE_SESSION_UP:await this.moveSession(-1);return;case A.MOVE_SESSION_DOWN:await this.moveSession(1);return;case A.EXPAND_SESSION:this.expandActiveSession();return;case A.COLLAPSE_SESSION:this.collapseActiveSession();return;case A.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case A.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case A.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case A.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case A.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case A.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case A.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case A.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case A.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case A.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case A.OPEN_HELP:this.openHelpModal();return;case A.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case A.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case A.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case A.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case A.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case A.OPEN_LOG_FILTER:this.openLogFilter();return;case A.OPEN_FILES_FILTER:this.openFilesFilter();return;case A.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case A.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case A.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case A.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case A.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case A.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case A.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case A.SCROLL_UP:this.scrollCurrentPane(1);return;case A.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case A.PAGE_UP:if(this.getState().ui.focusRegion===T.SESSIONS){await this.moveSessionPage(-1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(-10);return}this.scrollCurrentPane(10);return;case A.PAGE_DOWN:if(this.getState().ui.focusRegion===T.SESSIONS){await this.moveSessionPage(1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(10);return}this.scrollCurrentPane(-10);return;case A.EXPAND_HISTORY:await this.expandActiveHistory();return;case A.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case A.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case A.CANCEL_SESSION:await this.cancelActiveSession();return;case A.STOP_TURN:await this.stopActiveSessionTurn();return;case A.DONE_SESSION:await this.completeActiveSession();return;case A.DELETE_SESSION:await this.deleteActiveSession();return;case A.REGENERATE_SESSION:await this.regenerateActiveSession();return;case A.PIN_SESSION:this.togglePinActiveSession();return;case A.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case A.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case A.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case A.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case A.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case A.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case A.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case A.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case A.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case A.ADMIN_SHOW_GHCP:this.setAdminSection("ghcp");return;case A.ADMIN_SHOW_PACKAGES:this.setAdminSection("packages");return;case A.ADMIN_SHOW_WORKERS:this.setAdminSection("workers");return;case A.ADMIN_WORKERS_REFRESH:await this.refreshAdminWorkers();return;case A.ADMIN_PACKAGES_REFRESH:await this.refreshAdminAgentPackages();return;case A.ADMIN_PACKAGES_NEXT:await this.stepAdminPackageSelection(1);return;case A.ADMIN_PACKAGES_PREV:await this.stepAdminPackageSelection(-1);return;case A.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case A.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case A.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case A.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 Ws=0;function _e(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 In(){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 ch(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 uh(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 dh(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 r=typeof e=="string"?e.trim():"";return r?(n.length>0&&n.push({text:" ",color:"gray"}),n.push({text:r,color:"cyan",bold:!0}),n):n.length>0?n:null}function ph(t=2e3){const[e,s]=l.useState(()=>In());return l.useEffect(()=>{if(In()==null)return;const n=()=>{const r=In();r!=null&&s(o=>o===r?o:r)};n();const i=setInterval(n,t);return()=>clearInterval(i)},[t]),l.useMemo(()=>ch(e),[e])}function Dt(t,e){return t&&e?{[t]:e}:{}}function Xr(t){return typeof t=="string"?{text:t,color:"white"}:t}function is(t,e,s,n,i,r){const o=(e.tabs||We).map(d=>({text:d===e.activeTab?`[${d}] `:`${d} `,color:d===e.activeTab?"magenta":"gray",bold:d===e.activeTab})),a=(e.lines||[]).map(Xr),c=(e.stickyLines||[]).map(Xr),u=e.activeTab==="sequence"?[o,...c]:[],p=e.activeTab==="sequence"?a:[o,...a];return l.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:i,stickyLines:u,marginBottom:Ws,lines:p,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="sequence"||e.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:r})}function Qr(t,e){const s=String(t||"");return e<=0?"":s.length<=e?s:e===1?s.slice(0,1):`${s.slice(0,e-1)}...`}l.memo(function({controller:e,maxRows:s,width:n,height:i,frame:r,versionLabel:o=null}){const a=Ge(),c=ph(),u=Z(e,g=>({sessions:g.sessions,mode:g.connection?.mode||"local",brandingTitle:g.branding?.title||"PilotSwarm",focused:g.ui.focusRegion==="sessions",identityLabel:uh(g.auth)}),_e),p=l.useMemo(()=>dh(c,o,u.identityLabel),[c,o,u.identityLabel]),d=l.useMemo(()=>({sessions:u.sessions,connection:{mode:u.mode},branding:{title:u.brandingTitle}}),[u.brandingTitle,u.mode,u.sessions]),f=l.useMemo(()=>On(d,s),[d,s]),m=l.useMemo(()=>f.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:f.map(g=>g.active?la(g.runs,{preserveColors:!0}):g.runs),[f]);return l.createElement(a.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:p,color:"yellow",focused:u.focused,width:n,height:i,marginBottom:Ws,lines:m,paneId:"sessions",paneLabel:"Sessions",frame:r})});l.memo(function({controller:e,width:s,height:n,frame:i}){const r=Ge(),o=Z(e,x=>{const w=x.sessions.activeSessionId;return{activeSessionId:w,activeSession:w&&x.sessions.byId[w]||null,activeHistory:w&&x.history.bySessionId.get(w)||null,activeOutbox:w&&x.outbox?.bySessionId?.[w]||null,authPrincipal:x.auth?.principal||null,branding:x.branding,connectionError:x.connection.error,connectionMode:x.connection.mode,chatViewMode:x.ui.chatViewMode||"transcript",chatScroll:x.ui.scroll.chat,focused:x.ui.focusRegion==="chat"}},_e),a=Math.max(20,s-4),c=l.useMemo(()=>{const x=new Map;return o.activeSessionId&&o.activeHistory&&x.set(o.activeSessionId,o.activeHistory),{branding:o.branding,auth:{principal:o.authPrincipal},connection:{error:o.connectionError,mode:o.connectionMode},ui:{chatViewMode:o.chatViewMode},sessions:{activeSessionId:o.activeSessionId,byId:Dt(o.activeSessionId,o.activeSession)},history:{bySessionId:x},outbox:{bySessionId:o.activeSessionId&&o.activeOutbox?{[o.activeSessionId]:o.activeOutbox}:{}}}},[o.activeHistory,o.activeSessionId,o.activeSession,o.activeOutbox,o.authPrincipal,o.branding,o.chatViewMode,o.connectionError,o.connectionMode]),u=l.useMemo(()=>Ma(c,{width:a}),[a,c]),p=ko(!!u?.animateTitleRight),d=l.useMemo(()=>Ao(u?.titleRight,p),[p,u?.titleRight]),f=!o.activeSessionId&&o.connectionError,m=l.useMemo(()=>f?[{kind:"markup",value:o.branding.splash},{text:"",color:"gray"},{text:"Startup failed",color:"red",bold:!0},{text:o.connectionError,color:"white"},{text:"",color:"gray"},{text:"Check env credentials and model provider config, then relaunch.",color:"yellow"}]:di(c,a),[o.branding.splash,o.connectionError,a,c,f]),g=String(o.activeSession?.status||"").toLowerCase()==="running",h=vo(g),y=l.useMemo(()=>f?[]:ui(c,{spinnerFrame:h,maxWidth:a}),[c,f,h,a]),S=l.useMemo(()=>f?[]:fi(c,a),[c,f,a]),E=l.useMemo(()=>S.length>0||y.length>0?[...S,...y]:[],[S,y]);return l.createElement(r.Panel,{title:u.title,titleRight:d,color:u.color,focused:o.focused,width:s,height:n,lines:m,bottomStickyLines:E,scrollOffset:o.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:i})});const fh=l.memo(function({controller:e,width:s,height:n,shellTitle:i,focused:r=!1,frame:o,showFullscreenTitle:a=!1,embedded:c=!1}){const u=Ge(),p=Z(e,B=>({activeSessionId:B.sessions.activeSessionId,activeSession:B.sessions.activeSessionId&&B.sessions.byId[B.sessions.activeSessionId]||null,sessionsFlat:B.sessions.flat,filesBySessionId:B.files.bySessionId,filesFullscreen:!!B.files.fullscreen,selectedArtifactId:B.files.selectedArtifactId,filesFilter:B.files.filter,filePreviewScroll:B.ui.scroll.filePreview}),_e),d=Math.max(20,s-4),f=l.useMemo(()=>({sessions:{activeSessionId:p.activeSessionId,byId:p.activeSessionId&&p.activeSession?{[p.activeSessionId]:p.activeSession}:{},flat:p.sessionsFlat},files:{bySessionId:p.filesBySessionId,fullscreen:p.filesFullscreen,selectedArtifactId:p.selectedArtifactId,filter:p.filesFilter},ui:{scroll:{filePreview:p.filePreviewScroll}}}),[p]),m=l.useMemo(()=>gi(f,{listWidth:Math.max(8,d-4),previewWidth:Math.max(8,d-4)}),[d,f]),g=i||(a?m.fullscreenTitle:m.panelTitle||m.listTitle)||[{text:"Files",color:"magenta",bold:!0}],h=Math.max(9,n-4),y=Math.max(5,Math.min(10,Math.floor(h*.35)));let S=Math.max(5,Math.min(y,(m.listBodyLines||[]).length+2)),E=Math.max(5,h-S-1);const x=8;if(E<x){const B=x-E;S=Math.max(5,S-B),E=Math.max(5,h-S-1)}const w=Math.max(1,S-2),b=Math.max(0,m.selectedIndex-Math.floor(w/2)),I=!c&&o?{x:o.x+2,y:o.y+2,width:d,height:S}:null,k=!c&&o?{x:o.x+2,y:o.y+2+S+1,width:d,height:E}:null,P=We.map(B=>({text:B==="files"?`[${B}] `:`${B} `,color:B==="files"?"magenta":"gray",bold:B==="files"})),M=l.createElement(u.Column,{width:d},l.createElement(u.Lines,{lines:[P]}),l.createElement(u.Panel,{title:m.listTitle,color:"gray",focused:!1,width:d,height:S,lines:m.listBodyLines||m.listLines.slice(1),scrollOffset:b,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:I}),l.createElement(u.Panel,{title:m.previewTitle,color:"gray",focused:!1,width:d,height:E,lines:m.previewLines,scrollOffset:m.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:k}));return c?M:l.createElement(u.Panel,{title:g,color:"magenta",focused:r,width:s,height:n,marginBottom:Ws,paneId:"inspector",paneLabel:"Inspector",frame:o},M)}),hh=l.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Ge(),a=Math.max(20,s-4),c=Z(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null}),_e),u=l.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Dt(c.activeSessionId,c.activeSession)},ui:{inspectorTab:"files"}}),[c.activeSession,c.activeSessionId]),p=l.useMemo(()=>it(u,{width:a}),[a,u]);return l.createElement(o.Panel,{title:p.title,color:"magenta",focused:r.focused,width:s,height:n,marginBottom:Ws,paneId:"inspector",paneLabel:"Inspector",frame:i},l.createElement(fh,{controller:e,width:s,height:n,frame:i,focused:r.focused,embedded:!0}))}),mh=l.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Ge(),a=Math.max(20,s-4),c=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}),_e),u=l.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Dt(c.activeSessionId,c.activeSession)},history:{bySessionId:c.histories},orchestration:{bySessionId:c.activeSessionId&&c.activeOrchestration?{[c.activeSessionId]:c.activeOrchestration}:{}},ui:{inspectorTab:"sequence"}}),[c.activeOrchestration,c.activeSession,c.activeSessionId,c.histories]),p=l.useMemo(()=>it(u,{width:a,sequenceExpansion:{expandedTurns:c.expandedTurns||[],selectedTurn:c.selectedTurn??null}}),[a,u,c.expandedTurns,c.selectedTurn]);return is(o,p,r,s,n,i)}),gh=l.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Ge(),a=Math.max(20,s-4),c=Z(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,logs:d.logs}),_e),u=l.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Dt(c.activeSessionId,c.activeSession)},logs:c.logs,ui:{inspectorTab:"logs"}}),[c.activeSession,c.activeSessionId,c.logs]),p=l.useMemo(()=>it(u,{width:a}),[a,u]);return is(o,p,r,s,n,i)}),yh=l.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Ge(),a=Math.max(20,s-4),c=Z(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,executionHistory:d.executionHistory}),_e),u=l.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Dt(c.activeSessionId,c.activeSession)},executionHistory:c.executionHistory,ui:{inspectorTab:"history"}}),[c.activeSession,c.activeSessionId,c.executionHistory]),p=l.useMemo(()=>it(u,{width:a}),[a,u]);return is(o,p,r,s,n,i)}),Sh=l.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Ge(),a=Math.max(20,s-4),c=Z(e,d=>({activeSessionId:d.sessions.activeSessionId,sessionsById:d.sessions.byId,sessionsFlat:d.sessions.flat,histories:d.history.bySessionId}),_e),u=l.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:c.sessionsById,flat:c.sessionsFlat},history:{bySessionId:c.histories},ui:{inspectorTab:"nodes"}}),[c.activeSessionId,c.histories,c.sessionsById,c.sessionsFlat]),p=l.useMemo(()=>it(u,{width:a}),[a,u]);return is(o,p,r,s,n,i)}),bh=l.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Ge(),a=Math.max(20,s-4),c=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}),_e),u=l.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Dt(c.activeSessionId,c.activeSession)},sessionStats:c.sessionStats,fleetStats:c.fleetStats,ui:{inspectorTab:"stats",statsViewMode:c.statsViewMode}}),[c.activeSession,c.activeSessionId,c.fleetStats,c.sessionStats,c.statsViewMode]),p=l.useMemo(()=>it(u,{width:a}),[a,u]);return is(o,p,r,s,n,i)});l.memo(function({controller:e,width:s,height:n,frame:i}){const r=Z(e,o=>({inspectorTab:o.ui.inspectorTab,inspectorScroll:o.ui.scroll.inspector,inspectorFollowBottom:o.ui.followBottom?.inspector!==!1,focused:o.ui.focusRegion==="inspector"}),_e);return r.inspectorTab==="files"?l.createElement(hh,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="sequence"?l.createElement(mh,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="logs"?l.createElement(gh,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="history"?l.createElement(yh,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="stats"?l.createElement(bh,{controller:e,width:s,height:n,frame:i,meta:r}):l.createElement(Sh,{controller:e,width:s,height:n,frame:i,meta:r})});l.memo(function({controller:e,width:s,height:n,maxLines:i,frame:r}){const o=Ge(),a=Z(e,d=>{const f=d.sessions.activeSessionId;return{sessionsById:d.sessions.byId,activeSessionId:f,activeSession:f&&d.sessions.byId[f]||null,activeHistory:f&&d.history.bySessionId.get(f)||null,scroll:d.ui.scroll.activity,followBottom:d.ui.followBottom?.activity!==!1,focused:d.ui.focusRegion==="activity",inspectorTab:d.ui.inspectorTab,nodeMapSelectedNode:d.ui.nodeMapSelectedNode,adminWorkers:d.admin?.workers,branding:d.branding,historyBySessionId:d.history.bySessionId,sessionsFlat:d.sessions.flat}},_e),c=a.inspectorTab==="nodes",u=l.useMemo(()=>{const d=new Map;return a.activeSessionId&&a.activeHistory&&d.set(a.activeSessionId,a.activeHistory),{branding:a.branding,admin:{workers:a.adminWorkers},ui:{nodeMapSelectedNode:a.nodeMapSelectedNode},sessions:{activeSessionId:a.activeSessionId,byId:a.sessionsById,flat:a.sessionsFlat},history:{bySessionId:c?a.historyBySessionId:d}}},[a.activeHistory,a.activeSessionId,a.sessionsById,a.adminWorkers,a.branding,a.historyBySessionId,a.nodeMapSelectedNode,a.sessionsFlat,c]),p=l.useMemo(()=>c?Pa(u):mi(u,i),[i,c,u]);return l.createElement(o.Panel,{title:p.title,color:"gray",focused:a.focused,width:s,height:n,lines:p.lines,scrollOffset:a.scroll,scrollMode:a.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:r})});l.memo(function({controller:e,rows:s}){const n=Ge(),i=Z(e,r=>{const o=r.sessions.activeSessionId,a=o&&r.sessions.byId[o]||null,c=o&&r.outbox?.bySessionId?.[o]?r.outbox.bySessionId[o]:[];return{prompt:r.ui.prompt,promptCursor:r.ui.promptCursor,focused:r.ui.focusRegion==="prompt",answeringQuestion:!!a?.pendingQuestion?.question,editingPending:r.ui.promptEdit?.sessionId===o,hasOutbox:c.length>0,hasPendingOutbox:c.some(u=>u?.phase==="pending")}},_e);return l.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})});l.memo(function({controller:e}){const s=Ge(),n=Z(e,p=>({connected:p.connection.connected,workersOnline:p.connection.workersOnline,focusRegion:p.ui.focusRegion,inspectorTab:p.ui.inspectorTab,chatViewMode:p.ui.chatViewMode||"transcript",fullscreenPane:p.ui.fullscreenPane||null,logsAvailable:p.logs.available,logsTailing:p.logs.tailing,filesFullscreen:!!p.files.fullscreen,mode:p.connection.mode,statusText:p.ui.statusText,modal:p.ui.modal,activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,selectedIds:p.sessions.selectedIds,selectMode:p.sessions.selectMode}),_e),i=l.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]),r=l.useMemo(()=>Wd(i),[i]),o=typeof s.getViewport=="function"?s.getViewport():{width:120},a=Math.max(20,(o.width||120)-4),c=Math.min(Math.max(18,Math.floor(a*.45)),a-8),u=Math.max(8,a-c-3);return l.createElement(s.StatusLine,{left:Qr(r.left,u),right:Qr(r.right,c)})});const wh="modulepreload",Ih=function(t){return"/"+t},Jr={},Za=function(e,s,n){let i=Promise.resolve();if(s&&s.length>0){let c=function(u){return Promise.all(u.map(p=>Promise.resolve(p).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");i=c(s.map(u=>{if(u=Ih(u),u in Jr)return;Jr[u]=!0;const p=u.endsWith(".css"),d=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":wh,p||(f.as="script"),f.crossOrigin="",f.href=u,a&&f.setAttribute("nonce",a),document.head.appendChild(f),p)return new Promise((m,g)=>{f.addEventListener("load",m),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})};var el=Ll();const xh=920,tl=7,sl=19,Ei=.24,nl=16,il=8,Eh=224,vh=190,kh=48,Qe=16,rl=.5,Wt=rl,Ah=24,Ch=700,Th=5e3,Nh=new Set(["low","medium","high","xhigh"]),Mh=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],Ph=["pilotswarm_theme","pilotswarm_session_owner_filter"],_h={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"History",files:"Files",stats:"Stats"},$h={sequence:"⇶",logs:"≣",nodes:"⬡",history:"⟲",files:"⧉",stats:"▁▄▇"};function Rh(t,e,s){const n=Array.isArray(t)?t.filter(Boolean):[];if(n.length===0)return e;const i=n.indexOf(e),o=((i===-1?0:i)+s+n.length)%n.length;return n[o]}function Oh(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function Lh(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function Fh(t){return typeof t?.transport?.listArtifacts=="function"}function Bh(t){return typeof t?.transport?.deleteArtifact=="function"}function Dh(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const Hh="Session link copied to clipboard",Gh=140,jh="Only people with access can open this link.";function Uh(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function Zr(t){navigator?.clipboard?.writeText&&navigator.clipboard.writeText(t).catch(()=>{})}async function Wh(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 Kh(){if(!(typeof window>"u")){try{for(const t of Mh)window.localStorage.removeItem(t)}catch{}try{for(const t of Ph)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function pt(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()),ke(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=ke(n,"includeShared")?n:{...n,includeShared:!0}}if(ke(e,"layoutAdjustments")&&(s.layoutAdjustments=ti(e.layoutAdjustments)),ke(e,"pinnedSessionIds")&&(s.pinnedSessionIds=Cs(e.pinnedSessionIds)),ke(e,"sessionOrder")&&(s.sessionOrder=si(e.sessionOrder)),ke(e,"collapsedSessionIds")&&(s.collapsedSessionIds=Vh(e.collapsedSessionIds)),ke(e,"activeSessionId")){const n=e.activeSessionId==null?null:String(e.activeSessionId).trim();s.activeSessionId=n||null}return Zt(e.chatViewMode)&&(s.chatViewMode=e.chatViewMode),Zt(e.chatViewModeMobile)&&(s.chatViewModeMobile=e.chatViewModeMobile),s}function Zt(t){return t==="summary"||t==="transcript"||t==="rich"}function ol(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches}function Os(){return ol()?"chatViewModeMobile":"chatViewMode"}function Ls(){return ol()?"chatViewMode":"chatViewModeMobile"}function Vh(t){if(t instanceof Set){const n=[];for(const i of t){const r=String(i||"").trim();r&&n.push(r)}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 ke(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function xn(t,e=null){return pt({themeId:t.themeId,sessionOwnerFilter:t.ownerFilter,layoutAdjustments:{paneAdjust:t.paneAdjust,sessionPaneAdjust:t.sessionPaneAdjust,portalSessionColumnAdjust:t.portalSessionColumnAdjust,activityPaneAdjust:t.activityPaneAdjust},pinnedSessionIds:t.pinnedIds,sessionOrder:t.manualOrder,collapsedSessionIds:t.collapsedSessionIds,activeSessionId:t.activeSessionId,[Os()]:t.chatViewMode,...Zt(e)?{[Ls()]:e}:{}})}function eo(t,e=null){return pt({themeId:t?.ui?.themeId,sessionOwnerFilter:Rs(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,sessionOrder:t?.sessions?.manualOrder,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,[Os()]:t?.ui?.chatViewMode,...Zt(e)?{[Ls()]:e}:{}})}function qh(t,e){const s=pt(t),n=pt(e);return pt({themeId:ke(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:ke(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:ke(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:ke(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,sessionOrder:ke(s,"sessionOrder")?s.sessionOrder:n.sessionOrder,...ke(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...ke(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...ke(s,Os())?{chatViewMode:s[Os()]}:{}})}async function zh(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:pt(e)})}function vi(t){return Fh(t)?We:We.filter(e=>e!=="files")}function He(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Object.is(t[i],e[i]))return!1;return!0}function Un(t,e,s){return Math.max(e,Math.min(s,t))}function Wn(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-nl-il*2),n=s*Ei,i=Math.max(0,s-Eh);return{minAdjust:-n,maxAdjust:i-n}}function Yh(t,e){const s=Wn(t),n=Math.max(0,Number(t)||0),r=Math.max(0,n-nl-il*2)*Ei;return Un(r+(Number(e)||0),0,r+s.maxAdjust)}function Xh(t){return t<=kh?"hidden":t<=vh?"compact":"wrap"}function al(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:Nt(t?.ui?.prompt||"")}function Ks(t){return Xt({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,al(t),t.ui.layout?.sessionPaneAdjust??0)}function Qh(t,e){return Math.max(20,t-4)}function ve(t){const e=[],s=n=>{const i=String(n||"");return!i.includes("\\n")||i.includes(`
85
- `)?i:i.replace(/\\n/g,`
86
- `)};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 r of i)for(const o of No(r.text||""))e.push({kind:"runs",runs:o,preserve:!0,splashVariant:r.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 r=i[0]||{},o=s(r.text||"");if(o.includes(`
87
- `)){const a=o.split(`
88
- `);for(const c of a)e.push({kind:"runs",runs:[{...r,text:c}]});continue}e.push({kind:"runs",runs:[{...r,text:o}]});continue}e.push({kind:"runs",runs:i.map(r=>({...r,text:s(r?.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(`
89
- `)){const r=i.split(`
90
- `);for(const o of r)e.push({kind:"text",...n,text:o});continue}e.push({kind:"text",...n,text:i});continue}e.push({kind:"text",...n})}return e}function ge(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function ll(t=[]){return t.map(e=>String(e?.text||"")).join("")}function to(t){return Array.isArray(t)?ll(t):String(t||"")}function so(t,e=40){if(!Array.isArray(t)){const r=String(t||"");return[{text:r.length>e?`${r.slice(0,e-1)}…`:r,color:"white",bold:!0}]}const s=[],n=r=>/^[\s·—-]+$/.test(String(r?.text||""));let i=Math.max(8,e);for(const r of t){if(i<=0)break;if(r?.color==="gray"&&s.length>0&&!n(r))continue;const a=String(r?.text||"");if(!a)continue;if(n(r)&&i<a.length+2)break;const c=a.length>i&&i>1?`${a.slice(0,i-1)}…`:a.slice(0,i);c&&(s.push({...r,text:c}),i-=c.length)}for(;s.length>0&&n(s[s.length-1]);)s.pop();return s.length>0?s:t}function Jh(t){const e=Be(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),s.style.setProperty("--ps-accent",e.tui.cyan),s.style.setProperty("--ps-success",e.tui.green),s.style.setProperty("--ps-warning",e.tui.yellow),s.style.setProperty("--ps-danger",e.tui.red),s.dataset.psTheme=e.id}function no(t){const[e,s]=l.useState({width:0,height:0});return l.useLayoutEffect(()=>{const n=t.current;if(!n)return;const i=()=>{s({width:n.clientWidth,height:n.clientHeight})};i();const r=new ResizeObserver(i);return r.observe(n),window.addEventListener("resize",i),()=>{r.disconnect(),window.removeEventListener("resize",i)}},[t]),e}function Zh(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/tl)),height:Math.max(18,Math.floor(s/sl))}}function em(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function tm(t){return em(t)<=rl}function sm(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 r=Math.max(0,Number(e)||0)*Qe;return s==="bottom"?Math.max(0,i-r):Math.min(i,r)}function nm(t,e,s,n,i,r,{stickyBottom:o=!1}={}){const a=l.useMemo(()=>ve(e),[e]),c=l.useRef(null),u=l.useRef({scrollMode:n,scrollOffset:s}),p=l.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),d=l.useRef({width:null,height:null}),[f,m]=l.useState(0);l.useLayoutEffect(()=>{const b=t.current;if(!b||typeof ResizeObserver>"u")return;d.current={width:b.clientWidth,height:b.clientHeight};const I=new ResizeObserver(()=>{const k={width:b.clientWidth,height:b.clientHeight},P=d.current;k.width===P.width&&k.height===P.height||(d.current=k,m(M=>M+1))});return I.observe(b),()=>I.disconnect()},[t]),l.useLayoutEffect(()=>{const b=t.current;if(!b)return;const I=u.current,k=p.current,P=typeof performance<"u"?performance.now():Date.now(),M=k.touching||P-(k.lastUserScrollAt||0)<Ch,B=k.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-k.lastDispatchedOffset)<2;if(M&&n===I?.scrollMode&&(s===I?.scrollOffset||B)){u.current={scrollMode:n,scrollOffset:s};return}const O=o&&n==="top"&&I?.scrollMode==="top"&&I?.scrollOffset===s,_=sm(b,s,n,O);if(Math.abs(b.scrollTop-_)>Wt){const L={target:_};c.current=L,b.scrollTop=_,window.requestAnimationFrame(()=>{c.current===L&&(c.current=null)})}u.current={scrollMode:n,scrollOffset:s}},[a,t,n,s,o,f]);const g=rm(b=>{r.dispatch({type:"ui/scroll",pane:i,offset:b})}),h=l.useCallback(()=>{const b=t.current;if(!b||!i)return;const I=c.current;if(I){if(Math.abs(b.scrollTop-I.target)<=Wt)return;c.current=null}p.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const k=Math.max(0,b.scrollHeight-b.clientHeight);if(k<=0)return;if(o&&typeof r.updatePaneScrollFromViewport=="function"){const M=Math.max(0,b.scrollTop)/Qe;p.current.lastDispatchedOffset=M,r.updatePaneScrollFromViewport(i,M,{atBottom:tm(b)});return}const P=n==="bottom"?Math.max(0,k-b.scrollTop):Math.max(0,b.scrollTop);p.current.lastDispatchedOffset=P/Qe,g(P/Qe),i==="chat"&&n==="bottom"&&b.scrollTop<=Wt&&r.armChatTopHistoryLoad?.()},[r,g,i,t,n,o]),y=l.useCallback(b=>{const I=t.current;if(!I||i!=="chat"||n!=="bottom"||b.deltaY>=0||I.scrollTop>Wt)return;const k=Math.max(0,I.scrollHeight-I.clientHeight);r.handleChatTopHistoryScrollIntent?.(k/Qe)},[r,i,t,n]),S=l.useRef({startY:null,fired:!1}),E=l.useCallback(b=>{p.current.touching=!0,!(i!=="chat"||n!=="bottom")&&(S.current={startY:b.touches?.[0]?.clientY??null,fired:!1})},[i,n]),x=l.useCallback(()=>{p.current.touching=!1,p.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),w=l.useCallback(b=>{const I=t.current,k=S.current;if(!I||i!=="chat"||n!=="bottom"||k.fired||k.startY==null||I.scrollTop>Wt)return;const P=b.touches?.[0]?.clientY;if(P==null||P-k.startY<Ah)return;k.fired=!0;const M=Math.max(0,I.scrollHeight-I.clientHeight);r.handleChatTopHistoryScrollIntent?.(M/Qe+1,{force:!0})},[r,i,t,n]);return{normalizedLines:a,onScroll:h,onWheel:y,onTouchStart:E,onTouchMove:w,onTouchEnd:x}}function Ae({runs:t,theme:e}){return l.createElement(l.Fragment,null,(t||[]).map((s,n)=>{const i={color:ge(e,s.color),backgroundColor:ge(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"};if(s?.trailingRule)return l.createElement("span",{key:`${n}:rule`,className:"ps-line-trailing-rule",style:i},s.text||"");const r=String(s?.href||"").trim(),o=/^https?:\/\//i.test(r),a=fl(r);return a?l.createElement(ml,{key:`${n}:${s.text||""}`,label:s.text||"",artifactRef:a,style:i}):o?l.createElement("a",{key:`${n}:${s.text||""}`,className:"ps-md-link",href:r,target:"_blank",rel:"noreferrer",style:i},s.text||""):l.createElement("span",{key:`${n}:${s.text||""}`,style:i},s.text||"")}))}function im({line:t,theme:e}){const s=String(t?.body||"").trim();return l.createElement("details",{className:"ps-system-notice"},l.createElement("summary",{className:"ps-system-notice-summary",style:{color:ge(e,t?.color)||"var(--ps-muted)"}},l.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),s?l.createElement("div",{className:"ps-system-notice-body"},l.createElement(Vs,{content:s,theme:e})):null)}function rm(t){const e=l.useRef(0),s=l.useRef(null),n=l.useRef(t);return n.current=t,l.useEffect(()=>()=>{e.current&&cancelAnimationFrame(e.current)},[]),l.useCallback((...i)=>{s.current=i,!e.current&&(e.current=requestAnimationFrame(()=>{e.current=0;const r=s.current;s.current=null,r&&n.current(...r)}))},[])}const Te=l.memo(function({line:e,theme:s,className:n=""}){const i=n?`ps-line ${n}`:"ps-line";return e?e.kind==="systemNotice"?l.createElement(im,{line:e,theme:s}):e.kind==="runs"?l.createElement("div",{className:i},l.createElement(Ae,{runs:e.runs,theme:s})):l.createElement("div",{className:i,style:{color:ge(s,e.color),backgroundColor:ge(s,e.backgroundColor),fontWeight:e.bold?700:400,textDecoration:e.underline?"underline":"none"}},e.text||" "):l.createElement("div",{className:i}," ")});function Oe(t){return t?t.kind==="runs"?ll(t.runs):String(t.text||""):""}function cl(t,e,s,n){const i=l.useRef(!1);return l.useLayoutEffect(()=>{const r=t.current;if(!r||!s)return;const o=Math.max(0,r.scrollHeight-r.clientHeight),a=Math.min(o,Math.max(0,Number(e)||0)*Qe);Math.abs(r.scrollTop-a)>2&&(i.current=!0,r.scrollTop=a,window.requestAnimationFrame(()=>{i.current=!1}))},[t,e,s]),l.useCallback(r=>{if(i.current)return;const o=t.current;!o||!s||r&&r.target!==o||o.scrollHeight<=o.clientHeight||n.dispatch({type:"ui/scroll",pane:s,offset:Math.max(0,o.scrollTop)/Qe})},[n,s,t])}const om={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"},am=new Set(["diff","patch","udiff"]),lm=/\.(patch|diff)$/i,ul=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,dl=/\.(png|jpe?g|gif|webp|avif|bmp|svg|ico)$/i,cm={js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",json:"json",jsonl:"json",py:"python",rs:"rust",go:"go",java:"java",rb:"ruby",sh:"bash",bash:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",toml:"toml",sql:"sql",css:"css",html:"html",xml:"xml"};function um(t){const e=String(t||"");if(!/^---[ \t]*\r?\n/.test(e))return e;const s=/\r?\n---[ \t]*(\r?\n|$)/.exec(e.slice(3));return s?e.slice(3+s.index+s[0].length):e}const dm=/\.(csv|tsv)$/i;function pm(t,e){return dm.test(String(t||""))?!0:/^text\/(csv|tab-separated-values)$/i.test(String(e||"").trim())}const En=2e3;function fm(t){const e=String(t??"");return/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function hm({content:t,filename:e}){const[s,n]=l.useState(null),i=l.useRef(null),r=l.useRef(null),o=l.useRef(null);l.useEffect(()=>{let w=!1;return n(null),Za(()=>import("./papaparse.min-BRXtjEI6.js").then(b=>b.p),[]).then(b=>{if(w)return;const I=b.default||b,k=/\.tsv$/i.test(String(e||""))?" ":"",P=I.parse(String(t||"").trim(),{delimiter:k,skipEmptyLines:"greedy"});n({rows:P.data||[],errors:P.errors||[]})}).catch(()=>{w||n({rows:null,errors:[{message:"parser unavailable"}]})}),()=>{w=!0}},[t,e]),l.useEffect(()=>{const w=()=>{o.current=null};return window.addEventListener("mouseup",w),()=>window.removeEventListener("mouseup",w)},[]);const a=l.useCallback((w,b)=>{if(!w||!b)return;const I=window.getSelection();if(!I)return;const k=!!(w.compareDocumentPosition(b)&Node.DOCUMENT_POSITION_PRECEDING),P=document.createRange();P.setStartBefore(k?b:w),P.setEndAfter(k?w:b),I.removeAllRanges(),I.addRange(P)},[]),c=w=>w.target?.closest?w.target.closest("td,th"):null,u=l.useCallback(w=>{if(w.button!==0)return;const b=c(w);b&&(w.preventDefault(),i.current?.focus(),o.current=b,a(b,b))},[a]),p=l.useCallback(w=>{if(!o.current||!(w.buttons&1))return;const b=c(w);b&&a(o.current,b)},[a]),d=l.useCallback(w=>{if(!(w.metaKey||w.ctrlKey)||w.altKey||w.key!=="a"&&w.key!=="A")return;const b=r.current,I=window.getSelection();if(!b||!I)return;w.preventDefault(),w.stopPropagation();const k=document.createRange();k.selectNodeContents(b),I.removeAllRanges(),I.addRange(k)},[]),f=l.useCallback(w=>{const b=r.current,I=window.getSelection();if(!b||!I||I.rangeCount===0)return;const k=I.getRangeAt(0),P=new Map;for(const M of b.querySelectorAll("th,td")){if(!k.intersectsNode(M))continue;const B=M.parentElement;P.has(B)||P.set(B,[]),P.get(B).push(fm(M.textContent))}P.size!==0&&(w.clipboardData.setData("text/plain",Array.from(P.values(),M=>M.join(" ")).join(`
91
- `)),w.preventDefault())},[]);if(!s)return l.createElement("div",{className:"ps-csv-status"},"Parsing…");if(!s.rows||s.rows.length===0)return l.createElement("pre",{className:"ps-md-code-pre"},l.createElement("code",null,String(t||"")));const[m,...g]=s.rows,h=g.reduce((w,b)=>Math.max(w,b.length),m.length),y=Array.from({length:h},(w,b)=>m[b]??""),S=g.length>En,E=S?g.slice(0,En):g,x=[];return S&&x.push(`showing first ${En} of ${g.length} rows`),s.errors.length&&x.push(`${s.errors.length} parse warning${s.errors.length===1?"":"s"}`),l.createElement("div",{className:"ps-csv-wrap",ref:i,tabIndex:0,onMouseDown:u,onMouseMove:p,onKeyDown:d,onCopy:f},l.createElement("table",{className:"ps-csv-table",ref:r},l.createElement("thead",null,l.createElement("tr",null,y.map((w,b)=>l.createElement("th",{key:`h${b}`},String(w??""))))),l.createElement("tbody",null,E.map((w,b)=>l.createElement("tr",{key:`r${b}`},y.map((I,k)=>l.createElement("td",{key:`c${k}`},String(w[k]??""))))))),x.length?l.createElement("div",{className:"ps-csv-status"},x.join(" · ")):null)}function pl(t){const e=/\.([A-Za-z0-9]+)$/.exec(String(t||""));return e&&cm[e[1].toLowerCase()]||null}function ki(t,e){return lm.test(String(t||""))?!0:/^text\/x-(patch|diff)$/i.test(String(e||"").trim())}function fl(t){const e=/^artifact:\/\/([^/]+)\/(.+)$/i.exec(String(t||"").trim());if(!e)return null;try{return{sessionId:e[1],filename:decodeURIComponent(e[2])}}catch{return{sessionId:e[1],filename:e[2]}}}const hl=l.createContext(null);function ml({label:t,artifactRef:e,style:s}){const n=l.useContext(hl),i=ki(e.filename),r=l.useCallback(o=>{if(o.preventDefault(),o.stopPropagation(),!n?.revealArtifact)return;const a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;Promise.resolve(n.revealArtifact(e.sessionId,e.filename,{fullscreen:a})).catch(()=>{})},[n,e.sessionId,e.filename]);return l.createElement("button",{type:"button",className:`ps-artifact-link${i?" is-diff":""}`,onClick:r,title:i?`Open ${e.filename} as a diff`:`Open ${e.filename} in Files`,style:s},i?l.createElement("span",{className:"ps-artifact-link-glyph","aria-hidden":"true"},"±"):null,l.createElement("span",{className:"ps-artifact-link-label"},t||e.filename))}function gl(t){return am.has(String(t||"").trim().toLowerCase())}const mm=/^(?:diff --git |index |--- |\+\+\+ |new file mode|deleted file mode|old mode|new mode|similarity index|dissimilarity index|rename (?:from|to) |copy (?:from|to) |Binary files |GIT binary patch|\\)/;function gm(t){return mm.test(t)?"meta":t.startsWith("@@")?"hunk":t.startsWith("+")?"add":t.startsWith("-")?"del":"context"}const ym={add:"green",del:"red",hunk:"cyan",meta:"gray"};function Ai(t,e){return String(t||"").replace(/\n$/,"").split(`
92
- `).map((n,i)=>{const r=gm(n),o=ym[r],a=r==="add"||r==="del"||r==="context"&&n.startsWith(" "),c=a?n.slice(0,1):"",u=a?n.slice(1):n;return l.createElement("span",{key:`d:${i}`,className:`ps-diff-line is-${r}`,style:o?{color:ge(e,o)||void 0}:void 0},l.createElement("span",{className:"ps-diff-marker","aria-hidden":"true"},c.trim()),l.createElement("span",{className:"ps-diff-text"},u))})}function yl(t){return String(t||"").trim().toLowerCase()==="mermaid"}const io={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 Sm(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},r={type:"identifier",re:/[A-Za-z_$][\w$]*/y},o={type:"string",re:/"(?:\\.|[^"\\])*"?/y},a={type:"string",re:/'(?:\\.|[^'\\])*'?/y},c={type:"string",re:/`(?:\\.|[^`\\])*`?/y},u={type:"string",re:/"""[\s\S]*?"""|'''[\s\S]*?'''/y};switch(t){case"python":return[e,u,o,a,i,r];case"shell":return[e,o,a,i,r];case"sql":return[n,a,o,i,r];case"yaml":return[e,o,a,i,r];case"json":return[o,i,r];case"css":return[{type:"comment",re:/\/\*[\s\S]*?\*\//y},o,a,i,r];default:return[s,o,a,c,i,r]}}const bm={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},wm=2e4,at=new Map,Im=120;function xm(t,e){const s=`${e||""}\0${t}`,n=at.get(s);if(n)return at.delete(s),at.set(s,n),n;const i=Em(t,e);return at.set(s,i),at.size>Im&&at.delete(at.keys().next().value),i}function Em(t,e){const s=om[String(e||"").trim().toLowerCase()]||"default",n=io[s]||io.js,i=Sm(s),r=[];let o=0,a=0;const c=u=>{u>a&&r.push({type:"plain",text:t.slice(a,u)})};for(;o<t.length;){let u=null;for(const d of i){d.re.lastIndex=o;const f=d.re.exec(t);if(f&&f.index===o&&f[0].length>0){u={type:d.type,text:f[0]};break}}if(!u){o+=1;continue}let p=u.type;if(p==="identifier")if(n.has(u.text))p="keyword";else{const d=t.slice(o+u.text.length);p=/^\s*\(/.test(d)?"fn":"plain"}if(p==="plain"){o+=u.text.length;continue}c(o),r.push({type:p,text:u.text}),o+=u.text.length,a=o}return c(t.length),r}function es(t,e,s){const n=String(t||"");if(!n||n.length>wm)return n;let i;try{i=xm(n,e)}catch{return n}return i.map((r,o)=>{const a=bm[r.type];return a?l.createElement("span",{key:`t:${o}`,className:`ps-code-token is-${r.type}`,style:{color:ge(s,a)||void 0}},r.text):l.createElement(l.Fragment,{key:`t:${o}`},r.text)})}let fs=null;function vm(){return fs||(fs=Za(()=>import("./mermaid.core-o7PszRUc.js").then(t=>t.bp),[]).then(t=>t.default||t).catch(t=>{throw fs=null,t})),fs}function km(t,e){return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"default":"dark",fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"}),t}let ro=0,oo=Promise.resolve();function Am(t){const e=oo.then(t,t);return oo=e.then(()=>{},()=>{}),e}function Sl({code:t,theme:e,fallback:s}){const[n,i]=l.useState(null),[r,o]=l.useState(!1),[a,c]=l.useState(""),u=l.useMemo(()=>eu(e),[e]);return l.useEffect(()=>{let p=!0;const d=String(t||"").trim();if(d)return o(!1),vm().then(f=>Am(async()=>{if(!p)return;km(f,u),ro+=1;const m=`ps-mermaid-${ro}`;await f.parse(d);const{svg:g}=await f.render(m,d);p&&i(g)})).catch(f=>{p&&(i(null),o(!0),c(String(f?.message||f)))}),()=>{p=!1}},[t,u]),n&&!r?l.createElement("div",{className:"ps-mermaid",dangerouslySetInnerHTML:{__html:n}}):r&&a?l.createElement("div",{className:"ps-mermaid-failed"},l.createElement("div",{className:"ps-mermaid-error"},`Diagram could not be rendered — ${String(a).split(`
93
- `)[0]}`),s):s}function ze(t,e,s="md"){return Qn(t).map((n,i)=>{const r=`${s}:${i}`;if(n.type==="code")return l.createElement("code",{key:r,className:"ps-md-inline-code"},n.text);if(n.type==="strong")return l.createElement("strong",{key:r,className:"ps-md-strong"},ze(n.text,e,`${r}:strong`));if(n.type==="em")return l.createElement("em",{key:r,className:"ps-md-em"},ze(n.text,e,`${r}:em`));if(n.type==="link"){const o=fl(n.href);return o?l.createElement(ml,{key:r,label:n.text,artifactRef:o,style:{color:ge(e,"cyan")}}):/^https?:\/\//i.test(String(n.href||"").trim())?l.createElement("a",{key:r,className:"ps-md-link",href:n.href,target:"_blank",rel:"noreferrer",style:{color:ge(e,"cyan")}},n.text):l.createElement("span",{key:r,style:{color:ge(e,"cyan")}},n.text)}return l.createElement(l.Fragment,{key:r},n.text)})}function Kn(t=""){return String(t||"").replace(/\s+/g," ").trim()}const Cm=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],Tm=24,Nm=32,Mm=6,ao=30,Pm=56,vn=.4,_m=1.4,$m=2;function bl(t=[]){const e=Math.max(0,...t.map(g=>g.length));if(e<=0)return null;const s=t[0]||[],n=Math.max(1,t.length-1),i=Array.from({length:e},()=>({max:0,spaceCells:0}));for(let g=0;g<t.length;g+=1){const h=t[g];for(let y=0;y<e;y+=1){const S=Kn(h[y]||"");S.length>i[y].max&&(i[y].max=S.length),g>0&&/\s/.test(S)&&(i[y].spaceCells+=1)}}let r=-1,o=0;for(let g=0;g<e;g+=1){const h=i[g];if(h.max<Tm||h.spaceCells/n<.4)continue;const S=Kn(s[g]||"").toLowerCase(),E=Cm.some(w=>S.includes(w))?60:0,x=h.max+E;x>o&&(o=x,r=g)}if(r<0)return null;const a=i.map((g,h)=>h===r?0:Math.max(Mm,Math.min(g.max+2,Nm))),c=a.reduce((g,h)=>g+h,0),u=i[r],p=Math.max(ao,Math.min(u.max*.45,Pm,Math.max(ao,c*_m))),d=a.map((g,h)=>h===r?p:g),f=d.reduce((g,h)=>g+h,0);if(f>0&&d[r]/f<vn){const g=f-d[r];d[r]=g*(vn/(1-vn))}const m=d.reduce((g,h)=>g+h,0);return m>0?{widths:d.map(g=>`${(g/m*100).toFixed(2)}%`),flexIndex:r,minWidth:`${Math.ceil(m+$m)}ch`}:null}function wl(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(r=>Kn(r?.[n]||"")).filter(Boolean).join(" / ")||null)}function lo(t="",e=""){const s=String(t||"");return/^\s*#{1,6}\s+/.test(s)||/^\s*>/.test(s)||/^\s*([-*]|\d+\.)\s+/.test(s)||/^\s*```/.test(s)||s.includes("|")&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(String(e||""))}function co(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Rm(t=""){const s=String(t||"").replace(/\r\n?/g,`
94
- `).split(`
95
- `),n=[];for(let i=0;i<s.length;){const r=s[i],o=r.trim();if(!o){i+=1;continue}const a=/^```(\S*)\s*$/.exec(o);if(a){const d=a[1]||"",f=[];for(i+=1;i<s.length&&!/^```/.test(s[i].trim());)f.push(s[i]),i+=1;i<s.length&&(i+=1),n.push({type:"code",language:d,content:f.join(`
96
- `)});continue}const c=/^(#{1,6})\s+(.*)$/.exec(r);if(c){n.push({type:"heading",level:c[1].length,text:c[2].trim()}),i+=1;continue}if(r.includes("|")&&i+1<s.length&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(s[i+1].trim())){const d=co(r);i+=2;const f=[];for(;i<s.length&&s[i].includes("|")&&s[i].trim();)f.push(co(s[i])),i+=1;n.push({type:"table",header:d,rows:f});continue}if(/^\s*>/.test(r)){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(`
97
- `).trim()});continue}const u=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(r);if(u){const d=/\d+\./.test(u[2]),f=[];for(;i<s.length;){const m=s[i],g=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(m);if(!g||/\d+\./.test(g[2])!==d)break;const h=[g[3].trim()];for(i+=1;i<s.length&&s[i].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[i])&&!lo(s[i],s[i+1]||"");)h.push(s[i].trim()),i+=1;if(f.push(h.join(" ")),!s[i]?.trim())break}n.push({type:"list",ordered:d,items:f});continue}const p=[r.trim()];for(i+=1;i<s.length&&s[i].trim()&&!lo(s[i],s[i+1]||"");)p.push(s[i].trim()),i+=1;n.push({type:"paragraph",text:p.join(" ")})}return n}function Vs({content:t,theme:e}){const s=l.useMemo(()=>Rm(t),[t]);return s.length===0?l.createElement("div",{className:"ps-empty-state"},"No preview content."):l.createElement("div",{className:"ps-markdown-preview"},s.map((n,i)=>{if(n.type==="heading")return l.createElement("div",{key:`block:${i}`,className:`ps-md-heading is-h${n.level}`},ze(n.text,e,`heading:${i}`));if(n.type==="code"){const r=gl(n.language),o=l.createElement("section",{key:`block:${i}`,className:`ps-md-code-block${r?" is-diff":""}`},l.createElement("div",{className:"ps-md-code-header"},n.language||"text"),l.createElement("pre",{className:"ps-md-code-pre"},l.createElement("code",null,r?Ai(n.content,e):es(n.content,n.language,e))));return yl(n.language)?l.createElement(Sl,{key:`block:${i}`,code:n.content,theme:e,fallback:o}):o}if(n.type==="blockquote")return l.createElement("blockquote",{key:`block:${i}`,className:"ps-md-quote"},ze(n.text,e,`quote:${i}`));if(n.type==="list"){const r=n.ordered?"ol":"ul";return l.createElement(r,{key:`block:${i}`,className:`ps-md-list${n.ordered?" is-ordered":""}`},n.items.map((o,a)=>l.createElement("li",{key:`item:${a}`,className:"ps-md-list-item"},ze(o,e,`list:${i}:${a}`))))}if(n.type==="table"){const r=Math.max(n.header.length||0,...n.rows.map(g=>g.length)),o=r>0&&r<=6,a=o?bl([n.header,...n.rows]):null,c=!!a,u=a?a.flexIndex:-1,p=g=>g===u?"is-flex-column":null,d=wl([n.header],r),f=`ps-md-table${o?" is-fit-width":""}${c?" has-flex-column":""}`,m=`ps-md-table-wrap${o?" is-fit-width":""}${c?" has-flex-column":""}`;return l.createElement("div",{key:`block:${i}`,className:m},l.createElement("table",{className:f,style:a?.minWidth?{"--ps-table-min-width":a.minWidth}:void 0},a?l.createElement("colgroup",null,a.widths.map((g,h)=>l.createElement("col",{key:`col:${h}`,className:p(h)||void 0,style:{width:g}}))):null,l.createElement("thead",null,l.createElement("tr",null,n.header.map((g,h)=>l.createElement("th",{key:`head:${h}`,className:p(h)||void 0},ze(g,e,`table:${i}:head:${h}`))))),l.createElement("tbody",null,n.rows.map((g,h)=>l.createElement("tr",{key:`row:${h}`},g.map((y,S)=>l.createElement("td",{key:`cell:${h}:${S}`,className:p(S)||void 0,"data-label":d[S]||void 0},l.createElement("span",{className:"ps-table-cell-value"},ze(y,e,`table:${i}:${h}:${S}`)))))))))}return l.createElement("p",{key:`block:${i}`,className:"ps-md-paragraph"},ze(n.text,e,`para:${i}`))}))}function kn({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:r,theme:o,className:a="",focusRegion:c=null,children:u}){const p=l.useRef(null),d=cl(p,i,r,t),f=l.useCallback(()=>{const m=Ci(r,c);m&&t?.setFocus&&t.setFocus(m)},[t,r,c]);return l.createElement(ht,{title:e,color:s,focused:n,theme:o},l.createElement("div",{ref:p,className:`ps-scroll-panel is-preview ${a}`.trim(),onScroll:d,onMouseDown:f},u))}function Om({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:r,theme:o,content:a,focusRegion:c=null}){const u=l.useCallback(()=>{const f=Ci(r,c);f&&t?.setFocus&&t.setFocus(f)},[t,r,c]),p=l.useRef(null),d=cl(p,i,r,t);return l.createElement(ht,{title:e,color:s,focused:n,theme:o},l.createElement("div",{ref:p,className:"ps-scroll-panel ps-markdown-scroll",onScroll:d,onMouseDown:u},l.createElement(Vs,{content:a,theme:o})))}function Lm(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 uo({title:t,color:e,focused:s,theme:n,filename:i,contentType:r,sizeBytes:o,source:a,uploadedAt:c,controller:u=null,sessionId:p=null}){const d=[];r&&d.push(r),o!=null&&d.push(Lm(o)),a&&d.push(a);const f=c?new Date(c).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"",m=ul.test(String(r||""))||dl.test(String(i||"")),[g,h]=l.useState(null);return l.useEffect(()=>{if(h(null),!m||!u||!p||!i)return;let y=!1;return El(u,p,i).then(S=>{y||h(S)}).catch(()=>{y||h("error")}),()=>{y=!0}},[m,u,p,i]),l.createElement(ht,{title:t,color:e,focused:s,theme:n},l.createElement("div",{className:"ps-binary-preview-card"},l.createElement("div",{className:"ps-binary-preview-kicker"},m?"Image artifact":"Binary artifact"),l.createElement("h3",{className:"ps-binary-preview-title"},i||"Artifact"),d.length>0?l.createElement("div",{className:"ps-binary-preview-meta"},d.join(" • ")):null,f?l.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${f}`):null,m&&g&&g!=="error"?l.createElement("img",{className:"ps-binary-preview-image",src:g,alt:i||"artifact image",onClick:()=>{try{window.open(g,"_blank","noopener")}catch{}}}):l.createElement("p",{className:"ps-binary-preview-copy"},m?g==="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 ys(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function An(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function Fm(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function Qt(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function Bm(t){const e=String(Oe(t)||"").trim();return ys(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function Dm(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=Oe(t);return Qt(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function Hm(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 po(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?Hm(t.runs.slice(1,-1)):[{text:Oe(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function Gm(t){const e=String(t||"").trim();return Qt(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function jm(t="",e=""){const s=String(t||"").trimEnd(),n=String(e||"").trimStart();if(!s||!n)return!1;const i=s.slice(-1),r=n[0];return!!(/^[,.;:!?%)\]}>]/u.test(r)||/^[._/\\-]/u.test(r)||/[([{<._/\\-]$/u.test(i)||/\.[A-Za-z0-9]{0,4}$/u.test(s)&&/^[A-Za-z0-9]/u.test(r))}function Um(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)=>jm(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function fo(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>Um(t.map(i=>String(i[n]||"").trim()).filter(Boolean)))}function Il(t=[]){const e=[];for(let s=0;s<t.length;){const n=t[s];if(n?.preserve){const r=n.splashVariant||null,o=[];for(;s<t.length&&t[s]?.preserve&&(t[s].splashVariant||null)===r;)o.push(t[s]),s+=1;e.push({type:"preserve",lines:o,splashVariant:r});continue}if(n?.kind==="cardStart"){const r=[];for(s+=1;s<t.length&&t[s]?.kind!=="cardEnd";)r.push(t[s]),s+=1;s<t.length&&(s+=1),s<t.length&&Oe(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:Il(r)});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=Oe(n);if(ys(i)&&i.includes("┬")){const r=[],o=[];let a=[],c=!0;for(s+=1;s<t.length;){const u=t[s],p=Oe(u);if(An(p)){if(a.length>0){const d=fo(a);d.length>0&&(c?r.push(d):o.push(d))}s+=1;break}if(Fm(p)){if(a.length>0){const d=fo(a);d.length>0&&(c?r.push(d):o.push(d))}a=[],c=!1,s+=1;continue}if(Qt(p)){const d=Gm(p);d.length>0&&a.push(d)}s+=1}e.push({type:"table",headerRows:r,bodyRows:o});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&ys(i)){const r=Bm(n),o=[];for(s+=1;s<t.length;){const a=t[s],c=Oe(a);if(An(c)){s+=1;break}Qt(c)?o.push(Dm(a)):o.push(Oe(a)),s+=1}s<t.length&&Oe(t[s]).trim().length===0&&(s+=1),e.push({type:"code",language:r||"text",content:o.join(`
98
- `)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&ys(i)){const r=po(n),o=n.runs[0]?.color||"gray",a=[];for(s+=1;s<t.length;){const c=t[s],u=Oe(c);if(An(u)){s+=1;break}Qt(u)?a.push(po(c)):a.push(c?.kind==="runs"?c.runs:[{text:Oe(c),color:c?.color||null}]),s+=1}s<t.length&&Oe(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:r,bodyLines:a,borderColor:o});continue}e.push({type:"line",line:n}),s+=1}return e}function xl({lines:t,theme:e,controller:s=null}){const n=l.useMemo(()=>Il(t),[t]);return l.createElement(kl,{blocks:n,theme:e,controller:s})}const Wm=l.memo(function({block:e,theme:s,controller:n,continued:i}){const r=e.header||{},o=e.role==="user"?" is-user":" is-assistant",a=e.pendingPhase?` is-${e.pendingPhase}`:"",c=String(e.text||""),u=e.role==="user"&&r.fromOtherPerson;return l.createElement("article",{className:`ps-rich-msg${o}${a}${i?" is-continued":""}`},l.createElement("header",{className:"ps-rich-msg-head"},u?l.createElement("span",{className:"ps-rich-msg-label",style:{color:ge(s,r.roleColor)||void 0}},r.roleLabel):null,l.createElement("span",{className:"ps-rich-msg-meta"},r.glyph?l.createElement("span",{className:"ps-rich-msg-glyph",title:e.pendingPhase||void 0,style:{color:ge(s,r.glyphColor)||void 0}},r.glyph):null,r.time?l.createElement("span",{className:"ps-rich-msg-time"},r.time):null)),c.trim()?l.createElement("div",{className:"ps-rich-msg-body"},l.createElement(Vs,{content:c,theme:s})):null,e.attachments?l.createElement(vl,{controller:n,sessionId:e.attachments.sessionId,attachments:e.attachments.attachments}):null)}),Km=l.memo(function({block:e,theme:s,controller:n}){const i=l.useMemo(()=>ve(e.lines||[]),[e.lines]);return l.createElement("div",{className:`ps-rich-lineblock is-${e.variant||"event"}`},l.createElement(xl,{lines:i,theme:s,controller:n}))});function Vm({blocks:t,theme:e,controller:s=null}){return l.createElement("div",{className:"ps-rich-chat"},(t||[]).map((n,i)=>{if(n.kind==="message"){const r=t[i-1],o=n.header||{},a=n.role==="user"&&o.fromOtherPerson,c=!!(r&&r.kind==="message"&&r.role===n.role&&!(r.header&&r.header.fromOtherPerson)&&!a);return l.createElement(Wm,{key:n.id!=null?`msg:${n.id}`:`msg:${i}`,block:n,theme:e,controller:s,continued:c})}return l.createElement(Km,{key:`lines:${i}`,block:n,theme:e,controller:s})}))}const Xe=new Map,qm=60;function El(t,e,s){const n=`${e}/${s}`,i=Xe.get(n);if(i)return Xe.delete(n),Xe.set(n,i),i;const r=t?.transport?.api?.downloadArtifactResponse;if(typeof r!="function")return Promise.reject(new Error("artifact download unavailable"));const o=r.call(t.transport.api,e,s).then(async a=>{if(!a?.ok)throw new Error(`download failed (${a?.status})`);const c=await a.blob();return URL.createObjectURL(c)}).catch(a=>{throw Xe.get(n)===o&&Xe.delete(n),a});for(Xe.set(n,o);Xe.size>qm;){const[a,c]=Xe.entries().next().value;Xe.delete(a),Promise.resolve(c).then(u=>URL.revokeObjectURL(u)).catch(()=>{})}return o}function vl({controller:t,sessionId:e,attachments:s}){const[n,i]=l.useState({});return l.useEffect(()=>{if(!t||!e)return;let r=!1;for(const o of s){const a=o?.filename;a&&El(t,e,a).then(c=>{r||i(u=>u[a]===c?u:{...u,[a]:c})}).catch(()=>{r||i(c=>c[a]==="error"?c:{...c,[a]:"error"})})}return()=>{r=!0}},[t,e,s]),l.createElement("div",{className:"ps-chat-image-strip"},s.map((r,o)=>{const a=r?.filename||`image-${o}`,c=n[a];return c&&c!=="error"?l.createElement("img",{key:`thumb:${o}:${a}`,className:"ps-chat-image-thumb",src:c,alt:a,title:`${a} — click to view full size`,onClick:()=>{try{window.open(c,"_blank","noopener")}catch{}}}):l.createElement("div",{key:`thumb:${o}:${a}`,className:`ps-chat-image-thumb is-pending${c==="error"?" is-error":""}`,title:a},c==="error"?"⚠":"🖼")}))}function kl({blocks:t,theme:e,controller:s=null}){return l.createElement(l.Fragment,null,(t||[]).map((n,i)=>{if(n.type==="imageAttachments")return l.createElement(vl,{key:`imageAttachments:${i}`,controller:s,sessionId:n.sessionId,attachments:n.attachments});if(n.type==="preserve"){const r=n.splashVariant?` is-splash-${n.splashVariant}`:"";return l.createElement("div",{key:`preserve:${i}`,className:`ps-chat-preserve-block${r}`},n.lines.map((o,a)=>l.createElement(Te,{key:`preserve:${i}:${a}`,line:o,theme:e,className:"ps-line-preserve"})))}if(n.type==="code"){const r=gl(n.language),o=l.createElement("section",{key:`code:${i}`,className:`ps-md-code-block ps-chat-code-block${r?" is-diff":""}`},l.createElement("div",{className:"ps-md-code-header"},n.language||"text"),l.createElement("pre",{className:"ps-md-code-pre"},l.createElement("code",null,r?Ai(n.content||"",e):es(n.content||"",n.language,e))));return yl(n.language)?l.createElement(Sl,{key:`code:${i}`,code:n.content||"",theme:e,fallback:o}):o}if(n.type==="card")return l.createElement("section",{key:`card:${i}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":ge(e,n.borderColor)||"var(--ps-border)"}},l.createElement("header",{className:"ps-chat-card-header"},l.createElement(Ae,{runs:n.headerRuns,theme:e})),l.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?l.createElement(kl,{blocks:n.blocks,theme:e,controller:s}):(n.bodyLines||[]).map((r,o)=>l.createElement("div",{key:`card:${i}:line:${o}`,className:"ps-chat-card-line"},l.createElement(Ae,{runs:r,theme:e})))));if(n.type==="table"){const r=n.headerRows||[],o=n.bodyRows||[],a=Math.max(1,...r.map(y=>y.length),...o.map(y=>y.length)),c=a<=6,u=c?bl([...r,...o]):null,p=!!u,d=u?u.flexIndex:-1,f=y=>y===d?"is-flex-column":null,m=wl(r,a),g=`ps-chat-table${c?" is-fit-width":""}${p?" has-flex-column":""}`,h=`ps-chat-table-wrap${c?" is-fit-width":""}${p?" has-flex-column":""}`;return l.createElement("div",{key:`table:${i}`,className:h},l.createElement("table",{className:g,style:u?.minWidth?{"--ps-table-min-width":u.minWidth}:void 0},u?l.createElement("colgroup",null,u.widths.map((y,S)=>l.createElement("col",{key:`col:${S}`,className:f(S)||void 0,style:{width:y}}))):null,r.length>0?l.createElement("thead",null,r.map((y,S)=>l.createElement("tr",{key:`thead:${S}`},Array.from({length:a},(E,x)=>l.createElement("th",{key:`th:${S}:${x}`,className:f(x)||void 0},ze(y[x]||"",e,`chat-table:${i}:head:${S}:${x}`)))))):null,l.createElement("tbody",null,o.map((y,S)=>l.createElement("tr",{key:`tbody:${S}`},Array.from({length:a},(E,x)=>l.createElement("td",{key:`td:${S}:${x}`,className:f(x)||void 0,"data-label":m[x]||void 0},l.createElement("span",{className:"ps-table-cell-value"},ze(y[x]||"",e,`chat-table:${i}:${S}:${x}`)))))))))}return l.createElement(Te,{key:`line:${i}`,line:n.line,theme:e})}))}function zm(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 ht({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:i=null,children:r,theme:o,className:a=""}){const c=ge(o,s),u=!!((Array.isArray(t)?t.length>0:String(t??"").trim())||e||i);return l.createElement("section",{className:`ps-panel${n?" is-focused":""}${u?"":" is-chromeless"}${a?` ${a}`:""}`,style:{"--ps-panel-accent":c||"var(--ps-border)"}},u?l.createElement("header",{className:"ps-panel-header"},l.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?l.createElement(Ae,{runs:t,theme:o}):to(t)),e||i?l.createElement("div",{className:"ps-panel-header-right"},e?l.createElement("div",{className:"ps-panel-title-right"},Array.isArray(e)?l.createElement(Ae,{runs:e,theme:o}):to(e)):null,i?l.createElement("div",{className:"ps-panel-actions"},i):null):null):null,l.createElement("div",{className:"ps-panel-body"},r))}function Ym({lines:t,theme:e,controller:s}){return l.createElement("div",{className:"ps-nodemap"},(t||[]).map((n,i)=>{const r=Array.isArray(n?.runs)?n.runs:Array.isArray(n)?n:[n],o=r.find(u=>u?.nodeSelect)?.nodeSelect||null,a=r.some(u=>u?.nodeSelected),c=l.createElement(Ae,{runs:r,theme:e});return o?l.createElement("button",{key:`line:${i}`,type:"button",className:`ps-nodemap__row${a?" is-selected":""}`,onPointerDown:u=>{u.preventDefault(),u.stopPropagation(),s.selectNodeMapNode(o)}},c):l.createElement("div",{key:`line:${i}`,className:"ps-nodemap__line"},c)}))}function Xm({lines:t,theme:e,completionByTurn:s}){const[n,i]=l.useState(()=>new Set),r=l.useCallback(p=>{i(d=>{const f=new Set(d);return f.has(p)?f.delete(p):f.add(p),f})},[]),o=p=>Number(p||0).toLocaleString("en-US"),a=p=>{const d=Number(p||0);if(!Number.isFinite(d))return"?K";const f=d/1e3,m=Math.abs(f)>=10?1:2;return`${f.toFixed(m)}K`},c=p=>{const d=Number(p||0);return Number.isFinite(d)?`${(d/1e3).toFixed(1)}s`:"?s"},u=p=>{const d=String(p||"").trim();if(!d)return"unknown";const f=d.split(":").filter(Boolean),m=f[f.length-1]||"",g=f.length>1&&Nh.has(m.toLowerCase())?f.length-2:f.length-1;return f[Math.max(0,g)]||f[0]||"unknown"};return l.createElement(l.Fragment,null,t.map((p,d)=>{const f=p?.kind==="runs"&&Array.isArray(p.runs)?p.runs.find(k=>k?.completedTurn!=null)?.completedTurn:null,m=f!=null?s.get(Number(f)):null;if(!m)return l.createElement(Te,{key:`line:${d}`,line:p,theme:e});const g=m.data||{},h=String(m.seq??`${g.turnIndex??f}:${m.createdAt??d}`),y=n.has(h),S=g.reasoningEffort?`${g.model||"(unknown)"}:${g.reasoningEffort}`:g.model||"(unknown)",E=u(g.model),x=g.durationMs!=null?c(g.durationMs):"duration n/a",w=g.durationMs!=null?`${o(g.durationMs)} ms`:"duration n/a",b=`${a(g.tokensInput)} / ${a(g.tokensOutput)}`,I=[["model",S],["started",g.startedAt?new Date(g.startedAt).toLocaleString():null],["ended",g.endedAt?new Date(g.endedAt).toLocaleString():null],["duration",w],["tokens",`${o(g.tokensInput)} in / ${o(g.tokensOutput)} out`],["cache",`${o(g.tokensCacheRead)} read / ${o(g.tokensCacheWrite)} write`],["tools",`${o(g.toolCalls)} calls / ${o(g.toolErrors)} errors`],["names",Array.isArray(g.toolNames)&&g.toolNames.length?g.toolNames.join(", "):null],["worker",g.workerNodeId||null],["result",g.resultType||null],["error",g.errorMessage||null]].filter(([,k])=>k!=null&&k!=="");return l.createElement(l.Fragment,{key:`seq:${d}`},l.createElement(Te,{line:p,theme:e}),l.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>r(h)},l.createElement("span",{className:"ps-sequence-turn-caret"},y?"v":">"),l.createElement("span",{className:"ps-sequence-turn-rule"},"--- "),l.createElement("span",{className:"ps-sequence-turn-key"},"Mod: "),l.createElement("span",{className:"ps-sequence-turn-model"},E),l.createElement("span",{className:"ps-sequence-turn-rule"}," ("),l.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),l.createElement("span",{className:"ps-sequence-turn-tokens"},b),l.createElement("span",{className:"ps-sequence-turn-rule"},", "),l.createElement("span",{className:"ps-sequence-turn-key"},"dur: "),l.createElement("span",{className:"ps-sequence-turn-duration"},x),l.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),y?l.createElement("div",{className:"ps-sequence-turn-details"},I.map(([k,P])=>l.createElement("div",{key:k},l.createElement("span",{className:"ps-sequence-turn-detail-label"},`${k}: `),l.createElement("span",null,String(P))))):null)}))}const Qm={chat:"chat",activity:"activity",inspector:"inspector",filePreview:"inspector"};function Ci(t,e=null){return e||Qm[String(t||"")]||null}function qs({title:t,titleRight:e=null,color:s,focused:n,actions:i,lines:r,stickyLines:o=[],bottomStickyLines:a=[],scrollOffset:c=0,scrollMode:u="top",paneKey:p,controller:d,className:f="",panelClassName:m="",topContent:g=null,bottomContent:h=null,structuredBlocks:y=!1,stickyBottom:S=!1,renderBody:E=null,focusRegion:x=null}){const w=Z(d,N=>N.ui.themeId),b=Be(w),I=l.useRef(null),k=l.useRef(null),P=l.useRef(!1),{normalizedLines:M,onScroll:B,onWheel:O,onTouchStart:_,onTouchMove:L,onTouchEnd:W}=nm(I,r,c,u,p,d,{stickyBottom:S}),Y=l.useMemo(()=>ve(o),[o]),te=l.useMemo(()=>ve(a),[a]),ne=f.includes("is-preserve")&&m.includes("has-preserved-sticky"),Pe=l.useCallback(()=>{const N=Ci(p,x);N&&d?.setFocus&&d.setFocus(N)},[d,p,x]),ee=l.useCallback((N,F)=>{!N||!F||Math.abs((F.scrollLeft||0)-(N.scrollLeft||0))<=1||(P.current=!0,F.scrollLeft=N.scrollLeft,window.requestAnimationFrame(()=>{P.current=!1}))},[]),[ye,v]=l.useState({up:!1,down:!1}),$=l.useCallback(N=>{if(!N)return;const F=N.scrollHeight-N.scrollTop-N.clientHeight>4,U=N.scrollTop>4;v(z=>z.up===F&&z.down===U?z:{up:F,down:U})},[]),H=l.useCallback(N=>{B(),$(N.currentTarget),!(!ne||P.current)&&ee(N.currentTarget,k.current)},[B,ne,ee,$]);l.useEffect(()=>{$(I.current)});const C=l.useCallback(N=>{!ne||P.current||ee(N.currentTarget,I.current)},[ne,ee]);return l.createElement(ht,{title:t,titleRight:e,color:s,focused:n,actions:i,theme:b,className:m},g,Y.length>0?l.createElement("div",{ref:k,className:`ps-panel-sticky${ne?" is-scroll-sync":""}`,onScroll:C},Y.map((N,F)=>l.createElement(Te,{key:`sticky:${F}`,line:N,theme:b}))):null,l.createElement("div",{ref:I,className:`ps-scroll-panel ${f}${ye.down?" is-scrolled-down":""}${ye.up?" is-scrolled-up":""}`.trim(),"data-session-scroll":x==="sessions"?"1":void 0,onScroll:H,onMouseDown:Pe,onTouchStart:_,onWheel:O,onTouchMove:L,onTouchEnd:W,onTouchCancel:W},typeof E=="function"?E(M,b):y?l.createElement(xl,{lines:M,theme:b,controller:d}):M.map((N,F)=>l.createElement(Te,{key:`line:${F}`,line:N,theme:b}))),te.length>0?l.createElement("div",{className:"ps-panel-bottom-sticky"},te.map((N,F)=>l.createElement(Te,{key:`bottom-sticky:${F}`,line:N,theme:b}))):null,h)}const Jm={group:"🗂",system:"⚙",service:"⚗"},ho="—";function Zm({session:t,childCount:e=0}){const s=(d,f,m="")=>{const g=f==null||f===""?ho:String(f),h=g===ho;return l.createElement("div",{className:`ps-session-detail-field${m?` ${m}`:""}${h?" is-none":""}`,key:d},l.createElement("span",{className:"ps-session-detail-label"},d),l.createElement("span",{className:"ps-session-detail-value",title:g},g))},n=t?.contextUsage,i=n&&Number.isFinite(n.currentTokens)&&Number.isFinite(n.tokenLimit)&&n.tokenLimit>0,r=i?Math.round(n.currentTokens/n.tokenLimit*100):null,o=i?`${X(n.currentTokens)} / ${X(n.tokenLimit)} · ${r}%`:null;let a=null;t&&!t.isGroup&&(a="off",t.cronActive===!0&&(a=t.cronKind==="wall-clock"?`next ${Ts(t.cronNextFireAt)}`:typeof t.cronInterval=="number"?`every ${Et(t.cronInterval)}`:"on"));const c=t?.model?t.reasoningEffort&&!String(t.model).includes(String(t.reasoningEffort))?`${t.model}:${t.reasoningEffort}`:t.model:null,u=t?t.visibility==="shared_write"?"shared · write":t.visibility==="shared_read"?"shared · read":"private":null,p=t?.isGroup?t.memberCount==null?null:String(t.memberCount):e>0?String(e):null;return l.createElement("div",{className:"ps-session-detail-box"},s("Title",t?.title,"is-title"),s("ID",t?.sessionId,"is-id"),s("Model",c),s("Context",o,r!=null&&r>=85?"is-hot":r!=null&&r>=70?"is-warm":""),s("Cron",a,t?.cronActive===!0?"is-armed":""),s("Agent",t?.agentId),s("Status",t?.status),s("Children",p),s("Access",u))}function eg(){const t="(pointer: coarse)",e=()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(t).matches:!1,[s,n]=l.useState(e);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const i=window.matchMedia(t),r=o=>n(o.matches);return i.addEventListener?.("change",r),()=>i.removeEventListener?.("change",r)},[]),s}const Al=13,Cl=11,Tl=1.5,tg=7;function sg(t){return Al+(t-1)*Cl+Tl/2-tg/2}const ng=l.memo(function({row:e,theme:s,rich:n,structuredRows:i,mobile:r,onRowClick:o,setRef:a,drag:c}){const u=Math.max(0,e.depth),p=l.useMemo(()=>{if(u<1)return;const x=Array.from({length:u},(w,b)=>b);return{backgroundImage:x.map(()=>"linear-gradient(var(--ps-rail), var(--ps-rail))").join(", "),backgroundSize:x.map(()=>`${Tl}px 100%`).join(", "),backgroundPosition:x.map(w=>`${Al+w*Cl}px 0`).join(", "),backgroundRepeat:"no-repeat"}},[u]),d=l.useCallback(x=>a(e.sessionId,x),[a,e.sessionId]),f=l.useCallback(x=>o(x,e),[o,e]),m=e.groupId||null,g=!!(c?.dragging&&c.overGroupId&&m===c.overGroupId),h=g&&!!e.isGroup,y=!!(c?.dragging&&c.insertBeforeId===e.sessionId),S=!!(c?.dragging&&c.insertAfterId&&c.insertAfterId===e.sessionId),E=l.useCallback(x=>{if(c?.onPointerDown&&x.button===0){if(x.currentTarget?.setPointerCapture&&x.pointerId!=null)try{x.currentTarget.setPointerCapture(x.pointerId)}catch{}c.onPointerDown(x,e)}},[c,e]);return l.createElement("button",{type:"button",ref:d,className:`ps-list-button ps-session-list-button${e.active?" is-selected":""}${e.selected?" is-multiselected":""}${e.pinned?" is-pinned":""}${g?" is-drop-zone":""}${h?" is-drop-target":""}${y?" is-insert-before":""}${S?" is-insert-after":""}${e.depth>0?" is-nested":""}`,style:p,tabIndex:e.active?0:-1,"aria-selected":e.active?"true":"false","data-session-id":e.sessionId,"data-group-row":e.isGroup?"1":void 0,"data-group-id":e.isGroup?e.groupId||"":void 0,"data-drop-group":m||void 0,"data-order-container":e.orderContainer??void 0,"data-orderable":e.orderable?"1":void 0,onPointerDown:E,onClick:f,onContextMenu:x=>{x.ctrlKey&&(x.preventDefault(),o(x,e))}},l.createElement("div",{className:n?"ps-session-row-content is-rich":"ps-line ps-session-row-content",style:{paddingInlineStart:u>0?`${sg(u)}px`:"0px"}},n?l.createElement(ig,{row:e,theme:s,showDetail:r}):l.createElement(Nl,{row:e,theme:s,structured:i,showInlineDetail:r})))});function ig({row:t,theme:e,showDetail:s=!1}){const n=t.chrome;if(!n)return l.createElement(Nl,{row:t,theme:e,structured:!0,showInlineDetail:s});const i=Jm[n.kind]||null,r=ge(e,n.accentColor)||void 0,o=s&&Array.isArray(t.detailRuns)?t.detailRuns:[];return l.createElement("div",{className:"ps-rich-session-row"},l.createElement("div",{className:"ps-rich-session-main"},n.selectMode?l.createElement("span",{className:`ps-rich-session-check${n.checked?" is-checked":""}`},n.checked?"✓":""):null,i?l.createElement("span",{className:"ps-rich-session-kind"},i):l.createElement("span",{className:`ps-rich-session-dot${t.depth>0?" is-node":""}`,style:t.depth>0?{borderColor:ge(e,n.statusColor)||void 0}:{background:ge(e,n.statusColor)||void 0},title:t.status||void 0}),n.owner?l.createElement("span",{className:`ps-rich-session-owner${n.owner.isMine?" is-mine":""}`,title:n.owner.initials},n.owner.initials):null,l.createElement("span",{className:`ps-rich-session-title${n.untitled?" is-untitled":""}`,style:n.kind==="session"?void 0:{color:r},title:n.title},n.title),n.pinned?l.createElement("span",{className:"ps-rich-session-pin",title:"Pinned"},l.createElement(Ml)):null,n.cron?l.createElement("span",{className:"ps-rich-session-cron",title:"Scheduled"},"⏱"):null,n.childBadge?l.createElement("span",{className:"ps-rich-session-count",style:{color:ge(e,n.childBadge.color)||void 0}},n.childBadge.text):null,n.ctx?l.createElement("span",{className:"ps-rich-session-ctx",style:{color:ge(e,n.ctx.color)||void 0}},n.ctx.text):null),o.length>0?l.createElement("div",{className:"ps-rich-session-detail"},l.createElement(Ae,{runs:o,theme:e})):null)}function mo(t,e){if(!Array.isArray(t))return{statusColor:null,rest:t};let s=null;const n=[];for(const i of t)if(i?.role!=="depth"){if(i?.role==="status"){s=ge(e,i.color)||null;continue}n.push(i)}return{statusColor:s,rest:n}}function go({color:t,node:e=!1}){return l.createElement("span",{className:`ps-session-status-dot${e?" is-node":""}`,style:t?e?{borderColor:t}:{background:t}:void 0})}function Vn({badge:t,size:e="sm"}){return t?l.createElement("span",{className:`ps-owner-avatar is-${e}${t.isMine?" is-mine":""}`,"data-owner-hue":String(t.hue??0),title:t.isMine?`${t.name} (you)`:t.name,"aria-label":t.name},t.initials):null}function yo(t){return Array.isArray(t)?t.filter(e=>!e?.ownerChip):t}function Nl({row:t,theme:e,structured:s=!1,showInlineDetail:n=!1}){if(!(s&&Array.isArray(t.titleRuns))){if(!Array.isArray(t.runs))return t.text;const p=mo(yo(t.runs),e);return l.createElement(l.Fragment,null,p.statusColor?l.createElement(go,{color:p.statusColor,node:t.depth>0}):null,l.createElement(Vn,{badge:t.ownerBadge}),l.createElement(Ae,{runs:p.rest,theme:e}))}const r=mo(yo(t.titleRuns),e),o=Array.isArray(t.ctxRuns)?t.ctxRuns:[],a=o.length>0,c=Array.isArray(t.detailRuns)?t.detailRuns:Array.isArray(t.selectedMetaRuns)?t.selectedMetaRuns:[],u=n&&t.active&&c.length>0;return l.createElement(l.Fragment,null,l.createElement("div",{className:"ps-session-row-line"},l.createElement("div",{className:"ps-session-row-title"},r.statusColor?l.createElement(go,{color:r.statusColor,node:t.depth>0}):null,l.createElement(Vn,{badge:t.ownerBadge}),l.createElement(Ae,{runs:r.rest,theme:e})),a?l.createElement("div",{className:"ps-session-row-ctx"},l.createElement(Ae,{runs:o,theme:e})):null),u?l.createElement("div",{className:"ps-session-row-detail"},l.createElement(Ae,{runs:c,theme:e})):null)}function rg(t){const e=l.useRef(t),s=l.useRef(null),n=l.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]);return(n===null||s.current!==n)&&(s.current=n,e.current=t),e.current}function Ti({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1}){const i=String(s).includes("ps-mobile-session-pane"),r=i||eg(),o=Z(t,D=>D.ui.themeId),a=Be(o),c=l.useRef(new Map),u=Z(t,D=>({branding:D.branding,activeSessionId:D.sessions.activeSessionId,sessionsById:D.sessions.byId,sessionsFlat:D.sessions.flat,filterQuery:D.sessions.filterQuery||"",ownerFilter:D.sessions.ownerFilter,pinnedIds:D.sessions.pinnedIds,manualOrder:D.sessions.manualOrder,selectedIds:D.sessions.selectedIds,selectMode:D.sessions.selectMode,auth:D.auth,connectionMode:D.connection?.mode||"local",modalOpen:!!D.ui.modal,focused:D.ui.focusRegion==="sessions",rich:!!Be(D.ui.themeId)?.richChat,listDeselected:!!D.sessions.listDeselected}),He),p=l.useMemo(()=>Ot({sessions:{activeSessionId:u.activeSessionId,byId:u.sessionsById,flat:u.sessionsFlat,filterQuery:u.filterQuery,ownerFilter:u.ownerFilter,pinnedIds:u.pinnedIds,manualOrder:u.manualOrder,selectedIds:u.selectedIds,selectMode:u.selectMode,listDeselected:u.listDeselected},auth:u.auth,connection:{mode:u.connectionMode},branding:u.branding}),[u.activeSessionId,u.auth,u.branding,u.connectionMode,u.filterQuery,u.listDeselected,u.ownerFilter,u.pinnedIds,u.manualOrder,u.selectedIds,u.selectMode,u.sessionsById,u.sessionsFlat]),d=rg(p),f=u.activeSessionId&&u.sessionsById[u.activeSessionId]||null,m=u.activeSessionId&&d.find(D=>D.sessionId===u.activeSessionId)||null,[g,h]=l.useState(!1),[y,S]=l.useState(null),E=l.useRef(!1),x=["modelPicker","reasoningEffortPicker","contextTierPicker"],w=Z(t,D=>x.includes(D.ui.modal?.type));l.useEffect(()=>{!w&&E.current&&(E.current=!1,h(!0))},[w]);const b=()=>{E.current=!0,h(!1),t.openSwitchModelPicker(()=>{E.current=!1}).then(()=>{!x.includes(t.getState().ui.modal?.type)&&E.current&&(E.current=!1,h(!0))}).catch(D=>{E.current=!1,h(!0),t.dispatch({type:"ui/status",text:D?.message||String(D)||"Failed to switch model"})})},I=u.auth?.principal||null,k=u.auth?.authorization?.role,P=k==="admin"||k==="anonymous",M=!!(f?.owner&&I&&String(f.owner.provider)===String(I.provider)&&String(f.owner.subject)===String(I.subject)),B=!!(f&&!f.isSystem&&!f.isGroup&&(P||M)),O=Array.isArray(u.selectedIds)?u.selectedIds.length:0,_=O>1,L=!!(f&&!f.isSystem&&(f.isGroup||!f.parentSessionId&&!f.groupId)),W=!!(f&&Array.isArray(u.pinnedIds)&&u.pinnedIds.includes(f.sessionId)),Y=!!(f?.isGroup&&Number(f.memberCount||0)===0),te=_?Array.isArray(u.selectedIds)&&u.selectedIds.some(D=>{const G=u.sessionsById[D];return G&&!G.isSystem&&!G.isGroup}):f?.isGroup?!0:!!f,ne=O>0,Pe=!!(f&&!u.listDeselected&&!f.isSystem&&!f.isGroup&&!f.parentSessionId),ee=ne?u.selectedIds.filter(D=>{const G=u.sessionsById[D];return G&&!G.isSystem&&!G.isGroup&&!G.parentSessionId}):Pe?[f.sessionId]:[],ye=`ps-session-pane${u.rich?" is-rich":""}${s?` ${s}`:""}`,v=l.useRef(null);v.current={rows:d,viewState:u,controller:t};const[$,H]=l.useState({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),C=l.useRef(null),N=l.useRef(null),F=l.useCallback(()=>{N.current!=null&&(cancelAnimationFrame(N.current),N.current=null)},[]),U=l.useCallback((D,G)=>{const se=document.elementFromPoint(D,G)?.closest?.("[data-session-scroll]")||document.querySelector("[data-session-scroll]");if(!se){F();return}const V=se.getBoundingClientRect();let ie=0;if(G<V.top+48?ie=-14*Math.min(1,(V.top+48-G)/48):G>V.bottom-48&&(ie=14*Math.min(1,(G-(V.bottom-48))/48)),C.current&&(C.current.autoScrollStep=ie),!C.current){F();return}if(N.current!=null)return;const ae=()=>{const Ce=C.current;if(!Ce||!Ce.autoScrollStep){F();return}se.scrollTop+=Ce.autoScrollStep,N.current=requestAnimationFrame(ae)};N.current=requestAnimationFrame(ae)},[F]),z=l.useCallback(D=>{const G=C.current;if(C.current=null,F(),H({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),!(!D||!G?.started||G.ids.length===0)){if(G.intent==="reorder"){t.dispatch({type:"sessions/reorder",sessionId:G.ids[0],beforeSessionId:G.beforeSessionId});return}G.intent!=="file"&&G.intent!=="unfile"||t.moveSessionsToGroup(G.overGroupId,G.ids).catch(re=>{t.dispatch({type:"ui/status",text:`Move failed: ${re?.message||re}`})})}},[t,F]),Q=l.useCallback((D,G)=>typeof D!="number"||typeof G!="number"?null:(document.elementFromPoint(D,G)?.closest?.("[data-drop-group]")||null)?.getAttribute("data-drop-group")||null,[]),pe=l.useCallback((D,G,re,R)=>{if(typeof D!="number"||typeof G!="number"||re==null)return;const j=Array.from(document.querySelectorAll(`[data-order-container="${CSS.escape(re)}"][data-orderable="1"]`));if(j.length===0)return;for(const ie of j){const ae=ie.getBoundingClientRect();if(G<ae.top+ae.height/2)return{before:ie.getAttribute("data-session-id")||null,after:null}}const V=j[j.length-1]?.getAttribute("data-session-id")||null;return{before:null,after:V&&V!==R?V:null}},[]),Se=l.useCallback((D,G,re)=>{const R=Q(D,G),j=re?.ownGroupId||null;if(R&&R!==j)return{kind:"file",overGroupId:R,before:void 0,after:null};if(!R&&j)return{kind:"unfile",overGroupId:null,before:void 0,after:null};const V=re?.orderable&&re.ids.length===1?pe(D,G,re.container,re.ids[0]):void 0;return V===void 0?{kind:R?"file":"none",overGroupId:R,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:V.before,after:V.after}},[Q,pe]);l.useEffect(()=>{if(!$.dragging)return;const D=j=>{const se=C.current;if(!se)return;const V=Se(j.clientX,j.clientY,se);se.intent=V.kind,se.overGroupId=V.overGroupId,se.beforeSessionId=V.before,U(j.clientX,j.clientY),document.body.classList.toggle("ps-drop-ok",V.kind==="file"),H(ie=>({...ie,intent:V.kind,overGroupId:V.overGroupId,insertBeforeId:V.before,insertAfterId:V.after,x:j.clientX,y:j.clientY}))},G=j=>{const se=C.current;if(se&&typeof j?.clientX=="number"){const V=Se(j.clientX,j.clientY,se);se.intent=V.kind,se.overGroupId=V.overGroupId,se.beforeSessionId=V.before}z(!0)},re=()=>z(!1),R=j=>{j.key==="Escape"&&z(!1)};return window.addEventListener("pointermove",D),window.addEventListener("pointerup",G),window.addEventListener("pointercancel",re),window.addEventListener("keydown",R),document.body.classList.add("ps-dragging-sessions"),()=>{window.removeEventListener("pointermove",D),window.removeEventListener("pointerup",G),window.removeEventListener("pointercancel",re),window.removeEventListener("keydown",R),document.body.classList.remove("ps-dragging-sessions"),document.body.classList.remove("ps-drop-ok")}},[$.dragging,z,Se,U]);const $e=l.useMemo(()=>({dragging:$.dragging,overGroupId:$.overGroupId,insertBeforeId:$.insertBeforeId,insertAfterId:$.insertAfterId,onPointerDown:(D,G)=>{if(G.isSystem||!G.orderable&&!G.isGroup&&G.depth>0)return;const re=D.clientX,R=D.clientY,j={row:G,startX:re,startY:R,started:!1,ids:[],overGroupId:null,beforeSessionId:void 0,orderable:!!G.orderable,container:G.orderContainer??null,ownGroupId:G.groupId||null,intent:"none",autoScrollStep:0},se=ie=>{if(j.started||Math.hypot(ie.clientX-re,ie.clientY-R)<5)return;j.started=!0;const ae=v.current.viewState,Ce=Array.isArray(ae.selectedIds)?ae.selectedIds:[],Ht=Ce.includes(G.sessionId)&&Ce.length>1?Ce:[G.sessionId],zs=ae.sessionsById||{};j.ids=Ht,C.current=j,H({dragging:!0,ids:Ht,titles:Ht.map(rs=>zs[rs]?.title||String(rs).slice(0,8)).slice(0,3),overGroupId:null,x:ie.clientX,y:ie.clientY})},V=()=>{window.removeEventListener("pointermove",se),window.removeEventListener("pointerup",V)};window.addEventListener("pointermove",se),window.addEventListener("pointerup",V)}}),[$.dragging,$.overGroupId,$.insertBeforeId,$.insertAfterId]),K=l.useCallback((D,G)=>{const{rows:re,viewState:R,controller:j}=v.current;if(D.metaKey||D.ctrlKey){D.preventDefault(),R.selectMode||j.dispatch({type:"sessions/selectMode",enabled:!0}),j.dispatch({type:"sessions/selectToggle",sessionId:G.sessionId}),j.setFocus("sessions");return}if(D.shiftKey&&R.activeSessionId){D.preventDefault();const V=re.map(Ce=>Ce.sessionId),ie=V.indexOf(R.activeSessionId),ae=V.indexOf(G.sessionId);if(ie>=0&&ae>=0){const[Ce,Ht]=ie<=ae?[ie,ae]:[ae,ie],zs=V.slice(Ce,Ht+1),rs=Array.from(new Set([...R.selectedIds||[],...zs]));j.setSessionSelection(rs),j.setFocus("sessions");return}}if(G.hasChildren&&G.active){j.dispatch({type:G.collapsed?"sessions/expand":"sessions/collapse",sessionId:G.sessionId}),j.setFocus("sessions");return}R.selectMode&&j.dispatch({type:"sessions/selectClear"}),j.setFocus("sessions"),G.sessionId===R.activeSessionId?j.dispatch({type:"sessions/listReselect"}):G.active||j.loadSession(G.sessionId).catch(()=>{})},[]),xe=l.useCallback((D,G)=>{D&&(G?c.current.set(D,G):c.current.delete(D))},[]);l.useEffect(()=>{if(u.modalOpen||!u.focused||!u.activeSessionId)return;const D=c.current.get(u.activeSessionId);D&&(document.activeElement!==D&&D.focus({preventScroll:!0}),D.scrollIntoView({block:"nearest"}))},[u.activeSessionId,u.focused,u.modalOpen]);const Ve=l.createElement(l.Fragment,null,_?l.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."},`${O} selected`):null,_?l.createElement(he,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(A.CLEAR_SESSION_SELECTION).catch(()=>{})}):l.createElement(he,{className:"ps-mini-button ps-pin-icon",icon:l.createElement(Ml),onClick:()=>t.handleCommand(A.PIN_SESSION).catch(()=>{}),disabled:!L,active:W,label:L?W?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"}),l.createElement(he,{className:"ps-mini-button",icon:ee.length>1?l.createElement("span",{className:"ps-icon-badge"},l.createElement(bo),l.createElement("span",{className:"ps-icon-badge__count"},String(ee.length))):l.createElement(bo),onClick:()=>t.handleCommand(A.OPEN_MOVE_TO_GROUP).catch(()=>{}),label:ee.length>1?`Move ${ee.length} selected sessions to a group`:ee.length===1?"Move this session to a group":"New group"}),l.createElement(he,{className:"ps-mini-button",icon:l.createElement(ag),onClick:()=>h(!0),disabled:!B||_,label:_?"Disabled while multiple sessions are selected":"Manage session — rename, switch model, and sharing"}),l.createElement(he,{className:"ps-mini-button",icon:l.createElement(lg),onClick:()=>{const D=f?.sessionId;if(!D)return;const G=Uh(D);G&&(Zr(G),S({url:G,warn:!1}),Wh(t,D).then(re=>{S(R=>R&&R.url===G?{...R,warn:re}:R)}).catch(()=>{}))},disabled:!f||f.isGroup||_,label:"Copy link — copy a direct link to this session"}),l.createElement(he,{className:"ps-mini-button",icon:f?.isSystem?"↻":l.createElement(cg),onClick:()=>t.handleCommand(f?.isGroup?A.DELETE_SESSION:A.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!te,label:_?`Terminate ${O} selected sessions (Mark Completed, Cancel, or Delete)`:f?.isGroup?Y?"Delete this empty group":"This group cannot be deleted yet":f?.isSystem?"Restart this system session (complete, terminate, or hard delete)":"Terminate — mark completed, cancel, or delete this session"}),e),mt=$.dragging?l.createElement("div",{className:"ps-drag-ghost",style:{left:`${$.x}px`,top:`${$.y}px`}},l.createElement("div",{className:`ps-drag-ghost__stack${$.ids.length>1?" is-collection":""}`},$.ids.length>1?l.createElement("span",{className:"ps-drag-ghost__count"},String($.ids.length)):null,l.createElement("span",{className:"ps-drag-ghost__title"},$.ids.length>1?`${$.ids.length} sessions`:$.titles[0]||"session")),l.createElement("div",{className:"ps-drag-ghost__hint"},$.overGroupId?"Release to file here":"Release to remove from folder")):null;return l.createElement(l.Fragment,null,mt,l.createElement(ht,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:u.focused,theme:a,actions:Ve,className:ye},l.createElement("div",{className:`ps-action-list ps-session-list${$.dragging?" is-dragging":""}`,onClick:D=>{D.target instanceof Element&&D.target.closest(".ps-session-list-button")||t.dispatch({type:"sessions/listDeselect"})}},d.length===0?l.createElement("div",{className:"ps-empty-state"},u.filterQuery?`No sessions matched "@@${u.filterQuery}".`:"No sessions yet."):d.map(D=>l.createElement(ng,{key:D.sessionId,row:D,theme:a,rich:u.rich,structuredRows:n,mobile:i,onRowClick:K,setRef:xe,drag:r?null:$e}))),i?null:l.createElement(Zm,{session:f,childCount:m?.childCount||0})),g&&f&&!f.isGroup?l.createElement(pg,{controller:t,sessionId:f.sessionId,initialTitle:f.title||"",currentModel:f.model||"",currentReasoningEffort:f.reasoningEffort||"",principal:u.auth?.principal||null,onClose:()=>h(!1),onSwitchModel:b,onChanged:()=>{}}):null,y?l.createElement(og,{url:y.url,warn:y.warn,onCopyAgain:()=>{Zr(y.url),t.dispatch({type:"ui/status",text:Hh})},onClose:()=>S(null)}):null)}function og({url:t,warn:e,onCopyAgain:s,onClose:n}){const i=l.useRef(null);l.useEffect(()=>{const o=i.current;o&&(o.focus(),o.select())},[]);const r=o=>o.stopPropagation();return l.createElement("div",{className:"ps-share-overlay",onClick:n},l.createElement("div",{className:"ps-link-modal",onClick:r},l.createElement("div",{className:"ps-share-modal-head"},l.createElement("span",null,"Link copied"),l.createElement("button",{className:"ps-modal-close",onClick:n,"aria-label":"Close",title:"Close"},"✕")),l.createElement("div",{className:"ps-share-section-sub"},"Copied to your clipboard — anyone with access can open the session from this link."),l.createElement("div",{className:"ps-link-row"},l.createElement("input",{ref:i,className:"ps-link-input",readOnly:!0,value:t,onFocus:()=>i.current?.select()}),l.createElement("button",{className:"ps-mini-button",onClick:s},"Copy")),e?l.createElement("div",{className:"ps-link-warn"},jh):null))}const So={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function ag(){return l.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},l.createElement("line",{x1:"4",y1:"6",x2:"20",y2:"6"}),l.createElement("line",{x1:"4",y1:"12",x2:"20",y2:"12"}),l.createElement("line",{x1:"4",y1:"18",x2:"20",y2:"18"}),l.createElement("circle",{cx:"9",cy:"6",r:"2",fill:"currentColor"}),l.createElement("circle",{cx:"15",cy:"12",r:"2",fill:"currentColor"}),l.createElement("circle",{cx:"8",cy:"18",r:"2",fill:"currentColor"}))}function lg(){return l.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},l.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"}),l.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 cg(){return l.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},l.createElement("path",{d:"M3 6h18"}),l.createElement("path",{d:"M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"}),l.createElement("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),l.createElement("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),l.createElement("line",{x1:"14",y1:"11",x2:"14",y2:"17"}))}function bo(){return l.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},l.createElement("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V18a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"}))}function Ml(){return l.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},l.createElement("path",{d:"M9 3h6"}),l.createElement("path",{d:"M10 3v6l-3 3v2h10v-2l-3-3V3"}),l.createElement("line",{x1:"12",y1:"14",x2:"12",y2:"21"}))}function ug(){return l.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},l.createElement("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),l.createElement("path",{d:"M3 3v5h5"}),l.createElement("path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"}),l.createElement("path",{d:"M21 21v-5h-5"}))}function dg(t,e,s){const[n,i]=l.useState({access:null,loading:!1}),r=l.useCallback(()=>{if(!e||s||typeof t.transport.getSessionAccess!="function"){i({access:null,loading:!1});return}let o=!1;return i(a=>({...a,loading:!0})),t.transport.getSessionAccess(e).then(a=>{o||i({access:a,loading:!1})}).catch(()=>{o||i({access:null,loading:!1})}),()=>{o=!0}},[t,e,s]);return l.useEffect(()=>{let o;const a=setTimeout(()=>{o=r()},Gh);return()=>{clearTimeout(a),typeof o=="function"&&o()}},[r]),{access:n.access,loading:n.loading,reload:r}}function pg({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:i,principal:r,onClose:o,onSwitchModel:a,onChanged:c}){const[u,p]=l.useState("general"),[d,f]=l.useState(null),[m,g]=l.useState(s||""),[h,y]=l.useState([]),[S,E]=l.useState([]),[x,w]=l.useState("private"),[b,I]=l.useState(""),[k,P]=l.useState("write"),[M,B]=l.useState([]),[O,_]=l.useState(!1),[L,W]=l.useState(null);l.useEffect(()=>{let R=!1;return t.transport.getSessionAccess(e).then(j=>{!R&&j&&(f(j),w(j.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(j=>{R||B(Array.isArray(j)?j:[])}).catch(()=>{}),()=>{R=!0}},[t,e]);const Y=l.useCallback(()=>{t.transport.listSessionShares(e).then(R=>{const j=Array.isArray(R)?R:[];y(j),E(j)}).catch(()=>{y([]),E([])})},[t,e]);l.useEffect(()=>{Y()},[Y]);const te=async R=>{_(!0),W(null);try{await R(),c?.()}catch(j){W(j?.message||String(j))}finally{_(!1)}},ne=()=>te(async()=>{await t.transport.renameSession(e,m.trim())}),Pe=R=>{const j=R.trim().toLowerCase();if(!j)return null;const se=M.find(V=>V.displayName&&V.displayName.toLowerCase()===j||V.email&&V.email.toLowerCase()===j||V.subject&&V.subject.toLowerCase()===j);return se||{provider:r?.provider||"dev",subject:R.trim(),email:null,displayName:null}},ee=R=>`${R.provider}${R.subject}`,ye=R=>{const j=ee(R);E(se=>[...se.filter(V=>ee(V)!==j),{provider:R.provider,subject:R.subject,email:R.email??null,displayName:R.displayName??null,access:k}]),I("")},v=()=>{const R=Pe(b);R&&ye(R)},$=R=>{const j=ee(R);E(se=>se.filter(V=>ee(V)!==j))},H=new Set(S.map(ee)),C=d?.owner?`${d.owner.provider}${d.owner.subject}`:null,N=b.trim().toLowerCase(),F=N?M.filter(R=>{const j=ee(R);return j===C||H.has(j)?!1:R.displayName&&R.displayName.toLowerCase().includes(N)||R.email&&R.email.toLowerCase().includes(N)||R.subject&&R.subject.toLowerCase().includes(N)}).slice(0,25):[],U=!!d?.canManage,z=d?.visibility||"private",Q=new Set(S.map(R=>`${ee(R)}:${R.access}`)),pe=new Set(h.map(R=>`${ee(R)}:${R.access}`)),Se=Q.size!==pe.size||[...Q].some(R=>!pe.has(R)),$e=U&&(x!==z||Se),K=()=>te(async()=>{x!==z&&await t.transport.setSessionVisibility(e,x);const R=new Map(h.map(ie=>[ee(ie),ie])),j=new Map(S.map(ie=>[ee(ie),ie]));for(const[ie,ae]of j){const Ce=R.get(ie);(!Ce||Ce.access!==ae.access)&&await t.transport.grantSessionShare(e,{provider:ae.provider,subject:ae.subject,email:ae.email??null,displayName:ae.displayName??null},ae.access)}for(const[ie,ae]of R)j.has(ie)||await t.transport.revokeSessionShare(e,{provider:ae.provider,subject:ae.subject});const se=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(se)&&(y(se),E(se));const V=await t.transport.getSessionAccess(e).catch(()=>null);V&&(f(V),w(V.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),xe=a||(()=>{o(),t.openSwitchModelPicker().catch(R=>{t.dispatch({type:"ui/status",text:R?.message||String(R)||"Failed to switch model"})})}),Ve=n?i?`${n}:${i}`:n:"—",mt=[{id:"general",label:"General"},...U?[{id:"access",label:"Access"}]:[]],D=mt.some(R=>R.id===u)?u:"general",G=typeof t.transport?.regenerateSession=="function",re=R=>R.stopPropagation();return l.createElement("div",{className:"ps-share-overlay",onClick:o},l.createElement("div",{className:"ps-share-modal",onClick:re},l.createElement("div",{className:"ps-share-modal-head"},l.createElement("span",null,"Manage session"),l.createElement("button",{className:"ps-modal-close",onClick:o,"aria-label":"Close",title:"Close"},"✕")),l.createElement("div",{className:"ps-manage-tabs",role:"tablist"},mt.map(R=>l.createElement("button",{key:R.id,type:"button",role:"tab","aria-selected":D===R.id?"true":"false",className:`ps-manage-tab${D===R.id?" is-active":""}`,onClick:()=>p(R.id)},R.label))),l.createElement("div",{className:"ps-share-modal-body"},D==="general"?l.createElement(l.Fragment,null,l.createElement("div",{className:"ps-share-section-label"},"Name"),l.createElement("div",{className:"ps-share-add-row"},l.createElement("input",{className:"ps-share-add-input",placeholder:"Session title",value:m,disabled:O,onChange:R=>g(R.target.value),onKeyDown:R=>{R.key==="Enter"&&ne()}}),l.createElement("button",{className:"ps-mini-button",disabled:O||!m.trim(),onClick:ne},"Save")),l.createElement("div",{className:"ps-share-section-label"},"Model"),l.createElement("div",{className:"ps-share-section-sub"},"The model this session uses on its next turn."),l.createElement("div",{className:"ps-share-add-row"},l.createElement("span",{className:"ps-manage-model-current"},Ve),l.createElement("button",{className:"ps-mini-button",disabled:O,onClick:xe},"Switch model…")),G?l.createElement(l.Fragment,null,l.createElement("div",{className:"ps-share-section-label"},"Context"),l.createElement("div",{className:"ps-share-section-sub"},"Rebuild this session's working context from its summary. The transcript is archived and the session keeps running — it is not a terminal action."),l.createElement("div",{className:"ps-share-add-row"},l.createElement("button",{className:"ps-mini-button ps-manage-regenerate",disabled:O,onClick:()=>{o(),t.handleCommand(A.REGENERATE_SESSION).catch(()=>{})}},l.createElement(ug),l.createElement("span",null,"Regenerate context…")))):null):null,D==="access"&&U?l.createElement(l.Fragment,null,l.createElement("div",{className:"ps-share-section-label"},"General access"),l.createElement("div",{className:"ps-share-section-sub"},"The baseline level for everyone signed in to this workspace."),["private","shared_read","shared_write"].map(R=>l.createElement("label",{key:R,className:`ps-share-radio${x===R?" is-active":""}`},l.createElement("input",{type:"radio",name:"visibility",checked:x===R,disabled:O,onChange:()=>w(R)}),l.createElement("span",{className:"ps-share-radio-glyph"},So[R].glyph),l.createElement("span",null,So[R].label),l.createElement("span",{className:"ps-share-radio-hint"},R==="private"?"only you and admins":R==="shared_read"?"everyone here can view":"everyone here can view and send"))),l.createElement("div",{className:"ps-share-section-label"},"Special access"),l.createElement("div",{className:"ps-share-section-sub"},"Give specific people more than the general level. A person's grant wins over general access."),S.length===0?l.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):S.map(R=>l.createElement("div",{key:`${R.provider}/${R.subject}`,className:"ps-share-grant-row"},l.createElement("span",{className:"ps-share-grant-name"},R.displayName||R.subject),l.createElement("span",{className:"ps-share-grant-access"},`can ${R.access}`),l.createElement("button",{className:"ps-mini-button",disabled:O,onClick:()=>$(R)},"Remove"))),l.createElement("div",{className:"ps-share-add-wrap"},l.createElement("div",{className:"ps-share-add-row"},l.createElement("input",{className:"ps-share-add-input",placeholder:"Name, email, or id",value:b,disabled:O,autoComplete:"off",onChange:R=>I(R.target.value),onKeyDown:R=>{R.key==="Enter"&&v()}}),l.createElement("select",{className:"ps-share-add-select",value:k,disabled:O,onChange:R=>P(R.target.value)},l.createElement("option",{value:"read"},"can read"),l.createElement("option",{value:"write"},"can write")),l.createElement("button",{className:"ps-mini-button",disabled:O||!b.trim(),onClick:v},"Add")),F.length>0?l.createElement("div",{className:"ps-share-suggestions"},F.map(R=>l.createElement("button",{key:`${R.provider}/${R.subject}`,type:"button",className:"ps-share-suggestion",disabled:O,onClick:()=>ye(R)},l.createElement("span",{className:"ps-share-suggestion-name"},R.displayName||R.subject),R.email?l.createElement("span",{className:"ps-share-suggestion-email"},R.email):null))):null),l.createElement("div",{className:"ps-share-foot-hint"},"Sharing applies to this session and its sub-agents. Suggestions are people who have signed in before — you can also grant by email to someone who hasn't; it takes effect when they first sign in.")):null),D==="access"&&U?l.createElement("div",{className:"ps-manage-apply-bar is-footer"},l.createElement("span",{className:"ps-share-section-sub"},$e?"Unsaved access changes.":"No changes to apply."),l.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:O||!$e,onClick:K},"Apply")):null,L?l.createElement("div",{className:"ps-share-error"},L):null))}function Ni({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const i=Z(t,L=>L.ui.themeId),r=Be(i),o=Z(t,L=>{const W=L.sessions.activeSessionId,Y=Ks(L),te=s||e?Y.totalWidth:Y.leftWidth,ne=Math.max(20,te-4);return{activeSessionId:W,activeHistory:W&&L.history.bySessionId.get(W)||null,activeOutbox:W&&L.outbox?.bySessionId?.[W]?L.outbox.bySessionId[W]:[],branding:L.branding,connection:L.connection,sessionsById:L.sessions.byId,sessionsFlat:L.sessions.flat,inspectorTab:L.ui.inspectorTab,chatViewMode:L.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(W&&L.sessions.byId[W]?.isGroup),activeSessionStatus:W?String(L.sessions.byId[W]?.status||"").toLowerCase():"",focused:L.ui.focusRegion==="chat",scroll:L.ui.scroll.chat,authPrincipal:L.auth?.principal||null,contentWidth:ne}},He),a=l.useMemo(()=>({branding:o.branding,connection:o.connection,auth:{principal:o.authPrincipal},sessions:{activeSessionId:o.activeSessionId,byId:o.sessionsById,flat:o.sessionsFlat},history:{bySessionId:o.activeSessionId&&o.activeHistory?new Map([[o.activeSessionId,o.activeHistory]]):new Map},outbox:{bySessionId:o.activeSessionId?{[o.activeSessionId]:o.activeOutbox}:{}},ui:{inspectorTab:o.inspectorTab,chatViewMode:o.chatViewMode}}),[o.activeHistory,o.activeSessionId,o.activeOutbox,o.authPrincipal,o.branding,o.connection,o.chatViewMode,o.inspectorTab,o.sessionsById,o.sessionsFlat]),c=l.useMemo(()=>Ma(a,{width:o.contentWidth}),[a,o.contentWidth]),u=ko(!!c.animateTitleRight),p=l.useMemo(()=>Ao(c.titleRight,c.animateTitleRight?u:""),[u,c.animateTitleRight,c.titleRight]),d=!!r?.richChat&&!o.activeSessionIsGroup,[f,m]=l.useState(!1),g=!!(o.activeHistory?.hasOlderEvents&&Number(o.activeHistory?.loadedEventCount||0)>=jn),h=l.useMemo(()=>d?kd(a,o.contentWidth,{tableMode:"sentinel"}):null,[d,a,o.contentWidth]),y=l.useMemo(()=>h?h.map((L,W)=>({text:L.kind==="message"?`m:${L.id??W}:${(L.text||"").length}:${L.pendingPhase||""}`:`l:${W}:${(L.lines||[]).length}`})):di(a,o.contentWidth,{tableMode:"sentinel"}),[h,a,o.contentWidth]),S=vo(o.activeSessionStatus==="running"),x=l.useMemo(()=>ui(a,{spinnerFrame:S,maxWidth:o.contentWidth}),[a,S,o.contentWidth]),w=l.useMemo(()=>fi(a,o.contentWidth,{tableMode:"sentinel"}),[a,o.contentWidth]),b=l.useMemo(()=>x.length>0?[...w,...x]:w,[w,x]),{access:I}=dg(t,o.activeSessionId,o.activeSessionIsGroup),k=Z(t,zu,He),P=n&&!o.activeSessionIsGroup&&o.chatViewMode!=="summary",M=!!o.sessionsById?.[o.activeSessionId]?.serviceKind,B=M||!!I&&I.canWrite===!1,O=P?l.createElement("div",{className:"ps-chat-composer"},B?l.createElement("div",{className:"ps-composer-readonly"},M?"⚗ 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.`):l.createElement(yg,{controller:t,mobile:e,active:!0})):null,_=!!(o.activeSessionId&&o.sessionsById[o.activeSessionId]);return k&&!_?l.createElement(ht,{title:c.title,color:c.color,focused:o.focused,theme:r,className:"ps-chat-panel"},l.createElement("div",{className:"ps-empty-state ps-nav-error-state"},l.createElement("div",{className:"ps-nav-error-message"},k.message),k.retryable?l.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(k.sessionId)},"Retry"):null)):l.createElement(qs,{controller:t,title:(()=>{const L=e?so(c.title,28):c.title;return d?zm(L):L})(),titleRight:e&&p?so(p,18):p,actions:null,color:c.color,focused:o.focused,lines:y,bottomStickyLines:b,scrollOffset:o.scroll,scrollMode:"bottom",paneKey:"chat",className:d?"is-wrapped is-rich":"is-wrapped",panelClassName:d?"ps-chat-panel is-rich":"ps-chat-panel",bottomContent:O,topContent:g?l.createElement("div",{className:"ps-load-older-bar"},l.createElement("button",{type:"button",className:"ps-load-older-button",disabled:f,onClick:()=>{m(!0),t.handleCommand(A.EXPAND_HISTORY).catch(()=>{}).finally(()=>m(!1))}},f?"Loading older messages…":"↑ Load older messages")):null,structuredBlocks:!0,renderBody:h?(L,W)=>l.createElement(Vm,{blocks:h,theme:W,controller:t}):null})}function fg({controller:t}){const e=Z(t,o=>{const a=o.files.selectedArtifactId||"";return{filename:a?a.slice(a.indexOf("/")+1):"",origin:o.files.previewOrigin||null,canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},He),s=!!pl(e.filename)||ki(e.filename),[n,i]=l.useState(!1);l.useEffect(()=>{i(!1)},[e.filename]);const r=l.useCallback(o=>{t.stepArtifactPreview(o).catch(()=>{})},[t]);return l.createElement("div",{className:"ps-artifact-overlay"},l.createElement("header",{className:"ps-artifact-overlay-bar"},l.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",onClick:()=>t.closeArtifactPreview().catch(()=>{}),"aria-label":e.origin==="chat"?"Close, back to chat":"Close, back to artifacts"},"✕"),l.createElement("span",{className:"ps-artifact-overlay-title"},e.filename||"Artifact"),s?l.createElement("button",{type:"button",className:`ps-artifact-overlay-btn${n?" is-active":""}`,onClick:()=>i(o=>!o),"aria-label":n?"Wrap lines":"Show full lines",title:n?"Wrap to screen width":"Full line width (scroll horizontally)"},n?"⇥":"↔"):null,l.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canPrev,onClick:()=>r(-1),"aria-label":"Previous artifact"},"‹"),l.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canNext,onClick:()=>r(1),"aria-label":"Next artifact"},"›")),l.createElement("div",{className:`ps-artifact-overlay-body${n?" is-content-width":""}`},l.createElement(Mi,{controller:t,focused:!0,mobile:!0,previewOnly:!0,nativeScroll:!0})))}function hg({controller:t}){return l.createElement("div",{className:"ps-mobile-workspace"},l.createElement(Ti,{controller:t,panelClassName:"ps-mobile-session-pane"}),l.createElement("div",{className:"ps-mobile-chat-pane"},l.createElement(Ni,{controller:t,mobile:!0,fullWidth:!0})))}function Pl({activeTab:t,controller:e}){const s=l.useMemo(()=>vi(e),[e]);return l.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>l.createElement(he,{key:n,icon:$h[n]||"•",label:_h[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function Mi({controller:t,focused:e,mobile:s=!1,previewOnly:n=!1,nativeScroll:i=!1}){const r=Z(t,_=>_.ui.themeId),o=Be(r),a=l.useRef(null),c=Z(t,_=>{const L=_.sessions.activeSessionId,W=Ks(_),Y=s||_.files.fullscreen?_.ui.layout?.viewportWidth??120:W.rightWidth;return{activeSessionId:L,sessionsById:_.sessions.byId,sessionsFlat:_.sessions.flat,filesBySessionId:_.files.bySessionId,filesFilter:_.files.filter,selectedArtifactId:_.files.selectedArtifactId,markedIds:_.files.markedIds||[],previewOrigin:_.files.previewOrigin||null,focused:e,previewScroll:_.ui.scroll.filePreview,fullscreen:!!_.files.fullscreen,contentWidth:Math.max(20,Y-4),canBrowserUpload:Oh(t),canPathUpload:Lh(t),canDeleteArtifacts:Bh(t),canOpenLocally:Dh(t)}},He),u=l.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:c.sessionsById,flat:c.sessionsFlat},files:{bySessionId:c.filesBySessionId,selectedArtifactId:c.selectedArtifactId,filter:c.filesFilter,fullscreen:c.fullscreen},ui:{scroll:{filePreview:c.previewScroll}}}),[c.activeSessionId,c.filesBySessionId,c.filesFilter,c.fullscreen,c.previewScroll,c.selectedArtifactId,c.sessionsById,c.sessionsFlat]),p=l.useMemo(()=>gi(u,{listWidth:Math.max(18,c.contentWidth-4),previewWidth:Math.max(18,c.contentWidth-4),showHints:!1}),[u,c.contentWidth]),d=l.useMemo(()=>ct(u),[u]),f=d.length>0,m=l.useCallback(_=>{const L=Array.isArray(_)?_.filter(Boolean):[];L.length!==0&&t.uploadArtifactFiles(L).catch(()=>{})},[t]),g=l.useCallback(()=>{if(c.canBrowserUpload&&a.current){a.current.click();return}c.canPathUpload&&t.handleCommand(A.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,c.canBrowserUpload,c.canPathUpload]),h=l.useMemo(()=>new Set(c.markedIds||[]),[c.markedIds]),y=l.createElement(l.Fragment,null,h.size>0?l.createElement(l.Fragment,null,l.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",opacity:.85},title:"Cmd/Ctrl-click to mark, Shift-click for a range"},`${h.size} marked`),c.canDeleteArtifacts?l.createElement(he,{icon:"🗑",label:`Delete ${h.size} marked`,onClick:()=>t.deleteMarkedArtifacts().catch(()=>{})}):null,l.createElement(he,{icon:"✕",label:"Clear marks",onClick:()=>t.clearArtifactMarks()})):null,l.createElement("input",{ref:a,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:_=>{m(Array.from(_.currentTarget.files||[])),_.currentTarget.value=""}}),l.createElement(he,{icon:"↥",label:"Upload",onClick:g,disabled:!c.canBrowserUpload&&!c.canPathUpload}),l.createElement(he,{icon:"↧",label:"Download",onClick:()=>t.handleCommand(A.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!f}),c.canDeleteArtifacts?l.createElement(he,{icon:"✕",label:"Delete",onClick:()=>t.handleCommand(A.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,c.canOpenLocally?l.createElement(he,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(A.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,l.createElement(he,{icon:"▾",label:"Filter",onClick:()=>t.handleCommand(A.OPEN_FILES_FILTER).catch(()=>{})}),l.createElement(he,{icon:c.fullscreen?"⇱":"⛶",label:c.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(A.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),S=l.useRef(null);l.useEffect(()=>{const _=S.current;_&&typeof _.scrollIntoView=="function"&&_.scrollIntoView({block:"nearest"})},[p.selectedIndex,c.selectedArtifactId]);const E=d.length===0?ve(p.listBodyLines||[]).map((_,L)=>l.createElement(Te,{key:`empty:${L}`,line:_,theme:o})):d.map((_,L)=>l.createElement("button",{key:_.id,type:"button",ref:L===p.selectedIndex?S:null,className:`ps-list-button${L===p.selectedIndex?" is-selected":""}`+(h.has(_.id)?" is-marked":""),onClick:W=>{if(t.setFocus("inspector"),W.metaKey||W.ctrlKey){t.toggleArtifactMark(_);return}if(W.shiftKey){t.markArtifactRange(_);return}t.clearArtifactMarks(),t.selectFileBrowserItem(_).then(()=>{s&&t.handleCommand(A.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})}).catch(()=>{})}},l.createElement(Te,{line:ve([p.listBodyLines?.[L]])[0],theme:o}))),x=!p.previewLoading&&!p.previewError,w=x&&ki(p.selectedFilename,p.previewContentType)&&!p.previewIsBinary&&!!p.previewContent,b=x&&(ul.test(String(p.previewContentType||""))||dl.test(String(p.selectedFilename||""))),I=x&&!p.previewIsBinary&&!w&&p.previewRenderMode!=="markdown"&&p.previewContent?pl(p.selectedFilename):null,k=n?"activity":null,P=i?null:"filePreview",B=x&&!p.previewIsBinary&&pm(p.selectedFilename,p.previewContentType)&&!!p.previewContent?l.createElement(kn,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:P,scrollOffset:c.previewScroll,className:"ps-csv-preview",focusRegion:k},l.createElement(hm,{content:p.previewContent,filename:p.selectedFilename})):b?l.createElement(uo,{title:null,color:"cyan",focused:!1,theme:o,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,source:p.previewSource,uploadedAt:p.previewUploadedAt,controller:t,sessionId:p.selectedSessionId}):I?l.createElement(kn,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:P,scrollOffset:c.previewScroll,className:"ps-diff-preview",focusRegion:k},l.createElement("pre",{className:"ps-md-code-pre"},l.createElement("code",null,es(p.previewContent,I,o)))):w?l.createElement(kn,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:P,scrollOffset:c.previewScroll,className:"ps-diff-preview",focusRegion:k},l.createElement("pre",{className:"ps-md-code-pre is-diff"},l.createElement("code",null,Ai(p.previewContent,o)))):p.previewRenderMode==="markdown"&&!p.previewLoading&&!p.previewError?l.createElement(Om,{controller:t,title:null,color:"cyan",focused:!1,scrollOffset:c.previewScroll,paneKey:P,theme:o,focusRegion:k,content:um(p.previewContent||"")}):p.previewIsBinary&&!p.previewLoading&&!p.previewError?l.createElement(uo,{title:null,color:"cyan",focused:!1,theme:o,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,source:p.previewSource,uploadedAt:p.previewUploadedAt,controller:t,sessionId:p.selectedSessionId}):l.createElement(qs,{controller:t,title:null,color:"cyan",focused:!1,lines:p.previewLines,scrollOffset:c.previewScroll,scrollMode:"top",paneKey:P,focusRegion:k,className:"is-preview is-wrapped"}),O=c;return n?B:l.createElement(ht,{title:O.fullscreen?p.fullscreenTitle:s&&p.panelTitleMobile?p.panelTitleMobile:p.panelTitle,color:"magenta",focused:O.focused,actions:y,theme:o},l.createElement(Pl,{activeTab:"files",controller:t}),O.fullscreen?B:l.createElement("div",{className:"ps-files-grid is-list-only"},l.createElement("div",{className:"ps-action-list ps-files-list"},E)))}function Yt({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const i=Z(t,f=>{const m=Ks(f),g=f.ui.inspectorTab,h=e?f.ui.layout?.viewportWidth??120:m.rightWidth;return{inspectorTab:g,statsViewMode:f.ui.statsViewMode,adminWorkers:f.admin?.workers,nodeMapSelectedNode:f.ui.nodeMapSelectedNode,activeSessionId:f.sessions.activeSessionId,sessionsById:f.sessions.byId,sessionsFlat:f.sessions.flat,historyBySessionId:f.history.bySessionId,sessionStats:f.sessionStats,fleetStats:f.fleetStats,connection:f.connection,orchestrationBySessionId:f.orchestration.bySessionId,executionHistoryBySessionId:f.executionHistory?.bySessionId||{},executionHistoryFormat:f.executionHistory?.format||"pretty",logs:f.logs,files:f.files,focused:f.ui.focusRegion==="inspector",scroll:f.ui.scroll.inspector,followBottom:f.ui.followBottom?.inspector!==!1,logsTailing:f.logs.tailing,filesFullscreen:!!f.files.fullscreen,contentWidth:Qh(h)}},He),r=l.useMemo(()=>({sessions:{activeSessionId:i.activeSessionId,byId:i.sessionsById,flat:i.sessionsFlat},history:{bySessionId:i.historyBySessionId},sessionStats:i.sessionStats,fleetStats:i.fleetStats,connection:i.connection,admin:{workers:i.adminWorkers},ui:{inspectorTab:i.inspectorTab,statsViewMode:i.statsViewMode,nodeMapSelectedNode:i.nodeMapSelectedNode,scroll:{inspector:i.scroll}},logs:i.logs,files:i.files,orchestration:{bySessionId:i.orchestrationBySessionId},executionHistory:{bySessionId:i.executionHistoryBySessionId,format:i.executionHistoryFormat}}),[i.activeSessionId,i.adminWorkers,i.connection,i.executionHistoryBySessionId,i.executionHistoryFormat,i.fleetStats,i.nodeMapSelectedNode,i.files,i.historyBySessionId,i.inspectorTab,i.sessionStats,i.statsViewMode,i.logs,i.orchestrationBySessionId,i.scroll,i.sessionsById,i.sessionsFlat]),o=l.useMemo(()=>it(r,{width:i.contentWidth,allowWideColumns:e}),[e,r,i.contentWidth]),a=l.useMemo(()=>{const f=i.activeSessionId&&i.historyBySessionId?.get(i.activeSessionId)||null,m=new Map;for(const g of f?.events||[]){if(g?.eventType!=="session.turn_completed")continue;const h=Number(g?.data?.turnIndex??g?.data?.iteration);Number.isFinite(h)&&m.set(h,g)}return m},[i.activeSessionId,i.historyBySessionId]),c=l.useCallback((f,m)=>l.createElement(Xm,{lines:f,theme:m,completionByTurn:a}),[a]),u=l.useCallback((f,m)=>l.createElement(Ym,{lines:f,theme:m,controller:t}),[t]);if(l.useEffect(()=>{if(i.inspectorTab!=="nodes")return;t.ensureInspectorData("nodes");const f=window.setInterval(()=>{t.ensureInspectorData("nodes")},1e4);return()=>window.clearInterval(f)},[t,i.inspectorTab]),i.inspectorTab==="files"&&!o.disabled)return l.createElement(Mi,{controller:t,focused:i.focused,mobile:e});const p=[];if(i.inspectorTab==="logs")p.push(l.createElement(he,{key:"tail",icon:i.logsTailing?"■":"⇣",label:i.logsTailing?"Stop tailing":"Tail (follow)",active:i.logsTailing,onClick:()=>t.handleCommand(A.TOGGLE_LOG_TAIL).catch(()=>{})})),p.push(l.createElement(he,{key:"filter",icon:"▾",label:"Filter",onClick:()=>t.handleCommand(A.OPEN_LOG_FILTER).catch(()=>{})}));else if(i.inspectorTab==="history")p.push(l.createElement(he,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(A.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),p.push(l.createElement(he,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(A.EXPORT_EXECUTION_HISTORY).catch(()=>{})}));else if(i.inspectorTab==="stats"){const f={session:"◉",fleet:"⬢",users:"⚇"};for(const m of["session","fleet","users"])p.push(l.createElement(he,{key:`stats-view:${m}`,icon:f[m],label:`${m.replace(/^./u,g=>g.toUpperCase())} stats`,active:i.statsViewMode===m,onClick:()=>t.setStatsViewMode(m)}))}const d=n?p.concat(n):p;return l.createElement(qs,{controller:t,title:o.title,color:"magenta",focused:i.focused,actions:d,topContent:l.createElement(Pl,{activeTab:o.activeTab,controller:t}),stickyLines:o.stickyLines||[],lines:o.lines,renderBody:o.activeTab==="sequence"?c:o.activeTab==="nodes"?u:null,scrollOffset:i.scroll,scrollMode:o.activeTab==="sequence"||o.activeTab==="logs"&&i.followBottom?"bottom":"top",stickyBottom:o.activeTab==="logs",paneKey:"inspector",className:o.activeTab==="history"||o.activeTab==="logs"?"is-wrapped":"is-preserve",panelClassName:`ps-inspector-pane${o.activeTab==="sequence"?" has-preserved-sticky":""}${s?` ${s}`:""}`.trim()})}function qn({controller:t,panelClassName:e="",extraActions:s=null}){const n=Z(t,a=>{const c=a.sessions.activeSessionId,u=Ks(a),p=Math.max(3,u.activityPaneHeight-2);return{activeSessionId:c,activeSession:c&&a.sessions.byId[c]||null,activeHistory:c&&a.history.bySessionId.get(c)||null,focused:a.ui.focusRegion==="activity",scroll:a.ui.scroll.activity,followBottom:a.ui.followBottom?.activity!==!1,maxLines:p,nodeMapSelectedNode:a.ui.nodeMapSelectedNode,adminWorkers:a.admin?.workers,branding:a.branding,sessionsById:a.sessions.byId,sessionsFlat:a.sessions.flat,historyBySessionId:a.history.bySessionId,inspectorTab:a.ui.inspectorTab}},He),i=n.inspectorTab==="nodes",r=l.useMemo(()=>({branding:n.branding,admin:{workers:n.adminWorkers},ui:{nodeMapSelectedNode:n.nodeMapSelectedNode},sessions:{activeSessionId:n.activeSessionId,byId:i?n.sessionsById:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{},flat:n.sessionsFlat},history:{bySessionId:i?n.historyBySessionId:n.activeSessionId&&n.activeHistory?new Map([[n.activeSessionId,n.activeHistory]]):new Map}}),[i,n.activeHistory,n.activeSession,n.activeSessionId,n.adminWorkers,n.branding,n.historyBySessionId,n.nodeMapSelectedNode,n.sessionsById,n.sessionsFlat]),o=l.useMemo(()=>i?Pa(r):mi(r,n.maxLines),[i,r,n.maxLines]);return l.createElement(qs,{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 zn=[{id:"sessions",label:"Sessions",side:"left"},{id:"inspector",label:"Inspector",side:"right"},{id:"activity",label:"Activity",side:"right"}];function mg({controller:t,pane:e,onClose:s,mobile:n=!1}){if(!e)return null;let i=null;e==="sessions"?i=l.createElement(Ti,{controller:t,panelClassName:"ps-chat-focus-pane",structuredRows:n,actions:l.createElement("button",{type:"button",className:"ps-mini-button ps-overlay-close",onClick:s,"aria-label":"Close",title:"Close"},"✕")}):e==="inspector"?i=l.createElement(Yt,{controller:t,mobile:!1,panelClassName:"ps-chat-focus-pane",extraActions:l.createElement("button",{type:"button",className:"ps-mini-button ps-overlay-close",onClick:s,"aria-label":"Close",title:"Close"},"✕")}):e==="activity"&&(i=l.createElement(qn,{controller:t,panelClassName:"ps-chat-focus-pane",extraActions:l.createElement("button",{type:"button",className:"ps-mini-button ps-overlay-close",onClick:s,"aria-label":"Close",title:"Close"},"✕")}));const r=zn.find(o=>o.id===e);return l.createElement("div",{className:`ps-chat-focus-overlay${r?.side==="left"?" is-left":" is-right"}`},i)}function gg({controller:t,openPane:e,onTogglePane:s,onExitFocus:n,mobile:i=!1}){const r=Z(t,a=>a.ui.focusRegion),o=i?l.createElement("div",{className:"ps-chat-focus-rail"},l.createElement("button",{type:"button",className:"ps-mini-button ps-chat-focus-button",onClick:n},"Exit Focus"),l.createElement("button",{type:"button",className:`ps-mini-button ps-chat-focus-button${e==="sessions"?" is-active":""}`,onClick:()=>s("sessions")},"Sessions")):l.createElement("div",{className:"ps-chat-focus-rail"},zn.map(a=>l.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)),l.createElement("div",{className:"ps-chat-focus-status"},e?`Focused: ${zn.find(a=>a.id===e)?.label||e}`:`Focused: ${r==="prompt"?"Prompt":"Chat"}`));return l.createElement("div",{className:"ps-chat-focus-shell"},o,l.createElement("div",{className:"ps-chat-focus-body"},l.createElement(Ni,{controller:t,mobile:i,fullWidth:!0}),l.createElement(mg,{controller:t,pane:e,onClose:()=>s(e),mobile:i})))}const wo=Object.freeze([]);function Io(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 yg({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const i=Z(t,I=>{const k=I.sessions.activeSessionId,P=k&&I.sessions.byId[k]||null,M=k&&I.outbox?.bySessionId?.[k]?I.outbox.bySessionId[k]:[];return{value:I.ui.prompt,cursor:I.ui.promptCursor,focused:I.ui.focusRegion==="prompt",modalOpen:!!I.ui.modal,answerMode:!!P?.pendingQuestion?.question,canStopTurn:Ia(P),hasOutbox:M.length>0,hasPendingOutbox:M.some(B=>B?.phase==="pending"),pendingCount:M.filter(B=>B?.phase==="pending").length,editingPending:I.ui.promptEdit?.sessionId===k,selectedOutboxPhase:I.ui.promptEdit?.sessionId===k&&I.ui.promptEdit?.phase||null,promptAttachments:I.ui.promptAttachments||wo}},He),r=l.useRef(null),o=l.useRef(null),[a,c]=l.useState(!1),u=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",p=u?i.promptAttachments.filter(I=>I?.kind==="image"):wo,d=l.useRef(new Map);l.useEffect(()=>{const I=d.current,k=new Set(p.map(P=>P.file));for(const[P,M]of I)k.has(P)||(URL.revokeObjectURL(M),I.delete(P));for(const P of p)if(P.file&&!I.has(P.file))try{I.set(P.file,URL.createObjectURL(P.file))}catch{}},[p]),l.useEffect(()=>()=>{for(const I of d.current.values())URL.revokeObjectURL(I);d.current.clear()},[]);const f=l.useCallback(I=>{if(!u)return 0;const k=Array.from(I||[]).filter(M=>M&&typeof M.type=="string"&&M.type.startsWith("image/"));return k.length===0?0:t.addPendingImageFiles(k)?.accepted||0},[t,u]);l.useEffect(()=>{const I=r.current;if(!(!s||i.modalOpen||!i.focused||!I)){if(document.activeElement!==I)try{I.focus({preventScroll:!0})}catch{I.focus()}I.setSelectionRange(i.cursor,i.cursor)}},[s,i.cursor,i.focused,i.modalOpen]);const m=l.useCallback(()=>{t.handleCommand(A.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[g,h]=l.useState(!1),y=l.useCallback(()=>{h(!0),t.handleCommand(A.STOP_TURN).catch(()=>{}).finally(()=>h(!1))},[t]),S=l.useCallback(()=>{if(t.getState().ui.promptEdit){typeof t.cancelSelectedOutboxPrompt=="function"?t.cancelSelectedOutboxPrompt().catch(()=>{}):t.cancelSelectedPendingPrompt();return}typeof t.cancelLatestQueuedOutbox=="function"&&t.cancelLatestQueuedOutbox().catch(()=>{})},[t]),E=i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"⇪":i.hasOutbox?"+":"❯",x=i.selectedOutboxPhase==="queued",w=i.selectedOutboxPhase==="cancelling",b=x||w;return l.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}${a?" is-drag-over":""}`,...u?{onDragOver:I=>{I.dataTransfer?.types?.includes?.("Files")&&(I.preventDefault(),c(!0))},onDragLeave:I=>{I.currentTarget.contains(I.relatedTarget)||c(!1)},onDrop:I=>{c(!1),I.dataTransfer?.files?.length&&(I.preventDefault(),f(I.dataTransfer.files))}}:{}},p.length>0?l.createElement("div",{className:"ps-prompt-attachments"},p.map((I,k)=>{const P=I.file?d.current.get(I.file):null;return l.createElement("div",{key:`attach:${k}:${I.filename}`,className:"ps-attach-chip",title:`${I.filename} · ${Io(I.sizeBytes)}`},P?l.createElement("img",{className:"ps-attach-thumb",src:P,alt:I.filename}):l.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),l.createElement("div",{className:"ps-attach-size"},Io(I.sizeBytes)),l.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${I.filename}`,"aria-label":`Remove attachment ${I.filename}`,onClick:()=>t.removePendingImageAttachment(k)},"✕"))})):null,(()=>{const I=i.answerMode?"answer":w?"cancelling":x?"queued":i.editingPending?"pending":"you";return l.createElement("label",{className:`ps-prompt-label${I==="you"?" is-default":""}`},I)})(),l.createElement("textarea",{ref:r,className:"ps-prompt-input",rows:e?2:Math.max(2,Nt(i.value)),value:i.value,readOnly:b,placeholder:i.answerMode?"Type an answer and press Enter":i.editingPending?w?"Cancellation requested":x?"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:I=>t.setPromptCursor(I.currentTarget.selectionStart||0),onChange:I=>t.setPrompt(I.currentTarget.value,I.currentTarget.selectionStart||I.currentTarget.value.length),onPaste:u?I=>{const P=Array.from(I.clipboardData?.items||[]).filter(M=>M.kind==="file"&&M.type.startsWith("image/")).map(M=>M.getAsFile()).filter(Boolean);P.length>0&&f(P)>0&&I.preventDefault()}:void 0,onKeyDown:I=>{if(I.key==="Tab"&&!I.shiftKey&&t.acceptPromptReferenceAutocomplete()){I.preventDefault();return}if(I.key==="ArrowUp"&&!I.shiftKey&&!I.metaKey&&!I.altKey){I.preventDefault(),t.movePromptCursorVertical(-1);return}if(I.key==="ArrowDown"&&!I.shiftKey&&!I.metaKey&&!I.altKey){I.preventDefault(),t.movePromptCursorVertical(1);return}if(I.key==="Escape"&&i.editingPending){if(I.preventDefault(),b){t.exitPendingPromptEdit({restoreDraft:!0});return}S();return}I.key==="Enter"&&!I.shiftKey&&!I.metaKey&&!e&&(I.preventDefault(),m())}}),l.createElement("div",{className:"ps-prompt-actions"},u?l.createElement(l.Fragment,null,l.createElement("input",{ref:o,type:"file",accept:"image/*",multiple:!0,className:"ps-hidden-file-input","aria-hidden":!0,tabIndex:-1,onChange:I=>{f(I.currentTarget.files),I.currentTarget.value=""}}),l.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:()=>o.current?.click()},"📎")):null,i.editingPending&&!w?l.createElement("button",{type:"button",className:"ps-mini-button",title:x?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":x?"Delete selected queued prompt":"Cancel selected pending prompt",onClick:S},x?"Delete":"Cancel"):null,i.canStopTurn||g?l.createElement("button",{type:"button",className:`ps-stop-button${g?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:g,onClick:y},"■"):null,l.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:m},E)))}const Sg=1e3;function he({icon:t,label:e,onClick:s,disabled:n=!1,active:i=!1,className:r="ps-toolbar-button"}){const[o,a]=l.useState(null),c=l.useRef(null),u=l.useRef(null),p=l.useRef(null),d=l.useRef(!1);l.useLayoutEffect(()=>{if(!o||!u.current||typeof window>"u")return;const k=u.current.offsetWidth/2,P=6,M=Math.max(k+P,Math.min(o.x,window.innerWidth-k-P));u.current.style.left=`${M}px`},[o]);const f=(k=!1)=>{const P=c.current;if(!P||typeof window>"u")return;const M=P.getBoundingClientRect(),B=k?M.top-44<0:M.bottom+44<window.innerHeight;a({x:M.left+M.width/2,y:B?M.bottom+6:M.top-6,placement:B?"below":"above"})},m=l.useRef(null),g=l.useRef(null),h=k=>{k.pointerType==="mouse"&&(clearTimeout(p.current),clearTimeout(m.current),p.current=setTimeout(f,Sg))},y=k=>{k.pointerType==="mouse"&&(clearTimeout(p.current),clearTimeout(m.current),a(null))},S=k=>{k.pointerType!=="mouse"&&(d.current=!1,g.current={x:k.clientX,y:k.clientY},clearTimeout(p.current),clearTimeout(m.current),p.current=setTimeout(()=>{d.current=!0,f(!0)},450))},E=k=>{if(k.pointerType==="mouse"||!g.current)return;const P=k.clientX-g.current.x,M=k.clientY-g.current.y;P*P+M*M>100&&(g.current=null,clearTimeout(p.current),a(null))},x=k=>{k.pointerType!=="mouse"&&(g.current=null,clearTimeout(p.current),d.current?(clearTimeout(m.current),m.current=setTimeout(()=>a(null),3e3),setTimeout(()=>{d.current=!1},250)):a(null))};l.useEffect(()=>()=>{clearTimeout(p.current),clearTimeout(m.current)},[]);const w=k=>{if(d.current){d.current=!1,k.preventDefault?.();return}n||s?.(k)},b=k=>{k.preventDefault?.()},I=o&&typeof document<"u"&&document.body?el.createPortal(l.createElement("span",{ref:u,className:`ps-icon-tooltip is-${o.placement}`,role:"tooltip",style:{left:`${o.x}px`,top:`${o.y}px`}},e),document.body):null;return l.createElement("button",{ref:c,type:"button",className:`${r} ps-icon-button${i?" is-active":""}`,onClick:w,disabled:n,"aria-label":e,onPointerEnter:h,onPointerLeave:y,onPointerDown:S,onPointerMove:E,onPointerUp:x,onPointerCancel:x,onContextMenu:b},l.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),I)}function bg({controller:t,mobile:e,chatFocusMode:s=!1,onToggleChatFocus:n=null,chatFocusDisabled:i=!1}){const r=Z(t,m=>!!Be(m.ui.themeId)?.richChat),[o,a]=l.useState(null);l.useEffect(()=>{typeof document>"u"||a(e?null:document.getElementById("ps-header-toolbar-slot"))},[r,e]);const c=Z(t,m=>!!m.admin?.visible),u=Z(t,m=>({mode:m.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(m.sessions.activeSessionId&&m.sessions.byId[m.sessions.activeSessionId]?.isGroup)}),He),p=[{key:"new",icon:"+",label:"New session — choose model and agent",onClick:()=>t.handleCommand(A.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:"▾",label:"Filter sessions",onClick:()=>t.handleCommand(A.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:"◑",label:"Theme",onClick:()=>t.handleCommand(A.OPEN_THEME_PICKER).catch(()=>{})},{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}]:[],...e?[]:[{key:"admin",icon:"⚙",label:c?"Close admin console":"Admin console",onClick:()=>t.handleCommand(c?A.CLOSE_ADMIN_CONSOLE:A.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:c}]],d=m=>l.createElement(he,{key:m.key,icon:m.icon,label:m.label,onClick:m.onClick,disabled:!!m.disabled,active:!!m.active});if(e)return l.createElement("div",{className:"ps-toolbar is-mobile"},l.createElement("div",{className:"ps-toolbar-row ps-toolbar-row-primary"},l.createElement("div",{className:"ps-toolbar-row-actions"},p.map(d))));const f=l.createElement("div",{className:"ps-toolbar"},l.createElement("div",{className:"ps-toolbar-actions"},p.map(d)));return o?el.createPortal(f,o):f}function wg({controller:t,paneAdjust:e=0}){const s=l.useRef(null),[n,i]=l.useState(!1);return l.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")};let o=0,a=0;const c=()=>{o=0;const p=s.current;if(!p)return;const d=Math.round((a-p.startX)/tl),f=d-p.appliedCells;f&&(t.adjustPaneSplit(f),p.appliedCells=d)},u=p=>{s.current&&(a=p.clientX,!o&&(o=requestAnimationFrame(c)))};return window.addEventListener("pointermove",u),window.addEventListener("pointerup",r),window.addEventListener("pointercancel",r),()=>{o&&(cancelAnimationFrame(o),o=0),window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",r),window.removeEventListener("pointercancel",r),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),l.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:r=>{r.button===0&&(r.preventDefault(),s.current={startX:r.clientX,appliedCells:0},i(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{e&&t.adjustPaneSplit(-e)},onKeyDown:r=>{if(r.key==="ArrowLeft"){r.preventDefault(),t.handleCommand(A.GROW_RIGHT_PANE).catch(()=>{});return}r.key==="ArrowRight"&&(r.preventDefault(),t.handleCommand(A.GROW_LEFT_PANE).catch(()=>{}))}},l.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},l.createElement("span",{className:"ps-column-resizer-dot"}),l.createElement("span",{className:"ps-column-resizer-dot"}),l.createElement("span",{className:"ps-column-resizer-dot"})))}function Ig({controller:t,portalSessionColumnAdjust:e=0}){const s=l.useRef(null),[n,i]=l.useState(!1);return l.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")},o=a=>{const c=s.current;if(!c)return;const u=Un(c.startAdjust+(a.clientX-c.startX),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:u})};return window.addEventListener("pointermove",o),window.addEventListener("pointerup",r),window.addEventListener("pointercancel",r),()=>{window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",r),window.removeEventListener("pointercancel",r),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),l.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:r=>{if(r.button!==0)return;r.preventDefault();const o=r.currentTarget.closest(".ps-workspace-main-grid"),a=Wn(o?.getBoundingClientRect?.().width);s.current={startX:r.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:r=>{const o=r.currentTarget.closest(".ps-workspace-main-grid"),a=Wn(o?.getBoundingClientRect?.().width),c=u=>{const p=Un((Number(e)||0)+u,a.minAdjust,a.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:p})};if(r.key==="ArrowLeft"){r.preventDefault(),c(-24);return}r.key==="ArrowRight"&&(r.preventDefault(),c(24))}},l.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},l.createElement("span",{className:"ps-column-resizer-dot"}),l.createElement("span",{className:"ps-column-resizer-dot"}),l.createElement("span",{className:"ps-column-resizer-dot"})))}function xg({controller:t,activityPaneAdjust:e=0}){const s=l.useRef(null),[n,i]=l.useState(!1);return l.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-y")},o=a=>{const c=s.current;if(!c)return;const u=Math.round((a.clientY-c.startY)/sl),p=u-c.appliedCells;p&&(t.adjustActivityPaneSplit(-p),c.appliedCells=u)};return window.addEventListener("pointermove",o),window.addEventListener("pointerup",r),window.addEventListener("pointercancel",r),()=>{window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",r),window.removeEventListener("pointercancel",r),document.body.classList.remove("is-resizing-pane-y")}},[t,n]),l.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:r=>{r.button===0&&(r.preventDefault(),s.current={startY:r.clientY,appliedCells:0},i(!0),document.body.classList.add("is-resizing-pane-y"))},onDoubleClick:()=>{e&&t.adjustActivityPaneSplit(-e)},onKeyDown:r=>{if(r.key==="ArrowUp"){r.preventDefault(),t.adjustActivityPaneSplit(1);return}r.key==="ArrowDown"&&(r.preventDefault(),t.adjustActivityPaneSplit(-1))}},l.createElement("span",{className:"ps-row-resizer-handle","aria-hidden":"true"},l.createElement("span",{className:"ps-row-resizer-dot"}),l.createElement("span",{className:"ps-row-resizer-dot"}),l.createElement("span",{className:"ps-row-resizer-dot"})))}function Eg({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 l.createElement("div",{className:"ps-mobile-nav"},n.map(i=>l.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 vg({controller:t}){const e=Z(t,h=>h.ui.themeId),s=Be(e),n=Z(t,h=>({rawModal:h.ui.modal,themePicker:zp(h),modelPicker:wp(h),reasoningEffortPicker:xp(h),contextTierPicker:Ep(h),sessionAgentPicker:Ip(h),sessionGroupPicker:vp(h),sessionGroupName:Ap(h),artifactPicker:Pp(h),logFilter:Np(h),filesFilter:Mp(h),historyFormat:qp(h),renameSession:kp(h),sessionOwnerFilter:Tp(h),artifactUpload:Cp(h),confirm:Yp(h),logsFilter:h.logs.filter,filesFilterState:h.files.filter,historyFormatState:h.executionHistory?.format||"pretty"}),He),i=n.rawModal,r=l.useRef(null),o=l.useRef(null),a=l.useRef(null),[c,u]=l.useState(""),p=i?.type==="sessionOwnerFilter";if(l.useEffect(()=>{p||u("")},[p]),l.useEffect(()=>{if(i?.type!=="renameSession"||!n.renameSession)return;const h=r.current;if(h){if(document.activeElement!==h)try{h.focus({preventScroll:!0})}catch{h.focus()}h.setSelectionRange(n.renameSession.cursorIndex,n.renameSession.cursorIndex)}},[i?.type,n.renameSession?.cursorIndex,n.renameSession?.value]),l.useEffect(()=>{if(i?.type!=="sessionGroupName"||!n.sessionGroupName)return;const h=o.current;if(h){if(document.activeElement!==h)try{h.focus({preventScroll:!0})}catch{h.focus()}h.setSelectionRange(n.sessionGroupName.cursorIndex,n.sessionGroupName.cursorIndex)}},[i?.type,n.sessionGroupName?.cursorIndex,n.sessionGroupName?.value]),l.useEffect(()=>{if(!i||!["themePicker","modelPicker","reasoningEffortPicker","contextTierPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(i.type))return;const h=a.current;if(!h)return;const y=h.querySelector(".ps-list-button.is-selected");y&&typeof y.scrollIntoView=="function"&&y.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 d=()=>t.handleCommand(A.CLOSE_MODAL).catch(()=>{}),f=(h,y="Apply")=>{const S=Array.isArray(h.rows)?h.rows:[],E=Array.isArray(h.rowItemIndexes)?h.rowItemIndexes:null,x=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",w=E&&E.length===S.length?S.map((b,I)=>{const k=E[I],P=Array.isArray(b)?b:ve([b])[0]?.runs||[{text:b?.text||"",color:b?.color}];if(k==null||k<0)return l.createElement("div",{key:`row:${I}`,className:"ps-line ps-modal-list-heading-line"},l.createElement(Ae,{runs:P,theme:s}));const M=i.items?.[k];return l.createElement("button",{key:M?.id||`row:${I}`,type:"button",className:`ps-list-button ps-modal-list-button${k===i.selectedIndex?" is-selected":""}${x?" is-hanging":""}${M?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:k})},l.createElement("div",{className:"ps-line ps-modal-list-line"},l.createElement(Ae,{runs:P,theme:s})))}):(i.items||[]).map((b,I)=>l.createElement("button",{key:b.id||I,type:"button",className:`ps-list-button ps-modal-list-button${I===i.selectedIndex?" is-selected":""}${x?" is-hanging":""}${b?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:I})},l.createElement("div",{className:"ps-line ps-modal-list-line"},l.createElement(Ae,{runs:Array.isArray(S?.[I])?S[I]:ve([S?.[I]])[0]?.runs||[{text:S?.[I]?.text||"",color:S?.[I]?.color}],theme:s}))));return l.createElement("div",{className:"ps-modal-backdrop",onClick:d},l.createElement("div",{className:`ps-modal is-list${i.type==="themePicker"?" is-theme-picker":""}`,onClick:b=>b.stopPropagation()},l.createElement("div",{className:"ps-modal-header"},l.createElement("div",{className:"ps-modal-title"},h.title),l.createElement("button",{type:"button",className:"ps-modal-close",onClick:d,"aria-label":"Close",title:"Close"},"✕")),l.createElement("div",{className:"ps-modal-grid"},l.createElement("div",{ref:a,className:"ps-modal-list"},w),l.createElement("div",{className:"ps-modal-details"},l.createElement("div",{className:"ps-modal-details-title"},h.detailsTitle||"Details"),ve(h.detailsLines||[]).map((b,I)=>l.createElement(Te,{key:`detail:${I}`,line:b,theme:s,className:"ps-modal-detail-line"})))),l.createElement("div",{className:"ps-modal-footer"},l.createElement("button",{type:"button",className:"ps-modal-button",onClick:d},"Cancel"),l.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(A.MODAL_CONFIRM).catch(()=>{})},y))))};if(i.type==="confirm"&&n.confirm){const h=!!i.alert,y=!h&&i.action==="deleteSession",S=i.action==="regenerateSession",E=i.extras||{};return l.createElement("div",{className:"ps-modal-backdrop",onClick:d},l.createElement("div",{className:"ps-modal is-narrow",onClick:x=>x.stopPropagation()},l.createElement("div",{className:"ps-modal-header"},l.createElement("div",{className:"ps-modal-title"},n.confirm.title),l.createElement("button",{type:"button",className:"ps-modal-close",onClick:d,"aria-label":"Close",title:"Close"},"✕")),l.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},l.createElement("p",{style:{color:"#94a3b8",margin:0}},n.confirm.message)),S?l.createElement("div",{className:"ps-modal-body",style:{padding:"0 20px 12px",display:"flex",flexDirection:"column",gap:10}},l.createElement("label",{style:{color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8}},"Distillation",l.createElement("select",{className:"ps-modal-input",style:{flex:"1",padding:"4px 8px"},value:E.distillMode||"llm",onChange:x=>t.updateConfirmExtras({distillMode:x.currentTarget.value})},l.createElement("option",{value:"llm"},"Intelligent (LLM reads the whole transcript)"),l.createElement("option",{value:"deterministic"},"Fast (no LLM — tail + pointers)"))),(E.distillMode||"llm")==="llm"?l.createElement(kg,{controller:t,extras:E}):null,(E.distillMode||"llm")==="llm"?l.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:E.instructions||"",maxLength:4e3,onChange:x=>t.updateConfirmExtras({instructions:x.currentTarget.value})}):null):null,l.createElement("div",{className:"ps-modal-footer"},h?null:l.createElement("button",{type:"button",className:"ps-modal-button",onClick:d},"Cancel"),l.createElement("button",{type:"button",className:`ps-modal-button ${y?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(A.MODAL_CONFIRM).catch(()=>{})},n.confirm.confirmLabel))))}if(i.type==="themePicker"&&n.themePicker)return f(n.themePicker,"Apply Theme");const m=i.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(i.type==="modelPicker"&&n.modelPicker)return f(n.modelPicker,m);if(i.type==="reasoningEffortPicker"&&n.reasoningEffortPicker)return f(n.reasoningEffortPicker,m);if(i.type==="contextTierPicker"&&n.contextTierPicker)return f(n.contextTierPicker,m);if(i.type==="sessionAgentPicker"&&n.sessionAgentPicker)return f(n.sessionAgentPicker,"Create Session");if(i.type==="sessionGroupPicker"&&n.sessionGroupPicker)return f(n.sessionGroupPicker,"Move");if(i.type==="artifactPicker"&&n.artifactPicker)return f(n.artifactPicker,n.artifactPicker.confirmLabel||"Open / Download");if(i.type==="sessionOwnerFilter"&&n.sessionOwnerFilter){const h=n.sessionOwnerFilter,y=Array.isArray(h.rows)?h.rows:[],S=c.trim().toLowerCase(),E=w=>{const b=y?.[w];return(Array.isArray(b)?b:ve([b])[0]?.runs||[]).map(k=>k?.text||"").join("")||String(b?.text||"")},x=(i.items||[]).map((w,b)=>b).filter(w=>{if(!S)return!0;const b=(i.items||[])[w]||{};return`${E(w)} ${b.label||""} ${b.description||""}`.toLowerCase().includes(S)});return l.createElement("div",{className:"ps-modal-backdrop",onClick:d},l.createElement("div",{className:"ps-modal is-list",onClick:w=>w.stopPropagation()},l.createElement("div",{className:"ps-modal-header"},l.createElement("div",{className:"ps-modal-title"},h.title),l.createElement("button",{type:"button",className:"ps-modal-close",onClick:d,"aria-label":"Close",title:"Close"},"✕")),l.createElement("input",{className:"ps-modal-input ps-modal-search",value:c,placeholder:"Search people…",autoFocus:!0,onChange:w=>u(w.currentTarget.value),onKeyDown:w=>{w.key==="Escape"&&c&&(w.stopPropagation(),u(""))}}),l.createElement("div",{className:"ps-modal-grid"},l.createElement("div",{ref:a,className:"ps-modal-list"},x.length===0?l.createElement("div",{className:"ps-empty-state"},`No one matches "${c}".`):null,x.map(w=>(b=>l.createElement("button",{key:b.id||w,type:"button",className:`ps-list-button ps-modal-list-button${w===i.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(w)},l.createElement("div",{className:"ps-line ps-modal-list-line"},l.createElement(Ae,{runs:Array.isArray(y?.[w])?y[w]:ve([y?.[w]])[0]?.runs||[{text:y?.[w]?.text||"",color:y?.[w]?.color}],theme:s}))))((i.items||[])[w]||{}))),l.createElement("div",{className:"ps-modal-details"},l.createElement("div",{className:"ps-modal-details-title"},h.detailsTitle||"Details"),ve(h.detailsLines||[]).map((w,b)=>l.createElement(Te,{key:`detail:${b}`,line:w,theme:s,className:"ps-modal-detail-line"})))),l.createElement("div",{className:"ps-modal-footer"},l.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:d},"Done"))))}if(i.type==="renameSession"&&n.renameSession)return l.createElement("div",{className:"ps-modal-backdrop",onClick:d},l.createElement("div",{className:"ps-modal is-narrow",onClick:h=>h.stopPropagation()},l.createElement("div",{className:"ps-modal-header"},l.createElement("div",{className:"ps-modal-title"},n.renameSession.title),l.createElement("button",{type:"button",className:"ps-modal-close",onClick:d,"aria-label":"Close",title:"Close"},"✕")),l.createElement("input",{ref:r,className:"ps-modal-input",value:n.renameSession.value,placeholder:n.renameSession.placeholder,onChange:h=>t.setRenameSessionValue(h.currentTarget.value,h.currentTarget.selectionStart??h.currentTarget.value.length),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),t.handleCommand(A.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),l.createElement("div",{className:"ps-modal-details"},ve(n.renameSession.helpLines||[]).map((h,y)=>l.createElement(Te,{key:`help:${y}`,line:h,theme:s,className:"ps-modal-detail-line"}))),l.createElement("div",{className:"ps-modal-footer"},l.createElement("button",{type:"button",className:"ps-modal-button",onClick:d},"Cancel"),l.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(A.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(i.type==="sessionGroupName"&&n.sessionGroupName)return l.createElement("div",{className:"ps-modal-backdrop",onClick:d},l.createElement("div",{className:"ps-modal is-narrow",onClick:h=>h.stopPropagation()},l.createElement("div",{className:"ps-modal-header"},l.createElement("div",{className:"ps-modal-title"},n.sessionGroupName.title),l.createElement("button",{type:"button",className:"ps-modal-close",onClick:d,"aria-label":"Close",title:"Close"},"✕")),l.createElement("input",{ref:o,className:"ps-modal-input",value:n.sessionGroupName.value,placeholder:n.sessionGroupName.placeholder,onChange:h=>t.setSessionGroupNameValue(h.currentTarget.value,h.currentTarget.selectionStart??h.currentTarget.value.length),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),t.handleCommand(A.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),l.createElement("div",{className:"ps-modal-details"},ve(n.sessionGroupName.helpLines||[]).map((h,y)=>l.createElement(Te,{key:`help:${y}`,line:h,theme:s,className:"ps-modal-detail-line"}))),l.createElement("div",{className:"ps-modal-footer"},l.createElement("button",{type:"button",className:"ps-modal-button",onClick:d},"Cancel"),l.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(A.MODAL_CONFIRM).catch(()=>{})},"Create and Move"))));if(i.type==="terminatePicker"){const h=Number(i.bulkCount)>1,y=!!i.systemRestart,S=String(i.sessionTitle||"").trim()||"this session",E=Number(i.bulkCount)||0,x=h?`What should happen to the ${E} selected sessions? Choose an action; you'll be asked to confirm.`:y?`How should "${S}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${S}"? Choose an action; you'll be asked to confirm.`,w=b=>()=>{t.pickTerminateAction(b).catch(()=>{})};return l.createElement("div",{className:"ps-modal-backdrop",onClick:d},l.createElement("div",{className:"ps-modal is-narrow",onClick:b=>b.stopPropagation()},l.createElement("div",{className:"ps-modal-header"},l.createElement("div",{className:"ps-modal-title"},i.title||"Session Lifecycle"),l.createElement("button",{type:"button",className:"ps-modal-close",onClick:d,"aria-label":"Close",title:"Close"},"✕")),l.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},l.createElement("p",{style:{color:"#94a3b8",margin:0}},x)),l.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},i.canRegenerate?l.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:w("regenerate")},"Regenerate Context"):null,l.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:w("complete")},h?`Mark ${E} Completed`:y?"Complete & Restart":"Mark Completed"),l.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:w("cancel")},h?`Cancel ${E} Sessions`:y?"Terminate & Restart":"Cancel Session"),l.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:w("delete")},h?`Hard Delete ${E} Sessions`:y?"Hard Delete & Restart":"Delete Session")),l.createElement("div",{className:"ps-modal-footer"},l.createElement("button",{type:"button",className:"ps-modal-button",onClick:d},"Close"))))}if(i.type==="artifactUpload"&&n.artifactUpload)return l.createElement("div",{className:"ps-modal-backdrop",onClick:d},l.createElement("div",{className:"ps-modal is-narrow",onClick:h=>h.stopPropagation()},l.createElement("div",{className:"ps-modal-header"},l.createElement("div",{className:"ps-modal-title"},n.artifactUpload.title),l.createElement("button",{type:"button",className:"ps-modal-close",onClick:d,"aria-label":"Close",title:"Close"},"✕")),l.createElement("input",{className:"ps-modal-input",value:n.artifactUpload.value,placeholder:n.artifactUpload.placeholder,onChange:h=>t.setArtifactUploadValue(h.currentTarget.value,h.currentTarget.selectionStart||h.currentTarget.value.length),autoFocus:!0}),l.createElement("div",{className:"ps-modal-details"},ve(n.artifactUpload.helpLines||[]).map((h,y)=>l.createElement(Te,{key:`help:${y}`,line:h,theme:s,className:"ps-modal-detail-line"}))),l.createElement("div",{className:"ps-modal-footer"},l.createElement("button",{type:"button",className:"ps-modal-button",onClick:d},"Cancel"),l.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(A.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const g=i.type==="logFilter"?n.logFilter:i.type==="filesFilter"?n.filesFilter:i.type==="historyFormat"?n.historyFormat:null;return g?l.createElement("div",{className:"ps-modal-backdrop",onClick:d},l.createElement("div",{className:"ps-modal is-wide",onClick:h=>h.stopPropagation()},l.createElement("div",{className:"ps-modal-header"},l.createElement("div",{className:"ps-modal-title"},g.title),l.createElement("button",{type:"button",className:"ps-modal-close",onClick:d,"aria-label":"Close",title:"Close"},"✕")),l.createElement("div",{className:"ps-filter-grid"},(i.items||[]).map((h,y)=>{const S=i.type==="filesFilter"?n.filesFilterState?.[h.id]||h.options?.[0]?.id:i.type==="historyFormat"?n.historyFormatState:n.logsFilter?.[h.id]||h.options?.[0]?.id;return l.createElement("div",{key:h.id||y,className:"ps-filter-column"},l.createElement("div",{className:"ps-filter-title"},h.label),(h.options||[]).map(E=>l.createElement("button",{key:E.id,type:"button",className:`ps-filter-option${E.id===S?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:y}),i.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:E.id}):i.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[h.id]:E.id}}),t.ensureFilesForScope(E.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[h.id]:E.id}})}},E.label)))})),l.createElement("div",{className:"ps-modal-footer"},l.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:d},"Done")))):null}function kg({controller:t,extras:e}){const s=Array.isArray(e.distillerModelOptions)?e.distillerModelOptions:[],n=s.find(u=>u.qualifiedName===e.distillerModel)||null,i=n?.supportedReasoningEfforts||[],r=n?.supportedContextTiers||[],o={color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8},a={flex:"1",padding:"4px 8px"},c=u=>t.updateConfirmExtras(u);return l.createElement(l.Fragment,null,l.createElement("label",{style:o},"Distiller model",l.createElement("select",{className:"ps-modal-input",style:a,value:e.distillerModel||"",onChange:u=>c({distillerModel:u.currentTarget.value,distillerEffort:"",distillerContextTier:""})},l.createElement("option",{value:""},"Deployment default"),s.map(u=>l.createElement("option",{key:u.qualifiedName,value:u.qualifiedName},u.qualifiedName)))),i.length>0?l.createElement("label",{style:o},"Reasoning",l.createElement("select",{className:"ps-modal-input",style:a,value:e.distillerEffort||"",onChange:u=>c({distillerEffort:u.currentTarget.value})},l.createElement("option",{value:""},"Model default"),i.map(u=>l.createElement("option",{key:u,value:u},u)))):null,r.length>0?l.createElement("label",{style:o},"Context",l.createElement("select",{className:"ps-modal-input",style:a,value:e.distillerContextTier||"",onChange:u=>c({distillerContextTier:u.currentTarget.value})},l.createElement("option",{value:""},"Model default"),r.map(u=>l.createElement("option",{key:u,value:u},u==="long_context"?"long context (fits a larger transcript)":u)))):null)}function Ag(t,e){l.useEffect(()=>{const s=n=>{const i=n.target,r=i instanceof HTMLElement&&(i.tagName==="TEXTAREA"||i.tagName==="INPUT"||i.tagName==="SELECT"||i.isContentEditable),o=t.getState().ui.modal,a=vi(t),c=t.getState().ui.inspectorTab,u=t.getState().ui.focusRegion,p=!n.metaKey&&!n.ctrlKey&&!n.altKey,d=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="T"&&n.shiftKey,f=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="N"&&n.shiftKey,m=g=>{const h=Rh(a,c,g);t.selectInspectorTab(h).catch(()=>{})};if(!r&&d){n.preventDefault(),t.handleCommand(A.OPEN_THEME_PICKER).catch(()=>{});return}if(!r&&f){n.preventDefault(),t.handleCommand(A.OPEN_MODEL_PICKER).catch(()=>{});return}if(o&&!r){if(n.key==="Escape"||o.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(A.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||o.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(A.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(A.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(A.MODAL_PANE_NEXT).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(A.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(A.MODAL_NEXT).catch(()=>{}));return}if(!r){if(n.key==="r"&&p&&u!=="prompt"){n.preventDefault(),t.handleCommand(A.REFRESH).catch(()=>{});return}if(u==="chat"&&n.key==="s"&&p){n.preventDefault(),t.handleCommand(A.TOGGLE_CHAT_VIEW).catch(()=>{});return}if(n.key==="n"&&p){n.preventDefault(),t.handleCommand(A.NEW_SESSION).catch(()=>{});return}if(u==="inspector"&&c==="files"&&(n.key==="u"&&p||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(A.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="a"&&p){n.preventDefault(),t.handleCommand(A.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="x"&&p){n.preventDefault(),t.handleCommand(A.DELETE_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="o"&&p){n.preventDefault(),t.handleCommand(A.OPEN_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(A.OPEN_FILES_FILTER).catch(()=>{});return}if(u==="inspector"&&c==="stats"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(A.TOGGLE_STATS_VIEW).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="v"&&p){n.preventDefault(),t.handleCommand(A.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(u==="inspector"&&c==="logs"&&n.key==="t"&&p){n.preventDefault(),t.handleCommand(A.TOGGLE_LOG_TAIL).catch(()=>{});return}if(u==="inspector"&&c==="logs"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(A.OPEN_LOG_FILTER).catch(()=>{});return}if(u==="inspector"&&c==="history"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(A.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(u==="inspector"&&c==="history"&&n.key==="r"&&p){n.preventDefault(),t.handleCommand(A.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(u==="inspector"&&c==="history"&&n.key==="a"&&p){n.preventDefault(),t.handleCommand(A.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&p){n.preventDefault(),t.handleCommand(A.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&p){n.preventDefault(),t.handleCommand(A.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&p){n.preventDefault(),t.handleCommand(A.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&p){n.preventDefault(),t.handleCommand(A.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(A.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&p&&u==="inspector"){n.preventDefault(),m(1);return}if(n.key==="["&&p){n.preventDefault(),t.handleCommand(A.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&p){n.preventDefault(),t.handleCommand(A.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&p){n.preventDefault(),t.handleCommand(A.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&p){n.preventDefault(),t.handleCommand(A.GROW_SESSION_PANE).catch(()=>{});return}if(u==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),m(-1);return}if(u==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),m(1);return}if(u==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(A.MOVE_SESSION_UP).catch(()=>{});return}if(u==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(A.MOVE_SESSION_DOWN).catch(()=>{});return}if(u==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(A.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(u==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(A.PAGE_UP).catch(()=>{});return}if(u==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(A.PAGE_DOWN).catch(()=>{});return}if(u==="sessions"&&n.key==="t"&&p){n.preventDefault(),t.handleCommand(A.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(A.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(A.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&p){n.preventDefault(),t.handleCommand(A.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(A.SCROLL_BOTTOM).catch(()=>{});return}if(u!=="prompt"&&n.key==="h"&&p){n.preventDefault(),t.handleCommand(A.FOCUS_LEFT).catch(()=>{});return}if(u!=="prompt"&&n.key==="l"&&p){n.preventDefault(),t.handleCommand(A.FOCUS_RIGHT).catch(()=>{});return}if(!e&&u==="inspector"&&c==="files"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(A.MOVE_FILE_UP).catch(()=>{});return}if(!e&&u==="inspector"&&c==="files"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(A.MOVE_FILE_DOWN).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(A.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(A.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(A.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function Cg(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 Tg({controller:t,mobile:e=!1}){const s=Z(t,Ud,He),n=l.useRef(null),i=s.packages||{},r=s.section==="packages",o=s.section==="workers",[a,c]=l.useState(()=>{const M={wsWidth:440,treePct:44,navWidth:240};try{return{...M,...JSON.parse(window.localStorage.getItem("ps-admin-ws-layout")||"{}")}}catch{return M}}),u=l.useCallback(M=>{c(B=>{const O={...B,...M};O.wsWidth=Math.min(900,Math.max(300,Math.round(O.wsWidth))),O.treePct=Math.min(85,Math.max(15,O.treePct)),O.navWidth=Math.min(420,Math.max(170,Math.round(O.navWidth??240)));try{window.localStorage.setItem("ps-admin-ws-layout",JSON.stringify(O))}catch{}return O})},[]),p=l.useCallback(M=>{M.preventDefault(),document.body.style.cursor="col-resize";const B=M.clientX,O=a.navWidth??240,_=W=>u({navWidth:O+(W.clientX-B)}),L=()=>{window.removeEventListener("pointermove",_),window.removeEventListener("pointerup",L),window.removeEventListener("pointercancel",L),document.body.style.cursor=""};window.addEventListener("pointermove",_),window.addEventListener("pointerup",L),window.addEventListener("pointercancel",L)},[a.navWidth,u]);l.useEffect(()=>{if(s.ghcpKey.editing){const M=window.requestAnimationFrame(()=>{n.current&&n.current.focus()});return()=>window.cancelAnimationFrame(M)}},[s.ghcpKey.editing]);const d=l.useCallback(()=>{t.closeAdminConsole()},[t]),f=l.useCallback(()=>{t.refreshAdminProfile().catch(()=>{})},[t]),m=l.useCallback(()=>{t.beginAdminEditGhcpKey()},[t]),g=l.useCallback(()=>{t.cancelAdminEditGhcpKey()},[t]),h=l.useCallback(()=>{t.clearAdminGhcpKey().catch(()=>{})},[t]),y=l.useCallback(M=>{M.preventDefault(),t.saveAdminGhcpKey().catch(()=>{})},[t]),S=l.useCallback(M=>{t.setAdminGhcpKeyDraft(M.target.value)},[t]),E=Cg(s.principal),x=l.createElement("header",{className:"ps-admin-console__header"},l.createElement("h2",null,"Admin Console"),l.createElement("span",{className:"ps-admin-console__who"},E),l.createElement("button",{type:"button",className:"ps-mini-button",onClick:d},"Close")),w=l.createElement(Og,{view:s,draftRef:n,onBeginEdit:m,onCancelEdit:g,onClear:h,onSubmit:y,onDraftChange:S,onRefresh:f,controller:t}),b=l.createElement(Ng,{controller:t,view:s}),I=l.createElement(Mg,{controller:t,view:s}),k=r&&i.selectedName?l.createElement(Pg,{controller:t,view:s,layout:a,onLayout:u}):null,P=i.addDialog?.open?l.createElement(Rg,{controller:t,dialog:i.addDialog}):null;if(e){let M;return r&&i.selectedName?M=l.createElement("div",{className:"ps-admin-mobile-stack"},l.createElement("button",{type:"button",className:"ps-mini-button ps-admin-back",onClick:()=>t.selectAdminPackage(null)},"← All packages"),I,k):r?M=b:o?M=l.createElement("div",{className:"ps-admin-mobile-stack"},b,l.createElement(xo,{controller:t,view:s})):M=l.createElement("div",{className:"ps-admin-mobile-stack"},b,w),l.createElement("div",{className:"ps-admin-console is-mobile"},x,s.loadError?l.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,M,P)}return l.createElement("div",{className:"ps-admin-console is-workspace"},x,s.loadError?l.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,l.createElement("div",{className:"ps-admin-workspace",style:k?{gridTemplateColumns:`${a.navWidth}px minmax(0, 1fr) minmax(0, ${a.wsWidth}px)`}:{gridTemplateColumns:`${a.navWidth}px minmax(0, 1fr)`}},l.createElement("div",{className:"ps-admin-nav"},b,l.createElement("div",{className:"ps-admin-nav__resize",onPointerDown:p,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings column"})),l.createElement("div",{className:"ps-admin-main"},r?I:o?l.createElement(xo,{controller:t,view:s}):w),k),P)}function xo({controller:t,view:e}){const s=e.workers||{},n=s.rows||[],i=s.counts||{};return l.useEffect(()=>{const r=window.setInterval(()=>{t.refreshAdminWorkers()},25e3);return()=>window.clearInterval(r)},[t]),l.createElement("div",{className:"ps-admin-detail ps-admin-workers"},l.createElement("div",{className:"ps-admin-workers__head"},l.createElement("h3",null,"Workers"),s.summaryText?l.createElement("span",{className:"ps-admin-workers__summary"},`${s.summaryText}${i.pools>1?` · ${i.pools} pools`:""}${i.draining?` · ${i.draining} draining`:""}`):null,l.createElement("button",{type:"button",className:"ps-mini-button",disabled:!!s.loading,onClick:()=>t.refreshAdminWorkers()},s.loading?"Refreshing…":"Refresh")),s.error?l.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.error):null,s.empty?l.createElement("p",{className:"ps-admin-console__hint"},"No workers registered. Workers appear here on their first heartbeat and self-prune after an hour of silence."):l.createElement("div",{className:"ps-admin-workers__scroll"},l.createElement("table",{className:"ps-admin-workers__table"},l.createElement("thead",null,l.createElement("tr",null,["Worker","Pool","Phase","Heartbeat","Uptime","RSS","Sessions","Loop p99","Packages","SDK"].map(r=>l.createElement("th",{key:r},r)))),l.createElement("tbody",null,n.map(r=>l.createElement("tr",{key:r.id,className:r.live?"is-live":"is-stale"},l.createElement("td",{className:"ps-admin-workers__id",title:r.owner?`owner: ${r.owner}`:void 0},l.createElement("span",{className:`ps-worker-dot${r.live?" is-live":""}`}),r.id,r.substrate&&r.substrate!=="kubernetes"?l.createElement("span",{className:"ps-admin-workers__substrate"},r.substrate):null),l.createElement("td",null,r.pool),l.createElement("td",null,l.createElement("span",{className:`ps-worker-phase is-${r.phase}`},r.phase)),l.createElement("td",null,r.agoText),l.createElement("td",null,r.uptimeText??"—"),l.createElement("td",null,r.rssText??"—"),l.createElement("td",null,r.sessions??"—"),l.createElement("td",null,r.eventLoopText??"—"),l.createElement("td",{title:r.pkgEpoch!=null?`epoch ${r.pkgEpoch}`:void 0},r.pkgText??"—"),l.createElement("td",null,r.sdkVersion??"—")))))))}function Ng({controller:t,view:e}){const s=e.packages||{};return l.createElement("nav",{className:"ps-admin-tree"},l.createElement("div",{className:"ps-admin-tree__label"},"Settings"),(e.settingsTree||[]).map(n=>{if(n.kind==="group")return l.createElement("div",{key:n.id,className:"ps-admin-tree__group"},`${n.label}`,l.createElement("span",{className:"ps-admin-tree__count"},String(n.count??0)));const i=n.kind==="package"?()=>t.selectAdminPackage(n.name):()=>t.setAdminSection(n.id==="agents"?"packages":n.id==="workers"?"workers":"ghcp");return l.createElement("button",{key:n.id,type:"button",className:`ps-admin-tree__row depth-${n.depth}${n.selected?" is-selected":""}${n.kind==="package"&&!n.enabled?" is-disabled":""}`,onClick:i},n.kind==="package"?n.ownerBadge?l.createElement(Vn,{badge:n.ownerBadge}):l.createElement("span",{className:"ps-scope-badge is-shared",title:"shared with the whole deployment"},"S"):null,l.createElement("span",{className:"ps-admin-tree__name"},n.label),n.kind==="package"&&n.semver?l.createElement("span",{className:"ps-admin-tree__ver"},n.semver):null)}),s.loading?l.createElement("div",{className:"ps-admin-tree__hint"},"Loading packages…"):null,s.error?l.createElement("div",{className:"ps-admin-tree__hint is-error"},s.error):null,l.createElement("button",{type:"button",className:"ps-admin-tree__add",onClick:()=>t.openAdminAddPackage()},"+ Add package"))}function Mg({controller:t,view:e}){const s=e.packages||{},n=s.detail;if(!s.selectedName)return l.createElement("div",{className:"ps-admin-detail is-empty"},l.createElement("h3",null,"Agents"),l.createElement("p",{className:"ps-admin-console__hint"},s.empty?"No agent packages yet. Add one from a GitHub/ADO repo, a tarball URL, or upload a folder — or push from a terminal with `pilotswarm agents push ./my-agents`.":"Select a package from the tree to see its detail, versions, and files."));const i=()=>{window.confirm(`Delete ${n.name}? Every version and its artifacts are removed. Live sessions using its agents will fail on their next turn.`)&&t.runAdminPackageAction("delete")},r=(a,c)=>()=>t.runAdminPackageAction(a,c),o=n.actionPending;return l.createElement("div",{className:"ps-admin-detail"},n.error?l.createElement("div",{className:"ps-admin-console__error",role:"alert"},`Package load failed: ${n.error}`):null,n.loading?l.createElement("p",{className:"ps-admin-console__hint"},"Loading package…"):null,l.createElement("div",{className:"ps-admin-detail__head"},l.createElement("h3",null,n.name),l.createElement("span",{className:`ps-scope-badge is-${n.scope}`},n.scope),n.enabled?null:l.createElement("span",{className:"ps-scope-badge is-off"},"disabled")),n.description?l.createElement("p",{className:"ps-admin-detail__desc"},n.description):null,l.createElement("dl",{className:"ps-admin-detail__meta"},l.createElement("dt",null,"Version"),l.createElement("dd",null,n.activeSemver?`${n.activeSemver} · sha ${n.activeSha12||"?"} · ${n.sizeText}`:"no active version"),n.fleet?[l.createElement("dt",{key:"fk"},"Fleet"),l.createElement("dd",{key:"fv",className:"is-ok"},n.fleet.text)]:null,l.createElement("dt",null,"Created"),l.createElement("dd",null,`${n.createdBy||"unknown"} · ${n.createdAtText}`)),n.agents.length?l.createElement("div",null,l.createElement("div",{className:"ps-admin-detail__label"},"Agents in this package"),l.createElement("div",{className:"ps-admin-detail__chips"},n.agents.map(a=>l.createElement("span",{key:a.name,className:"ps-agent-chip",title:a.description},a.name,a.toolCount?l.createElement("i",null,` · ${a.toolCount} tools`):null)))):null,n.versions.length?l.createElement("div",null,l.createElement("div",{className:"ps-admin-detail__label"},"Versions"),l.createElement("div",{className:"ps-admin-versions"},n.versions.map(a=>l.createElement("div",{key:a.semver,className:`ps-admin-version${a.active?" is-active":""}`},l.createElement("b",null,a.semver),l.createElement("span",null,a.sha12),l.createElement("span",null,a.dateText),a.active?l.createElement("span",{className:"is-ok"},"● active"):n.canManage?l.createElement("button",{type:"button",className:"ps-mini-button",onClick:r("pin",a.semver),disabled:!!o},"Pin"):null)))):null,n.canManage?l.createElement("div",{className:"ps-admin-detail__actions"},n.source?l.createElement("button",{type:"button",className:"ps-primary-button",onClick:r("sync"),disabled:!!o},o==="sync"?"Syncing…":"Sync now"):null,l.createElement("button",{type:"button",className:"ps-primary-button",onClick:()=>t.openAdminUpdatePackage(n.name,n.scope),disabled:!!o,title:`Publish a new version of ${n.name} from a repo folder`},"Update"),l.createElement("button",{type:"button",className:"ps-mini-button",onClick:r(n.scope==="shared"?"demote":"promote"),disabled:!!o},n.scope==="shared"?"Demote to user":"Promote to shared"),l.createElement("button",{type:"button",className:"ps-mini-button",onClick:r(n.enabled?"disable":"enable"),disabled:!!o},n.enabled?"Disable":"Enable"),l.createElement("button",{type:"button",className:"ps-mini-button is-danger",onClick:i,disabled:!!o},"Delete")):l.createElement("p",{className:"ps-admin-console__hint"},"Read-only: only the package creator or an admin can modify it."),n.actionError?l.createElement("div",{className:"ps-admin-console__error",role:"alert"},n.actionError):null)}function Pg({controller:t,view:e,layout:s=null,onLayout:n=null}){const i=Z(t,d=>d.ui.themeId),r=Be(i),o=e.packages?.workspace,a=l.useRef(null),c=l.useCallback((d,f)=>{if(!n)return;d.preventDefault();const m=d.clientX,g=d.clientY,h={...s},y=E=>f(h,E.clientX-m,E.clientY-g),S=()=>{window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",S),window.removeEventListener("pointercancel",S),document.body.style.cursor=""};window.addEventListener("pointermove",y),window.addEventListener("pointerup",S),window.addEventListener("pointercancel",S)},[s,n]),u=l.useCallback(d=>{document.body.style.cursor="col-resize",c(d,(f,m)=>n({wsWidth:f.wsWidth-m}))},[c,n]),p=l.useCallback(d=>{document.body.style.cursor="row-resize";const f=a.current?.getBoundingClientRect().height||600;c(d,(m,g,h)=>n({treePct:m.treePct+h/f*100}))},[c,n]);return o?l.createElement("div",{className:"ps-admin-ws",ref:a,style:s?{gridTemplateRows:`auto minmax(80px, ${s.treePct}%) auto minmax(0, 1fr)`}:void 0},n?l.createElement("div",{className:"ps-admin-ws__vdivider",title:"Drag to resize the workspace",onPointerDown:u}):null,l.createElement("div",{className:"ps-admin-ws__head"},`Package workspace${o.semver?` · ${e.packages.selectedName}@${o.semver}`:""}`),l.createElement("div",{className:"ps-admin-ws__tree"},o.loading?l.createElement("div",{className:"ps-admin-tree__hint"},"Loading files…"):null,o.error?l.createElement("div",{className:"ps-admin-tree__hint is-error"},o.error):null,o.treeRows.map(d=>l.createElement("button",{key:`${d.type}:${d.path}`,type:"button",style:{paddingLeft:`${8+(d.depth||0)*16}px`},className:`ps-admin-ws__row is-${d.type}${d.selected?" is-selected":""}`,onClick:d.type==="dir"?()=>t.toggleAdminPackageDir(d.path):()=>t.selectAdminPackageFile(d.path)},l.createElement("span",{className:"ps-admin-ws__caret"},d.type==="dir"?d.expanded?"▾":"▸":""),l.createElement("span",{className:"ps-admin-ws__name"},d.label),d.sizeText?l.createElement("span",{className:"ps-admin-ws__size"},d.sizeText):null))),l.createElement("div",{className:`ps-admin-ws__preview-head${n?" is-resizable":""}`,title:n?"Drag to resize file list vs preview":void 0,onPointerDown:n?p:void 0},o.selectedPath?`Preview · ${o.selectedPath}`:"Preview"),l.createElement("div",{className:"ps-admin-ws__preview"},o.fileLoading?l.createElement("div",{className:"ps-admin-tree__hint"},"Loading…"):null,o.fileError?l.createElement("div",{className:"ps-admin-tree__hint is-error"},o.fileError):null,o.file?o.file.isBinary?l.createElement("div",{className:"ps-admin-tree__hint"},`Binary file · ${o.file.sizeText}`):l.createElement($g,{file:o.file,theme:r}):null)):null}function _g(t){const e=/^---\n([\s\S]*?)\n---\n?/.exec(t||"");if(!e)return{meta:null,body:t||""};const s=e[1].split(`
99
- `).map(n=>/^([A-Za-z0-9_-]+):\s*(.*)$/.exec(n)).filter(Boolean).map(([,n,i])=>({key:n,value:i}));return s.length===0?{meta:null,body:t||""}:{meta:s,body:(t||"").slice(e[0].length)}}function $g({file:t,theme:e}){const s=t.language||"text",n=t.truncated?l.createElement("div",{className:"ps-admin-tree__hint"},"… truncated preview"):null;if(s==="markdown"){const{meta:i,body:r}=_g(t.text||"");return l.createElement("div",{className:"ps-admin-ws__doc"},i?l.createElement("div",{className:"ps-admin-ws__frontmatter"},i.map(o=>l.createElement("div",{key:o.key,className:"ps-admin-ws__fm-row"},l.createElement("span",{className:"ps-admin-ws__fm-key"},o.key),l.createElement("span",{className:"ps-admin-ws__fm-val"},o.value)))):null,l.createElement(Vs,{content:r,theme:e}),n)}if(s==="json"){let i=t.text||"";if(!t.truncated)try{i=JSON.stringify(JSON.parse(i),null,2)}catch{}return l.createElement("div",{className:"ps-admin-ws__doc"},l.createElement("pre",{className:"ps-admin-ws__code lang-json"},l.createElement("code",null,es(i,"json",e))),n)}return l.createElement("div",{className:"ps-admin-ws__doc"},l.createElement("pre",{className:`ps-admin-ws__code lang-${s}`},l.createElement("code",null,es(t.text||"",s,e))),n)}function Rg({controller:t,dialog:e}){const s=Z(t,d=>d.docs?.agentPackageGuideUrl||null),n=d=>f=>t.setAdminAddPackageField(d,f.target.value),i=[["repo","GitHub / Azure DevOps"],["upload","Upload folder"]],r=e.kind==="repo"||e.kind==="github"||e.kind==="ado",o=l.useRef(null),[a,c]=l.useState(!1),u=2*1024*1024,p=d=>{if(d.preventDefault(),!(a||e.submitting)){if(e.kind==="upload"){const f=o.current;if(!f?.files?.length){t.failAdminAddPackage("Choose a package folder first.");return}const m=[...f.files].map(h=>({file:h,path:h.webkitRelativePath.split("/").slice(1).join("/")||h.name})).filter(({path:h})=>h&&!h.split("/").includes("node_modules")&&!h.split("/").includes(".git")),g=m.reduce((h,{file:y})=>h+y.size,0);if(m.length===0){t.failAdminAddPackage("The chosen folder has no uploadable files.");return}if(g>u){t.failAdminAddPackage(`Folder is ${(g/(1024*1024)).toFixed(1)} MB after filtering — the upload envelope is 2 MB. Use a repo/URL source or 'pilotswarm agents push' for larger packages.`);return}c(!0),Promise.all(m.map(({file:h,path:y})=>new Promise((S,E)=>{const x=new FileReader;x.onerror=()=>E(new Error(`could not read ${y}`)),x.onload=()=>S({path:y,contentBase64:String(x.result).split(",",2)[1]||""}),x.readAsDataURL(h)}))).then(h=>t.submitAdminUploadPackage(h,e.scope)).catch(h=>t.failAdminAddPackage(h?.message||"Could not read the chosen folder.")).finally(()=>c(!1));return}t.submitAdminAddPackage().catch(()=>{})}};return l.createElement("div",{className:"ps-modal-backdrop",onClick:()=>t.closeAdminAddPackage()},l.createElement("form",{className:"ps-modal ps-admin-add",onClick:d=>d.stopPropagation(),autoComplete:"off",onSubmit:p},l.createElement("div",{className:"ps-modal-header"},l.createElement("span",null,e.updateName?`Update ${e.updateName}`:"Add agent package"),l.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage()},"✕")),l.createElement("div",{className:"ps-admin-add__body"},l.createElement("div",{className:"ps-admin-add__tabs"},i.map(([d,f])=>l.createElement("button",{key:d,type:"button",className:`ps-admin-add__tab${e.kind===d?" is-on":""}`,onClick:()=>t.setAdminAddPackageField("kind",d)},f))),r?[l.createElement("label",{key:"u",className:"ps-admin-add__field"},"Link to plugin.json (or the folder containing it)",l.createElement("input",{value:e.repoUrl,onChange:n("repoUrl"),placeholder:"https://github.com/org/repo/blob/main/my-agents/plugin.json",autoFocus:!0,type:"url",name:"agent-package-link",autoComplete:"off",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true"})),l.createElement("div",{key:"h",className:"ps-admin-add__hint"},"Paste the browser URL — branch and path are read from the link. The files are read by THIS BROWSER with your access (public GitHub needs nothing; Azure DevOps uses your signed-in account) and uploaded as a package artifact."),l.createElement("label",{key:"t",className:"ps-admin-add__field"},"PAT (only for private GitHub repos, or to override — used here, never stored)",l.createElement("input",{type:"password",value:e.authToken,onChange:n("authToken"),name:"agent-package-pat",autoComplete:"new-password","data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true"}))]:l.createElement("label",{className:"ps-admin-add__field"},"Package folder with plugin.json — the manifest (≤ 2 MB; node_modules skipped)",l.createElement("input",{ref:o,type:"file",webkitdirectory:"",directory:"",multiple:!0})),l.createElement("div",{className:"ps-admin-add__scope"},l.createElement("label",null,l.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="shared",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","shared")})," Shared — everyone can use it"),l.createElement("label",null,l.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="user",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","user")})," User — only you see it")),e.updateName?l.createElement("p",{className:"ps-admin-console__hint"},`Publishes a new version of ${e.updateName}. Its scope is unchanged — use Demote/Promote on the package to move it.`):null,s?l.createElement("p",{className:"ps-admin-console__hint"},"New to this? ",l.createElement("a",{href:s,target:"_blank",rel:"noreferrer noopener"},"How to build an agent package")," — a complete guide you can also hand straight to Claude or Copilot."):null,l.createElement("p",{className:"ps-admin-console__hint"},"Same thing from a terminal: pilotswarm agents push ./my-agents --shared"),e.progress&&!e.error?l.createElement("p",{className:"ps-admin-add__progress"},e.progress):null,e.error?l.createElement("pre",{className:"ps-admin-add__error",role:"alert"},e.error):null),l.createElement("div",{className:"ps-modal-footer"},l.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage(),disabled:e.submitting},"Cancel"),l.createElement("button",{type:"submit",className:"ps-primary-button",disabled:e.submitting||a},a?"Reading folder…":e.submitting?"Importing…":e.updateName?"Import & update":"Import & publish"))))}function Og({view:t,draftRef:e,onBeginEdit:s,onCancelEdit:n,onClear:i,onSubmit:r,onDraftChange:o,onRefresh:a,controller:c}){return l.createElement("section",{className:"ps-admin-console__section"},l.createElement("h3",null,"GitHub Copilot key"),t.ghcpKey.storeAsSystem?l.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."):l.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."),t.isAdmin&&t.systemGhcpKey.supported?l.createElement("label",{className:"ps-admin-console__system-toggle"},l.createElement("input",{type:"checkbox",checked:t.ghcpKey.storeAsSystem,disabled:t.ghcpKey.saving,onChange:u=>c.setAdminGhcpKeyStoreAsSystem(u.target.checked)}),"Store as System key"):null,l.createElement("p",{className:`ps-admin-console__status${t.ghcpKey.error?" is-error":""}`},t.ghcpKey.error||t.ghcpKey.statusText),t.ghcpKey.editing?l.createElement("form",{className:"ps-admin-console__form",onSubmit:r},l.createElement("input",{ref:e,type:"password",autoComplete:"off",spellCheck:!1,value:t.ghcpKey.draft,disabled:t.ghcpKey.saving,placeholder:"Paste GitHub Copilot key",onChange:o}),l.createElement("div",{className:"ps-admin-console__actions"},l.createElement("button",{type:"submit",className:"ps-primary-button",disabled:t.ghcpKey.saving},t.ghcpKey.saving?"Saving...":"Save"),l.createElement("button",{type:"button",className:"ps-mini-button",onClick:n,disabled:t.ghcpKey.saving},"Cancel"))):l.createElement("div",{className:"ps-admin-console__actions"},l.createElement("button",{type:"button",className:"ps-primary-button",onClick:s},t.ghcpKey.targetConfigured?t.ghcpKey.storeAsSystem?"Replace System key":"Replace key":t.ghcpKey.storeAsSystem?"Set System key":"Set key"),t.ghcpKey.targetConfigured?l.createElement("button",{type:"button",className:"ps-mini-button",onClick:i},t.ghcpKey.storeAsSystem?"Clear System key":"Clear key"):null,l.createElement("button",{type:"button",className:"ps-mini-button",onClick:a},t.loading?"Refreshing...":"Refresh")))}function Fg({transport:t,mode:e="remote",branding:s=null,docs:n=null}={}){Kh();const i=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches,r=hf(ff,_n({mode:e,branding:s,docs:n,chatViewMode:i?"transcript":"rich"}));return new lh({store:r,transport:t})}function Bg({controller:t}){const e=Z(t,N=>!!Be(N.ui.themeId)?.richChat);l.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-rich-ui",e),()=>document.body.classList.remove("ps-rich-ui")},[e]);const s=l.useRef(null),n=l.useRef(null),i=no(s),r=no(n),o=Zh(i);l.useEffect(()=>{const N=()=>{const z=document.createElement("span");z.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const Q=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");Q&&(z.style.font=window.getComputedStyle(Q).font),z.textContent="0".repeat(100),(Q?.parentElement||document.body).appendChild(z);const pe=z.getBoundingClientRect().width/100||8;z.remove(),t.dispatch({type:"ui/viewport",width:Math.floor(window.innerWidth/pe),height:Math.floor(window.innerHeight/Qe)})};N();let F;const U=()=>{clearTimeout(F),F=setTimeout(N,150)};return window.addEventListener("resize",U),window.addEventListener("orientationchange",U),()=>{clearTimeout(F),window.removeEventListener("resize",U),window.removeEventListener("orientationchange",U)}},[t]);const[a,c]=l.useState(!1),[u,p]=l.useState(null),d=Z(t,N=>({themeId:N.ui.themeId,ownerFilter:N.sessions.ownerFilter,pinnedIds:N.sessions.pinnedIds,manualOrder:N.sessions.manualOrder,collapsedSessionIds:N.sessions.collapsedIds,activeSessionId:N.sessions.activeSessionId||null,promptRows:al(N),chatViewMode:N.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(N.sessions.activeSessionId&&N.sessions.byId[N.sessions.activeSessionId]?.isGroup),paneAdjust:N.ui.layout?.paneAdjust??0,sessionPaneAdjust:N.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:N.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:N.ui.layout?.activityPaneAdjust??0,focusRegion:N.ui.focusRegion,inspectorTab:N.ui.inspectorTab,filesFullscreen:!!N.files.fullscreen,selectedArtifactId:N.files.selectedArtifactId||null,adminVisible:!!N.admin?.visible}),He),f=l.useRef(!1),m=l.useRef(null),g=l.useRef(null),h=l.useRef(null),y=l.useRef(null),S=l.useRef(!1),E=l.useRef(!1),x=l.useRef(null),w=l.useRef(null),[b,I]=l.useState("workspace"),k=(i.width||window.innerWidth||0)<xh,M=d.activeSessionIsGroup||d.chatViewMode==="summary"?0:d.promptRows;Ag(t,k),l.useEffect(()=>{t.setViewport(o)},[t,o.height,o.width]),l.useEffect(()=>{let N=!0;f.current=!1,m.current=null,x.current=null,w.current=eo(t.getState()),h.current&&(clearTimeout(h.current),h.current=null),y.current&&(clearInterval(y.current),y.current=null),S.current=!1,E.current=!1;const F=t.transport;if(typeof F?.getCurrentUserProfile!="function"||typeof F?.setCurrentUserProfileSettings!="function")return f.current=!0,()=>{N=!1};const U=async()=>{if(!(!N||S.current)){S.current=!0;try{const z=await F.getCurrentUserProfile();if(!N)return;const Q=pt(z?.profileSettings);Zt(Q[Ls()])&&(g.current=Q[Ls()]),w.current=eo(t.getState(),g.current);const pe=qh(z?.profileSettings,w.current),Se=JSON.stringify(pe),$e=xn(t.getState(),g.current),K=JSON.stringify($e),xe=f.current&&m.current!=null&&K!==m.current,Ve=!!h.current||E.current||xe;if(!Ve&&x.current!==Se&&(t.dispatch({type:"profileSettings/apply",settings:pe}),x.current=Se),!f.current||!Ve){const mt=xn(t.getState(),g.current);m.current=JSON.stringify(mt)}f.current=!0}catch{if(!N)return;f.current=!0}finally{S.current=!1}}};return U().catch(()=>{}),y.current=setInterval(()=>{U().catch(()=>{})},Th),()=>{N=!1,h.current&&(clearTimeout(h.current),h.current=null),y.current&&(clearInterval(y.current),y.current=null),S.current=!1}},[t]),l.useEffect(()=>{if(!f.current)return;const N=xn(d,g.current),F=JSON.stringify(N);m.current!==F&&(m.current=F,h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,E.current=!0,zh(t,N).catch(()=>{}).finally(()=>{E.current=!1})},400))},[t,d.activeSessionId,d.activityPaneAdjust,d.chatViewMode,d.collapsedSessionIds,d.ownerFilter,d.paneAdjust,d.manualOrder,d.pinnedIds,d.portalSessionColumnAdjust,d.sessionPaneAdjust,d.themeId]),l.useEffect(()=>{Jh(d.themeId)},[d.themeId]);const B=l.useRef(null);l.useEffect(()=>{const N=B.current;B.current=d.focusRegion,N!==null&&N!==d.focusRegion&&k&&d.focusRegion!=="prompt"&&I(d.focusRegion==="activity"?"activity":d.focusRegion==="inspector"?"inspector":"workspace")},[k,d.focusRegion]),l.useEffect(()=>{const N=vi(t);!N.includes(d.inspectorTab)&&N.length>0&&t.selectInspectorTab(N[0]).catch(()=>{})},[t,d.inspectorTab]);const O=l.useMemo(()=>Xt(o,d.paneAdjust,M,d.sessionPaneAdjust,d.activityPaneAdjust),[o,d.activityPaneAdjust,d.paneAdjust,M,d.sessionPaneAdjust]),_=d.filesFullscreen&&d.inspectorTab==="files",L=d.inspectorTab==="files"&&!!d.selectedArtifactId&&!_;l.useEffect(()=>{!_||!a||(c(!1),p(null))},[a,_]);const W=l.useCallback(()=>{c(N=>{const F=!N;return F?t.setFocus("chat"):p(null),F})},[t]),Y=l.useCallback(N=>{p(F=>{const U=F===N?null:N;return t.setFocus(U||"chat"),U})},[t]),te=Math.max(0,(i.width||0)*.68),ne=r.width||te,Pe=Yh(ne,d.portalSessionColumnAdjust),ee=Xh(Pe),ye=ee==="hidden"?"0px":`clamp(0px, calc(${Ei*100}% + ${Number(d.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,v=l.createElement("div",{className:"ps-workspace-grid",style:{gridTemplateColumns:`minmax(0, ${O.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${O.rightWidth}fr)`}},l.createElement("div",{ref:n,className:`ps-workspace-main-grid is-session-${ee}`,style:{gridTemplateColumns:`${ye} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},ee!=="hidden"?l.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},l.createElement(Ti,{controller:t,structuredRows:!0})):null,l.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},l.createElement(Ig,{controller:t,portalSessionColumnAdjust:d.portalSessionColumnAdjust})),l.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},l.createElement(Ni,{controller:t}))),l.createElement(wg,{controller:t,paneAdjust:d.paneAdjust}),l.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`${O.inspectorPaneHeight}fr var(--ps-resizer-track, 16px) ${O.activityPaneHeight}fr`}},l.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},O.inspectorHidden?null:l.createElement(Yt,{controller:t,mobile:!1})),l.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},l.createElement(xg,{controller:t,activityPaneAdjust:d.activityPaneAdjust})),l.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},L?l.createElement(Mi,{controller:t,focused:!1,previewOnly:!0}):O.activityHidden?null:l.createElement(qn,{controller:t})))),$=l.createElement(gg,{controller:t,openPane:u,onTogglePane:Y,onExitFocus:W,mobile:k}),H=l.createElement("div",{className:"ps-workspace-full"},l.createElement(Yt,{controller:t,mobile:!1}));let C=null;return _&&!k?C=l.createElement("div",{className:"ps-mobile-pane-fill"},l.createElement(Yt,{controller:t,mobile:!0})):b==="inspector"?C=l.createElement("div",{className:"ps-mobile-pane-fill"},l.createElement(Yt,{controller:t,mobile:!0})):b==="activity"?C=l.createElement("div",{className:"ps-mobile-pane-fill"},l.createElement(qn,{controller:t})):C=l.createElement(hg,{controller:t}),l.createElement(hl.Provider,{value:t},l.createElement("div",{ref:s,className:"ps-web-shell"},k&&(a||b==="inspector"||b==="activity")?null:l.createElement(bg,{controller:t,mobile:k,chatFocusMode:a,onToggleChatFocus:W,chatFocusDisabled:_}),l.createElement("div",{className:"ps-workspace"},d.adminVisible?l.createElement(Tg,{controller:t,mobile:k}):_?H:a?$:k?C:v),k&&!a?l.createElement(Eg,{activePane:b,setActivePane:I,controller:t}):null,k&&_?l.createElement(fg,{controller:t}):null,l.createElement(vg,{controller:t})))}export{Bg as P,l as R,Za as _,Ll as a,Wd as b,Fg as c,_l as g,Eo as r,Lg as s};