pilotswarm 0.5.32 → 0.5.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/tui/src/app.js +10 -0
- package/tui/src/node-sdk-transport.js +11 -0
- package/ui/core/src/controller.js +381 -12
- package/ui/core/src/reducer.js +125 -28
- package/ui/core/src/selectors.js +158 -268
- package/ui/core/src/state.js +6 -1
- package/ui/core/src/themes/catppuccin-mocha.js +2 -1
- package/ui/core/src/themes/cobalt2.js +2 -1
- package/ui/core/src/themes/doom.js +2 -1
- package/ui/core/src/themes/dracula.js +2 -1
- package/ui/core/src/themes/github-dark.js +2 -1
- package/ui/core/src/themes/github-light.js +2 -1
- package/ui/core/src/themes/gruvbox-dark.js +2 -1
- package/ui/core/src/themes/hacker-x-matrix.js +2 -1
- package/ui/core/src/themes/hacker-x-orion-prime.js +2 -1
- package/ui/core/src/themes/helpers.js +22 -4
- package/ui/core/src/themes/high-contrast-mono.js +2 -1
- package/ui/core/src/themes/index.js +24 -5
- package/ui/core/src/themes/ms-dos.js +2 -1
- package/ui/core/src/themes/noctis-obscuro.js +2 -1
- package/ui/core/src/themes/noctis.js +2 -1
- package/ui/core/src/themes/rust.js +125 -0
- package/ui/core/src/themes/spongebob.js +110 -0
- package/ui/core/src/themes/terminal-green.js +2 -1
- package/ui/core/src/themes/win95.js +2 -1
- package/ui/core/src/themes/winamp.js +2 -1
- package/ui/core/src/themes/workspace-dark.js +2 -1
- package/ui/react/src/web-app.js +240 -266
- package/web/dist/assets/{abnfDiagram-VRR7QNED-mXFQ4a3c.js → abnfDiagram-VRR7QNED-BFOimVWK.js} +1 -1
- package/web/dist/assets/{arc-BPuuvbge.js → arc-uUHjvwEo.js} +1 -1
- package/web/dist/assets/{architectureDiagram-ZJ3FMSHR-Dt4uUYIe.js → architectureDiagram-ZJ3FMSHR-CxeX_vea.js} +1 -1
- package/web/dist/assets/{blockDiagram-677ZJIJ3-Ax8Q22vV.js → blockDiagram-677ZJIJ3-Cno8kltG.js} +1 -1
- package/web/dist/assets/{c4Diagram-LMCZKHZV-CPiukyHt.js → c4Diagram-LMCZKHZV-viONVybf.js} +1 -1
- package/web/dist/assets/channel-IURmSsjn.js +1 -0
- package/web/dist/assets/{chunk-2Q5K7J3B-VJLqCZJX.js → chunk-2Q5K7J3B-CKfICIGD.js} +1 -1
- package/web/dist/assets/{chunk-32BRIVSS-DqOshxhf.js → chunk-32BRIVSS-CxmwEY56.js} +1 -1
- package/web/dist/assets/{chunk-5VM5RSS4-KPqV21jV.js → chunk-5VM5RSS4-_eVYLGll.js} +1 -1
- package/web/dist/assets/{chunk-EX3LRPZG-DfhiCVl_.js → chunk-EX3LRPZG-C4aqbjrf.js} +1 -1
- package/web/dist/assets/{chunk-JWPE2WC7-H6khJPuW.js → chunk-JWPE2WC7-Bh8ZxrI8.js} +1 -1
- package/web/dist/assets/{chunk-MOJQB5TN-BKMAzQxj.js → chunk-MOJQB5TN-BXgLlWVP.js} +1 -1
- package/web/dist/assets/{chunk-RYQCIY6F-DNXRTxtj.js → chunk-RYQCIY6F-B1rMIdfF.js} +1 -1
- package/web/dist/assets/{chunk-V7JOEXUC-B56PM6Gv.js → chunk-V7JOEXUC-C3AnSHXk.js} +1 -1
- package/web/dist/assets/{chunk-VR4S4FIN-Boi3hGkB.js → chunk-VR4S4FIN-CeoMJIBs.js} +1 -1
- package/web/dist/assets/{chunk-XXDRQBXY-DmJyn890.js → chunk-XXDRQBXY-DzaxQ9iP.js} +1 -1
- package/web/dist/assets/classDiagram-OUVF2IWQ-FsfpM3iu.js +1 -0
- package/web/dist/assets/classDiagram-v2-EOCWNBFH-FsfpM3iu.js +1 -0
- package/web/dist/assets/{cose-bilkent-JH36ORCC-BRdFlFWt.js → cose-bilkent-JH36ORCC-G46fvUOx.js} +1 -1
- package/web/dist/assets/{cynefin-VYW2F7L2-DqE-xib2.js → cynefin-VYW2F7L2-DXwqVhWA.js} +1 -1
- package/web/dist/assets/{cynefinDiagram-TSTJHNR4-D-QBZjIL.js → cynefinDiagram-TSTJHNR4-DNNFmaXb.js} +1 -1
- package/web/dist/assets/{dagre-VKFMJZFB-DYu9oQV6.js → dagre-VKFMJZFB-BCfh-h3o.js} +1 -1
- package/web/dist/assets/{diagram-FQU43EPY-DOwYccCg.js → diagram-FQU43EPY-CyG9b6bj.js} +1 -1
- package/web/dist/assets/{diagram-G47NLZAW-DTSEmrPr.js → diagram-G47NLZAW-DdxDahK3.js} +1 -1
- package/web/dist/assets/{diagram-NH7WQ7WH-OqbzzquA.js → diagram-NH7WQ7WH-CjrZ_eja.js} +1 -1
- package/web/dist/assets/{diagram-OA4YK3LP-BMVG6A8I.js → diagram-OA4YK3LP-5NAjQpk2.js} +1 -1
- package/web/dist/assets/{diagram-WEI45ONY-Rn2Q5xaz.js → diagram-WEI45ONY-fLuDb54-.js} +1 -1
- package/web/dist/assets/{ebnfDiagram-CCIWWBDH-aL32_v5y.js → ebnfDiagram-CCIWWBDH-DL9qnZpa.js} +1 -1
- package/web/dist/assets/{erDiagram-Q63AITRT-DKCpyczx.js → erDiagram-Q63AITRT-C_ynfrWY.js} +1 -1
- package/web/dist/assets/{flowDiagram-23GEKE2U-CrZTPgR_.js → flowDiagram-23GEKE2U-dYuH8HYv.js} +1 -1
- package/web/dist/assets/{ganttDiagram-NO4QXBWP-DnSE1OtC.js → ganttDiagram-NO4QXBWP-e8Meh3f3.js} +1 -1
- package/web/dist/assets/{gitGraphDiagram-IHSO6WYX-C5SeYPUR.js → gitGraphDiagram-IHSO6WYX-D_tZ4VL9.js} +1 -1
- package/web/dist/assets/index-Ct7SQv1M.css +1 -0
- package/web/dist/assets/{index-B-TEKrRB.js → index-DcQes9h8.js} +6 -6
- package/web/dist/assets/{infoDiagram-FWYZ7A6U-DDnJZp0X.js → infoDiagram-FWYZ7A6U-Dffhqp73.js} +1 -1
- package/web/dist/assets/{ishikawaDiagram-FXEZZL3T-ewhzfFkq.js → ishikawaDiagram-FXEZZL3T-DYt9H7kU.js} +1 -1
- package/web/dist/assets/{journeyDiagram-5HDEW3XC-T0iWWkLM.js → journeyDiagram-5HDEW3XC-Qv1vVu0F.js} +1 -1
- package/web/dist/assets/{kanban-definition-HUTT4EX6-D1MFQZjb.js → kanban-definition-HUTT4EX6-CTAUo40G.js} +1 -1
- package/web/dist/assets/{linear-BKfPK9wE.js → linear-CqLsWFLj.js} +1 -1
- package/web/dist/assets/{mermaid.core-CyzD7dTc.js → mermaid.core-okRCGPQQ.js} +4 -4
- package/web/dist/assets/{mindmap-definition-LN4V7U3C-CWXtcTlP.js → mindmap-definition-LN4V7U3C-DVOOrIwD.js} +1 -1
- package/web/dist/assets/{papaparse.min-DLUoV5k5.js → papaparse.min-Ddflu8oC.js} +1 -1
- package/web/dist/assets/{pegDiagram-2B236MQR-BFjZun-r.js → pegDiagram-2B236MQR-BLJlC0MZ.js} +1 -1
- package/web/dist/assets/{pieDiagram-ENE6RG2P-DMDtW4g7.js → pieDiagram-ENE6RG2P-DdOwICOg.js} +1 -1
- package/web/dist/assets/pilotswarm-CKh2MxfL.js +99 -0
- package/web/dist/assets/{quadrantDiagram-ABIIQ3AL-CAwPVaYL.js → quadrantDiagram-ABIIQ3AL-B0Th1YO5.js} +1 -1
- package/web/dist/assets/{railroadDiagram-RFXS5EU6-Co102PkQ.js → railroadDiagram-RFXS5EU6-BF2XKMKf.js} +1 -1
- package/web/dist/assets/{requirementDiagram-TGXJPOKE-D19VlRSl.js → requirementDiagram-TGXJPOKE-Mr1iSwbS.js} +1 -1
- package/web/dist/assets/{sankeyDiagram-HTMAVEWB-Sd_a3ukL.js → sankeyDiagram-HTMAVEWB-CrOjVZyg.js} +1 -1
- package/web/dist/assets/{sequenceDiagram-DBY2YBRQ-CojDRK1c.js → sequenceDiagram-DBY2YBRQ-H0X4Lydk.js} +1 -1
- package/web/dist/assets/{sizeCapture-X5ZJPWSS-XqXcxnDo.js → sizeCapture-X5ZJPWSS-Dus1QEqh.js} +1 -1
- package/web/dist/assets/{stateDiagram-2N3HPSRC-BcN_w699.js → stateDiagram-2N3HPSRC-BOBUSwdR.js} +1 -1
- package/web/dist/assets/stateDiagram-v2-6OUMAXLB-DABTDwFh.js +1 -0
- package/web/dist/assets/{swimlanes-5IMT3BWC-BcO6ai_I.js → swimlanes-5IMT3BWC-BoqT-Lh7.js} +2 -2
- package/web/dist/assets/swimlanesDiagram-G3AALYLV-BF5mFN4t.js +8 -0
- package/web/dist/assets/{timeline-definition-FHXFAJF6-DOPfYxUq.js → timeline-definition-FHXFAJF6-BOrqUQHX.js} +1 -1
- package/web/dist/assets/{vennDiagram-L72KCM5P-BSKLkEOC.js → vennDiagram-L72KCM5P-DDkNL-Oo.js} +1 -1
- package/web/dist/assets/{wardleyDiagram-EHGQE667-BdcYAVw2.js → wardleyDiagram-EHGQE667-XUAJQ2X0.js} +1 -1
- package/web/dist/assets/{xychartDiagram-FW5EYKEG-C6EJT4jB.js → xychartDiagram-FW5EYKEG-ph69PV9y.js} +1 -1
- package/web/dist/index.html +3 -3
- package/ui/core/src/themes/dark-high-contrast.js +0 -56
- package/ui/core/src/themes/workspace-dark-rich.js +0 -65
- package/web/dist/assets/channel-BCzDctYg.js +0 -1
- package/web/dist/assets/classDiagram-OUVF2IWQ-ChqjVZil.js +0 -1
- package/web/dist/assets/classDiagram-v2-EOCWNBFH-ChqjVZil.js +0 -1
- package/web/dist/assets/index-D2B5bzSN.css +0 -1
- package/web/dist/assets/pilotswarm-DA0u7Cq_.js +0 -99
- package/web/dist/assets/stateDiagram-v2-6OUMAXLB-BV_w1D3C.js +0 -1
- package/web/dist/assets/swimlanesDiagram-G3AALYLV-BnYdP0qP.js +0 -8
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
function Vl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var nn={exports:{}},q={};var zi;function ql(){if(zi)return q;zi=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"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),u=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),f=Symbol.iterator;function h(v){return v===null||typeof v!="object"?null:(v=f&&v[f]||v["@@iterator"],typeof v=="function"?v:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,S={};function y(v,O,G){this.props=v,this.context=O,this.refs=S,this.updater=G||m}y.prototype.isReactComponent={},y.prototype.setState=function(v,O){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,O,"setState")},y.prototype.forceUpdate=function(v){this.updater.enqueueForceUpdate(this,v,"forceUpdate")};function w(){}w.prototype=y.prototype;function x(v,O,G){this.props=v,this.context=O,this.refs=S,this.updater=G||m}var I=x.prototype=new w;I.constructor=x,g(I,y.prototype),I.isPureReactComponent=!0;var E=Array.isArray;function b(){}var k={H:null,A:null,T:null,S:null},M=Object.prototype.hasOwnProperty;function N(v,O,G){var L=G.ref;return{$$typeof:t,type:v,key:O,ref:L!==void 0?L:null,props:G}}function B(v,O){return N(v.type,O,v.props)}function _(v){return typeof v=="object"&&v!==null&&v.$$typeof===t}function P(v){var O={"=":"=0",":":"=2"};return"$"+v.replace(/[=:]/g,function(G){return O[G]})}var j=/\/+/g;function K(v,O){return typeof v=="object"&&v!==null&&v.key!=null?P(""+v.key):O.toString(36)}function z(v){switch(v.status){case"fulfilled":return v.value;case"rejected":throw v.reason;default:switch(typeof v.status=="string"?v.then(b,b):(v.status="pending",v.then(function(O){v.status==="pending"&&(v.status="fulfilled",v.value=O)},function(O){v.status==="pending"&&(v.status="rejected",v.reason=O)})),v.status){case"fulfilled":return v.value;case"rejected":throw v.reason}}throw v}function se(v,O,G,L,R){var C=typeof v;(C==="undefined"||C==="boolean")&&(v=null);var H=!1;if(v===null)H=!0;else switch(C){case"bigint":case"string":case"number":H=!0;break;case"object":switch(v.$$typeof){case t:case e:H=!0;break;case u:return H=v._init,se(H(v._payload),O,G,L,R)}}if(H)return R=R(v),H=L===""?"."+K(v,0):L,E(R)?(G="",H!=null&&(G=H.replace(j,"$&/")+"/"),se(R,O,G,"",function(le){return le})):R!=null&&(_(R)&&(R=B(R,G+(R.key==null||v&&v.key===R.key?"":(""+R.key).replace(j,"$&/")+"/")+H)),O.push(R)),1;H=0;var Q=L===""?".":L+":";if(E(v))for(var Y=0;Y<v.length;Y++)L=v[Y],C=Q+K(L,Y),H+=se(L,O,G,C,R);else if(Y=h(v),typeof Y=="function")for(v=Y.call(v),Y=0;!(L=v.next()).done;)L=L.value,C=Q+K(L,Y++),H+=se(L,O,G,C,R);else if(C==="object"){if(typeof v.then=="function")return se(z(v),O,G,L,R);throw O=String(v),Error("Objects are not valid as a React child (found: "+(O==="[object Object]"?"object with keys {"+Object.keys(v).join(", ")+"}":O)+"). If you meant to render a collection of children, use an array instead.")}return H}function ne(v,O,G){if(v==null)return v;var L=[],R=0;return se(v,L,"","",function(C){return O.call(G,C,R++)}),L}function ve(v){if(v._status===-1){var O=v._result;O=O(),O.then(function(G){(v._status===0||v._status===-1)&&(v._status=1,v._result=G)},function(G){(v._status===0||v._status===-1)&&(v._status=2,v._result=G)}),v._status===-1&&(v._status=0,v._result=O)}if(v._status===1)return v._result.default;throw v._result}var oe=typeof reportError=="function"?reportError:function(v){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var O=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(O))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",v);return}console.error(v)},be={map:ne,forEach:function(v,O,G){ne(v,function(){O.apply(this,arguments)},G)},count:function(v){var O=0;return ne(v,function(){O++}),O},toArray:function(v){return ne(v,function(O){return O})||[]},only:function(v){if(!_(v))throw Error("React.Children.only expected to receive a single React element child.");return v}};return q.Activity=p,q.Children=be,q.Component=y,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,O,G){if(v==null)throw Error("The argument must be a React element, but you passed "+v+".");var L=g({},v.props),R=v.key;if(O!=null)for(C in O.key!==void 0&&(R=""+O.key),O)!M.call(O,C)||C==="key"||C==="__self"||C==="__source"||C==="ref"&&O.ref===void 0||(L[C]=O[C]);var C=arguments.length-2;if(C===1)L.children=G;else if(1<C){for(var H=Array(C),Q=0;Q<C;Q++)H[Q]=arguments[Q+2];L.children=H}return N(v.type,R,L)},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,O,G){var L,R={},C=null;if(O!=null)for(L in O.key!==void 0&&(C=""+O.key),O)M.call(O,L)&&L!=="key"&&L!=="__self"&&L!=="__source"&&(R[L]=O[L]);var H=arguments.length-2;if(H===1)R.children=G;else if(1<H){for(var Q=Array(H),Y=0;Y<H;Y++)Q[Y]=arguments[Y+2];R.children=Q}if(v&&v.defaultProps)for(L in H=v.defaultProps,H)R[L]===void 0&&(R[L]=H[L]);return N(v,C,R)},q.createRef=function(){return{current:null}},q.forwardRef=function(v){return{$$typeof:l,render:v}},q.isValidElement=_,q.lazy=function(v){return{$$typeof:u,_payload:{_status:-1,_result:v},_init:ve}},q.memo=function(v,O){return{$$typeof:d,type:v,compare:O===void 0?null:O}},q.startTransition=function(v){var O=k.T,G={};k.T=G;try{var L=v(),R=k.S;R!==null&&R(G,L),typeof L=="object"&&L!==null&&typeof L.then=="function"&&L.then(b,oe)}catch(C){oe(C)}finally{O!==null&&G.types!==null&&(O.types=G.types),k.T=O}},q.unstable_useCacheRefresh=function(){return k.H.useCacheRefresh()},q.use=function(v){return k.H.use(v)},q.useActionState=function(v,O,G){return k.H.useActionState(v,O,G)},q.useCallback=function(v,O){return k.H.useCallback(v,O)},q.useContext=function(v){return k.H.useContext(v)},q.useDebugValue=function(){},q.useDeferredValue=function(v,O){return k.H.useDeferredValue(v,O)},q.useEffect=function(v,O){return k.H.useEffect(v,O)},q.useEffectEvent=function(v){return k.H.useEffectEvent(v)},q.useId=function(){return k.H.useId()},q.useImperativeHandle=function(v,O,G){return k.H.useImperativeHandle(v,O,G)},q.useInsertionEffect=function(v,O){return k.H.useInsertionEffect(v,O)},q.useLayoutEffect=function(v,O){return k.H.useLayoutEffect(v,O)},q.useMemo=function(v,O){return k.H.useMemo(v,O)},q.useOptimistic=function(v,O){return k.H.useOptimistic(v,O)},q.useReducer=function(v,O,G){return k.H.useReducer(v,O,G)},q.useRef=function(v){return k.H.useRef(v)},q.useState=function(v){return k.H.useState(v)},q.useSyncExternalStore=function(v,O,G){return k.H.useSyncExternalStore(v,O,G)},q.useTransition=function(){return k.H.useTransition()},q.version="19.2.4",q}var Vi;function Go(){return Vi||(Vi=1,nn.exports=ql()),nn.exports}var Yl=Go();const a=Vl(Yl);var rn={exports:{}},xe={};var qi;function Xl(){if(qi)return xe;qi=1;var t=Go();function e(c){var d="https://react.dev/errors/"+c;if(1<arguments.length){d+="?args[]="+encodeURIComponent(arguments[1]);for(var u=2;u<arguments.length;u++)d+="&args[]="+encodeURIComponent(arguments[u])}return"Minified React error #"+c+"; visit "+d+" 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,d,u){var p=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:p==null?null:""+p,children:c,containerInfo:d,implementation:u}}var o=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,d){if(c==="font")return"";if(typeof d=="string")return d==="use-credentials"?d:""}return xe.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,xe.createPortal=function(c,d){var u=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d||d.nodeType!==1&&d.nodeType!==9&&d.nodeType!==11)throw Error(e(299));return r(c,d,null,u)},xe.flushSync=function(c){var d=o.T,u=n.p;try{if(o.T=null,n.p=2,c)return c()}finally{o.T=d,n.p=u,n.d.f()}},xe.preconnect=function(c,d){typeof c=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,n.d.C(c,d))},xe.prefetchDNS=function(c){typeof c=="string"&&n.d.D(c)},xe.preinit=function(c,d){if(typeof c=="string"&&d&&typeof d.as=="string"){var u=d.as,p=l(u,d.crossOrigin),f=typeof d.integrity=="string"?d.integrity:void 0,h=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;u==="style"?n.d.S(c,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:p,integrity:f,fetchPriority:h}):u==="script"&&n.d.X(c,{crossOrigin:p,integrity:f,fetchPriority:h,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},xe.preinitModule=function(c,d){if(typeof c=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var u=l(d.as,d.crossOrigin);n.d.M(c,{crossOrigin:u,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0})}}else d==null&&n.d.M(c)},xe.preload=function(c,d){if(typeof c=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var u=d.as,p=l(u,d.crossOrigin);n.d.L(c,u,{crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0,type:typeof d.type=="string"?d.type:void 0,fetchPriority:typeof d.fetchPriority=="string"?d.fetchPriority:void 0,referrerPolicy:typeof d.referrerPolicy=="string"?d.referrerPolicy:void 0,imageSrcSet:typeof d.imageSrcSet=="string"?d.imageSrcSet:void 0,imageSizes:typeof d.imageSizes=="string"?d.imageSizes:void 0,media:typeof d.media=="string"?d.media:void 0})}},xe.preloadModule=function(c,d){if(typeof c=="string")if(d){var u=l(d.as,d.crossOrigin);n.d.m(c,{as:typeof d.as=="string"&&d.as!=="script"?d.as:void 0,crossOrigin:u,integrity:typeof d.integrity=="string"?d.integrity:void 0})}else n.d.m(c)},xe.requestFormReset=function(c){n.d.r(c)},xe.unstable_batchedUpdates=function(c,d){return c(d)},xe.useFormState=function(c,d,u){return o.H.useFormState(c,d,u)},xe.useFormStatus=function(){return o.H.useHostTransitionStatus()},xe.version="19.2.4",xe}var Yi;function Ql(){if(Yi)return rn.exports;Yi=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(),rn.exports=Xl(),rn.exports}const Jl=a.createContext(null);function We(){const t=a.useContext(Jl);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function ee(t,e,s=Object.is){const n=a.useRef(e),i=a.useRef(s);n.current=e,i.current=s;const[r,o]=a.useState(()=>e(t.getState())),l=a.useRef(r);return a.useEffect(()=>{l.current=r},[r]),a.useEffect(()=>t.subscribe(c=>{const d=n.current(c);i.current(l.current,d)||(l.current=d,o(d))}),[t]),r}const Xi=[". ",".. ","..."],Qi=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function jo(t,e=120){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(r=>(r+1)%Qi.length)},e);return()=>clearInterval(i)},[t,e]),t?Qi[s]:""}function Uo(t,e=360){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(r=>(r+1)%Xi.length)},e);return()=>clearInterval(i)},[t,e]),t?Xi[s]:""}function Wo(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"},Ve=["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 bt(t,e,s){const n=t.indexOf(e),r=((n===-1?0:n)+s+t.length)%t.length;return t[r]}function ii(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 Ln(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 Zl(t){const e=ii(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function ec(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=ii(t);return e==null?null:{text:`ctx ${Ln(t.currentTokens)}/${Ln(t.tokenLimit)} ${e}%`,color:Zl(t)}}function tc(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 Ko(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function sc(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function zo(t,e,s={},n={}){if(!e)return null;const i=Ko(t)||{},r=sc(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 nc(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 ${Ln(s.tokensRemoved)}`,color:"gray"}]:[]]}const Fn=/\{(\/?)([a-z-]+)\}/g,ic={color:null,bold:!1,underline:!1},Cs=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,Ji=/session:\/\/([A-Za-z0-9-]+)/g,rc={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function Es(t){return{color:t.color,bold:t.bold,underline:t.underline}}function oc(t,e,s){const n=Es(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:rc[i]||null,n}return n}function ri(t){return String(t||"").replace(Fn,"")}function Vo(t){const e=[],n=String(t||"").split(`
|
|
2
|
+
`);for(const i of n){const r=[];let o=Es(ic),l=0,c;for(;(c=Fn.exec(i))!==null;){const[d,u,p]=c;c.index>l&&r.push({text:i.slice(l,c.index),...Es(o)}),o=oc(o,p,u==="/"),l=c.index+d.length}(l<i.length||r.length===0)&&r.push({text:i.slice(l),...Es(o)}),e.push(r),Fn.lastIndex=0}return e}function ue(t){return String(t||"").slice(0,8)}function qo(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}let on=null,an=null,ln=null,cn=null;function ac(){return on||(on=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})),on}function Yo(){return an||(an=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})),an}function lc(){return ln||(ln=new Intl.DateTimeFormat("en-GB",{month:"short"})),ln}function cc(){return cn||(cn=new Intl.DateTimeFormat("en-GB",{month:"short",day:"numeric"})),cn}function Xo(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 Yo().format(s);const i=ac().format(s),r=String(s.getDate()),o=lc().format(s),l=s.getFullYear()===e.getFullYear()?"":String(s.getFullYear()).slice(-2);return`${r}${o}${l} ${i}`}catch{return""}}function _e(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t),n=Yo().format(s);if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return n;const r=cc().format(s),o=s.getFullYear()===e.getFullYear()?"":` ${s.getFullYear()}`;return`${r}${o} ${n}`}catch{return""}}function Ct(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 uc(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function dc(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function Ts(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function Zi(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!(Ts(i)&&Ts(n))}function pc(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!(Ts(n)&&Ts(i))}function er(t,e,s){let n=s;for(;n<t.length;){const i=t.indexOf(e,n);if(i<0)return-1;if(pc(t,i,e))return i;n=i+e.length}return-1}function fc(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 hc(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function qt(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 nt(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 Qo(t){return(t||[]).map(e=>e?.text||"").join("")}function xs(t){return Ge(Qo(t))}function mc(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 l=ls(o,i);l&&(n.push({...r,text:l}),i-=Ge(l))}return n}function Jo(t,e){const s=Math.max(0,Number(e)||0),n=mc(t,s),i=xs(n),r=Math.max(0,s-i);return r>0&&n.push({text:" ".repeat(r),color:null,bold:!1,underline:!1}),n}function Zo(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 l of t||[]){let c=String(l?.text||"");if(c)for(;c.length>0;){const d=Math.max(1,s-r),u=ls(c,d);if(!u)break;if(u.length===c.length||Ge(u)<d){i.push({...l,text:u}),r+=Ge(u),c=c.slice(u.length),r>=s&&o();continue}const p=u.lastIndexOf(" ");if(p>0&&(r>0||p>0)){const f=u.slice(0,p+1);i.push({...l,text:f}),r+=Ge(f),c=c.slice(f.length),o()}else i.push({...l,text:u}),r+=Ge(u),c=c.slice(u.length),r>=s&&o()}}return(i.length>0||n.length===0)&&o(),n}function tr(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function ea(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 gc(t){const e=String(t||"");return Cs.lastIndex=0,[...e.matchAll(Cs)].map(s=>{const n=s[1],i=ea(s[2]);return!n||!i?null:{sessionId:n,filename:i,uri:`artifact://${n}/${i}`}}).filter(Boolean)}function Tt(t){const e=String(t||"");if(!e)return e;Cs.lastIndex=0;const s=e.replace(Cs,(n,i,r,o,l)=>{if(l.slice(Math.max(0,o-2),o)==="](")return n;const c=ea(r);return!i||!c?n:`[artifact: ${c}](artifact://${i}/${c}) (press a to download)`});return Ji.lastIndex=0,s.replace(Ji,(n,i)=>i?`[session: ${ue(i)}](session://${i})`:n)}function oi(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const r=hc(e,"`",n),o="`".repeat(r),l=dc(e,o,n+r);if(l>n+r-1){nt(s,{type:"code",text:e.slice(n+r,l)}),n=l+r;continue}}if(e.startsWith("**",n)||e.startsWith("__",n)){const r=e.slice(n,n+2),o=Zi(e,n,r)?er(e,r,n+2):-1;if(o>n+2){nt(s,{type:"strong",text:e.slice(n+2,o)}),n=o+2;continue}}if(e[n]==="["){const r=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(r){nt(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);nt(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:l}=fc(e.slice(n,r));if(o){nt(s,{type:"link",text:o,href:o}),l&&nt(s,{type:"text",text:l}),n=r;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&Zi(e,n,e[n])){const r=e[n],o=er(e,r,n+1);if(o>n+1){nt(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)}nt(s,{type:"text",text:e.slice(n,i)}),n=i}return s.length>0?s:[{type:"text",text:""}]}function yc(t=""){return oi(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 Jt(t){const e=oi(t),s=[];for(const n of e){if(n.type==="code"){qt(s,n.text,{color:"cyan"});continue}if(n.type==="strong"){qt(s,n.text,{bold:!0});continue}if(n.type==="em"){qt(s,n.text,{underline:!0});continue}if(n.type==="link"){qt(s,n.text,{color:"cyan",underline:!0,href:n.href});continue}qt(s,n.text)}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function Mt(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function Nt(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 Ms(t){return t.length>0&&t.every(e=>/^:?-+:?$/.test(String(e||"").replace(/\s+/g,"")))}function Ge(t){return Array.from(String(t||"")).length}function ls(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 ta(t,e){const s=String(t||""),n=Math.max(0,e-Ge(s));return s+" ".repeat(n)}function sa(t){return Qo(Jt(t))}function Sc(t,e){const s=sa(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),i=[];let r="";const o=l=>{let c=l;for(;Ge(c)>e;){const d=ls(c,e);if(!d)break;r&&(i.push(r),r=""),i.push(d),c=c.slice(d.length)}return c};for(const l of n){const c=o(l);if(!c)continue;if(!r){r=c;continue}const d=`${r} ${c}`;Ge(d)<=e?r=d:(i.push(r),r=c)}return r&&i.push(r),i.length>0?i:[""]}function bc(t,e){const s=Math.max(1,...t.map(u=>u.length)),n=Math.max(s*3,e-(s*3+1)),i=Array.from({length:s},(u,p)=>Math.max(3,...t.map(f=>Ge(f[p]||"")))),r=Array.from({length:s},(u,p)=>Math.max(3,...t.map(f=>Math.max(0,...String(f[p]||"").split(/\s+/).filter(Boolean).map(h=>Ge(h)))))),o=Array.from({length:s},(u,p)=>Math.max(3,Math.min(Math.max(Ge(t[0]?.[p]||"")||3,r[p]),24)));if(i.reduce((u,p)=>u+p,0)<=n)return i;const c=o.slice();let d=n-c.reduce((u,p)=>u+p,0);if(d<0){const u=Math.max(3,Math.floor(n/s));return c.map((p,f)=>f===s-1?Math.max(3,n-u*(s-1)):u)}for(;d>0;){let u=0,p=-1/0;for(let f=0;f<s;f++){const h=i[f]-c[f];h>p&&(p=h,u=f)}if(p<=0){c[s-1]+=d;break}c[u]+=1,d-=1}return c}function wc(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},(h,m)=>f[m]||"")).map(f=>f.map(h=>sa(h))),r=bc(i,e),o=[],l=`┌${r.map(f=>"─".repeat(f+2)).join("┬")}┐`,c=`├${r.map(f=>"─".repeat(f+2)).join("┼")}┤`,d=`└${r.map(f=>"─".repeat(f+2)).join("┴")}┘`,u=f=>{const h=f.map((g,S)=>Sc(g,r[S])),m=Math.max(...h.map(g=>g.length));for(let g=0;g<m;g++){const S=h.map((y,w)=>ta(y[g]||"",r[w]));o.push(`│ ${S.join(" │ ")} │`)}};o.push(l),u(i[0]),o.push(c);const p=i.slice(1);for(const f of p)u(f);return o.push(d),o.join(`
|
|
3
|
+
`)}function Ic(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(!Mt(o)||!Mt(c)){n.push(o);continue}const d=Nt(o),u=Nt(c);if(!Ms(u)||d.length!==u.length){n.push(o);continue}const p=[d];for(r+=1;r+1<s.length&&Mt(s[r+1]);){r+=1;const f=Nt(s[r]);Ms(f)||p.push(f)}n.push(wc(p,e))}return n.join(`
|
|
5
|
+
`)}function Ec(t,e){const s=String(t||"");if(!s)return[""];const n=[];let i=s;for(;i.length>0;){const r=ls(i,e);if(!r)break;n.push(r),i=i.slice(r.length)}return n.length>0?n:[""]}function sr(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",i=ls(n,Math.max(1,s-4)),r=Math.max(0,s-i.length-2);return[{text:`┌${i}${"─".repeat(r)}┐`,color:"gray"}]}function nr(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function ir(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),i=[];for(const r of t){const o=Ec(r,n);for(const l of o)i.push([{text:"│",color:"gray"},{text:ta(l,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 Ft(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),i=e.tableMode==="sentinel"?"sentinel":"boxArt",o=(i==="boxArt"?Ic(String(t||""),n):String(t||"")).split(`
|
|
6
|
+
`);let l=!1,c="",d=[];for(let u=0;u<o.length;u+=1){const p=o[u],f=p.trim();if(f.startsWith("```")){l?(s.push(sr(c,Math.max(8,n))),s.push(...ir(d,Math.max(8,n))),s.push(nr(Math.max(8,n))),l=!1,c="",d=[]):(l=!0,c=f.slice(3).trim(),d=[]);continue}if(l){d.push(p);continue}if(i==="sentinel"&&p&&Mt(p)){const y=o[u+1]||"";if(Mt(y)){const w=Nt(p),x=Nt(y);if(Ms(x)&&w.length===x.length){const I=[];let E=u+2;for(;E<o.length&&Mt(o[E]);){const b=Nt(o[E]);Ms(b)||I.push(b),E+=1}s.push({kind:"markdownTable",header:w,rows:I}),u=E-1;continue}}}if(!p){s.push([{text:"",color:null}]);continue}const h=/^(#{1,6})\s+(.*)$/.exec(p);if(h){s.push([{text:h[2],color:"white",bold:!0}]);continue}const m=/^>\s?(.*)$/.exec(p);if(m){s.push([{text:"> ",color:"gray"},...Jt(m[1]).map(y=>({...y,color:y.color||"gray"}))]);continue}const g=/^\s*[-*]\s+(.*)$/.exec(p);if(g){s.push([{text:"• ",color:"gray"},...Jt(g[1])]);continue}const S=/^\s*(\d+)\.\s+(.*)$/.exec(p);if(S){s.push([{text:`${S[1]}. `,color:"gray"},...Jt(S[2])]);continue}s.push(Jt(p))}return l&&(s.push(sr(c,Math.max(8,n))),s.push(...ir(d,Math.max(8,n))),s.push(nr(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:l=!1,tableMode:c=null}={}){const d=Math.max(l?12:20,Number(n)||(l?12:20)),u=Math.max(1,d-4),p=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:i,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]];if(c==="sentinel"){const x=Ft(String(s||""),{width:u,tableMode:c}),I=o?x.map(E=>Array.isArray(E)?tr(E,o):E):x;return[{kind:"cardStart",runs:p,borderColor:r},...I,{kind:"cardEnd"},[{text:"",color:null}]]}const f=Ft(String(s||""),{width:u}),h=f.length>0?f.flatMap(x=>Zo(x,u)):[[{text:"",color:null}]],m=o?h.map(x=>tr(x,o)):h,g=m.reduce((x,I)=>Math.max(x,xs(I)),0),S=l?Math.min(d,Math.max(12,xs(p)+3,g+4)):d,y=Math.max(1,S-4),w=Math.max(0,S-xs(p)-3);return[[{text:"┌─",color:r},...p,{text:`${"─".repeat(w)}┐`,color:r}],...m.map(x=>[{text:"│ ",color:r},...Jo(x,y),{text:" │",color:r}]),[{text:`└${"─".repeat(Math.max(1,S-2))}┘`,color:r}],[{text:"",color:null}]]}function Gt(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 na(t){const e=Gt(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}const ae=300,xc=[ae,1e3,3e3,1e4],vc=["user.message","assistant.message","system.message","session.epoch_committed","session.regenerate_refused","session.regenerate_failed"];function ia(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:_e(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function ra(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:_e(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function oa(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:_e(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Be(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(ae,Number(e)||ae);return s.length>n?s.slice(-n):s}function tt(t){return String(t||"").replace(/\r\n/g,`
|
|
7
|
+
`).trim()}function rr(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 aa=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,kc=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function ai(t){return aa.test(tt(t))}function ot(t){const e=String(t||"").replace(/\r\n/g,`
|
|
8
|
+
`).trim();if(!e)return"";const s=e.replace(kc,"").trimStart();return s!==e?s.trim():ai(e)?e.replace(aa,"").trim():e}function la(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 l=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(o);if(l){i(),s.push({kind:"system",text:l[1].trim()}),r+=1;continue}const c=[o.replace(/^\s*\[SYSTEM:\s*/i,"")];let d=-1;for(let u=r+1;u<e.length;u+=1){const p=e[u];if(p.trim()==="]"){d=u;break}if(/\]\s*$/.test(p.trim())){const f=p.replace(/\]\s*$/,"");f.trim()&&c.push(f),d=u;break}c.push(p)}if(d===-1){n.push(o),r+=1;continue}i(),s.push({kind:"system",text:c.join(`
|
|
12
|
+
`).trim()}),r=d+1}return i(),s}function ca(t,e){const s=String(t||"").replace(/\r\n/g,`
|
|
13
|
+
`);return e==="user"||e==="assistant"?la(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
|
|
14
|
+
`).trim():s.trim()}function Ac(t,e){return e!=="user"&&e!=="assistant"?[]:la(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function or(t){const e=tt(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=ca(e,t.role);if(s)return s}return ot(e)}function li(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 Cc(t){return tt(ri(t)).length>0}function Tc(t){const e=tt(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 Mc(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(tt(t))}function wt(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 l=r.length;for(const c of o){const d=r.indexOf(c);d>=0&&(l=Math.min(l,d))}return r.slice(0,l).trim()}function Nc(t,e){const s=tt(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
|
+
`,l=s.indexOf(o),c=l>=0?s.slice(l+o.length).trim():s.slice(n[0].length).trim(),d=wt(r,"request_id"),u=wt(r,"from"),p=wt(r,"subject"),f=/\bexpects_response=true\b/i.test(r),h=[u?`From: session-${ue(u)}`:"",d?`Request ID: ${d}`:"",p?`Subject: ${p}`:"",f?"Response: required":"Response: not required","",c].filter((m,g)=>g===4||String(m||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:h.join(`
|
|
19
|
+
`),time:_e(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,l=s.slice(i[0].length).trim().replace(o,"").trim(),c=wt(r,"request_id"),d=wt(r,"from"),u=wt(r,"verdict")||"answered",p=[d?`From: session-${ue(d)}`:"",c?`Request ID: ${c}`:"",`Verdict: ${u}`,"",l].filter((f,h)=>h===3||String(f||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:p.join(`
|
|
20
|
+
`),time:_e(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 Pc(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&Tc(s)?"system":e}function _c(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 Rc(t,e){if(!t||!e||t.role!==e.role)return!1;const s=or(t),n=or(e);if(!s||!n||s!==n)return!1;const i=_c(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 Pt(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!Rc(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 l=Math.min(Number(n?.firstDeliveredAt||i||1/0),Number(s?.firstDeliveredAt||r||1/0));e[e.length-1]={...o,redelivered:!0,...Number.isFinite(l)?{firstDeliveredAt:l}:{}};continue}e[e.length-1]=o}return e}function $c(t){return typeof t=="string"?t.replace(/^\[FROM:[^\]\n]*\]\n?/,""):t}function _t(t,e){const s=jt(t),n=Nc(t,s);if(n)return n;const i=$c(ca(s,e));if(!Cc(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,l=Array.isArray(t?.data?.attachments)?t.data.attachments.filter(c=>c&&typeof c.filename=="string"&&c.filename):[];return{id:`${t.sessionId}:${t.seq}`,role:Pc(t,e,i),text:i,time:_e(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...r.length>0?{clientMessageIds:r}:{},...o?{sender:o}:{},...l.length>0?{attachments:l}:{}}}function ua(t){return t?.eventType!=="system.message"?!1:!Mc(jt(t))}function Ns(t,e){return Ac(jt(t),e).map((s,n)=>rs({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function Oc(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=tt(e.text),n=li(e.text),i=n?tt(n.answer):"";let r=!1;return t.filter(o=>{if(r||!o?.optimistic||o.role!==e.role)return!0;const l=tt(o.text);return l!==s&&l!==i?!0:(r=!0,!1)})}function jt(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 uc(e)}function Lc(t){return(t||[]).map(e=>e?.text||"").join("")}function Fc(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function ci(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 Bc(t,e=""){return ci([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function Dc(t,e=""){return ci([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function Hc(t,e=""){const s=jt(t),n=ot(e);return ci([ot(s),n,t?.data?.detail,t?.data?.message])}function Gc(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 jc(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}=${Gc(r)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function ui(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function de(t,e,s,n="",i="white"){return[...ui(t),{text:e,color:s},...n?[{text:` ${n}`,color:i}]:[]]}function Uc(t,e=96){return Fc(ri(jt(t)),e)||""}function un(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,l=e?.data?.durableSessionId,c=jc(r,o),d=s==="start"?"▶":s==="partial"?"…":"✓",u=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...ui(t),{text:`${d} ${r}${c}`,color:u},...l?[{text:` [sess ${ue(l)}]`,color:"gray"}]:[]]}function rs(t){const e=_e(t.createdAt),s=Uc(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=un(e,t,"start");break;case"tool.execution_complete":n=un(e,t,"complete");break;case"tool.execution_partial_result":n=un(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=de(e,"[tool]","cyan",`${r} ${o}`,"white");break}case"assistant.reasoning":n=de(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=de(e,"[intent]","gray",r||"…","white");break}case"assistant.turn_start":n=de(e,"[turn start]","gray",s);break;case"session.turn_completed":n=de(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=de(e,"[lossy handoff]","yellow",Dc(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=de(e,"[dehydrated]","cyan",Bc(t,s));break;case"session.hydrated":case"session.rehydrated":n=de(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=de(e,"[wait]","yellow",`${i}${o}${r}`.trim());break}case"session.input_required_started":n=de(e,"[input]","yellow",s);break;case"session.agent_spawned":n=de(e,"[spawn]","cyan",t?.data?.agentId||ue(t?.data?.childSessionId),"white");break;case"session.cron_started":n=de(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=de(e,"[cron]","magenta",`scheduled${t?.data?.nextFireAt?` ${rr(t.data.nextFireAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_fired":n=de(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=de(e,"[cron]","magenta",`fired${t?.data?.scheduledAt?` ${rr(t.data.scheduledAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_cancelled":case"session.cron_at_cancelled":n=de(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=de(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=de(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=de(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.compaction_start":case"session.compaction_complete":n=nc(e,t.eventType,t.data||{});break;case"session.error":n=de(e,"[error]","red",s||"session error","white");break;case"system.message":ai(jt(t))?n=de(e,"[rehydrated]","green",Hc(t,s)||"conversation preserved"):n=de(e,"[system]","gray",s||"system message");break;default:n=[...ui(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:Lc(n),line:n}}function Wc(t=ae){const e=Math.max(ae,Number(t)||ae);return xc.find(n=>n>e)||Math.min(1e5,e*2)}function fs(t=[],e={}){const s=Math.max(ae,Number(e.requestedLimit??e.eventLimit??ae)||ae),n=[],i=[],r=[];for(const o of t){if(r.push(o),o.eventType==="user.message"){i.push(...Ns(o,"user"));const c=_t(o,"user");c&&n.push(c);continue}if(o.eventType==="assistant.message"){i.push(...Ns(o,"assistant"));const c=_t(o,"assistant");c&&n.push(c);continue}if(o.eventType==="system.message"){if(ua(o)){const c=rs(o);c&&i.push(c)}else{const c=_t(o,"system");c&&n.push(c)}continue}if(o.eventType==="session.epoch_committed"){n.push(ia(o));continue}if(o.eventType==="session.regenerate_refused"){n.push(ra(o));continue}if(o.eventType==="session.regenerate_failed"){n.push(oa(o));continue}const l=rs(o);l&&i.push(l)}return{chat:Pt(n),activity:i,events:r.slice(-s),loadedEventLimit:s,loadedEventCount:r.length,hasOlderEvents:r.length>=s}}function ar(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max(ae,Number(t?.loadedEventLimit??ae)||ae),i=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),r={chat:Be(t?.chat||[],n),activity:Be(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 l=Array.isArray(e?.data?.clientMessageIds)?e.data.clientMessageIds.filter(c=>typeof c=="string"&&c):[];if(l.length>0){const c=new Set([...r.stoppedMessageIds,...l]);r.stoppedMessageIds=Array.from(c),r.chat=r.chat.map(d=>Array.isArray(d.clientMessageIds)&&d.clientMessageIds.some(u=>c.has(u))?{...d,stopped:!0}:d)}return r}if(e.eventType==="user.message"){r.activity.push(...Ns(e,"user")),r.activity=Be(r.activity,n);const l=_t(e,"user");return l&&(Array.isArray(l.clientMessageIds)&&l.clientMessageIds.some(c=>r.stoppedMessageIds.includes(c))&&(l.stopped=!0),r.chat=Oc(r.chat,l),r.chat.push(l),r.chat=Be(Pt(r.chat),n)),r}if(e.eventType==="assistant.message"){r.activity.push(...Ns(e,"assistant")),r.activity=Be(r.activity,n);const l=_t(e,"assistant");return l&&(r.chat.push(l),r.chat=Be(Pt(r.chat),n)),r}if(e.eventType==="system.message"){if(ua(e)){const l=rs(e);l&&(r.activity.push(l),r.activity=Be(r.activity,n))}else{const l=_t(e,"system");if(!l)return r;r.chat.push(l),r.chat=Be(Pt(r.chat),n)}return r}if(e.eventType==="session.epoch_committed")return r.chat.push(ia(e)),r.chat=Be(r.chat,n),r;if(e.eventType==="session.regenerate_refused")return r.chat.push(ra(e)),r.chat=Be(r.chat,n),r;if(e.eventType==="session.regenerate_failed")return r.chat.push(oa(e)),r.chat=Be(r.chat,n),r;const o=rs(e);return o&&(r.activity.push(o),r.activity=Be(r.activity,n)),r}function dn(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?Gt(e,t?.title||"PilotSwarm"):e?.title||t?.title||"PilotSwarm",l="{gray-fg}Start interacting with this session to replace the splash screen.{/gray-fg}";return[{id:`splash:${o}`,role:"system",text:`${n}
|
|
21
|
+
|
|
22
|
+
${l}`,...r?{mobileText:`${r}
|
|
23
|
+
|
|
24
|
+
${l}`}:{},time:"",splash:!0}]}const Kc=.7,zc=30,lr=36,pn=18,fn=18,hn=0,da=3,Bt=6,Vs=10,Vc=.25,qc=.5,Rt=6,Ps=10,pa=.336,mn=Rt,gn=Ps,yn=Bt,Sn=Vs;function Zt(t,e,s){return Math.max(e,Math.min(s,t))}function Yc(t){return[T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY].includes(t)?t:null}function Xc(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function $t(t=""){const e=String(t||"").split(`
|
|
25
|
+
`).length;return Zt(e,1,da)}function fa(t){return Math.max(Bt,Math.floor(t*Vc))}function ha(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*qc),n=Math.max(Bt,e-Vs);return Math.max(Bt,Math.min(n,s))}function ns(t,e=0,s=1,n=0,i=0,r=null){const o=Xc(t),l=o.width,c=o.height,d=Zt(Number(s)||1,1,da),u=Yc(r),p=5+d,f=Math.max(18,c-p),m=Math.floor(l*Kc)+(Number(e)||0),g=l-m-hn;let S=!1,y=!1;m<=pn&&g>fn?S=!0:g<=fn&&m>pn?y=!0:m<=pn&&g<=fn&&(y=e>=0,S=!y);let w,x;S?(w=0,x=l):y?(w=l,x=0):(w=Zt(m,zc,l-lr-hn),x=Math.max(lr,l-w-hn));const E=fa(f)+(Number(n)||0),b=f-E;let k=!1,M=!1;b<=Sn&&E>yn?M=!0:E<=yn&&b>Sn?k=!0:b<=Sn&&E<=yn&&(M=(Number(n)||0)>=0,k=!M);let N,B;if(k)N=0,B=f;else if(M)N=f,B=0;else{const ve=ha(c,f);N=Zt(E,Bt,ve),B=Math.max(Vs,f-N)}const P=Math.max(Rt,Math.floor(f*pa))+(Number(i)||0),j=f-P;let K=!1,z=!1;j<=gn&&P>mn?K=!0:P<=mn&&j>gn?z=!0:j<=gn&&P<=mn&&(K=(Number(i)||0)>=0,z=!K);let se,ne;return K?(se=f,ne=0):z?(ne=f,se=0):(se=Zt(P,Rt,Math.max(Rt,f-Ps)),ne=Math.max(Ps,f-se)),{viewport:o,totalWidth:l,totalHeight:c,reservedRows:p,bodyHeight:f,promptRows:d,fullscreenPane:u,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(i)||0,leftHidden:S,rightHidden:y,inspectorHidden:K,activityHidden:z,sessionHidden:k,chatHidden:M,leftWidth:w,rightWidth:x,sessionPaneHeight:N,chatPaneHeight:B,activityPaneHeight:se,inspectorPaneHeight:ne}}function Bn(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 Je(t,e){const s=Bn(e);return s.includes(t)?t:s[0]||T.PROMPT}function Qc(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 Jc(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 ma(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,l,c,d,...u]=r,p=l.replace(/\.git$/u,""),f=`https://github.com/${o}/${p}`;return c?c!=="blob"&&c!=="tree"?{error:`Unrecognized GitHub link shape (…/${c}/…) — use a /blob/ or /tree/ link, or the bare repo URL.`}:d?{kind:"github",repoUrl:f,ref:d,path:u.length?`/${u.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"),l=s.searchParams.get("version"),c=l&&/^G[BT]/u.test(l)?l.slice(2):l||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 _s=2*1024*1024,Zc=new Set(["node_modules",".git"]);function Dn(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 ga(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 ya(t){return t.split("/").some(e=>Zc.has(e))}function Sa(t){const e=String(t||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.endsWith("/plugin.json")?e.slice(0,-12):e==="plugin.json"?"":e:""}function eu(t,e){return t?`${t}/${e}`:e}function ba(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 Rs(t,e,s,n){let i;try{i=await t(e,{headers:{accept:"application/json",...s}})}catch(r){throw ba(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 wa(t,e,s,n){let i;try{i=await t(e,{headers:s})}catch(o){throw ba(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 tu(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 su({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:i,onProgress:r}){const{owner:o,repo:l}=tu(t),c="https://api.github.com",d={"x-github-api-version":"2022-11-28",...i?{authorization:`Bearer ${i}`}:{}};let u=e;u||(r("resolving the default branch…"),u=(await Rs(n,`${c}/repos/${o}/${l}`,d,"api.github.com"))?.default_branch||"main"),r(`reading the file tree of ${o}/${l}@${u}…`);const p=await Rs(n,`${c}/repos/${o}/${l}/git/trees/${encodeURIComponent(u)}?recursive=1`,d,"api.github.com");if(p?.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(p?.tree)?p.tree:[],h=Sa(s),m=eu(h,"plugin.json");if(!f.some(I=>I.type==="blob"&&I.path===m))throw new Error(`no plugin.json at ${m||"the repository root"} on ${u} — link to the folder that contains the manifest`);const g=h?`${h}/`:"",S=f.filter(I=>I.type==="blob"&&(!g||I.path.startsWith(g))&&!ya(I.path.slice(g.length))),y=[];let w=0,x=0;for(const I of S){x+=1;const E=I.path.slice(g.length);r(`fetching ${x}/${S.length}: ${E}`);const b=i?await nu(n,c,o,l,I.sha,d):await wa(n,`https://raw.githubusercontent.com/${o}/${l}/${encodeURIComponent(u)}/${I.path.split("/").map(encodeURIComponent).join("/")}`,{},"raw.githubusercontent.com");if(w+=b.length,w>_s)throw new Error(`package exceeds the ${Math.round(_s/1024)} KB upload limit at ${E}`);y.push({path:E,contentBase64:Dn(b)})}return y}async function nu(t,e,s,n,i,r){const o=await Rs(t,`${e}/repos/${s}/${n}/git/blobs/${i}`,r,"api.github.com"),l=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 ga(l)}function iu(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(),l=o.endsWith(".visualstudio.com")?o.split(".")[0]:r[0],c=o.endsWith(".visualstudio.com")?r[0]:r[1];if(!l||!c)throw new Error(`could not read org/project from ${t}`);return{org:l,project:c,repo:i}}async function ru({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:l,project:c,repo:d}=iu(t),u=`https://dev.azure.com/${encodeURIComponent(l)}/${encodeURIComponent(c)}/_apis/git/repositories/${encodeURIComponent(d)}`,f={authorization:r==="pat"?`Basic ${Dn(new TextEncoder().encode(`:${i}`))}`:`Bearer ${i}`},h=Sa(s),m=`/${h}`,g=e?`&versionDescriptor.version=${encodeURIComponent(e)}&versionDescriptor.versionType=branch`:"";o(`reading ${d}${h?`/${h}`:""}…`);const S=await Rs(n,`${u}/items?scopePath=${encodeURIComponent(m)}&recursionLevel=Full${g}&api-version=7.1`,f,"dev.azure.com"),w=(Array.isArray(S?.value)?S.value:[]).filter(M=>M?.gitObjectType==="blob"&&!M?.isFolder),x=h?`/${h}/`:"/";if(!w.find(M=>M.path===`${x}plugin.json`.replace("//","/")))throw new Error(`no plugin.json under ${m} — link to the folder that contains the manifest`);const E=[];let b=0,k=0;for(const M of w){const N=String(M.path||"").slice(x.length);if(!N||ya(N))continue;k+=1,o(`fetching ${k}/${w.length}: ${N}`);const B=await wa(n,`${u}/blobs/${encodeURIComponent(M.objectId)}?api-version=7.1&$format=octetStream`,{...f,accept:"application/octet-stream"},"dev.azure.com");if(b+=B.length,b>_s)throw new Error(`package exceeds the ${Math.round(_s/1024)} KB upload limit at ${N}`);E.push({path:N,contentBase64:Dn(B)})}return E}async function ou(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=ma(t);if(r.error)throw new Error(r.error);const o={fetchImpl:e,token:s,tokenKind:n,onProgress:i},l=r.kind==="github"?await su(r,o):await ru(r,o);if(l.length===0)throw new Error("the package folder is empty");return{kind:r.kind,files:l}}function au(t=[]){const e=(Array.isArray(t)?t:[]).find(s=>s?.path==="plugin.json");if(!e?.contentBase64)return null;try{const s=ga(e.contentBase64),n=JSON.parse(new TextDecoder().decode(s));return String(n?.name||"").trim()||null}catch{return null}}function cr(t){return t?.isSystem?na(t):Number.MAX_SAFE_INTEGER}function lu(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 cu(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return lu(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 uu(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 Dt(t){return!!(t&&!t.isSystem&&!t.parentSessionId)}function du(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function ur(t,e){return!!(du(t)&&e&&e.has(t.sessionId))}function dr(t,e){return t.isSystem?0:t.isGroup&&ur(t,e)?1:ur(t,e)?2:t.isGroup?3:4}function pr(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function fr(t,e,s,n,i){const r=dr(t,n),o=dr(e,n);if(r!==o)return r-o;const l=cr(t),c=cr(e);if(l!==c)return l-c;if(i&&i.size>0&&Dt(t)&&Dt(e)){const y=i.has(t.sessionId)?i.get(t.sessionId):1/0,w=i.has(e.sessionId)?i.get(e.sessionId):1/0;if(y!==w)return y-w}const d=s.get(t.sessionId),u=s.get(e.sessionId);if(typeof d=="number"&&typeof u=="number"&&d!==u)return d-u;const p=pr(t),f=pr(e);if(p>0&&f>0&&p!==f)return p-f;const h=(t.createdAt||0)-(e.createdAt||0);if(h!==0)return h;const m=String(t.title||""),g=String(e.title||""),S=m.localeCompare(g);return S!==0?S:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function Ke(t=[],e=new Set,s=[],n=null,i=null){const r=new Map,o=new Map,l=cu(s),c=uu(i),d=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const g of t)r.set(g.sessionId,g);const u=[];for(const g of t){if(g.isGroup||!g.groupId||g.parentSessionId)continue;const S=`group:${g.groupId}`;if(r.has(S))continue;const y={sessionId:S,groupId:g.groupId,isGroup:!0,title:"Group",status:"group",shortSummary:"reconnecting…",createdAt:0,updatedAt:0};r.set(S,y),u.push(y)}const p=new Set(u.map(g=>g.sessionId));u.length>0&&(t=[...t,...u]);for(const g of t){const S=!g.isGroup&&g.groupId&&!g.parentSessionId&&r.has(`group:${g.groupId}`)?`group:${g.groupId}`:null,y=g.parentSessionId||S;!y||!r.has(y)||(o.has(y)||o.set(y,[]),o.get(y).push(g))}for(const g of o.values())g.sort((S,y)=>fr(S,y,l,d,c));const f=t.filter(g=>!(g.parentSessionId||!g.isGroup&&g.groupId)).sort((g,S)=>fr(g,S,l,d,c)),h=[];function m(g,S){const y=o.get(g.sessionId)||[];if(h.push({sessionId:g.sessionId,depth:S,hasChildren:y.length>0,collapsed:e.has(g.sessionId),...p.has(g.sessionId)?{standIn:g}:{}}),!e.has(g.sessionId))for(const w of y)m(w,S+1)}for(const g of f)m(g,0);return h}const qe="VS Code",Ut="Retro",Wt="Others",hr=Object.freeze([qe,Ut,Wt]);function pu(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function bn(t){return Number.parseInt(t,16)/255}function fu(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 wn(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function hu(t){const e=fu(t);if(!e)return 0;const s=wn(bn(e.slice(1,3))),n=wn(bn(e.slice(3,5))),i=wn(bn(e.slice(5,7)));return .2126*s+.7152*n+.0722*i}function mu(t){const e=t?.page?.background||t?.tui?.background||t?.terminal?.background;return hu(e)>=.5}function ge({id:t,label:e,description:s,group:n=Wt,page:i,terminal:r,tui:o={},icon:l=null}){const c={background:i?.background||r?.background||"#000000",surface:r?.background||i?.background||"#000000",foreground:r?.foreground||i?.foreground||"#ffffff",white:r?.foreground||i?.foreground||"#ffffff",gray:i?.hintColor||r?.brightBlack||r?.white||"#999999",black:r?.black||"#000000",red:r?.red||"#ff5555",green:r?.green||"#55ff55",yellow:r?.yellow||"#ffff55",blue:r?.blue||"#5555ff",magenta:r?.magenta||"#ff55ff",cyan:r?.cyan||"#55ffff",userChat:"#ffd866",userChatLabel:"#ffec99",otherUserChatLabel:r?.brightMagenta||r?.magenta||"#c9a3ff",activeHighlightBackground:r?.blue||"#5555ff",activeHighlightForeground:r?.background||"#000000",selectionBackground:r?.cursor||r?.blue||"#5555ff",selectionForeground:r?.cursorAccent||r?.background||"#000000",promptCursorBackground:r?.cursor||r?.green||"#55ff55",promptCursorForeground:r?.cursorAccent||r?.background||"#000000"};return pu({id:t,label:e,description:s,group:n,icon:l||null,page:i,terminal:r,tui:{...c,...o}})}const gu=ge({id:"github-dark",label:"GitHub Dark",description:"GitHub dark palette with soft blue accents and cool neutrals.",group:qe,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"}}),yu=ge({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",group:qe,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"}}),Su=ge({id:"workspace-dark",label:"Workspace Dark",description:"Flat workspace chrome: tone surfaces and hairlines instead of panel borders.",group:Wt,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"}}),bu=ge({id:"cobalt2",label:"Cobalt2",description:"Electric blue shell with bright yellow accents and saturated syntax colors.",group:qe,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"}}),wu=ge({id:"dracula",label:"Dracula",description:"Classic Dracula contrast with neon green, pink, and violet accents.",group:qe,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"}}),Iu=ge({id:"catppuccin-mocha",label:"Catppuccin Mocha",description:"Creamy dark palette with soft pastels and high legibility.",group:qe,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"}}),Eu=ge({id:"hacker-x-matrix",label:"Hacker X - Matrix",description:"Black-and-phosphor terminal palette with vivid green glow and CRT-style contrast.",group:qe,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"}}),xu=ge({id:"hacker-x-orion-prime",label:"Hacker X - Orion Prime",description:"Deep-space navy palette with electric cyan, violet, and amber accents.",group:qe,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"}}),vu=ge({id:"gruvbox-dark",label:"Gruvbox Dark",description:"Retro warm palette with earthy browns, oranges, and high readability.",group:qe,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"}}),ku=ge({id:"noctis",label:"Noctis",description:"Dark cyan-tinted palette with warm and cold medium contrast accents.",group:qe,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"}}),Ia=ge({id:"noctis-obscuro",label:"Noctis Obscuro",description:"Deep obsidian palette with cool blue accents and restrained contrast for long sessions.",group:qe,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"}}),Au=ge({id:"terminal-green",label:"Terminal Green",description:"Classic black terminal with phosphor green text, amber warnings, and crisp operator contrast.",group:Ut,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"}}),Cu=ge({id:"high-contrast-mono",label:"High Contrast Mono",description:"Accessibility-first monochrome theme with cobalt selection and severity colors only where they matter.",group:Wt,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"}}),Tu=ge({id:"win95",label:"Windows 95",description:"Authentic 3D-bevelled grey, navy title bars, teal desktop, and the 16-colour VGA terminal set.",group:Ut,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"}}),Mu=ge({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.",group:Ut,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"}}),Nu=ge({id:"doom",label:"DOOM",description:"STBAR brown metal, bone type, and the three keycards as the status palette.",group:Ut,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#2a1d14"},{d:"M6 7h20v20H6z",fill:"#c89a6a"},{d:"M5 6h22v6H5z",fill:"#4a2f1a"},{d:"M9 15h5v3.4H9z",fill:"#1a1008"},{d:"M18 15h5v3.4h-5z",fill:"#1a1008"},{d:"M8.6 13.6l6 1 -.3 1.7-6-1z",fill:"#3a2412"},{d:"M23.4 13.6l-6 1 .3 1.7 6-1z",fill:"#3a2412"},{d:"M14.5 18.5h3v2.4h-3z",fill:"#a8734a"},{d:"M11 22h10v1.8H11z",fill:"#7a3a2a"}]},page:{background:"#100b09",foreground:"#d9cba8",overlayBackground:"#1c1310",overlayForeground:"#d9cba8",hintColor:"#a08d68",modalBackdrop:"rgba(16, 11, 9, 0.82)",modalBackground:"#1c1310",modalBorder:"#6f5432",modalForeground:"#d9cba8",modalMuted:"#a08d68",modalSelectedBackground:"#6f5432",modalSelectedBorder:"#a4885c",modalSelectedForeground:"#fff4d6"},terminal:{background:"#100b09",foreground:"#d9cba8",cursor:"#b81c1c",cursorAccent:"#100b09",selectionBackground:"#6f5432",black:"#100b09",red:"#c42222",green:"#3f9e3f",yellow:"#e8c020",blue:"#3a5ce0",magenta:"#a0446a",cyan:"#4a8f8f",white:"#d9cba8",brightBlack:"#a08d68",brightRed:"#ff3a1e",brightGreen:"#5fc45f",brightYellow:"#ffd84a",brightBlue:"#5a7ae8",brightMagenta:"#c46a94",brightCyan:"#6fb5b5",brightWhite:"#fff4d6"},tui:{border:"#6f5432",userChat:"#e8c020",userChatLabel:"#ffd84a",selectionBackground:"#6f5432",selectionForeground:"#fff4d6",activeHighlightBackground:"#6f5432",activeHighlightForeground:"#fff4d6",promptCursorBackground:"#b81c1c",promptCursorForeground:"#fff4d6"}}),Pu=ge({id:"winamp",label:"WinAMP",description:"Bevelled grey chrome, black glass panes, phosphor green, and the spectrum ramp as the status palette.",group:Ut,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#000000"},{d:"M3 17h4v11H3z",fill:"#00e337"},{d:"M9 11h4v17H9z",fill:"#7ad91e"},{d:"M15 6h4v22h-4z",fill:"#b6e000"},{d:"M21 13h4v15h-4z",fill:"#ffb400"},{d:"M27 20h3v8h-3z",fill:"#ff3b00"},{d:"M3 15h4v1.6H3z",fill:"#d6d6cc"},{d:"M9 9h4v1.6H9z",fill:"#d6d6cc"},{d:"M15 4h4v1.6h-4z",fill:"#d6d6cc"},{d:"M21 11h4v1.6h-4z",fill:"#d6d6cc"},{d:"M27 18h3v1.6h-3z",fill:"#d6d6cc"}]},page:{background:"#000000",foreground:"#00e337",overlayBackground:"#1c1c1c",overlayForeground:"#00e337",hintColor:"#949494",modalBackdrop:"rgba(0, 0, 0, 0.82)",modalBackground:"#1c1c1c",modalBorder:"#5e5e5e",modalForeground:"#00e337",modalMuted:"#a0a0a0",modalSelectedBackground:"#0000c6",modalSelectedBorder:"#5e5e5e",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#00e337",cursor:"#ffb400",cursorAccent:"#000000",selectionBackground:"#0000c6",black:"#000000",red:"#ff3b00",green:"#00e337",yellow:"#ffb400",blue:"#4a7cf0",magenta:"#cc66cc",cyan:"#29c8c8",white:"#d6d6cc",brightBlack:"#949494",brightRed:"#ff6a3d",brightGreen:"#5cff7a",brightYellow:"#ffd24a",brightBlue:"#7fa5ff",brightMagenta:"#e08ae0",brightCyan:"#6fe0e0",brightWhite:"#ffffff"},tui:{border:"#5e5e5e",gray:"#949494",userChat:"#ffb400",userChatLabel:"#ffd24a",selectionBackground:"#0000c6",selectionForeground:"#ffffff",activeHighlightBackground:"#0000c6",activeHighlightForeground:"#ffffff",promptCursorBackground:"#ffb400",promptCursorForeground:"#000000"}}),_u=ge({id:"rust",label:"Rust",description:"Graphite and iron oxide, Ferris in the corner, and rustc's diagnostic levels as the status palette.",group:Wt,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#241f1c"},{d:"M11.5 9.5h1.5v2h-1.5z",fill:"#d63a00"},{d:"M19 9.5h1.5v2h-1.5z",fill:"#d63a00"},{d:"M10.5 6h3.5v3.5h-3.5z",fill:"#ffe9dd"},{d:"M18 6h3.5v3.5H18z",fill:"#ffe9dd"},{d:"M11.5 7h1.5v1.5h-1.5z",fill:"#1a1210"},{d:"M19 7h1.5v1.5H19z",fill:"#1a1210"},{d:"M10 11.5h12v2H10z",fill:"#ff7a3d"},{d:"M7 13.5h18v3H7z",fill:"#f74c00"},{d:"M5 16.5h22v4H5z",fill:"#f74c00"},{d:"M7 20.5h18v1.8H7z",fill:"#f74c00"},{d:"M14.5 18h3v1.4h-3z",fill:"#c23c00"},{d:"M0 11h4.5v6.5H0z",fill:"#d63a00"},{d:"M0 13.2h3v2H0z",fill:"#241f1c"},{d:"M27.5 11h4.5v6.5h-4.5z",fill:"#d63a00"},{d:"M29 13.2h3v2h-3z",fill:"#241f1c"},{d:"M8.5 22.3h2.5v2.4H8.5z",fill:"#d63a00"},{d:"M14.75 22.3h2.5v2.4h-2.5z",fill:"#d63a00"},{d:"M21 22.3h2.5v2.4H21z",fill:"#d63a00"}]},page:{background:"#1c1917",foreground:"#e7e0d8",overlayBackground:"#262220",overlayForeground:"#e7e0d8",hintColor:"#a39a8f",modalBackdrop:"rgba(28, 25, 23, 0.82)",modalBackground:"#262220",modalBorder:"#4a4038",modalForeground:"#e7e0d8",modalMuted:"#a9a096",modalSelectedBackground:"#7c2d12",modalSelectedBorder:"#ce422b",modalSelectedForeground:"#ffeadf"},terminal:{background:"#1c1917",foreground:"#e7e0d8",cursor:"#f74c00",cursorAccent:"#1c1917",selectionBackground:"#7c2d12",black:"#1c1917",red:"#f3554a",green:"#6cc24a",yellow:"#e5b02b",blue:"#58a6ff",magenta:"#c98bdf",cyan:"#f74c00",white:"#e7e0d8",brightBlack:"#a39a8f",brightRed:"#ff7b70",brightGreen:"#8fdd6e",brightYellow:"#ffcc55",brightBlue:"#83c0ff",brightMagenta:"#dcaaef",brightCyan:"#ff7a3d",brightWhite:"#fdf6ee"},tui:{border:"#4a4038",userChat:"#ffb454",userChatLabel:"#ffd08a",selectionBackground:"#7c2d12",selectionForeground:"#ffeadf",activeHighlightBackground:"#7c2d12",activeHighlightForeground:"#ffeadf",promptCursorBackground:"#f74c00",promptCursorForeground:"#1c1917"}}),Ru=ge({id:"spongebob",label:"SpongeBob",description:"Bikini Bottom at depth, sponge-yellow accents, and the cast as the status palette.",group:Wt,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#1a7fa8"},{d:"M7 2h18a3 3 0 0 1 3 3v15a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V5a3 3 0 0 1 3-3z",fill:"#ffe01b"},{d:"M6.2 6.4a1.4 1.4 0 1 0 2.8 0a1.4 1.4 0 1 0-2.8 0z",fill:"#e3c00c"},{d:"M23.4 4.8a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0z",fill:"#e3c00c"},{d:"M5.4 18.2a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0-3 0z",fill:"#e3c00c"},{d:"M24 19a1.3 1.3 0 1 0 2.6 0a1.3 1.3 0 1 0-2.6 0z",fill:"#e3c00c"},{d:"M7.3 10a4.2 4.2 0 1 0 8.4 0a4.2 4.2 0 1 0-8.4 0z",fill:"#ffffff"},{d:"M16.3 10a4.2 4.2 0 1 0 8.4 0a4.2 4.2 0 1 0-8.4 0z",fill:"#ffffff"},{d:"M9.4 10a2.1 2.1 0 1 0 4.2 0a2.1 2.1 0 1 0-4.2 0z",fill:"#3fa9d8"},{d:"M18.4 10a2.1 2.1 0 1 0 4.2 0a2.1 2.1 0 1 0-4.2 0z",fill:"#3fa9d8"},{d:"M10.5 10a1 1 0 1 0 2 0a1 1 0 1 0-2 0z",fill:"#10202b"},{d:"M19.5 10a1 1 0 1 0 2 0a1 1 0 1 0-2 0z",fill:"#10202b"},{d:"M10 16.6c2 3.6 10 3.6 12 0c-1.2 5-10.8 5-12 0z",fill:"#6b4e00"},{d:"M14 17.6h1.9v2.1H14z",fill:"#ffffff"},{d:"M16.1 17.6H18v2.1h-1.9z",fill:"#ffffff"},{d:"M6 23h20v3H6z",fill:"#ffffff"},{d:"M14.4 24.6h3.2v2h-3.2z",fill:"#d2232a"},{d:"M13 26.4h6l-3 5.2z",fill:"#d2232a"}]},page:{background:"#07293c",foreground:"#e6f4fb",overlayBackground:"#0e3852",overlayForeground:"#e6f4fb",hintColor:"#8fb9cf",modalBackdrop:"rgba(7, 41, 60, 0.84)",modalBackground:"#0e3852",modalBorder:"#1d6a8c",modalForeground:"#e6f4fb",modalMuted:"#95bed3",modalSelectedBackground:"#ffe01b",modalSelectedBorder:"#fff08a",modalSelectedForeground:"#07293c"},terminal:{background:"#07293c",foreground:"#e6f4fb",cursor:"#ffe01b",cursorAccent:"#07293c",selectionBackground:"#ffe01b",black:"#07293c",red:"#ff6152",green:"#7ed957",yellow:"#ffa62b",blue:"#7fd4c1",magenta:"#ff9bd2",cyan:"#ffe01b",white:"#e6f4fb",brightBlack:"#8fb9cf",brightRed:"#ff9084",brightGreen:"#a5e888",brightYellow:"#ffc46b",brightBlue:"#a8e5d8",brightMagenta:"#ffbde1",brightCyan:"#fff08a",brightWhite:"#ffffff"},tui:{border:"#1d6a8c",userChat:"#ffa62b",userChatLabel:"#ffc46b",selectionBackground:"#ffe01b",selectionForeground:"#07293c",activeHighlightBackground:"#ffe01b",activeHighlightForeground:"#07293c",promptCursorBackground:"#ffe01b",promptCursorForeground:"#07293c"}});function $u(t,e){const s=hr.indexOf(t.group),n=hr.indexOf(e.group),i=s===-1?Number.MAX_SAFE_INTEGER:s,r=n===-1?Number.MAX_SAFE_INTEGER:n;return i!==r?i-r:t.label.localeCompare(e.label,void 0,{sensitivity:"base"})}const Ea=Object.freeze([Su,wu,gu,yu,bu,xu,Eu,Iu,vu,ku,Ia,Au,Cu,Tu,Mu,Nu,Pu,_u,Ru].sort($u)),Ou=new Map(Ea.map(t=>[t.id,t])),Lu=Ia.id;function Fu(){return Ea}function st(t){return t?Ou.get(t)??null:null}const Bu=new Set(["agent","user","system"]);function $s(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 Du(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:Bu.has(t.source)?t.source:"agent"}}function Os(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const i of e){const r=Du(i);!r||n.has(r.filename)||(n.add(r.filename),s.push(r))}return s}function Hu(t,e){const s=String(e||"").trim();return s&&Os(t).find(n=>n.filename===s)||null}function di(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 Ls(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 pi(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 Hn(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 xa(t){if(t==null)return null;const e=String(t).trim();return e||null}function Gn({mode:t="local",branding:e=null,docs:s=null,themeId:n=null,chatViewMode:i=null,sessionOwnerFilter:r=null,layoutAdjustments:o=null,pinnedSessionIds:l=null,collapsedSessionIds:c=null,activeSessionId:d=null,sessionOrder:u=null}={}){const p=r!=null,f=c!=null,h=di(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:Ve[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:st(n)?.id||Lu,touchScale:!1,modal:null,fullscreenPane:null,layout:{...h,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:xa(d),collapsedIds:Hn(c),collapsedIdsExplicit:f,pinnedIds:Ls(l),manualOrder:pi(u),listingSeen:!1,groupsListingSeen:!1,selectedIds:[],selectMode:!1,listDeselected:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:p,ownerFilter:$s(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,changelog: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 va(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function Gu(t,e){return!(!va(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const ka="activeHighlightBackground",fi="activeHighlightForeground",In="userChat",ju="userChatLabel",Uu="otherUserChatLabel",mr=new WeakMap,gr=new WeakMap;function Wu(t){return t||fi}function Aa(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Wu(s?.color):fi,backgroundColor:ka,bold:s?.bold??!0}))}function Ye(t,{color:e=fi,bold:s=!0}={}){return{text:t,color:e,backgroundColor:ka,bold:s}}function ze(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Ku=72;function Ca(t){const e=Number(t)||0;return e>0&&e<=Ku}function hi(t){if(!t)return"unknown";const e=t.status||"unknown",s=e==="waiting"||e==="idle"||e==="unknown";return t.cronActive===!0&&s?"cron_waiting":s&&(Number(t.activeChildCount)||0)>0?"awaiting_children":e}function Ta(t,e){if(e==="cron_waiting")return"waiting";if(e==="awaiting_children"){const s=Number(t?.activeChildCount)||0;return s>0?`waiting on ${s}`:"waiting on children"}return e}function zu(t){const e=hi(t);return!e||e==="unknown"?"":Ta(t,e)}function Vu(t){if(!t)return null;const e=t.updatedAt||t.summaryUpdatedAt||t.latestSummaryUpdatedAt||t.createdAt||0;return{status:Ma(t)||"unknown",timestampMs:e||null,relative:e?Pi(e):"—"}}function Ma(t){const e=Na(t);return!e||e==="unknown"?"":Ta(t,e)}function Na(t){return t?.rowVisualStatus||hi(t)}function Pa(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function mi(t){const e=hi(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&va(t?.error)&&!Pa(t?.orchestrationStatus)?"warning":null}function _a(t,e="local"){const s=mi(t);if(s)return s;const n=Na(t);if(e==="remote"&&Pa(t?.orchestrationStatus)&&n!=="cron_waiting"&&n!=="awaiting_children"&&n!=="waiting"&&n!=="input_required"){if(t?.orchestrationStatus==="Completed")return"completed";if(t?.orchestrationStatus==="Terminated")return"terminated"}return n==="terminated"?"terminated":n}function Ot(t,e="local"){switch(_a(t,e)){case"running":return"green";case"cron_waiting":return"yellow";case"awaiting_children":return"magenta";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 Ra(t,e="local"){switch(_a(t,e)){case"running":return"*";case"cron_waiting":return"~";case"awaiting_children":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 he(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function qs(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const gi=he({provider:"system",subject:"system"});function yr(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 jn(t){return yr(t?.displayName)||yr(t?.email)||"?"}function qu(t,e=!1){return Dt(t)?e?t.isGroup?"pinned:folders":"pinned:sessions":t.isGroup?"folders":t.groupId?`g:${t.groupId}`:"":null}function $a(t,{isMine:e=!1}={}){if(!t)return null;const s=qs(t,t?.email||"");return{initials:jn(t),hue:Ju(Zu(t,t?.email)),name:s||"unknown user",isMine:!!e}}function Yu(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=he(n);i&&!e.has(i)&&e.set(i,n)}return e}function Xu(t,e){if(t?.owner?.displayName||t?.owner?.email)return t.owner;const s=e?.get?.(he(t?.owner))||null;return s||(t?.createdBy?{email:t.createdBy}:null)}const Qu=8;function Ju(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%Qu}function Zu(t,e){return String(e||t?.email||t?.displayName||(t?.provider&&t?.subject?`${t.provider}:${t.subject}`:"")||"").trim().toLowerCase()}function ed(t,e=1/0){const s=t?.sessions?.byId,n=t?.sessions?.ownerFilter||{all:!0},i=t?.auth||{},r=new Set;for(const o of Object.values(s||{})){if(!o||o.isSystem||o.isGroup)continue;const l=he(o.owner);if(!(!l||l===gi)&&Wn(o,n,i)&&(r.add(l),r.size>=e))break}return r.size}function Un(t){return ed(t,2)>1}function Oa(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function kt(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of Oa(t,e)){const i=he(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 br(t,e){const s=Sr(t),n=Sr(e?.agentId);return!!(s&&n&&s===n)}function td(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(),l=e.slice(n+s.length).trim();if(o&&br(l,t))return{displayTitle:o,agentTitle:l}}const i=/^(.+?)\s+[–—-]\s+(.+)$/u.exec(e);if(i){const o=i[1].trim(),l=i[2].trim();if(o&&l)return{displayTitle:l,agentTitle:o}}const r=e.indexOf(": ");if(r>0){const o=e.slice(0,r).trim(),l=e.slice(r+2).trim();if(l&&br(o,t))return{displayTitle:l,agentTitle:o}}return null}function sd(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 nd=[[/</g,"<"],[/>/g,">"],[/"/g,'"'],[/�?39;/g,"'"],[/'/g,"'"],[/ /g," "],[/&/g,"&"]];function id(t){let e=String(t??"");if(!e.includes("&"))return e;for(const[s,n]of nd)e=e.replace(s,n);return e}function Ys(t){return id(rd(t))}function rd(t){const e=String(t?.title||"").trim(),s=td(t);if(!s)return e;const n=sd(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function La(t,e){const s=ue(t?.sessionId);if(t?.isSystem)return`${Gt(t,e)} (${s})`;const n=Ys(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function Wn(t,e={},s={},n=void 0){if(!e||e.all===!0||t?.isGroup)return!0;if(t?.isSystem)return e.includeSystem===!0;const i=he(n!==void 0?n:t?.owner);if(!i)return e.includeUnowned===!0;if(i===gi)return e.includeSystem===!0;const r=he(s?.principal);return e.includeMe&&r&&i===r||e.includeShared===!0&&i!==r?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(i)}function Fa(t,e={},s={},n=null){const i=kt(t,n||{});if(Wn(t,e,s,i))return!0;if(!n)return!1;if(t?.isGroup)return Oa(t,n).some(l=>Fa(l,e,s,n));let r=t,o=0;for(;r?.parentSessionId&&o<16;){const l=n[r.parentSessionId];if(!l)return!1;if(Wn(l,e,s))return!0;r=l,o+=1}return!1}function od(t){return(t||[]).map(e=>e?.text||"").join("")}function yi(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 wr(t){const{childMap:e}=yi(t),s=new Map,n=new Set;function i(r){if(s.has(r))return s.get(r);if(n.has(r))return 0;n.add(r);const l=(e.get(r)||[]).reduce((c,d)=>c+1+i(d),0);return n.delete(r),s.set(r,l),l}for(const r of Object.keys(t||{}))i(r);return s}function Ir(t=[],e={}){const{parentMap:s}=yi(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 Si(t={}){if(!t||typeof t!="object")return wr(t);const e=mr.get(t);if(e)return e;const s=wr(t);return mr.set(t,s),s}function bi(t=[],e={}){if(!Array.isArray(t))return Ir(t,e);const s=gr.get(t);if(s)return s;const n=Ir(t,e);return gr.set(t,n),n}function Ba(t,e,s,n){const i=s.get(t)||0,r=n.get(t)||0,o=Math.max(0,i-r),l=e?.collapsed?i:o;return l?{text:`[+${l}]`,color:"cyan"}:null}function Fs(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 ad(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${Fs(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${Ct(t.cronInterval)}]`,color:"magenta"}:null}function Da(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function ld(t,e){const s=[];typeof t?.regenStage=="string"&&t.regenStage&&s.push({text:`↻ regen:${t.regenStage}`,color:"magenta"});const n=Ma(t);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:Ot(t,e)}));const i=ki(t?.model,t?.reasoningEffort);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i,color:"cyan"}));const r=ec(t?.contextUsage);r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r.text,color:r.color}));const o=tc(t?.contextUsage);return o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color})),s}function cd(t,e,s,n,i){const r=[],o=s.connection?.mode||"local",l=t.depth>0?`${" ".repeat(Math.max(0,t.depth-1))}└ `:"";l&&r.push({text:l,color:"gray",role:"depth"});const c=new Set(Array.isArray(s.sessions?.pinnedIds)?s.sessions.pinnedIds:[]),d=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),u=!!s.sessions?.selectMode,p=d.has(t.sessionId),f=c.has(t.sessionId);if(p&&r.push({text:"▌",color:"cyan",bold:!0,role:"selection"}),t.depth===0&&Da(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 z=Ra(e,o);r.push({text:z?`${z} `:" ",color:Ot(e,o),role:"status"})}const h=e?.isGroup?"cyan":e?.isSystem?"yellow":Ot(e,o),m=kt(e,s.sessions?.byId||{}),g=ue(e?.sessionId),S=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,y=S?Jp(S):"",w=ki(e?.model,e?.reasoningEffort),x=e?.isSystem?Gt(e,s.branding?.title||"PilotSwarm"):Ys(e),I=!!(e?.isSystem||e?.isGroup||x&&x.trim()),E=[...r];if(Un(s)&&!e?.isSystem&&!e?.isGroup){const z=he(s?.auth?.principal),se=!!(z&&he(m)===z),ne=m?jn(m):"?";E.push({text:`[${ne}] `,color:se?"green":"cyan",bold:!0,ownerChip:!0})}I?E.push({text:x,color:h,bold:!!(e?.isSystem||e?.isGroup)}):(E.push({text:g,color:h}),y&&(E.push({text:" · ",color:"gray"}),E.push({text:y,color:"gray"})),w&&(E.push({text:" · ",color:"gray"}),E.push({text:w,color:"green"})));const b=Ba(e?.sessionId,t,n,i);b&&E.push({text:` ${b.text}`,color:b.color,bold:b.bold});const k=ad(e);k&&E.push({text:" ⏱",color:"magenta"});const M=[],N=e?.contextUsage?.compaction?.state,B=ii(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&M.push({text:`${e.memberCount}`,color:"gray"}):N==="running"?M.push({text:"⇊",color:"magenta"}):N==="failed"?M.push({text:"!",color:"red"}):B!=null?M.push({text:`${B}%`,color:B>=85?"red":B>=70?"yellow":"green"}):M.push({text:"—",color:"gray"});const _=[];e?.isGroup&&e?.memberCount!=null&&(_.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),y&&(_.push({text:" · ",color:"gray"}),_.push({text:y,color:"gray"})));const P=[],j=()=>{P.length&&P.push({text:" · ",color:"gray"})};if(e?.isGroup)P.push(..._);else{I&&(P.push({text:g,color:"cyan"}),y&&(j(),P.push({text:y,color:"gray"})),w&&(j(),P.push({text:w,color:"green"})));const z=e?.contextUsage;z&&Number.isFinite(z.currentTokens)&&Number.isFinite(z.tokenLimit)&&z.tokenLimit>0&&(j(),P.push({text:`ctx ${X(z.currentTokens)}/${X(z.tokenLimit)}`,color:"gray"}));const se=n?.[e?.sessionId];se&&(j(),P.push({text:`${se} child${se===1?"":"ren"}`,color:"gray"})),k&&(j(),P.push({text:k.text,color:k.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(j(),P.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...E,...I&&y&&!e?.isGroup?[{text:" ",color:"gray"},{text:y,color:"gray"}]:[],...M.length&&!e?.isGroup?[{text:" · ",color:"gray"},...M]:[],...e?.isGroup&&_.length?[{text:" ",color:"gray"},..._]:[]],titleRuns:E,ctxRuns:M,metaRuns:_,badgeRuns:[],selectedMetaRuns:P,detailRuns:P,childCount:n?.get?.(e?.sessionId)||0,chrome:{kind:e?.isGroup?"group":e?.isSystem?"system":e?.serviceKind?"service":"session",title:I?x:g,untitled:!I,statusColor:Ot(e,o),accentColor:h,pinned:f,selectMode:u,checked:p,owner:Un(s)&&!e?.isSystem&&!e?.isGroup?{initials:m?jn(m):"?",isMine:!!(he(s?.auth?.principal)&&he(m)===he(s?.auth?.principal))}:null,childBadge:b?{text:b.text,color:b.color}:null,cron:!!k,age:y||null,model:w||null,shortId:g,ctx:M.length>0?{text:M[0].text,color:M[0].color}:null}}}function Ha(t){return String(t||"").trim().toLowerCase()}function ft(t,e){const s=Ha(e);return s?String(t||"").toLowerCase().includes(s):!0}function ud(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 Er=new WeakMap;function dd(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 Ht(t){const e=Si(t.sessions.byId),s=bi(t.sessions.flat,t.sessions.byId),n=Ha(t.sessions?.filterQuery||""),i=t.sessions?.ownerFilter||{all:!0},r=t.auth||{},o=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),l=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]),c=ud(t.sessions);let d=Er.get(t.sessions.flat);return d||(d=new Map,Er.set(t.sessions.flat,d)),t.sessions.flat.filter(u=>!!(t.sessions.byId[u.sessionId]||u.standIn)).map(u=>{const p=t.sessions.byId[u.sessionId]||u.standIn,f=u.sessionId===t.sessions.activeSessionId&&!t.sessions.listDeselected,h=o.has(u.sessionId),m=l.has(u.sessionId),g=[u,p,f,h,m,n,i,r,t.connection?.mode,t.sessions.selectMode,e,s,t.branding?.title],S=d.get(u.sessionId);if(S&&dd(S.deps,g))return S.row;const y=cd(u,p,t,e,s),w={sessionId:u.sessionId,text:od(y.runs),...y,depth:u.depth,status:p?.status,statusColor:Ot(p,t.connection?.mode||"local"),active:f,groupId:p?.groupId||u?.groupId||null,isSystem:!!p?.isSystem,isGroup:!!p?.isGroup,hasChildren:u.hasChildren,collapsed:u.collapsed,pinned:h,selected:m,canPin:Da(p),ownerBadge:Un(t)&&!p?.isSystem&&!p?.isGroup&&kt(p,t.sessions.byId)?$a(kt(p,t.sessions.byId),{isMine:!!(he(t?.auth?.principal)&&he(kt(p,t.sessions.byId))===he(t?.auth?.principal))}):null,orderable:Dt(p),orderContainer:qu(p,h)};return d.set(u.sessionId,{deps:g,row:w}),w}).filter(u=>{if(c?.has(u.sessionId))return!0;const p=t.sessions.byId[u.sessionId];if(!Fa(p,i,r,t.sessions.byId))return!1;const f=kt(p,t.sessions.byId),h=f?`${qs(f,"")} ${f.email||""}`:"",m=`${p?.shortSummary||""} ${p?.summaryState?.intent||""} ${p?.summaryState?.summary||""}`;return ft(u.text,n)||ft(u.sessionId,n)||ft(h,n)||ft(m,n)})}function Kn(t,e=8){const s=Ht(t);if(s.length===0)return[];const n=new Set(s.map(p=>p.sessionId)),i=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(p=>n.has(p.sessionId)),r=i.findIndex(p=>p.sessionId===t.sessions.activeSessionId),o=Math.max(0,r);if(i.length<=e)return s;const l=Math.floor(e/2);let c=Math.max(0,o-l),d=Math.min(i.length,c+e);d>i.length&&(d=i.length,c=Math.max(0,d-e));const u=i.slice(c,d);return Si(t.sessions.byId),bi(i,t.sessions.byId),s.filter(p=>u.some(f=>f.sessionId===p.sessionId))}function je(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function pd(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 Ey(t){const e=t.sessions?.filterExceptionId||null;return!e||!t.sessions?.byId?.[e]?null:"Showing linked session outside your current filters."}function Ga(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function fd(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 hd(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),i=String(s?.answer||"").trim();if(!n||!i||ja(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 md(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 ja(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>li(n?.text||"")?.question?.trim()===s):!1}function gd(t){const e=String(t?.error||"").trim();if(!e)return null;const s=mi(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 xr(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 yd(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function Sd(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=yd(r.text);if(o)return{...r,summaryText:o}}return null}function bd(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(E=>E?.role==="user"||E?.role==="assistant"),o=r[r.length-1]||null,l=o?.role==="user",c=l&&o?.optimistic===!0,d=(n||[]).filter(E=>E?.phase==="pending").length,u=(n||[]).filter(E=>E?.phase==="queued").length,p=(n||[]).filter(E=>E?.phase==="cancelling").length,f=Array.isArray(e?.events)?e.events:[],h=xr(f,"user.message"),m=xr(f,"assistant.message"),g=h>m;if(i==="waiting"||i==="input_required"||!l&&!g&&i!=="running"&&!c)return null;const S=Math.max(h,m),y=f.filter(E=>E?.eventType==="assistant.reasoning"&&Number(E?.seq||0)>S),w=y[y.length-1]||null,x=String(w?.data?.content||w?.data?.text||w?.data?.message||"").trim();if(x)return{kind:"thinking",label:"Thinking",text:x,createdAt:w?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:w?.seq||0};const I=Sd(e,S);return I?.summaryText?{kind:i==="running"?"working":"sending",label:i==="running"?"Working":"Sending",text:I.summaryText,createdAt:I.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:I.seq||0}:d>0?{kind:"pending",label:d===1?"Pending":`Pending ${d}`,text:d===1?"One prompt is waiting to be sent.":`${d} prompts are waiting to be sent.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:u>0?{kind:"queued",label:u===1?"Queued":`Queued ${u}`,text:u===1?"One prompt is durably queued, waiting for the LLM to receive it.":`${u} prompts are durably queued, waiting for the LLM to receive them.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:p>0?{kind:"cancelling",label:p===1?"Cancelling":`Cancelling ${p}`,text:p===1?"One queued prompt is waiting for cancellation confirmation.":`${p} queued prompts are waiting for cancellation confirmation.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:c?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:o?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:i==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:null}function wi(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return dn(t.branding);if(s?.isGroup){const d=Object.values(t.sessions.byId||{}).filter(h=>h&&!h.isGroup&&h.groupId===s.groupId&&!h.parentSessionId),u=h=>String(h??"").replace(/\|/g,"\\|").replace(/[\r\n]+/g," ").trim()||" ",p=d.map(h=>`| ${u(h.title||h.sessionId)} | ${u(h.status||"unknown")} | ${u(h.shortSummary||"")} |`),f=[`# ${s.title||s.groupId}`,s.shortSummary||"","","| Metric | Count |","|---|---:|",`| Members | ${s.memberCount??d.length} |`,`| Running | ${s.runningCount??0} |`,`| Waiting | ${s.waitingCount??0} |`,`| Completed | ${s.completedCount??0} |`,`| Failed | ${s.failedCount??0} |`,`| Cancelled | ${s.cancelledCount??0} |`,"","## Members",...p.length>0?["| Session | Status | Summary |","|---|---|---|",...p]:["_No top-level members._"]];return[{id:`group-details:${s.sessionId}`,role:"system",noChrome:!0,text:f.filter((h,m)=>m===1||String(h||"").length>0).join(`
|
|
30
|
+
`),createdAt:s.updatedAt||Date.now()}]}if(t.ui?.chatViewMode==="summary")return wd(s);const n=t.history.bySessionId.get(e),i=n?.chat||[],r=s?.pendingQuestion?.question&&!ja(i,s.pendingQuestion.question)?fd(s):null,o=hd(s,i),l=gd(s);if((!n||i.length===0)&&!r&&!o&&!l)return dn(t.branding,s);const c=i.length>0?[...i]:dn(t.branding,s);return r&&c.push(r),o&&c.push(o),l&&c.push(l),c}function wd(t){const e=d=>{const u=String(d||"");return u.includes("\\n")?u.replace(/\\\\n/g,`
|
|
31
|
+
`).replace(/\\n/g,`
|
|
32
|
+
`):u},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=Ys(t)||t?.title||t?.sessionId||"Session",r=[];r.push(`# ${i}`),r.push("");const o=[],l=zu(t);if(l&&o.push(["Status",l]),s?.intent&&o.push(["Intent",String(s.intent)]),t?.summaryUpdatedAt){const d=_e(t.summaryUpdatedAt);d&&o.push(["Updated",d])}for(const[d,u]of o)r.push(`**${d}:** ${u}`);o.length>0&&r.push("");const c=e(s?.summary||t?.shortSummary||"").trim();if(c&&(r.push(c),r.push("")),n){const d=Object.entries(n).filter(([,u])=>u!=null&&!(typeof u=="string"&&!u.trim()));if(d.length>0){r.push("## State");for(const[u,p]of d)if(Array.isArray(p))if(p.length===0)r.push(`- **${u}:** _(empty)_`);else{r.push(`- **${u}:**`);for(const f of p.slice(0,16)){const h=typeof f=="string"?e(f):JSON.stringify(f);r.push(` - ${h}`)}}else if(p&&typeof p=="object"){r.push(`- **${u}:**`);for(const[f,h]of Object.entries(p).slice(0,16)){const m=typeof h=="string"?e(h):JSON.stringify(h);r.push(` - **${f}:** ${m}`)}}else r.push(`- **${u}:** ${e(String(p))}`);r.push("")}}for(const[d,u]of[["Blockers","blockers"],["Open Questions","openQuestions"],["Next Actions","nextActions"]]){const p=Array.isArray(s?.[u])?s[u].filter(Boolean).slice(0,12):[];if(p.length!==0){r.push(`## ${d}`);for(const f of p)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 Id(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>md(e,s)).filter(Boolean):[]:[]}function En(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function Ed(t,e={}){const s=_e(t?.createdAt||t?.time),n=t?.sender,i=n?.kind==="user"?he(n):null,r=e?.viewerKey||null,o=e?.ownerKey||null,l=e?.sharedContext===!0,c=t?.role==="user",u=l&&c&&i&&!(c&&i&&r&&i===r),f=l&&c&&o&&(i&&i===o||!i&&r&&r===o)?" (owner)":"",h=c?(u?n.display||n.subject||"User":"You")+f:t?.role==="assistant"?"Agent":t?.role==="system"?"System":"PilotSwarm";let m=null,g=null;t?.pendingPhase==="pending"?(m="○",g="yellow"):t?.pendingPhase==="queued"?(m="✓",g="cyan"):t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?(m="x",g="red"):t?.role==="user"&&!t?.optimistic&&!t?.pendingPhase&&(t?.stopped?(m="⊘",g="yellow"):t?.redelivered?(m="✓✓↻",g="yellow"):(m="✓✓",g="green"));const S=t?.pendingPhase==="pending"?"yellow":t?.pendingPhase==="queued"?"cyan":t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?"red":u?Uu:t?.role==="user"?ju:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white";return{time:s,glyph:m,glyphColor:g,roleLabel:h,roleColor:S,fromOtherPerson:u}}function xd(t,e={}){const{time:s,glyph:n,glyphColor:i,roleLabel:r,roleColor:o}=Ed(t,e),l=s?`[${s}] `:"",c=[...En(l,"gray")];return n&&c.push(...En(`${n} `,i)),c.push(...En(`${r}: `,o,{bold:!0})),c}function at(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function Ua(){return[{text:"",color:null}]}function vd(t){const e=(t||[]).find(n=>at(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=at(e).trimStart();return/^[┌│└]/.test(s)}function Bs(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(at(s).trim().length>0)break;e.shift()}return e}function kd(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 Wa(t){const e=kd(t);if(e){const o=[];e.leadingText&&o.push({kind:"text",text:e.leadingText});const l=ot(e.systemText);return l&&o.push({kind:"system",text:l}),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 l=s[o];if(!/^\s*\[SYSTEM:/i.test(l)){i.push(l),o+=1;continue}const c=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(l);if(c){r();const f=ot(c[1].trim());if(!f){o+=1;continue}n.push({kind:"system",text:f}),o+=1;continue}const d=[l.replace(/^\s*\[SYSTEM:\s*/i,"")];let u=-1;for(let f=o+1;f<s.length;f+=1){const h=s[f];if(h.trim()==="]"){u=f;break}if(/\]\s*$/.test(h.trim())){const m=h.replace(/\]\s*$/,"");m.trim()&&d.push(m),u=f;break}d.push(h)}if(u===-1){i.push(l),o+=1;continue}r();const p=ot(d.join(`
|
|
40
|
+
`).trim());if(!p){o=u+1;continue}n.push({kind:"system",text:p}),o=u+1}return r(),n}function Cd(t){return t?t?.role==="system"?!ai(t?.text||"")||!!ot(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:Wa(t?.text||"").some(e=>e.kind==="system"):!1}function vr(t){return Cd(t)?"system":t?.role||"other"}function Ka(t,e){return!t||!e?!1:vr(t)!==vr(e)}function Td(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 Md(t,e=""){const s=Td(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:Tt(t),color:"gray"}}function kr({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:Tt(s||o),color:i}}function Nd(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 _d(t){const e=(t||[]).find(s=>at(s).trim().length>0);return e?at(e).trimStart().startsWith("┌"):!1}function Ds(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&_d(e)&&at(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function Rd(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 $d(t,e,s){const n=Math.max(20,Number(s)||20),i=_e(e?.createdAt||e?.time),r=Rd(t),o=l=>{const c=String(l||"").replace(/^session-/i,"");return ue(c)||c||String(l||"")};if(r?.kind==="subAgentSingle"){const l=o(r.agentId),c=[r.task?`**Task:** ${r.task}`:"",r.status?`**Status:** ${r.status}`:"","",r.result||"_(no result)_"].filter((d,u)=>u===2||d).join(`
|
|
41
|
+
`);return[kr({title:`Sub-agent Response — ${l}`,summary:r.status||"completed",timestamp:i,body:c,color:"cyan"})]}if(r?.kind==="subAgentMulti"){const l=r.agents.map(d=>{const u=o(d.agentId),p=d.task?`**Task:** ${d.task}`:"",f=d.status?`**Status:** ${d.status}`:"";return`${[`### ${u}`,p,f].filter(Boolean).join(`
|
|
42
|
+
`)}
|
|
43
|
+
|
|
44
|
+
${d.result||"_(no result)_"}`}),c=r.agents.map(d=>`${o(d.agentId)} ${d.status||"completed"}`).join(" · ");return[kr({title:`Sub-agent Responses (${r.agents.length})`,summary:c,timestamp:i,body:l.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 Od(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),i=_e(t?.createdAt||t?.time),r=String(t?.thinkingLabel||"Thinking…").trim()||"Thinking…",o=t?.progressKind==="working"?"yellow":(t?.progressKind==="sending","cyan"),l=ie([{text:` ⠋ ${r} `,color:o,bold:!0},...i?[{text:` ${i} `,color:"gray"}]:[]],Math.max(1,s-3)),c=l.reduce((f,h)=>f+String(h?.text||"").length,0),d=Math.max(0,s-c-3),u=String(t?.text||"").trim()?Bs(Ft(Tt(t.text),{width:n})).flatMap(f=>Zo(f,n)):[],p=[[{text:"┌─",color:"gray"},...l,{text:`${"─".repeat(d)}┐`,color:"gray"}]];for(const f of u)p.push([{text:"│ ",color:"gray"},...Jo(f.map(h=>({...h,color:h?.color&&h.color!=="white"?h.color:"gray"})),n),{text:" │",color:"gray"}]);return p.push([{text:`└${"─".repeat(Math.max(1,s-2))}┘`,color:"gray"}]),p.push([{text:"",color:null}]),p}function Ld(t){return String(t||"").split(`
|
|
49
|
+
`).reduce((e,s)=>Math.max(e,ri(s).length),0)}function Hs(t,e,s={}){if(t?.splash){const d=t.mobileText&&Ld(t.text)>e;return[{kind:"markup",value:d?t.mobileText:t.text,splashAlt:!d&&t.mobileText?t.mobileText:null}]}if(t?.thinking)return Od(t,e);if(t?.noChrome)return Bs(Ft(Tt(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const d=li(t?.text||"");if(d)return[...me({title:"Question",timestamp:_e(t?.createdAt||t?.time),body:d.question,width:Math.max(20,e),titleColor:In,borderColor:In,tableMode:s.tableMode}),...Hs({...t,text:d.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const d=Wa(t?.text||"");if(d.some(u=>u.kind==="system")){const u=[];let p=!1;for(const h of d)h.kind!=="system"&&h.text.trim()&&(Ds(u,Hs({...t,text:h.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:p})),p=!0);if(u.length>0)return u;const f=[];for(const h of d)h.kind!=="system"||!h.text.trim()||Ds(f,$d(h.text,t,e));if(f.length>0)return f}}if(t?.role!=="user"&&t?.role!=="assistant"){const d=ot(t?.text||"");if(t?.role==="system"&&!d)return[];const u=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!u)return[Md(d||t?.text||"",_e(t?.createdAt||t?.time))];const p=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return me({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:_e(t?.createdAt||t?.time),body:Tt(t?.text||""),width:Math.max(20,e),titleColor:t?.cardTitleColor||(t?.role==="system"?"yellow":"cyan"),borderColor:t?.cardBorderColor||"gray",tableMode:s.tableMode,...p?{bodyColor:"gray",fitToContent:!0}:{}})}const n=Bs(Ft(Tt(t?.text||""),{width:e,tableMode:s.tableMode})),i=Pd(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?In:null),r=s.skipPrefix?[]:xd(t,s),o=Fd(t,s);if(i.length===0){const d=r.length>0?[r]:[];return o.length>0?[...d,...o]:d}if(vd(i)){const d=r.length>0?[r,...i]:i;return o.length>0?[...d,...o]:d}const l=[];let c=r.length===0;for(const d of i){if(!Array.isArray(d)){c||(l.push(r),c=!0),l.push(d);continue}c?l.push(d):(l.push([...r,...d]),c=!0)}return l.push(...o),l}function Fd(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 Bd=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 Dd(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 Hd=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),Gd=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function jd(t,e){const s=String(t||"").toLowerCase();return s==="search_skills"||s.includes("skill")?e?"loading skills…":"loaded skills":Hd.has(s)?e?"reading facts…":"read facts":Gd.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 Ud(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=jd(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 Ii(t,e={}){if(t?.ui?.chatViewMode==="summary")return[];const s=je(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 w=r.length-1;w>=0;w-=1)if(r[w]?.role==="user"){o=Number(r[w]?.createdAt||0);break}const l=Array.isArray(i?.activity)?i.activity:[];let c=0,d=0;for(let w=l.length-1;w>=0;w-=1){const x=l[w],I=x?.eventType,E=Number(x?.createdAt||0);if(!c&&I==="assistant.turn_start"&&(c=E),!d&&(I==="assistant.turn_end"||I==="session.turn_completed")&&(d=E),c&&d)break}let u=0;o>d?u=o:c>d&&(u=c);let p=null;for(let w=l.length-1;w>=0;w-=1){const x=l[w];if(!(!x||Bd.has(x.eventType))){if(Number(x.createdAt||0)<=d)break;p=x;break}}const f=Number.isFinite(e.now)?e.now:Date.now(),h=u>0?Dd(f-u):"",m=String(e.spinnerFrame||"").trim()||"●",g=p?Ud(p):"",S=[{text:`${m} `,color:"cyan"},{text:"Working",color:"cyan"},...h?[{text:` · ${h}`,color:"gray"}]:[],...g?[{text:` — ${g}`,color:"gray"}]:[]],y=Math.max(24,Math.min(120,Math.floor(Number(e.maxWidth)||80)));return[ie(S,y)]}const Ar=4;let hs=[];function Ei(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 m of hs)if(m.sessionId===i.sessionId&&m.session===i.session&&m.byId===i.byId&&m.chat===i.chat&&m.viewMode===i.viewMode&&m.branding===i.branding&&m.principal===i.principal&&Object.is(m.maxWidth,i.maxWidth)&&m.tableMode===i.tableMode)return m.lines;const r=m=>(hs.unshift({...i,lines:m}),hs.length>Ar&&(hs.length=Ar),m),o=wi(t);if(!o||o.length===0)return r([{text:"No messages yet.",color:"gray"}]);const l=he(t?.auth?.principal),c=t?.sessions?.activeSessionId,d=c?t?.sessions?.byId?.[c]:null,u=he(d?.owner),p=!!(d&&(d.visibility&&d.visibility!=="private"||u&&l&&u!==l)),f={...s?.tableMode?{tableMode:s.tableMode}:{},...l?{viewerKey:l}:{},...u?{ownerKey:u}:{},...p?{sharedContext:!0}:{}},h=[];for(const[m,g]of o.entries()){if(g?.kind==="epoch-divider")h.push(Wd(g,e));else if(g?.kind==="regen-refused")h.push(zd(g,e));else if(g?.kind==="regen-failed")h.push(Vd(g,e));else{const y=Hs(g,e,f);Ds(h,y)}const S=o[m+1];S&&Ka(g,S)&&at(h[h.length-1]).trim().length>0&&h.push(Ua())}return r(h.length>0?h:[{text:"No messages yet.",color:"gray"}])}function xi(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 Wd(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 xi(n,"magenta",e)}const Kd={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 zd(t,e){const s=String(t?.reason||"unknown"),i=` ↻ regeneration refused · ${Kd[s]||s.replace(/_/g," ")} `;return xi(i,"yellow",e)}function Vd(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 xi(r,"red",e)}function vi(t,e=80,s={}){const n=Id(t);if(!n||n.length===0)return[];const i=Math.max(20,Number(e)||80),r=n.filter(m=>m.pendingPhase==="queued").length,o=n.filter(m=>m.pendingPhase==="pending").length,l=n.filter(m=>m.pendingPhase==="cancelling").length,c=n.filter(m=>m.pendingPhase==="rejected").length,d=[];o>0&&d.push(`${o} pending`),r>0&&d.push(`${r} queued`),l>0&&d.push(`${l} cancelling`),c>0&&d.push(`${c} rejected`);const f=[[{text:` queued prompts: ${d.length>0?d.join(" · "):"queued prompts"} `,color:"gray",trailingRule:!0}]],h=s?.tableMode?{tableMode:s.tableMode}:{};for(const[m,g]of n.entries()){Ds(f,Hs(g,i,h));const S=n[m+1];S&&Ka(g,S)&&at(f[f.length-1]).trim().length>0&&f.push(Ua())}return f}function qd(t){const e=wi(t),s=[],n=new Set;for(const i of e||[])for(const r of gc(i?.text||"")){const o=`${r.sessionId}/${r.filename}`;n.has(o)||(n.add(o),s.push(r))}return s}function Yd(t){const e=wi(t),s=[],n=new Set;for(const i of e||[])for(const r of yc(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 ki(t,e){const s=qo(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function Xd(t){return qo(t)||"(unknown)"}function za(t,e={}){const s=je(t),n=t.sessions?.byId||{},i=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],r=Si(n),o=bi(i,n),l=Ca(e?.width);if(!s)return{color:"cyan",title:ze("Chat","cyan"),titleRight:null,animateTitleRight:!1};const c=ue(s.sessionId),d=s.isSystem?"yellow":"cyan",u=ze(s.isSystem?`⚙ ${Gt(s,t.branding?.title||"PilotSwarm")}`:Ys(s)||"Chat",d),p=i.find(I=>I.sessionId===s.sessionId),f=Ba(s.sessionId,p,r,o);f&&u.push({text:` ${f.text}`,color:f.color}),l||u.push({text:` [${c}]`,color:"gray"});const h=t.history?.bySessionId?.get(s.sessionId)||null,m=Array.isArray(t.outbox?.bySessionId?.[s.sessionId])?t.outbox.bySessionId[s.sessionId]:[],g=t.ui?.chatViewMode==="summary"?null:bd(s,h,h?.chat||[],m),S=t.connection?.mode||"local",y=ld(s,S),w=Nd(g),x=w?[...y,...y.length?[{text:" · ",color:"gray"}]:[],...w]:y;return{color:s.isSystem?"yellow":"cyan",title:u,titleRight:x.length?x:null,animateTitleRight:!!g}}function Qd(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function Va(t){const e=tl(t),s=e.selected?e.nodes.find(o=>o.label===e.selected):null,n=ze("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,l,c="white")=>{l==null||l===""||i.push([{text:`${o.padEnd(10)} `,color:"gray"},{text:String(l),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,l=s.pkgInstalled.length-o;r("Packages",`epoch ${s.pkgEpoch} · ${o} ok${l?` · ${l} error`:""}`,l?"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?Ye(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 Ai(t,e=12){const s=Qd(t),n=je(t),i=ze("Activity","gray");return n?.isGroup?{title:i,disabled:!0,lines:[{text:il,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 qa(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 Ya(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":qa(e)}function Jd(t){return t==="raw"?"raw summary":"pretty text"}function Zd(t){return t?.sessionId?`session-${t.sessionId}`:null}function ep(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},i=Zd(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 tp(t){const e=cs(t?.podName)||t?.podName||"node",s=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):""),n=String(t?.level||"info").toUpperCase(),i=t?.category==="orchestration"?"◆":t?.category==="activity"?"●":"•";return[{text:`[${t?.time||"--:--:--"}] `,color:"gray"},{text:`${i} `,color:Ya(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${ue(s)}] `,color:"gray"}]:[],{text:`${n} `,color:qa(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function sp(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${ue(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:Ya(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function np(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:Jd(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=ep(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"?tp(o):sp(o))]}function Cr(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function ip(t){return/\.(json|jsonl)$/i.test(String(t||""))}function rp(t){return Ve.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function op(t=""){const e=String(t||"").split(`
|
|
51
|
+
`);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function Tr(t,{selected:e=!1,width:s=24,label:n=null}={}){const i=Math.max(8,s),r=Cr(t)?"# ":ip(t)?"{ ":"• ",o=Xa(`${r}${n||t}`,i).padEnd(i," ");return e?Ye(o):{text:o,color:Cr(t)?"cyan":"white",bold:!1}}function He(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function ap(t,e={}){if(!t)return new Set;const{childMap:s}=yi(e),n=new Set([t]),i=[t];for(;i.length>0;){const r=i.shift(),o=s.get(r)||[];for(const l of o)!l||n.has(l)||(n.add(l),i.push(l))}return n}function Gs(t,e=He(t)){const s=je(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=ap(s,t.sessions?.byId||{});if(r.size===0)return[];const o=[],l=new Set;for(const c of[s,...n,...Object.keys(t.sessions?.byId||{}),...i])!c||l.has(c)||!r.has(c)||(o.push(c),l.add(c));for(const c of r)l.has(c)||o.push(c);return o}function Mr(t){const s=je(t)?.sessionId;if(!s)return[];const i=t.history?.bySessionId?.get?.(s)?.events||[],r=new Set,o=[],l=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{})\]]+)/g;for(const c of i){const d=typeof c?.data?.content=="string"?c.data.content:"";if(!d)continue;l.lastIndex=0;let u;for(;(u=l.exec(d))!==null;){const p=`${u[1]}/${u[2]}`;r.has(p)||(r.add(p),o.push(p))}}return o}function ht(t){const e=He(t);je(t)?.sessionId;const s=t.files?.filter?.query||"",n=Gs(t,e),i=e==="allSessions"||n.length>1,r=[];for(const o of n){const l=Os(t.files?.bySessionId?.[o]?.entries);for(const c of l){const d=c.filename;r.push({id:`${o}/${d}`,sessionId:o,filename:d,entry:c,label:i?`[${ue(o)}] ${d}`:d})}}return r.filter(o=>ft(o.filename,s)||ft(o.sessionId,s)||ft(o.label,s))}function it(t){const e=ht(t);if(e.length===0)return null;const s=t.files?.selectedArtifactId||null;if(s){const o=e.find(l=>l.id===s);if(o)return o}if(He(t)==="allSessions"){const o=je(t)?.sessionId||null,l=o&&t.files?.bySessionId?.[o]?.selectedFilename||null;if(o&&l){const c=e.find(d=>d.sessionId===o&&d.filename===l);if(c)return c}return e[0]}const i=je(t)?.sessionId||null,r=i&&t.files?.bySessionId?.[i]?.selectedFilename||null;return e.find(o=>o.sessionId===i&&o.filename===r)||e[0]}function Ci(t,e={}){const s=je(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,l=He(t),c=t.files?.filter?.query||"",d=ht(t),u=it(t),p=u?.filename||null,f=Math.max(0,d.findIndex(P=>P.id===u?.id)),h=u?.sessionId&&p&&t.files?.bySessionId?.[u.sessionId]?.previews?.[p]||null,m=h||u?.entry||null,g=s?ue(s.sessionId):"",S=Gs(t,l),y=l!=="allSessions"&&S.some(P=>P&&P!==o),w=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(P=>P?.sessionId||P):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),x=l==="allSessions"&&w.some(P=>!t.files?.bySessionId?.[P]?.loaded||t.files?.bySessionId?.[P]?.loading),I=l==="allSessions"&&w.map(P=>t.files?.bySessionId?.[P]?.error).find(Boolean)||null,E=[rp("files"),...s||l==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(l==="allSessions")x&&d.length===0?E.push({text:"Loading exported files across all sessions…",color:"gray"}):I&&d.length===0?E.push({text:I,color:"red"}):d.length===0?(E.push({text:c?`No artifacts matched "${c}" across any session.`:"No exported files across any session yet.",color:"gray"}),E.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"})):E.push(...d.map((P,j)=>Tr(P.filename,{selected:j===f,width:n,label:P.label})));else if(s){const P=o?t.files?.bySessionId?.[o]:null;Array.isArray(P?.entries)&&P.entries;const j=d.filter(K=>S.includes(K.sessionId));P?.loading?E.push({text:"Loading exported files…",color:"gray"}):P?.error?E.push({text:P.error,color:"red"}):j.length===0&&S.every(K=>{const z=t.files?.bySessionId?.[K]?.entries;return!Array.isArray(z)||z.length===0})?(E.push({text:c?`No artifacts matched "${c}" for this ${y?"session tree":"session"}.`:`No exported files for this ${y?"session tree":"session"} yet.`,color:"gray"}),E.push({text:c?"Clear the query or upload an artifact to this session.":y?"Artifacts exported by this session or any child session will appear here.":"Agents must write/export artifacts before they appear here.",color:"gray"})):E.push(...j.map((K,z)=>Tr(K.filename,{selected:z===f,width:n,label:K.label})))}let b,k;!s&&l!=="allSessions"?(k=[{text:"Preview",color:"cyan",bold:!0}],b=[{text:"No session selected.",color:"gray"}]):p?h?.loading?(k=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||u?.sessionId&&u.sessionId!==o)&&u?.sessionId?[{text:` · ${ue(u.sessionId)}`,color:"gray"}]:[]],b=[{text:"Loading file preview…",color:"gray"}]):h?.error?(k=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||u?.sessionId&&u.sessionId!==o)&&u?.sessionId?[{text:` · ${ue(u.sessionId)}`,color:"gray"}]:[]],b=[{text:h.error,color:"red"}]):(k=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||u?.sessionId&&u.sessionId!==o)&&u?.sessionId?[{text:` · ${ue(u.sessionId)}`,color:"gray"}]:[],...h?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:h?.isBinary===!0?[{text:" [file]",color:"gray"}]:h?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],b=h?.renderMode==="markdown"?Bs(Ft(h?.content||"",{width:i})):op(h?.content||"")):(k=[{text:"Preview",color:"cyan",bold:!0}],b=[{text:"Select a file to preview it here.",color:"gray"}]);const M=l==="allSessions"?"Files: all sessions":s?`Files: ${g}${y?" tree":""}`:"Files",N=l==="allSessions"?"all sessions":s?`${g}${y?" tree":""}`:"Files",B=l==="allSessions"?`Artifacts${d.length>0?` [${d.length}]`:""}`:`Artifacts${y?" tree":""}${d.length>0?` [${d.length}]`:""}`,_=c?` · @${c}`:"";return{panelTitle:[{text:`${M}${_}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${N}${_}`,color:"magenta",bold:!0}],listTitle:[{text:`${B}${_}`,color:"cyan",bold:!0}],listLines:E,listBodyLines:E.slice(1),selectedIndex:f,selectedFilename:p,selectedSessionId:u?.sessionId||null,scope:l,previewTitle:k,previewLines:b,previewContent:h?.content||"",previewContentType:h?.contentType||"",previewRenderMode:h?.renderMode||null,previewIsBinary:m?.isBinary===!0,previewSizeBytes:m?.sizeBytes??null,previewUploadedAt:m?.uploadedAt||"",previewSource:m?.source||null,previewError:h?.error||null,previewLoading:!!h?.loading,previewScrollOffset:t.ui.scroll.filePreview||0,fullscreen:!!t.files?.fullscreen,fullscreenTitle:[{text:M,color:"magenta",bold:!0},...p?[{text:" · ",color:"gray"},{text:p,color:"cyan",bold:!0}]:[],...r?[{text:" [f filter] [u upload] [a download] [x delete] [o open] [v/esc close fullscreen]",color:"gray"}]:[]]}}function Nr(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);return Number.isNaN(e.getTime())?"—":e.toISOString().slice(0,10)}function At(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 lp(t){const e=String(t||"").toLowerCase();return e.endsWith(".md")?"markdown":e.endsWith(".json")?"json":/\.(mjs|cjs|js)$/.test(e)?"javascript":"text"}function cp(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,l=o&&!!n.storeAsSystem,c=l?!!r.configured:!!s?.githubCopilotKeySet,d=l?"System key":"key",u=r.configured&&r.changedBy?` (set by ${r.changedBy})`:"",p=n.saving?"Saving...":n.editing?"Editing — Enter to save, Esc to cancel":l?r.configured?`System key configured — ownerless system sessions use it for GitHub Copilot models${u}`:"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||{},h=Array.isArray(f.list)?f.list:[],m=C=>!!(o||C?.owner&&i&&C.owner.provider===i.provider&&C.owner.subject===i.subject),g=Yu(t?.sessions?.byId),S=new Set;for(const C of h){if(C?.scope==="shared")continue;const H=he(C?.owner)||String(C?.createdBy||"").trim().toLowerCase();!H||H===gi||S.add(H)}const y=S.size>1,w=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:m(C),ownerBadge:C.scope==="shared"||!y?null:$a(Xu(C,g)),selected:e.section==="packages"&&f.selectedName===C.name}),x=C=>!!(C?.owner&&i&&C.owner.provider===i.provider&&C.owner.subject===i.subject),I=t.sessions?.ownerFilter,E=C=>{if(!I||I.all===!0)return!0;const H=he(C?.owner);return H?Array.isArray(I.ownerKeys)&&I.ownerKeys.includes(H):I.includeUnowned===!0},b=h.filter(C=>C.scope==="shared").map(w),k=h.filter(C=>C.scope!=="shared"&&x(C)).map(w),M=h.filter(C=>C.scope!=="shared"&&!x(C)&&E(C)).map(C=>({...w(C),ownerLabel:C?.createdBy||C?.owner?.subject||"another user"})),N=["packages","workers"].includes(e.section)?e.section:"ghcp",B=[{id:"ghcp",kind:"section",depth:0,label:"GitHub Keys",selected:N==="ghcp"},{id:"agents",kind:"section",depth:0,label:"Agents",selected:N==="packages"&&!f.selectedName},{id:"group:shared",kind:"group",depth:1,label:"Shared",count:b.length},...b.map(C=>({id:`pkg:${C.name}`,kind:"package",depth:2,label:C.name,...C})),{id:"group:user",kind:"group",depth:1,label:"User",count:k.length},...k.map(C=>({id:`pkg:${C.name}`,kind:"package",depth:2,label:C.name,...C})),...M.length>0?[{id:"group:others",kind:"group",depth:1,label:"Other users",count:M.length},...M.map(C=>({id:`pkg:${C.name}`,kind:"package",depth:2,label:C.name,...C}))]:[],...o?[{id:"workers",kind:"section",depth:0,label:"Workers",selected:N==="workers"}]:[]],_=f.detail||null;let P=null;if(f.selectedName){const C=h.find(U=>U.name===f.selectedName)||null,H=_?.versions?.find(U=>U.versionId===_.activeVersionId)||null,Q=H?.manifest||C?.active?.manifest||{},le=Date.now()-9e4,ye=(Array.isArray(f.workerState)?f.workerState:[]).filter(U=>{const Te=U?.updatedAt instanceof Date?U.updatedAt:new Date(U?.updatedAt??0);return!Number.isNaN(Te.getTime())&&Te.getTime()>=le}),we=ye.length,Ie=H?ye.filter(U=>U.installed?.[f.selectedName]?.semver===H.semver&&U.installed?.[f.selectedName]?.status==="ok").length:0,Fe=_?m(_):C?m(C):!1;P={name:f.selectedName,loading:!!f.detailLoading,error:f.detailError||null,scope:(_?.scope||C?.scope)==="shared"?"shared":"user",enabled:_?!!_.enabled:!!C?.enabled,canManage:Fe,createdBy:_?.createdBy||C?.createdBy||null,createdAtText:Nr(_?.createdAt||C?.createdAt),description:typeof Q.description=="string"?Q.description:"",activeSemver:H?.semver||C?.active?.semver||null,activeSha12:H?.sha256?String(H.sha256).slice(0,12):null,sizeText:At(H?.sizeBytes??C?.active?.sizeBytes),agents:Array.isArray(Q.agents)?Q.agents.map(U=>({name:U.name,description:U.description||"",toolCount:Array.isArray(U.tools)?U.tools.length:0,skillCount:Array.isArray(U.skills)?U.skills.length:0})):[],versions:(_?.versions||[]).map(U=>({semver:U.semver,sha12:String(U.sha256||"").slice(0,12),dateText:Nr(U.createdAt),active:U.versionId===_?.activeVersionId})),fleet:we>0&&H?{current:Ie,total:we,text:`${Ie}/${we} workers current`}:null,actionPending:f.action?.pending||null,actionError:f.action?.error||null}}const j=f.workspace||{};let K=null;if(f.selectedName){const C=j.tree,H=new Set(j.expandedDirs||[]),Q=[];if(C){const le=U=>{const Te=U.split("/");for(let $e=1;$e<Te.length;$e++)if(!H.has(Te.slice(0,$e).join("/")))return!1;return!0},ye=Array.isArray(C.dirs)?C.dirs:[],we=Array.isArray(C.files)?C.files:[],Ie=U=>String(U).split("/").join("\0"),Fe=[...ye.map(U=>({type:"dir",path:U})),...we.map(U=>({type:"file",path:U.path,size:U.size}))].sort((U,Te)=>Ie(U.path)<Ie(Te.path)?-1:1);for(const U of Fe){if(!le(U.path))continue;const Te=U.path.split("/").length-1;Q.push({type:U.type,path:U.path,label:U.path.split("/").pop()+(U.type==="dir"?"/":""),depth:Te,expanded:U.type==="dir"?H.has(U.path):void 0,sizeText:U.type==="file"?At(U.size):null,selected:j.selectedPath===U.path})}}const Y=j.file;K={loading:!!j.treeLoading,error:j.treeError||null,semver:j.tree?.semver||null,treeRows:Q,file:Y?{path:Y.path,sizeText:At(Y.size),truncated:!!Y.truncated,isBinary:Y.encoding==="base64",text:Y.encoding==="base64"?null:String(Y.content||""),language:lp(Y.path)}:null,fileLoading:!!j.fileLoading,fileError:j.fileError||null,selectedPath:j.selectedPath||null}}const z=e.workers||{},se=Array.isArray(z.list)?z.list:[],ne=9e4,ve=Date.now(),oe=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`,be=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 H=Math.floor(C/3600);return H<48?`${H}h ${Math.floor(C%3600/60)}m`:`${Math.floor(H/24)}d ${H%24}h`},v=se.map(C=>{const H=C?.updatedAt instanceof Date?C.updatedAt:new Date(C?.updatedAt??0),Q=Number.isNaN(H.getTime())?Number.NaN:ve-H.getTime(),Y=C?.health||{},le=C?.info||{},ye=C?.state?.["agent-packages"]||null,we=ye?.installed&&typeof ye.installed=="object"?Object.values(ye.installed):[],Ie=we.filter(Fe=>Fe?.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(Q)&&Q<=ne,agoText:oe(Q),uptimeText:be(Y.uptimeS),rssText:At(Y.rssBytes),sessions:Number.isFinite(Y.activeSessions)?Y.activeSessions:null,eventLoopText:Number.isFinite(Y.eventLoopDelayP99Ms)?`${Y.eventLoopDelayP99Ms}ms`:null,sdkVersion:typeof le.sdkVersion=="string"?le.sdkVersion:null,substrate:typeof le.runtime?.substrate=="string"?le.runtime.substrate:null,consumes:Array.isArray(le.consumes)?le.consumes:[],owner:C?.owner?.subject?String(C.owner.subject):null,pkgEpoch:Number.isFinite(ye?.epoch)?ye.epoch:null,pkgText:ye?`${we.length-Ie} ok${Ie?` · ${Ie} error`:""}`:null}}).sort((C,H)=>C.pool===H.pool?C.id<H.id?-1:1:C.pool<H.pool?-1:1),O=v.filter(C=>C.live),G={loading:!!z.loading,error:z.error||null,empty:v.length===0&&!z.loading,rows:v,counts:{registered:v.length,live:O.length,ready:O.filter(C=>C.phase==="ready").length,starting:O.filter(C=>C.phase==="starting").length,draining:O.filter(C=>C.phase==="draining").length,pools:[...new Set(O.map(C=>C.pool))].length},summaryText:v.length?`${O.length} live / ${v.length} registered`:null},L={loading:!!f.loading,error:f.error||null,empty:h.length===0&&!f.loading,sharedCount:b.length,userCount:k.length,selectedName:f.selectedName||null,detail:P,workspace:K,changelog:f.changelog||null,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}},R=[];return N==="workers"?(R.push({id:"workersRefresh",label:"Refresh workers",key:"r"}),R.push({id:"showPackages",label:"Agents",key:"a"}),R.push({id:"showGhcp",label:"GitHub Keys",key:"g"}),R.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:o,section:N,settingsTree:B,packages:L,workers:G,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:c,storeAsSystem:l,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:p},systemGhcpKey:{supported:!!r.supported,loading:!!r.loading,configured:!!r.configured,changedBy:r.changedBy||null,changedAt:r.changedAt||null,error:r.error||null},actions:R}):N==="packages"?(R.push({id:"packagesRefresh",label:"Refresh packages",key:"r"}),R.push({id:"packagesNext",label:"Next package",key:"j"}),R.push({id:"packagesPrev",label:"Previous package",key:"k"}),R.push({id:"showGhcp",label:"GitHub Keys",key:"g"}),R.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:o,section:N,settingsTree:B,packages:L,workers:G,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:c,storeAsSystem:l,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:p},systemGhcpKey:{supported:!!r.supported,loading:!!r.loading,configured:!!r.configured,changedBy:r.changedBy||null,changedAt:r.changedAt||null,error:r.error||null},actions:R}):(n.editing?(R.push({id:"save",label:"Save",key:"Enter"}),R.push({id:"cancel",label:"Cancel",key:"Esc"})):(R.push({id:"edit",label:c?`Replace ${d}`:`Set ${d}`,key:"e"}),c&&R.push({id:"clear",label:`Clear ${d}`,key:"c"}),R.push({id:"refresh",label:"Refresh",key:"r"})),R.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),N==="ghcp"&&R.splice(R.length-1,0,{id:"showPackages",label:"Agents",key:"a"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:o,section:N,settingsTree:B,packages:L,workers:G,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:c,storeAsSystem:l,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:p},systemGhcpKey:{supported:!!r.supported,loading:!!r.loading,configured:!!r.configured,changedBy:r.changedBy||null,changedAt:r.changedAt||null,error:r.error||null},actions:R})}function up(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=je(t),i=!!n?.pendingQuestion?.question,r=n?.sessionId&&Array.isArray(t.outbox?.bySessionId?.[n.sessionId])?t.outbox.bySessionId[n.sessionId]:[],o=r.length>0,l=r.some(w=>w?.phase==="pending"),c=t.ui.promptEdit?.sessionId===n?.sessionId,d=c&&t.ui.promptEdit?.phase==="queued",u=c&&t.ui.promptEdit?.phase==="cancelling",p=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 · ←/→ open/close · enter start · 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,h=Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds.length:0;if(f&&e===T.SESSIONS)return{left:`Select mode · ${h} selected`,right:"up/down move · space toggle · ctrl-g group · c cancel · d complete · D hard delete · V/esc exit"};const g=(t.ui?.chatViewMode==="summary"?"summary":"transcript")==="summary"?"s transcript":"s summary",S={[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]:`${g} · j/k scroll · ctrl-u/ctrl-d page · e older history · g/G top/bottom · d done · ${p} · [/] 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 · ${p} · 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 · ${p} · 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 · ${p} · 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 · ${p} · 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 · ${p} · 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 · ${p} · [/] 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?d?`queued prompt selected · d delete · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:u?`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"}`:l?`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 y=S[e]||S[T.SESSIONS];return Ga(je(t))&&(y=`ctrl-x stop · ${y}`),{left:t.ui.statusText,right:y}}function yt(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function ie(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 Re(t){return Array.from(String(t||"")).length}function Xa(t,e){const s=String(t||"");return e<=0?"":Re(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function Lt(t,e){const s=Xa(t,e),n=Math.max(0,e-Re(s));return s+" ".repeat(n)}function J(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function Ee(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 Pr(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 Qa(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?Re(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function dp(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 Ja(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 pp(t,e=""){return Ja([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function fp(t,e=""){return Ja([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function cs(t){const e=String(t||"").trim();if(!e||e==="(unknown)")return null;const s=e.split(/[/:]/).pop()||e,n=s.length<=5?s:s.slice(-5);return n.replace(/^[^a-zA-Z0-9]+/,"")||n}const hp=300*1e3,mp="last 5m";function Ti(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-hp,endMs:e,label:mp}}function gp(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 Za(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 yp=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done"]);function Sp(t){return yp.has(t)}function bp(t){const e=Xo(t?.createdAt),s=cs(t?.workerNodeId),n=dp(t),i=Qa(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 l=Number(t?.data?.turnIndex??t?.data?.iteration);return{...o,type:"turn_end",color:"gray",detail:`turn ${t?.data?.iteration??"?"} done`,...Number.isFinite(l)?{completedTurn:l}:{}}}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 ${Ct(t?.data?.seconds??0)}`};case"session.wait_completed":return{...o,type:"timer",color:"yellow",detail:`${Ct(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const l=fp(t,i);return{...o,type:"dehydrate",color:"yellow",detail:l?`lossy ${l}`:"lossy handoff"}}case"session.dehydrated":return{...o,type:"dehydrate",color:"cyan",detail:`ZZ ${pp(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||ue(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${Ct(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${Fs(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 ${Fs(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 el(t=[]){const e=[];for(const s of t||[]){const n=bp(s);n&&e.push({...n,nodeLabel:Sp(n.type)?"orch":n.nodeLabel||"orch"})}return e}function wp(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 Ip(t){const e=String(t?.error||"").trim();if(!e)return null;const s=mi(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),i=Number.isFinite(n)?n:Date.now();return{time:Xo(i),createdAtMs:i,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${Qa(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function Ep(t,e){const s=Ip(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 xp(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=el(i?.events||[]);for(const o of r){if(!o?.nodeLabel||o.nodeLabel==="orch")continue;const l=Number(o.createdAtMs||0);Number.isFinite(l)&&(l<e||l>s||n.add(o.nodeLabel))}}return Array.from(n).sort((i,r)=>i.localeCompare(r))}function vp(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const i of n?.events||[]){if(!Za(i,e))continue;const r=cs(i?.workerNodeId);r&&s.add(r)}return Array.from(s).sort((n,i)=>n.localeCompare(i))}function Mi(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 _r(t){return Array.isArray(t?.runs)?t.runs.reduce((e,s)=>e+Re(String(s.text??"")),0):Array.isArray(t)?t.reduce((e,s)=>e+Re(String(s.text??"")),0):Re(String(t?.text??""))}function kp(t,e,s){const n=[{text:Lt("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((i,r)=>{r>0&&n.push({text:" ",color:null}),n.push({text:Lt(i,s),color:"white",bold:!0})}),Mi(n)}function Ap(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 Cp(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=[],l=[];if(typeof r.orchestrationVersion=="string"&&r.orchestrationVersion&&(o.push(`v ${r.orchestrationVersion}`),l.push(`v${r.orchestrationVersion}`)),r.historyEventCount!=null&&(o.push(`hist ${Number(r.historyEventCount)||0} ev`),l.push(`h${Number(r.historyEventCount)||0}`)),r.historySizeBytes!=null){const c=Ee(r.historySizeBytes);o.push(c),l.push(c)}r.queuePendingCount!=null&&(o.push(`q ${Number(r.queuePendingCount)||0}`),l.push(`q${Number(r.queuePendingCount)||0}`)),r.kvUserKeyCount!=null&&(o.push(`kv ${Number(r.kvUserKeyCount)||0} keys`),l.push(`kv${Number(r.kvUserKeyCount)||0}`)),r.kvTotalValueBytes!=null&&o.push(Ee(r.kvTotalValueBytes)),i=s<=40?l.join(" · "):o.join(" | "),i||(i="orchestration stats unavailable")}return s<=52?[ie([{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 Tp(t,e,s,n){const i=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],r=[{text:Lt(t.time||"",s),color:"white"},{text:" ",color:null}];return e.forEach((o,l)=>{l>0&&r.push({text:" ",color:null}),o===i?r.push({text:Lt(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):r.push({text:Lt("│",n),color:"gray"})}),Mi(r)}const Mp=new Set(["none","minimal","low","medium","high","xhigh","max"]);function Np(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&&Mp.has(n)?s.length-2:s.length-1;return s[Math.max(0,i)]||s[0]||"unknown"}function Rr(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 ut(t){return Number(t||0).toLocaleString("en-US")}function Pp(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 _p(t,{expanded:e,selected:s,maxWidth:n}){const i=e?"v":">",r=Np(t?.model),o=t?.durationMs!=null?`${(Number(t.durationMs)/1e3).toFixed(1)}s`:"n/a",l=`${i} Mod: ${r} tok ${Rr(t?.tokensInput)}/${Rr(t?.tokensOutput)} dur ${o}`,c=[];if(s?c.push(Ye(Lt(l,Math.max(18,n)))):c.push([{text:l,color:"magenta"}]),e){const d=[["model",t?.reasoningEffort?`${t?.model||"(unknown)"}:${t.reasoningEffort}`:t?.model||"(unknown)"],["duration",t?.durationMs!=null?`${ut(t.durationMs)} ms`:null],["tokens",`${ut(t?.tokensInput)} in / ${ut(t?.tokensOutput)} out`],["cache",`${ut(t?.tokensCacheRead)} read / ${ut(t?.tokensCacheWrite)} write`],["tools",`${ut(t?.toolCalls)} calls / ${ut(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(([,u])=>u!=null&&u!=="");for(const[u,p]of d)c.push([{text:` ${u}: `,color:"gray"},{text:String(p),color:"white"}])}return c}function Rp(t,e,s,n={}){const i=!!n?.allowWideColumns,r=Cp(t,e,s),o=t.history.bySessionId.get(e.sessionId),l=Ep(wp(el(o?.events||[])),e);if(l.length===0)return{stickyLines:r,lines:[J("No events yet - interact with this session to populate the sequence diagram.")]};const c=Ti(t),d=l.filter(_=>gp(_,c)),u=(d.length>0?d:l).slice(-48),p=xp(t,c.startMs,c.endMs),f=Array.from(new Set(u.map(_=>_.nodeLabel).filter(_=>_&&_!=="orch"))).sort((_,P)=>_.localeCompare(P)),h=p.length>0?p:f,m=Math.min(13,Math.max(8,...u.map(_=>Re(String(_.time||""))))),g=Math.max(18,s),S=Math.max(1,Math.floor((g-m-1)/6));let y=["orch",...h];if(!i&&y.length>S){const _=Math.max(1,S-1);y=[...y.slice(0,_),"…"]}const w=Math.max(0,y.length-1),x=Math.max(4,Math.floor((g-m-1-w)/Math.max(1,y.length))),I=n?.sequenceExpansion||null,E=I?Pp(o?.events||[]):null,b=I?new Set((I.expandedTurns||[]).map(Number)):null,k=I&&I.selectedTurn!=null?Number(I.selectedTurn):null,M=[];for(const _ of u)if(M.push(Tp(_,y,m,x)),I&&_.completedTurn!=null){const P=Number(_.completedTurn),j=E.get(P);if(j)for(const K of _p(j,{expanded:b.has(P),selected:k===P,maxWidth:g}))M.push(K)}const N=kp(y,m,x),B=M.reduce((_,P)=>Math.max(_,_r(P)),_r(N));return{stickyLines:[...r,J(`Window: ${c.label}`,"gray"),N,Ap(y,m,x,B)],lines:M}}function $p(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 Op(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!Za(s[n],e))continue;const i=cs(s[n]?.workerNodeId);if(i)return i}return null}function Lp(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 Fp(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 Bp(t,e,s){const n=t?.isSystem?Gt(t,e):t?.title||ue(t?.sessionId),i=t?.isSystem?"⚙ ":t?.serviceKind?"⚗ ":`${Ra(t)||"."} `;return{sessionId:t?.sessionId||null,text:`${i}${n}`,color:t?.isSystem?"yellow":Ot(t),bold:!!t?.isSystem,active:!!s}}function tl(t){const e=Ti(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,l=new Map;for(const h of i){const m=cs(h?.workerNodeId);if(!m)continue;const g=h?.updatedAt instanceof Date?h.updatedAt.getTime():new Date(h?.updatedAt??0).getTime(),S=Number.isFinite(g)?r-g:Number.NaN,y=h?.health||{};l.set(m,{label:m,workerNodeId:String(h?.workerNodeId??""),registered:!0,live:Number.isFinite(S)&&S<=o,phase:["starting","ready","draining"].includes(h?.phase)?h.phase:"ready",pool:String(h?.pool??"default"),agoText:Lp(S),uptimeText:Fp(y.uptimeS),rssText:Number.isFinite(y.rssBytes)?At(y.rssBytes):null,heapText:Number.isFinite(y.heapUsedBytes)?At(y.heapUsedBytes):null,eventLoopText:Number.isFinite(y.eventLoopDelayP99Ms)?`${y.eventLoopDelayP99Ms}ms`:null,sessions:Number.isFinite(y.activeSessions)?y.activeSessions:null,sdkVersion:typeof h?.info?.sdkVersion=="string"?h.info.sdkVersion:null,substrate:typeof h?.info?.runtime?.substrate=="string"?h.info.runtime.substrate:null,capabilities:h?.info?.capabilities&&typeof h.info.capabilities=="object"?Object.entries(h.info.capabilities).filter(([,w])=>!!w).map(([w])=>w).sort():[],consumes:Array.isArray(h?.info?.consumes)?h.info.consumes:[],owner:h?.owner?.subject?String(h.owner.subject):null,pkgEpoch:Number.isFinite(h?.state?.["agent-packages"]?.epoch)?h.state["agent-packages"].epoch:null,pkgInstalled:h?.state?.["agent-packages"]?.installed&&typeof h.state["agent-packages"].installed=="object"?Object.entries(h.state["agent-packages"].installed).map(([w,x])=>({name:w,semver:x?.semver??null,status:x?.status==="error"?"error":"ok",error:x?.error?String(x.error):null})):[],pkgLastError:h?.state?.["agent-packages"]?.lastError?String(h.state["agent-packages"].lastError):null,executing:[]})}for(const h of vp(t,e))l.has(h)||l.set(h,{label:h,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 h of $p(t)){const m=t.sessions.byId[h];if(!m)continue;const g=t.history.bySessionId.get(h);g?.events||(c+=1);const S=Op(g,e),y=S?l.get(S):null;y&&y.executing.push(Bp(m,s,h===n))}const d=Array.from(l.values()).sort((h,m)=>{if(h.registered!==m.registered)return h.registered?-1:1;if(h.live!==m.live)return h.live?-1:1;const g=String(h.pool??"~").localeCompare(String(m.pool??"~"));return g!==0?g:h.label.localeCompare(m.label)});d.forEach((h,m)=>{h.ordinal=m+1});const u=d.filter(h=>h.registered),p=t.ui?.nodeMapSelectedNode,f=p&&d.some(h=>h.label===p)?p:d[0]?.label??null;return{windowLabel:e.label,degraded:u.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:u.length,liveCount:u.filter(h=>h.live).length,executingTotal:d.reduce((h,m)=>h+m.executing.length,0),missingHistoryCount:c,selected:f,nodes:d}}function Dp(t,e,s={}){const n=tl(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,l=r.live?"●":"○",c=r.live?r.phase==="draining"?"red":r.phase==="starting"?"yellow":"green":"gray",d=[{text:o?"› ":" ",color:"green",bold:o,nodeSelect:r.label,nodeSelected:o},{text:r.ordinal<=9?`${r.ordinal} `:" ",color:"gray",nodeSelect:r.label},{text:`${l} `,color:c,nodeSelect:r.label},{text:r.label.padEnd(7),color:o||r.live?"white":"gray",bold:o,nodeSelect:r.label}];if(r.registered){d.push({text:` ${(r.phase||"").padEnd(8)}`,color:c,nodeSelect:r.label}),d.push({text:` ${r.pool}`,color:"gray",nodeSelect:r.label});const u=[r.executing.length?`${r.executing.length} sess`:null,r.rssText,r.uptimeText?`up ${r.uptimeText}`:null,r.agoText].filter(Boolean).join(" · ");u&&d.push({text:` ${u}`,color:"gray",nodeSelect:r.label})}else d.push({text:" activity only",color:"gray",nodeSelect:r.label}),r.executing.length&&d.push({text:` · ${r.executing.length} sess`,color:"gray",nodeSelect:r.label});i.push(Mi(d))}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 Hp(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=[],l=[];let c=0;for(const h of n){const m=ie([{text:`${h.providerId}`,color:"cyan",bold:!0},{text:` (${h.providerType||"provider"})`,color:"gray"}],r);o.push(m),l.push(null);for(const g of h.models||[]){const S=Array.isArray(s.items)?s.items.findIndex(E=>E.id===g.id):-1,y=S===i,w=!!g.disabled,x=ie([{text:"· ",color:"gray"},{text:g.modelName||g.qualifiedName||g.id,color:w?"gray":"white",bold:!!g.isDefault&&!w},...g.cost?[{text:` [${g.cost}]`,color:"gray"}]:[],...w?[{text:" ⊘ needs GitHub key",color:"yellow"}]:[],...g.isDefault?[{text:" ← current default",color:"gray"}]:[]],r),I=y?Ye(x.map(E=>E.text).join("").padEnd(r," ")):x;y&&(c=o.length),o.push(I),l.push(S>=0?S:null)}}const d=Array.isArray(s.items)&&s.items[i]||null,u=Array.isArray(d?.supportedReasoningEfforts)?d.supportedReasoningEfforts.filter(Boolean):[],p=typeof d?.defaultReasoningEffort=="string"?d.defaultReasoningEffort:null,f=d?[[{text:d.modelName||d.qualifiedName||d.id,color:"white",bold:!0}],[{text:`${d.providerId} (${d.providerType||"provider"})`,color:"gray"}],...d.cost?[[{text:`Cost: ${d.cost}`,color:"gray"}]]:[],...u.length>0?[[{text:`Reasoning: ${u.join(", ")}`,color:"gray"}]]:[],...p?[[{text:`Default reasoning: ${p}`,color:"gray"}]]:[],...d.disabled?[[{text:"Unavailable: requires a GitHub Copilot key. Add yours in the Admin console, then reopen this picker.",color:"yellow"}]]:[],[{text:"",color:"gray"}],[{text:d.description||"No description available for this model.",color:d.description?"white":"gray"}]]:[[{text:"No model selected.",color:"gray"}]];return{title:s.title||"Select model for new session",rows:o,rowItemIndexes:l,selectedRowIndex:c,detailsTitle:"Model Details",detailsLines:f,idealWidth:Math.min(Math.max(46,o.reduce((h,m)=>Array.isArray(m)?Math.max(h,yt(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function Gp(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=[],l=[];n.forEach((h,m)=>{const g=m===i,S=" ".repeat(Math.max(0,Number(h?.depth)||0)*2);let y;if(h?.kind==="section"){const w=h.collapsed?"▸":"▾",x=h.sectionKind==="package"&&h.packageScope==="user"&&!h.mine?" [private]":"";y=ie([{text:`${S}${w} `,color:"cyan"},{text:h.title||"Section",color:"white",bold:!0},...x?[{text:x,color:"cyan"}]:[],...h.meta?[{text:` · ${h.meta}`,color:"gray"}]:[]],r)}else{const w=h?.kind==="generic"||h?.supportsDirectStart!==!1,x=h?.kind==="generic"?"○ ":(h?.depth||0)>0&&h?.parentAgentName?"└ ":"★ ";y=ie([{text:`${S}${x}`,color:w?"yellow":"gray"},{text:h?.title||h?.agentName||h?.id||"Agent",color:w?"white":"gray",bold:w}],r)}o.push(g?Ye(y.map(w=>w.text).join("").padEnd(r," ")):y),l.push(m)});const c=n[i]||null,d=s.sessionOptions?.model||null,u=s.sessionOptions?.reasoningEffort||null,p=c?.kind==="section"?[[{text:c.title||"Section",color:"white",bold:!0}],...c.sectionKind==="package"?[[{text:`${c.packageName||"package"}@${c.packageSemver||"?"}`,color:"gray"}],...c.ownerLabel?[[{text:`Published by ${c.ownerLabel}`,color:"gray"}]]:[]]:[[{text:c.sectionKind==="builtin"?"Agents baked into this deployment.":"Agent packages installed on this deployment.",color:"gray"}]],[{text:"",color:"gray"}],[{text:c.meta||"",color:"gray"}],[{text:"",color:"gray"}],[{text:c.collapsed?"Enter or → to open.":"Enter or ← to close.",color:"gray"}]]:c?[[{text:c.title||c.agentName||c.id||"Agent",color:"white",bold:!0}],...c.kind==="generic"?[[{text:"Open-ended session",color:"gray"}]]:[[{text:c.agentName||c.id||"agent",color:"gray"}]],...c.packageName?[[{text:`Package: ${c.packageName}@${c.packageSemver||"?"} · ${c.packageScope||"shared"}`,color:"gray"}]]:c.kind==="agent"?[[{text:"Built-in agent",color:"gray"}]]:[],...c.startedBy?.length?[[{text:`Started by: ${c.startedBy.join(", ")}`,color:"gray"}]]:[],...c.kind!=="generic"&&c.supportsDirectStart===!1?[[{text:"Cannot be started on its own",color:"yellow"}]]:[],...d?[[{text:`Model: ${d}`,color:"gray"}]]:[],...u?[[{text:`Reasoning: ${u}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:c.description||(c.kind==="generic"?"Create a general-purpose session without a specialized named agent.":"No description available for this agent."),color:c.description?"white":"gray"}],[{text:"",color:"gray"}],[{text:c.tools?.length?`Tools: ${c.tools.join(", ")}`:"Tools: system defaults only",color:"gray"}]]:[[{text:"No agent selected.",color:"gray"}]],f=l.indexOf(i);return{title:s.title||"Select agent for new session",rows:o,rowItemIndexes:l,selectedRowIndex:f>=0?f:0,detailsTitle:"Agent Details",detailsLines:p,idealWidth:Math.min(Math.max(52,o.reduce((h,m)=>Array.isArray(m)?Math.max(h,yt(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function jp(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((u,p)=>{const f=p===i,h=ie([{text:"· ",color:"gray"},{text:String(u?.label||u?.id||"effort"),color:"white",bold:!0},...u?.isDefault?[{text:" ← model default",color:"gray"}]:[]],r);return f?Ye(h.map(m=>m.text).join("").padEnd(r," ")):h}),l=n[i]||null,c=s.modelItem||null,d=[[{text:c?.modelName||c?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${c?.providerId||"provider"} (${c?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:l?.id?`Using reasoning effort: ${l.id}`:"Choose an effort.",color:"white"}]];return{title:s.title||"Select reasoning effort",rows:o,selectedRowIndex:i,detailsTitle:"Reasoning Details",detailsLines:d,idealWidth:Math.min(Math.max(46,o.reduce((u,p)=>Array.isArray(p)?Math.max(u,yt(p)):Math.max(u,String(p?.text||"").length),0)+4),e)}}function Up(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((p,f)=>{const h=f===i,m=ie([{text:"· ",color:"gray"},{text:String(p?.label||p?.id||"tier"),color:"white",bold:!0},...p?.isDefault?[{text:" ← model default",color:"gray"}]:[]],r);return h?Ye(m.map(g=>g.text).join("").padEnd(r," ")):m}),l=n[i]||null,c=s.modelItem||null,d=l?.label||l?.id,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:d?`Using context window: ${d}`:"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:u,idealWidth:Math.min(Math.max(46,o.reduce((p,f)=>Array.isArray(f)?Math.max(p,yt(f)):Math.max(p,String(f?.text||"").length),0)+4),e)}}function Wp(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,l=n.map((u,p)=>{const f=p===i,h=u?.kind==="noGroup"?"○ ":u?.kind==="newGroup"?"+ ":"🗂 ",m=ie([{text:h,color:u?.kind==="group"?"cyan":"gray",bold:u?.kind!=="noGroup"},{text:u?.label||u?.groupId||"Group",color:"white",bold:!0},...u?.kind==="group"?[{text:` (${u.memberCount??0})`,color:"gray"}]:[]],r);return f?Ye(m.map(g=>g.text).join("").padEnd(r," ")):m}),c=n[i]||null,d=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:l,selectedRowIndex:i,detailsTitle:"Move Details",detailsLines:d,idealWidth:Math.min(Math.max(50,l.reduce((u,p)=>Array.isArray(p)?Math.max(u,yt(p)):Math.max(u,String(p?.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}: …`:"…",l=[[{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:l,idealWidth:Math.min(Math.max(56,Re(r||"(untitled session)")+18,Re(o)+18),e)}}function zp(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,Re(r)+18),e)}}function Vp(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?La(r,t.branding?.title):ue(i):"A new session will be created on upload",l=[[{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:l,idealWidth:Math.min(Math.max(60,Re(n||"~/path/to/file.md")+20,Re(o)+20),e)}}function Ni(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),l=r[o]||null,c=r.map((d,u)=>{const p=e?.[d.id]||d.options?.[0]?.id,f=(d.options||[]).map(h=>h.id===p?Ye(h.label):{text:h.label,color:"white"});return{id:d.id,title:d.label,focused:u===o,description:d.description||"",lines:f.length>0?f:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(d.label||"").length+4,...(d.options||[]).map(h=>String(h?.label||"").length+4))}});return{title:t.title||n,panes:c,helpTitle:l?.label||n,helpLines:[[{text:l?.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((d,u)=>d+u.idealWidth,0)+Math.max(0,c.length-1)*2+4),s)}}function sl(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&&!!he(s?.principal):t.kind==="shared"?e?.includeShared===!0:t.kind==="owner"?Array.isArray(e?.ownerKeys)&&e.ownerKeys.includes(t.ownerKey):!1:!1}function $r(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(i=>i?.kind!=="all"&&sl(i,e,s)).map(i=>i.kind==="me"?"Me":i.label);return n.length>0?n.join(" + "):"All sessions"}function qp(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))),l=n[o]||null,c=n.map((u,p)=>{const f=sl(u,i,r),h=u.kind==="system"?"yellow":u.kind==="unowned"?"gray":u.kind==="all"?"cyan":"white",m=[{text:f?"[x] ":"[ ] ",color:f?"cyan":"gray",bold:f},{text:u.label||u.id,color:h,bold:f}];return p===o?Aa(m,{preserveColors:!0}):m}),d=[[{text:"Active: ",color:"gray"},{text:$r(n,i,r),color:"white",bold:!0}],[{text:"",color:"gray"}],[{text:l?.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:l?.label||"Session Filter",detailsLines:d,idealWidth:Math.min(Math.max(48,c.reduce((u,p)=>Math.max(u,Array.isArray(p)?yt(p):Re(p?.text||"")),0)+8,Re($r(n,i,r))+16),e)}}function Yp(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:Ni(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function Xp(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:Ni(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function Qp(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(h=>h.kind==="artifact"),l=n.filter(h=>h.kind==="url"),c=o.reduce((h,m)=>{const g=t.files?.bySessionId?.[m.sessionId]?.downloads?.[m.filename];return h+(g?.localPath?1:0)},0),d=Math.max(0,o.length-c),u=n.map((h,m)=>{let g;if(h.kind==="downloadAll")g=ie([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${d} pending]`,color:"gray"}],r);else if(h.kind==="url")g=ie([{text:"go ",color:"cyan",bold:!0},{text:h.text&&h.text!==h.href?h.text:h.href,color:"white",bold:!0},...h.text&&h.text!==h.href?[{text:` ${h.href}`,color:"gray"}]:[]],r);else{const S=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];g=ie([{text:S?.localPath?"ok ":"dl ",color:S?.localPath?"green":"cyan",bold:!0},{text:`${ue(h.sessionId)}/`,color:"gray"},{text:h.filename,color:"white"}],r)}return m!==i?g:Ye(g.map(S=>S.text).join("").padEnd(r," "))}),p=n[i]||null;let f=[[{text:"No linked item selected.",color:"gray"}]];if(p?.kind==="downloadAll")f=[[{text:`${o.length} artifacts available`,color:"white",bold:!0}],...l.length>0?[[{text:`${l.length} links available`,color:"gray"}]]:[],[{text:`${c} already downloaded`,color:"gray"}],[{text:`${d} 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(p?.kind==="url")f=[[{text:p.text||p.href,color:"white",bold:!0}],[{text:p.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(p?.kind==="artifact"){const h=t.sessions?.byId?.[p.sessionId]||null,m=t.files?.bySessionId?.[p.sessionId]?.downloads?.[p.filename]||null;f=[[{text:p.filename,color:"white",bold:!0}],[{text:h?La(h,t.branding?.title):ue(p.sessionId),color:"gray"}],...m?.localPath?[[{text:`Saved to: ${m.localPath}`,color:"white"}]]:s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:m?.localPath?"Press Enter to download this artifact again.":"Press Enter to download this artifact.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]]}return{title:s.title||"Linked Items",rows:u.length>0?u:[{text:"No linked items available.",color:"gray"}],selectedRowIndex:i,detailsTitle:"Linked Item Details",detailsLines:f,confirmLabel:l.length>0?o.length>0?"Open / Download":"Open":"Download",idealWidth:Math.min(Math.max(54,u.reduce((h,m)=>Array.isArray(m)?Math.max(h,yt(m)):Math.max(h,String(m?.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 Pi(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 Jp(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 ms(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 es(t){return["session","fleet","users"].includes(t)?t:"session"}function Xs(t,e){const s=es(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"}),ie(n,e)}function Zp(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(Xs("session",o)),r.push(J("")),r.push(ie([{text:"Session ",color:"cyan",bold:!0},{text:ue(e.sessionId),color:"white"}],o));const l=e.isSystem?"system":e.owner?"user":"unowned",c=e.isSystem?"system":e.owner?qs(e.owner):"(?) unowned",d=e.owner?.email||"—";r.push(ie([{text:"Owner ",color:"cyan",bold:!0},{text:c,color:e.owner?"white":"gray"}],o)),r.push(ie([{text:"Email ",color:"cyan",bold:!0},{text:d,color:e.owner?.email?"white":"gray"}],o)),r.push(ie([{text:"Type ",color:"cyan",bold:!0},{text:l,color:l==="user"?"white":"gray"}],o)),i.agentId&&r.push(ie([{text:"Agent ",color:"cyan",bold:!0},{text:i.agentId,color:"white"}],o));const u=ki(i.model||e.model,i.reasoningEffort||e.reasoningEffort);u&&r.push(ie([{text:"Model ",color:"cyan",bold:!0},{text:u,color:"white"}],o)),e.createdAt&&r.push(ie([{text:"Created ",color:"cyan",bold:!0},{text:ms(e.createdAt),color:"white"}],o)),e.updatedAt&&r.push(ie([{text:"Updated ",color:"cyan",bold:!0},{text:ms(e.updatedAt),color:"white"}],o)),r.push(J(""));const p=Array.isArray(n.tokensByModel)?n.tokensByModel:[];p.length>1&&(r.push(...me({title:"Models",body:p.map(_=>`${Xd(_.model)} · ${_.turnCount||0} turns · ${X(_.totalTokensInput)} in / ${X(_.totalTokensOutput)} out`).join(`
|
|
52
|
+
`),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),r.push(J("")));const f=(i.tokensInput||0)+(i.tokensOutput||0),h=i.cacheHitRatio,m=h==null?"—":`${(h*100).toFixed(1)}%`;r.push(...me({title:"Tokens",body:mt([["Input",X(i.tokensInput)],["Output",X(i.tokensOutput)],["Total",X(f)],["Cache Read",X(i.tokensCacheRead)],["Cache Write",X(i.tokensCacheWrite)],["Hit Ratio",m]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0})),r.push(J(""));const g=Number(i.regenCount)||0,S=i.lastRegenStats&&typeof i.lastRegenStats=="object"?i.lastRegenStats:null,y=Number.isFinite(S?.toEpoch)?S.toEpoch:g,w=S?S.distillMode==="deterministic"||!S.distillMode&&!S.distillerModel?"fast":String(S.distillerModel||"llm").replace(/^[^:]*:/,""):null,x=S?`${S.turnsArchived??0} turn${S.turnsArchived===1?"":"s"} · ${(Number(S.totalMs)/1e3).toFixed(1)}s${w?` · ${w}`:""}`:null;r.push(...me({title:"Persistence",body:mt([["Epoch",String(y)],["Regens",g>0?String(g):null],["Last Regen",x],["Snapshot",Ee(i.snapshotSizeBytes)],["Uncompressed",i.rawSizeBytes?Ee(i.rawSizeBytes):null],["Compression",Pr(i.rawSizeBytes,i.snapshotSizeBytes)],["Dehydrations",String(i.dehydrationCount)],["Hydrations",String(i.hydrationCount)],["Lossy Handoffs",String(i.lossyHandoffCount)],["Last Dehydrated",i.lastDehydratedAt?ms(i.lastDehydratedAt):null],["Last Hydrated",i.lastHydratedAt?ms(i.lastHydratedAt):null]]),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const I=n.treeStats?.tree;if(I&&I.sessionCount>1){const _=I.cacheHitRatio,P=_==null?"—":`${(_*100).toFixed(1)}%`,j=(I.totalTokensInput||0)+(I.totalTokensOutput||0);r.push(J("")),r.push(...me({title:`Tree (${I.sessionCount} sessions)`,body:mt([["Input",X(I.totalTokensInput)],["Output",X(I.totalTokensOutput)],["Total",X(j)],["Cache Read",X(I.totalTokensCacheRead)],["Cache Write",X(I.totalTokensCacheWrite)],["Hit Ratio",P],["Snapshot",Ee(I.totalSnapshotSizeBytes)],["Uncompressed",I.totalRawSizeBytes?Ee(I.totalRawSizeBytes):null],["Compression",Pr(I.totalRawSizeBytes,I.totalSnapshotSizeBytes)],["Dehydrations",String(I.totalDehydrationCount)],["Hydrations",String(I.totalHydrationCount)]]),width:o,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const K=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];K.length>1&&(r.push(J("")),r.push(...me({title:"Tree By Model",body:of(K),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const E=Array.isArray(n.skillUsage)?n.skillUsage:[];E.length>0&&(r.push(J("")),r.push(...me({title:`Skills (${E.length})`,body:Or(E,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const b=n.treeSkillUsage,k=Array.isArray(b?.rolledUp)?b.rolledUp:[],M=Array.isArray(b?.perSession)?b.perSession.length:0;k.length>0&&M>1&&(r.push(J("")),r.push(...me({title:`Tree Skills (${k.length})`,body:Or(k,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const N=n.factsStats,B=n.treeFactsStats;if(N&&Array.isArray(N.rows)&&N.rows.length>0){r.push(J(""));const _=nl(N.rows),P=_?_.split(`
|
|
53
|
+
`).length:0,j=`${N.totalCount} · ${Ee(N.totalBytes)}`;let K=_;B&&B.totalCount>N.totalCount&&(K+=`
|
|
54
|
+
Tree (${B.sessionIds.length} sessions): ${B.totalCount} · ${Ee(B.totalBytes)}`),P>0&&r.push(...me({title:`Facts (${j})`,body:K,width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return r}function mt(t,e={}){const s=e.gap??2,n=(t||[]).filter(l=>Array.isArray(l)&&l[1]!=null&&l[1]!=="");if(n.length===0)return"";const i=n.reduce((l,[c])=>Math.max(l,String(c).length),0),r=n.reduce((l,[,c])=>Math.max(l,String(c).length),0),o=" ".repeat(s);return n.map(([l,c])=>`${String(l).padEnd(i)}${o}${String(c).padStart(r)}`).join(`
|
|
55
|
+
`)}function Qs(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 us(t,e={}){const s=e.gap??2,n=(t||[]).filter(l=>Array.isArray(l)&&l.length>0);if(n.length===0)return"";const i=n.reduce((l,c)=>Math.max(l,c.length),0),r=new Array(i).fill(0);for(const l of n)for(let c=0;c<i;c+=1){const d=l[c]==null?"":String(l[c]);d.length>r[c]&&(r[c]=d.length)}const o=" ".repeat(s);return n.map(l=>l.map((c,d)=>{const u=c==null?"":String(c);return d===0?u.padEnd(r[d]):u.padStart(r[d])}).join(o)).join(`
|
|
56
|
+
`)}function Or(t,e){const s=t.slice().sort((p,f)=>(f.invocations||0)-(p.invocations||0)).slice(0,12),n=s.map(p=>`${p.invocations||0} inv`),i=n.reduce((p,f)=>Math.max(p,f.length),0),l=4+2+i,c=Number.isFinite(e)&&e>0?Math.max(8,Math.floor(e)-l):1/0,d=s.map((p,f)=>{const h=p.kind==="learned"?"L":"S",m=String(p.name||"(unknown)");return[Qs(`${h} ${m}`,c),n[f]]}),u=us(d);return t.length>s.length?`${u}
|
|
57
|
+
… ${t.length-s.length} more`:u}function nl(t){const s=t.slice().sort((n,i)=>(i.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),Ee(n.totalValueBytes||0)]);return us(s)}function ef(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":Ct(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return us([["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 tf(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 sf(t,e){const s=t.slice().sort((p,f)=>(Number(f.calls)||0)-(Number(p.calls)||0)).slice(0,12),n=s.map(p=>`${Number(p.calls)||0} calls`),i=s.map(p=>`${Number(p.totalResults)||0} res`),r=n.reduce((p,f)=>Math.max(p,f.length),0),o=i.reduce((p,f)=>Math.max(p,f.length),0),l=6+r+2+o,c=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-l):1/0,d=s.map((p,f)=>{const h=p.namespace?` ${p.namespace}`:"";return[Qs(`${tf(p.operation)}${h}`,c),n[f],i[f]]}),u=us(d);return t.length>s.length?`${u}
|
|
58
|
+
… ${t.length-s.length} more`:u}function nf(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(Xs("fleet",r)),i.push(J(""));const o=n.windowStart?`Since: ${Pi(n.windowStart).replace(" ago","")}`:"All time",l=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";i.push(ie([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],r)),i.push(ie([{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 g of n.byAgent||[]){const S=g.model||"(default)",y=c.get(S)||{totalTokensInput:0,totalTokensOutput:0,totalTokensCacheRead:0,totalTokensCacheWrite:0,totalSnapshotSizeBytes:0,turnCount:0};y.totalTokensInput+=Number(g.totalTokensInput)||0,y.totalTokensOutput+=Number(g.totalTokensOutput)||0,y.totalTokensCacheRead+=Number(g.totalTokensCacheRead)||0,y.totalTokensCacheWrite+=Number(g.totalTokensCacheWrite)||0,y.totalSnapshotSizeBytes+=Number(g.totalSnapshotSizeBytes)||0,y.turnCount+=Number(g.turnCount)||0,c.set(S,y)}if(c.size>0){const g=[];for(const[S,y]of c.entries()){const w=y.totalTokensInput>0?y.totalTokensCacheRead/y.totalTokensInput:null;g.push(S),g.push(_i(y,w)),g.push("")}i.push(...me({title:"Tokens By Model",body:g.join(`
|
|
59
|
+
`).trimEnd(),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(J(""))}const d=n.totals.cacheHitRatio,u=d==null?"—":`${(d*100).toFixed(1)}%`;i.push(...me({title:"Fleet Totals",body:mt([["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",u],["Snapshots",Ee(n.totals.totalSnapshotSizeBytes)]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0}));const p=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(g=>!(g&&g.agentId==="facts-manager"&&String(g.name||"").startsWith("skills/")));p.length>0&&(i.push(J("")),i.push(...me({title:`Fleet Skills (${p.length})`,body:rf(p,e),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const f=Array.isArray(s.retrievalUsage?.rows)?s.retrievalUsage.rows:[];if(f.length>0){const g=f.reduce((S,y)=>S+(Number(y.calls)||0),0);i.push(J("")),i.push(...me({title:`Fleet Retrieval (${X(g)})`,body:sf(f,e),width:r,titleColor:"magenta",borderColor:"gray",fitToContent:!0}))}const h=s.sharedFactsStats;if(h&&Array.isArray(h.rows)&&h.rows.length>0){i.push(J(""));const g=`${h.totalCount} · ${Ee(h.totalBytes)}`;i.push(...me({title:`Shared Facts (${g})`,body:nl(h.rows),width:r,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const m=s.factsTombstoneStats;return m&&Number(m.pendingTotal)>0&&(i.push(J("")),i.push(...me({title:`Fact Tombstones (${Number(m.pendingTotal)||0})`,body:ef(m),width:r,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),i}function rf(t,e){const n=t.slice().sort((m,g)=>{const S=E=>E==="learned"?1:0,y=S(m.kind)-S(g.kind);if(y!==0)return y;const w=m.agentId?0:1,x=g.agentId?0:1;if(w!==x)return w-x;const I=String(m.agentId||"").localeCompare(String(g.agentId||""));return I!==0?I:String(m.name||"").localeCompare(String(g.name||""))}).slice(0,15),i=n.map(m=>`${m.invocations||0} inv`),r=n.map(m=>`${m.sessionCount||0} sess`),o=i.reduce((m,g)=>Math.max(m,g.length),0),l=r.reduce((m,g)=>Math.max(m,g.length),0),c=4,d=2,u=c+d+o+d+l,p=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-u):1/0,f=n.map((m,g)=>{const S=m.kind==="learned"?"L":"S",y=m.agentId||".",w=String(m.name||"(unknown)");return[Qs(`${S} ${y}/${w}`,p),i[g],r[g]]}),h=us(f);return t.length>n.length?`${h}
|
|
60
|
+
… ${t.length-n.length} more`:h}function of(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(_i(n,i)),s.push("")}return s.join(`
|
|
61
|
+
`).trimEnd()}function _i(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",Ee(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&i.push(["Orch",Ee(t.totalOrchestrationHistorySizeBytes||0)]),mt(i).split(`
|
|
62
|
+
`).map(o=>` ${o}`).join(`
|
|
63
|
+
`)}function zn(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":qs(t?.owner,"Unknown User")}function af(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=zn(t);return e&&e!==s?e:""}function lf(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=Qs(String(r.model||"(default)"),Math.max(12,e-10));i.push(`${o} · ${r.sessionCount||0} sess · ${r.turnCount||0} turns`),i.push(_i(r,r.cacheHitRatio)),i.push("")}return s.length>n.length&&i.push(`… ${s.length-n.length} more models`),i.join(`
|
|
64
|
+
`).trimEnd()}function cf(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(Xs("users",r)),i.push(J(""));const o=n.windowStart?`Since: ${Pi(n.windowStart).replace(" ago","")}`:"All time",l=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";i.push(ie([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],r)),i.push(ie([{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,d=c==null?"—":`${(c*100).toFixed(1)}%`;i.push(...me({title:"User Totals",body:mt([["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",d],["Snapshots",Ee(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",Ee(n.totals.totalOrchestrationHistorySizeBytes||0)]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0}));const u=Array.isArray(n.users)?n.users:[],p=u.slice().sort((f,h)=>(h.totalTokensInput||0)-(f.totalTokensInput||0)||(h.totalSnapshotSizeBytes||0)-(f.totalSnapshotSizeBytes||0)).slice(0,8);for(const f of p){const h=af(f),m=f.cacheHitRatio,g=m==null?"—":`${(m*100).toFixed(1)}%`,S=h?`${zn(f)} <${h}>`:zn(f),y=mt([["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",g],["Snapshots",Ee(f.totalSnapshotSizeBytes||0)],["Orch Size",Ee(f.totalOrchestrationHistorySizeBytes||0)]]),w=lf(f,r);i.push(J("")),i.push(...me({title:`${S} (${f.sessionCount||0})`,body:w?`${y}
|
|
65
|
+
|
|
66
|
+
${w}`:y,width:r,titleColor:f.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return u.length>p.length&&(i.push(J("")),i.push(J(`… ${u.length-p.length} more users`))),i}function lt(t,e={}){const s=je(t),n=t.ui.inspectorTab,i=Math.max(18,Number(e?.width)||36),r=!!e?.allowWideColumns,o=Ca(i);if(s?.isGroup)return{title:ze("Inspector","magenta"),activeTab:n,tabs:Ve,disabled:!0,stickyLines:[],lines:[J(il,"gray")]};const l=s?ue(s.sessionId):"",c=n==="sequence"||n==="nodes"?Ti(t):null,d=n==="nodes"?[...ze("Node Map","magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:s?n==="sequence"?[...ze(o?"Sequence":`Sequence: ${l}`,"magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:n==="logs"?[...ze(o?"Logs":`Logs: ${l}`,"magenta")]:n==="history"?[...ze(o?"Duroxide Events":`Duroxide Event History: ${l}`,"magenta")]:n==="stats"?[...ze(o?"Stats":`Stats: ${l}`,"magenta"),{text:` [${es(t.ui?.statsViewMode)}]`,color:"gray"}]:[...ze(o?"Files":`Files: ${l}`,"magenta")]:n==="stats"?`Stats: ${es(t.ui?.statsViewMode).replace(/^./u,f=>f.toUpperCase())}`:"No session selected";let u,p=[];switch(n){case"sequence":{const f=s?Rp(t,s,i,{allowWideColumns:r,sequenceExpansion:e?.sequenceExpansion||null}):{stickyLines:[],lines:["No session selected."]};p=f.stickyLines||[],u=f.lines;break}case"logs":u=s?np(t,s):["No session selected."];break;case"nodes":u=Dp(t,i,{});break;case"files":u=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":u=s?ff(t,s):["No session selected."];break;case"stats":u=es(t.ui?.statsViewMode)==="users"?cf(t,i):es(t.ui?.statsViewMode)==="fleet"?nf(t,i):s?Zp(t,s,i):[Xs("session",Math.max(24,i)),J(""),J("No session selected. Press f to cycle to fleet or users view.")];break;default:u=["Inspector view is scaffolded in the new architecture."];break}return{title:d,activeTab:n,tabs:Ve,stickyLines:p,lines:u}}const uf={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"},il="Select a session to see details.";function df(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=uf[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,l]of Object.entries(r)){const c=typeof l=="string"?l:JSON.stringify(l),d=c.length>100?c.slice(0,97)+"...":c;n.push([{text:` ${o}: `,color:"yellow"},{text:d,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 pf(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function ff(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 l=pf(n[o]).split(`
|
|
67
|
+
`);for(const c of l)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 l=df(n[o]);for(const c of l)r.push(c);o<n.length-1&&r.push({text:"────────────────────────────────",color:"gray"})}return r}function hf(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:Ni(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function Lr(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 mf(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,l=n.find(f=>f.id===o)||null,c=r&&r.id!==o,d=Math.max(24,e-4),u=n.map((f,h)=>{const m=f.id===o?" [current]":"",g=`${f.label}${m}`.slice(0,d);return h===i?Ye(g.padEnd(d," ")):[{text:g,color:f.id===o?"cyan":"white",bold:f.id===o}]}),p=r?[[{text:`theme: ${r.description||"Shared theme for the portal and native TUI."}`,color:"white"}],...r.group?[[{text:`group: ${r.group}`,color:"gray"}]]:[],{text:"",color:"gray"},[{text:c?`Previewing now. Cancel reverts to ${l?.label||"the previous theme"}.`:"Currently active in this TUI session.",color:c?"yellow":"green"}],Lr([{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"}]),Lr([{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:u,selectedRowIndex:i,detailsTitle:"Theme Details",detailsLines:p}}function gf(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 Fr(t){return new Map(t)}function ts(t){return new Set(t)}function yf(t){return Array.isArray(t)?[...t]:[]}function Sf(t){return Array.isArray(t)?[...t]:[]}const bf=5e3;function Br(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 rl(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function gs(t,e){const s=[],n=new Set;for(const i of t||[]){if(!i||n.has(i))continue;n.add(i);const r=e?.[i];(!r||rl(r))&&s.push(i)}return s}function ol(t){return ts(t)}function wf(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 Dr(t,e,s){const n=ol(t);if(!s||!e?.[s])return n;for(const i of wf(s,e))n.delete(i);return n}function Hr(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 If(t){return{...t||{}}}function Xe(t){return{...t||{}}}function Gr(t){return{...t||{}}}function ys(t){return{...t||{}}}function xn(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function Ef(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function xf(t){return[T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY].includes(t)?t:null}function vn(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(ae,Number(e)||ae);return s.length>n?s.slice(-n):s}function Vn(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(!Vn(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)||!Vn(t[i],e[i]))return!1;return!0}function jr(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 vf(t,e){const s=jr(t),n=jr(e);return s>0&&n>0&&n<=s}const kf=new Set(["completed","failed","cancelled","error"]);function Af(t,e){const s=String(e?.status??"").toLowerCase();if(t?.status!=="running"||s==="running"||kf.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:vf(t,e)}function Ur(t={},e={}){let s=t||{};const n=Af(t,e);for(const[i,r]of Object.entries(e||{}))if(r!==void 0&&!(i==="status"&&n)){if(i==="pendingQuestion"&&Mf(t,r)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}Vn(t?.[i],r)||(s===t&&(s={...t||{}}),s[i]=r)}return s}function Wr(t){if(!t)return"unknown";const e=t.status||"unknown",s=e==="waiting"||e==="idle"||e==="unknown";return t.cronActive===!0&&s?"cron_waiting":s&&(Number(t.activeChildCount)||0)>0?"awaiting_children":e}function Cf(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=Wr(e),i=t?.rowVisualStatus||Wr(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>=bf?{...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}}const Tf=new Set(["running","input_required"]);function kn(t){const e=new Map;for(const i of Object.values(t||{})){if(!i?.sessionId||i.isGroup||!Tf.has(i.status))continue;const r=new Set([i.sessionId]);let o=i.parentSessionId;for(;o&&t[o]&&!r.has(o);)r.add(o),e.set(o,(e.get(o)||0)+1),o=t[o].parentSessionId}let s=!1;const n={};for(const[i,r]of Object.entries(t||{})){const o=e.get(i)||0,l=Number(r?.activeChildCount)||0;if(o===l){n[i]=r;continue}s=!0,n[i]=o>0?{...r,activeChildCount:o}:{...r,activeChildCount:void 0}}return s?n:t}function Kr(t={},e={},s){let n=!1;const i={};for(const[r,o]of Object.entries(e)){const l=Cf(t[r],o,s);i[r]=l,l!==o&&(n=!0)}return n?i:e}function zr(t){return String(t?.question||"").trim()}function Mf(t,e){const s=zr(t?.answeredPendingQuestion),n=zr(e);return!!(s&&n&&s===n)}function Nf(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&na(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function Vr(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 qr(t={}){const e=String(t?.filterQuery||"").trim(),s=$s(t?.ownerFilter);return!!e||s.all!==!0}function Pf(t,e=[]){const s=Ht(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(r=>r.sessionId===n)||t.sessions?.navigationIntent||n&&t.sessions?.byId?.[n]&&!qr(t.sessions)||n&&!t.sessions?.listingSeen)return n;if(qr(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 Nf(i)}function _f(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 dt(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 p=Dr(s.collapsedIds,s.byId,r);Hr(p,s.collapsedIds)||(s={...s,collapsedIds:p,flat:Ke(Object.values(s.byId||{}),p,s.orderById,s.pinnedIds,s.manualOrder)})}i&&s.filterExceptionId!==i&&(Ht({...t,sessions:s}).some(f=>f.sessionId===i)||(s={...s,filterExceptionId:i}));const o={...t,sessions:s},l=Pf(o,Object.values(s.byId||{})),c=Dr(s.collapsedIds,s.byId,l);return{sessions:{...!Hr(c,s.collapsedIds)?{...s,collapsedIds:c,flat:Ke(Object.values(s.byId||{}),c,s.orderById,s.pinnedIds,s.manualOrder)}:s,activeSessionId:l},ui:_f(t,l)}}function An(t={},e=0,s=[]){const n=If(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 Rf(t=[],e=[]){const s=Ke(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 $f(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 Yr(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 Of(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"ui/touchScale":return!!e.enabled==!!t.ui.touchScale?t:{...t,ui:{...t.ui,touchScale:!!e.enabled}};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,"touchScale")&&typeof s.touchScale=="boolean",l=Object.prototype.hasOwnProperty.call(s,"chatViewMode")&&(s.chatViewMode==="summary"||s.chatViewMode==="transcript"),c=Object.prototype.hasOwnProperty.call(s,"pinnedSessionIds"),d=Object.prototype.hasOwnProperty.call(s,"collapsedSessionIds"),u=Object.prototype.hasOwnProperty.call(s,"sessionOrder"),p=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.status!=="failed"),f=Object.prototype.hasOwnProperty.call(s,"activeSessionId")&&!p,h=Object.keys(t.sessions.byId||{}).length>0,m=r?{...t.ui.layout||{},...di(s.layoutAdjustments)}:t.ui.layout,g=c?h?gs(Ls(s.pinnedSessionIds),t.sessions.byId):Ls(s.pinnedSessionIds):t.sessions.pinnedIds,S=d?h?ol(Hn(s.collapsedSessionIds),t.sessions.byId):Hn(s.collapsedSessionIds):t.sessions.collapsedIds,y=u?pi(s.sessionOrder):t.sessions.manualOrder,w=f?xa(s.activeSessionId):t.sessions.activeSessionId,x={...t.sessions,...i?{ownerFilter:$s(s.sessionOwnerFilter),ownerFilterExplicit:!0}:{},pinnedIds:g,manualOrder:y,collapsedIds:S,collapsedIdsExplicit:d?!0:t.sessions.collapsedIdsExplicit,activeSessionId:w,flat:c||d||u?Ke(Object.values(t.sessions.byId),S,t.sessions.orderById,g,y):t.sessions.flat},I=h&&(i||c||d||f)?dt(t,x):{sessions:x,ui:t.ui};return{...t,sessions:I.sessions,ui:{...I.ui,themeId:n?s.themeId.trim():I.ui.themeId,touchScale:o?s.touchScale:I.ui.touchScale,chatViewMode:l?s.chatViewMode:I.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=dt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:$s(e.filter),navigationIntent:null,filterExceptionId:null},n=dt(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=dt(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:$f(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:$t(e.prompt),promptAttachments:Yr(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:Yr(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=kn(r),l=Array.isArray(t.sessions.selectedIds)?t.sessions.selectedIds.filter(c=>c!==s):t.sessions.selectedIds;return{...t,sessions:{...t.sessions,byId:o,selectedIds:l,activeSessionId:i?null:t.sessions.activeSessionId}}}case"sessions/loaded":{const s={};let n=!1;const i=Date.now();for(const b of t.sessions.groupRows||[])s[b.sessionId]=t.sessions.byId[b.sessionId]||b;for(const b of e.sessions){const k=t.sessions.byId[b.sessionId];s[b.sessionId]=Ur(k,b)}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=kn(s),o=Kr(t.sessions.byId,r,i);for(const[b,k]of Object.entries(o))if(k!==t.sessions.byId[b]){n=!0;break}const l=Object.keys(t.sessions.byId),c=Object.keys(o);if(l.length!==c.length&&(n=!0),!n){for(const b of c)if(!t.sessions.byId[b]){n=!0;break}}if(!n)return t;const d=Object.values(o),u=Object.keys(t.sessions.orderById||{}).length>0,p=Vr(d),f=!!t.sessions.collapsedIdsExplicit,{orderById:h,nextOrderOrdinal:m}=u?An(t.sessions.orderById,t.sessions.nextOrderOrdinal,d):Rf(d,t.sessions.pinnedIds),g=f?ts(t.sessions.collapsedIds):p,S=t.sessions.listingSeen===!0;if(f&&S){const b=Vr(Object.values(t.sessions.byId));for(const k of p)b.has(k)||g.add(k)}const y=gs(t.sessions.pinnedIds,o),w=Br(t.sessions.selectedIds,o),x=Ke(d,g,h,y,t.sessions.manualOrder),I={...t.sessions,byId:o,collapsedIds:g,collapsedIdsExplicit:f,listingSeen:!0,pinnedIds:y,selectedIds:w,selectMode:t.sessions.selectMode&&w.length>0,flat:x,activeSessionId:t.sessions.activeSessionId,orderById:h,nextOrderOrdinal:m},E=dt(t,I);return{...t,sessions:E.sessions,ui:E.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(m=>m&&!m.isGroup&&m.groupId&&!m.parentSessionId).map(m=>`group:${m.groupId}`)),o=[];for(const m of Object.keys(n))if(n[m]?.isGroup&&!s.some(g=>g.sessionId===m)){if(r.has(m)){o.push(n[m]);continue}delete n[m]}for(const m of s)n[m.sessionId]={...n[m.sessionId]||{},...m};const l=gs(t.sessions.pinnedIds,n),{orderById:c,nextOrderOrdinal:d}=An(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(n)),u=t.sessions.groupsListingSeen===!0,p=ts(t.sessions.collapsedIds);for(const m of s)u&&(t.sessions.byId[m.sessionId]||p.add(m.sessionId));const f={...t.sessions,groupRows:[...s,...o],byId:n,pinnedIds:l,orderById:c,nextOrderOrdinal:d,collapsedIds:p,groupsListingSeen:!0,flat:Ke(Object.values(n),p,c,l,t.sessions.manualOrder)},h=dt(t,f);return{...t,sessions:h.sessions,ui:h.ui}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=Ur(s,e.session),i=Kr(t.sessions.byId,kn({...t.sessions.byId,[e.session.sessionId]:n}),Date.now());let r=!1;for(const[p,f]of Object.entries(i))if(f!==t.sessions.byId[p]){r=!0;break}if(!r)return t;const o=gs(t.sessions.pinnedIds,i),{orderById:l,nextOrderOrdinal:c}=An(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(i)),d={...t.sessions,byId:i,pinnedIds:o,flat:Ke(Object.values(i),t.sessions.collapsedIds,l,o,t.sessions.manualOrder),activeSessionId:t.sessions.activeSessionId,orderById:l,nextOrderOrdinal:c},u=dt(t,d);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=xf(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=ts(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:Ke(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds,t.sessions.manualOrder)}}}case"sessions/expand":{const s=ts(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:Ke(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(!rl(n))return t;const i=yf(t.sessions.pinnedIds),o=i.indexOf(s)>=0?i.filter(l=>l!==s):[...i,s];return{...t,sessions:{...t.sessions,pinnedIds:o,flat:Ke(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(!Dt(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(u=>u.sessionId).filter(u=>Dt(t.sessions.byId[u]))).filter(u=>u!==s),l=i?o.indexOf(i):-1,c=l>=0?[...o.slice(0,l),s,...o.slice(l)]:[...o,s];return c.length===(t.sessions.manualOrder||[]).length&&c.every((u,p)=>u===t.sessions.manualOrder[p])?t:{...t,sessions:{...t.sessions,manualOrder:c,flat:Ke(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=Sf(t.sessions.selectedIds),o=i.indexOf(s)>=0?i.filter(l=>l!==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=Br(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(ae,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??ae)||ae),r=vn(Pt(e.history?.chat||[]),i),o=n[n.length-1]?.id||null,l=r[r.length-1]?.id||null,c=e.sessionId===t.sessions.activeSessionId&&l!==o,d=Fr(t.history.bySessionId);return d.set(e.sessionId,{...e.history||{},chat:r,activity:vn(e.history?.activity||[],i),events:vn(e.history?.events||[],i),loadedEventLimit:i}),{...t,history:{...t.history,bySessionId:d},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=Fr(t.history.bySessionId);for(const o of s)n.delete(o);const i=Gr(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=Gr(t.outbox?.bySessionId);return n.length===0?delete i[s]:i[s]=n,{...t,outbox:{...t.outbox,bySessionId:i}}}case"orchestration/statsLoading":{const s=ys(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=ys(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=ys(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=ys(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,changelog: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/changelog/loaded":return t.admin.packages.selectedName!==e.name?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,changelog:e.content||null}}};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={...Gn().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:{...Gn().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=Xe(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=Xe(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=Xe(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},i=Os(e.entries),r=Number(e.fetchedAt)||0,o=c=>i.some(d=>d.filename===c),l=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:l,loading:!1,loaded:!0,fetchedAt:r,error:null},{...t,files:{...t.files,bySessionId:s}}}case"files/sessionError":{const s=Xe(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=Xe(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=Xe(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=Xe(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=Xe(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=Xe(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(p=>p!==`${e.sessionId}/${e.filename}`)}};const s=Xe(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},i=Os(n.entries).filter(p=>p.filename!==e.filename),r=n.selectedFilename===e.filename?i[0]?.filename||null:n.selectedFilename,{[e.filename]:o,...l}=n.previews||{},{[e.filename]:c,...d}=n.downloads||{},u=e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:null;return s[e.sessionId]={...n,entries:i,previews:l,downloads:d,selectedFilename:r},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:t.files.selectedArtifactId===u?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:{...xn(t.files.filter),...xn(e.filter)},...xn(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:Ef(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 Lf(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 Ff=2e4,Bf=2e4,Df=3e4,Hf=30,Xr="Session refresh failed",Gf=3,jf=200,Uf=5,Wf=new Set([T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY]);function Kf(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 Cn(t){return!t?.sessionId||t.isGroup?t:{...t,groupId:t.viewerGroupId??null,parentSessionId:t.parentSessionId??null}}function vs(t){return String(t||"").startsWith("group:")?String(t).slice(6):null}function Yt(t){return vs(t)!==null}function zf(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 Tn(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 Xt(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||s==="NOT_FOUND"}async function Vf(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<Uf;n+=1){const i=await t.listSessionsPage({limit:jf,cursor:s}),r=Array.isArray(i?.sessions)?i.sessions:[];if(e.push(...r),!i?.hasMore||!i?.nextCursor)break;s=i.nextCursor}return e}function qf(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 qn(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 Qr(t){const e=qn(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 Yn(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 Yf(t){const e=Yn(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 al={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function Xf(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 Qf(t,e){const s=Xf(e);return s?t==="long_context"?`Long context (${s} tokens, higher cost)`:`Default (${s} tokens)`:al[t]||t}function Xn(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 Jf(t){return Xn([t])}function Jr(t,e=[]){let s=Ko(t);for(const n of e){const i=zo(s,n?.eventType,n?.data,{timestamp:n?.createdAt});i&&(s=i)}return s}function js(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(!js(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)||!js(t[i],e[i]))return!1;return!0}function Zr(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 Ri(t,e){const s=Zr(t?.updatedAt),n=Zr(e?.updatedAt);return s>0&&n>0&&n<=s}function Zf(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function eh(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&Zf(e?.status)&&Ri(t,e)}function th(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!cl(e?.status)&&!ll(e?.orchestrationStatus)&&Ri(t,e)}function sh(t,e){if(!e?.sessionId)return null;const s={sessionId:e.sessionId};let n=!1;for(const[l,c]of Object.entries(e))l==="sessionId"||c===void 0||js(t?.[l],c)||(s[l]=c,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&!Ri(t,e)&&(s.pendingQuestion=null,n=!0),eh(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),Gu(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),th(t,e))for(const l of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[l]!=null&&(js(s[l],t[l])||(s[l]=t[l],n=!0));else if(e.cronActive!==!0){t?.cronReason&&(s.cronReason=null,n=!0);for(const l of["cronKind","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[l]!=null&&e[l]===void 0&&(s[l]=null,n=!0);t?.cronInterval!=null&&e.cronInterval===void 0&&(s.cronInterval=null,n=!0)}if((cl(e.status)||ll(e.orchestrationStatus))&&t?.contextUsage?.compaction?.state==="running"&&e.contextUsage===void 0){const l={...t.contextUsage};delete l.compaction,s.contextUsage=Object.keys(l).length>0?l:null,n=!0}return n?s:null}function eo(t){return String(t||"").replace(/\r\n/g,`
|
|
68
|
+
`).trim()}function ll(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function cl(t){return t==="completed"||t==="failed"||t==="cancelled"}function Ae(t){return String(t||"").slice(0,8)}function Us(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function Ss(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const nh=Us({provider:"system",subject:"system"});function to(t){const e=t.auth?.principal||null,s=Us(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=Ss(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,l=Us(o);!l||l===s||l===nh||i.has(l)||i.set(l,o)}for(const[r,o]of[...i.entries()].sort((l,c)=>Ss(l[1]).localeCompare(Ss(c[1])))){const l=Ss(o),c=String(o?.email||"").trim();n.push({id:`owner:${r}`,kind:"owner",ownerKey:r,label:c&&c!==l?`${l} <${c}>`:l,description:"Show sessions owned by this user."})}return n}function Ws(t){return Us(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,includeShared:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function ih(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||t?.includeShared||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function rh(t,e,s){const n=t||Ws(s);if(!e)return n;if(e.kind==="all")return n.all?Ws(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 ih(i)?i:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function $i(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 oh(t){const e=$i(t);return e?Math.max(1,60-`${e}: `.length):60}function ah(t){const e=String(t?.title||"").trim();if(!e)return"";const s=$i(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===Ae(t?.sessionId)?"":n}return e===Ae(t?.sessionId)?"":e}function so(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"}const ss="builtin",ul="installed:shared",dl="installed:mine";function pl(t){const e=String(t?.packageScope||t?.scope||"shared"),s=String(t?.ownerLabel||"");return`pkg:${e}:${s}:${String(t?.packageName||"")}`}function bs(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/g,"")}function no(t){const e=new Map;for(const u of t)u?.agentName&&e.set(bs(u.agentName),u);const s=new Map,n=new Map;for(const u of t){const p=bs(u.agentName),f=(u.startedBy||[]).map(m=>bs(m)).filter(m=>m&&e.has(m)&&m!==p);if(f.length===0)continue;const h=f[0];n.set(u,h),s.has(h)||s.set(h,[]),s.get(h).push(u)}const i=u=>n.has(u),r=u=>typeof u.supportsDirectStart=="boolean"?u.supportsDirectStart:!i(u),o=[],l=new Set,c=(u,p,f)=>{if(!l.has(u)){l.add(u),o.push({...u,depth:p,parentAgentName:f||null,supportsDirectStart:r(u)});for(const h of s.get(bs(u.agentName))||[])c(h,p+1,u.agentName)}};for(const u of t)i(u)||c(u,0,null);const d=u=>{const p=new Set;let f=u;for(;f&&!p.has(f);)if(p.add(f),f=e.get(n.get(f)),f===u)return!0;return!1};for(const u of t)!l.has(u)&&d(u)&&c(u,0,null);for(const u of t)c(u,0,null);return o}function lh(t=[]){const e=t.findIndex(n=>n.kind!=="section");if(e>=0)return e;const s=t.findIndex(n=>n.kind==="section"&&n.collapsed);return s>=0?s:0}function io(t=[],e=[],s=null){const n=new Set(e),i=[],r=t.filter(l=>l.builtin),o=t.filter(l=>!l.builtin);if(s&&i.push({...s,depth:0}),r.length>0){const l=no(r);i.push({id:`section:${ss}`,kind:"section",sectionKind:"builtin",sectionKey:ss,title:"Built-in",meta:`${l.length} agent${l.length===1?"":"s"}`,collapsed:n.has(ss),depth:0}),n.has(ss)||i.push(...l.map(c=>({...c,depth:c.depth+1})))}for(const[l,c,d]of[[ul,"Installed · Shared",u=>u.group!=="mine"],[dl,"Installed · Yours",u=>u.group==="mine"]]){const u=o.filter(d);if(u.length===0)continue;const p=new Map;for(const h of u){const m=pl(h);p.has(m)||p.set(m,[]),p.get(m).push(h)}if(i.push({id:`section:${l}`,kind:"section",sectionKind:"installed",sectionKey:l,title:c,meta:`${p.size} package${p.size===1?"":"s"}`,collapsed:n.has(l),depth:0}),n.has(l))continue;const f=[...p.keys()].sort((h,m)=>{const g=p.get(h)[0],S=p.get(m)[0];return String(g.packageTitle||g.packageName||"").localeCompare(String(S.packageTitle||S.packageName||""))});for(const h of f){const m=no(p.get(h)),g=m[0]||{},S=m.filter(y=>y.depth===0).length;i.push({id:`section:${h}`,kind:"section",sectionKind:"package",sectionKey:h,title:g.packageTitle||g.packageName||"Package",packageName:g.packageName||null,packageSemver:g.packageSemver||null,packageScope:g.packageScope||null,ownerLabel:g.ownerLabel||null,mine:g.group==="mine",meta:`${S} ${S===1?"entry":"entries"} · ${m.length} agent${m.length===1?"":"s"}`,collapsed:n.has(h),depth:1}),!n.has(h)&&i.push(...m.map(y=>({...y,depth:y.depth+2})))}}return i}function ro(t){return`📎 ${String(t||"").trim()}`}function oo(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],l=String(r[3]||"");return{kind:o==="@@"?"sessions":"artifacts",query:l,signature:`${o}${l}`,tokenStart:(r.index||0)+String(r[1]||"").length,tokenEnd:n}}function ch(t,e,s,n){const i=String(t||""),r=fe(i,e),o=fe(i,s),l=String(n||"");return{prompt:`${i.slice(0,r)}${l}${i.slice(o)}`,cursor:r+l.length}}function uh(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function dh(t){const e=String(t?.sessionId||"").trim(),s=Ae(e)||"session";return`Referenced session: ${uh(t?.title,s)} — session://${e}`}function ao(t,e,s){if(!e)return rt(t,String(t||"").length,s);const n=String(t||""),i=n.slice(e.tokenEnd,e.tokenEnd+1),r=!i||/\s/u.test(i);return ch(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${r?" ":""}`)}function ph(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 lo=new Set(["image/png","image/jpeg","image/gif","image/webp"]),co=4*1024*1024,Mn=4;function fh(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=ph(t,s);return n.join(`
|
|
71
|
+
`)+(i?`
|
|
72
|
+
|
|
73
|
+
${i}`:"")}function It(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function fl(t){return Array.from(String(t||"")).length}function hh(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=Vo(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 mh(t,e){const s=Math.max(1,Number(e)||1),n=fl(t);return Math.max(1,Math.ceil(n/s))}function Et(t,e){const s=Math.max(1,Number(e)||1);return hh(t).reduce((n,i)=>{if(!i)return n+1;if(Array.isArray(i)){const r=i.reduce((o,l)=>o+fl(l?.text||""),0);return n+Math.max(1,Math.ceil(r/s))}return n+mh(i.text||"",s)},0)}function fe(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function hl(t){return String(t||"").split(`
|
|
74
|
+
`)}function gh(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 yh(t,e,s){const n=hl(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 l=0;l<i;l+=1)o+=(n[l]?.length||0)+1;return fe(t,o+r)}function rt(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 xt(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 ws(t){return/\s/u.test(t||"")}function ml(t,e,s){const n=String(t||"");let i=fe(n,e);if(s<0){for(;i>0&&ws(n[i-1]);)i-=1;for(;i>0&&!ws(n[i-1]);)i-=1;return i}for(;i<n.length&&ws(n[i]);)i+=1;for(;i<n.length&&!ws(n[i]);)i+=1;return i}function Sh(t,e){const s=String(t||""),n=fe(s,e),i=ml(s,n,-1);return i===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,i)}${s.slice(n)}`,cursor:i}}function bh(t,e,s){const n=hl(t);if(n.length<=1)return fe(t,e);const i=gh(t,e),r=Math.max(0,Math.min(i.line+s,n.length-1));return r===i.line?fe(t,e):yh(t,r,i.column)}const Qn=3e3,wh=new Set(["logs","sequence"]),Ih=2e5,Eh=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),xh=new Set([".json",".jsonl"]),vh=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function gl(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function kh(t,e=""){const s=gl(t),n=String(e||"").toLowerCase();return vh.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}function uo(t,e=Ih){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 Ah(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 Ch(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${Ah(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
|
|
78
|
+
`)}function po(t,e,s="",n=null){const i=String(s||"").toLowerCase(),r=gl(t);if(n?.isBinary===!0||kh(t,s))return{content:Ch(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=uo(e);if(Eh.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(xh.has(r)||i.includes("json"))try{return{content:uo(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 Th=1e4,Mh=140,Nh=1500;class Ph{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),l=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:l}),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(l=>l.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(l=>l?.kind==="image"),r=[],o=[];for(const l of s){const c=String(l.type||"").toLowerCase();if(!lo.has(c)){o.push({name:l.name||"image",reason:"unsupported type"});continue}if((Number(l.size)||0)>co){o.push({name:l.name||"image",reason:"over 4 MB"});continue}if(i.length+r.length>=Mn){o.push({name:l.name||"image",reason:`max ${Mn} images`});continue}r.push({kind:"image",file:l,filename:String(l.name||"image"),contentType:c,sizeBytes:Number(l.size)||0})}return r.length>0&&this.setPromptAttachments([...n,...r]),o.length>0&&this.dispatch({type:"ui/status",text:`Skipped ${o.map(l=>`${l.name} (${l.reason})`).join(", ")}`}),{accepted:r.length,rejected:o}}stageUploadedImageAttachment(e,s){const n=String(e?.contentType||"").toLowerCase();return!lo.has(n)||(Number(e?.sizeBytes)||0)>co||this.getPromptAttachments().filter(r=>r?.kind==="image").length>=Mn?!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 l of s){if(!l.file){l.uploaded&&l.filename&&i.push({filename:l.filename});continue}o+=1;const c={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[l.contentType]||"png",d=`attach-${r}-${o}.${c}`;await this.transport.uploadArtifactFromFile(e,l.file,d),i.push({filename:d})}return i}acknowledgeOutboxPrompt(e,s,n=null){if(!e)return!1;const i=this.getSessionOutbox(e);if(n){const c=i.findIndex(d=>(d?.phase==="pending"||d?.phase==="queued"||d?.phase==="cancelling")&&Array.isArray(d.clientMessageIds)&&d.clientMessageIds.includes(n));if(c!==-1){const d=i[c];return this.setSessionOutboxItems(e,i.filter((u,p)=>p!==c)),this.getPromptEditSessionMatch(e)?.itemId===d?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const r=eo(s);if(!r)return!1;const o=i.findIndex(c=>(c?.phase==="pending"||c?.phase==="queued"||c?.phase==="cancelling")&&eo(c.text)===r);if(o===-1)return!1;const l=i[o];return this.setSessionOutboxItems(e,i.filter((c,d)=>d!==o)),this.getPromptEditSessionMatch(e)?.itemId===l?.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(u=>n.has(u)));if(r.length===i.length)return!1;const o=new Set(i.filter(c=>!r.some(d=>d.id===c.id)).map(c=>c.id));this.setSessionOutboxItems(e,r);const l=this.getPromptEditSessionMatch(e);return l&&o.has(l.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}scheduleOutboxDispatch(e){if(!e||(this._outboxDispatchTimers||(this._outboxDispatchTimers=new Map),this._outboxDispatchTimers.has(e)))return;const s=setTimeout(()=>{this._outboxDispatchTimers.delete(e),this.dispatchPendingOutbox(e).catch(()=>{})},10);this._outboxDispatchTimers.set(e,s)}async dispatchPendingOutbox(e){if(!e)return!1;await Promise.resolve();const s=this.outboxFlushPromises.get(e);if(s)return await s.catch(()=>{}),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e),!1;const n=this.getPendingOutboxItems(e),i=n.find(m=>m?.attempted===!0),r=i?[i]:n.filter(m=>m?.attempted!==!0);if(r.length===0)return!1;const o=r.flatMap(m=>Array.isArray(m.clientMessageIds)&&m.clientMessageIds.length>0?m.clientMessageIds:[m.id]),l=r.map(m=>String(m.text||"")).join(`
|
|
79
|
+
|
|
80
|
+
`),c=r.flatMap(m=>Array.isArray(m.attachments)?m.attachments:[]),d={id:r[0].id,text:l,createdAt:r[0].createdAt||Date.now(),phase:"pending",attempted:!0,clientMessageIds:o,...c.length>0?{attachments:c}:{}},u=new Set(r.map(m=>m.id)),p=this.getSessionOutbox(e).filter(m=>!u.has(m.id));this.setSessionOutboxItems(e,[...p,d]);const f=this.getPromptEditSessionMatch(e);f&&u.has(f.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const h=(async()=>{await this.transport.sendMessage(e,d.text,{enqueueOnly:!0,clientMessageIds:d.clientMessageIds,...Array.isArray(d.attachments)&&d.attachments.length>0?{attachments:d.attachments}:{}});const g=this.getSessionOutbox(e).map(S=>S.id===d.id?{...S,phase:"queued"}:S);return this.setSessionOutboxItems(e,g),this.syncSessionEvents(e).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(m=>{const g=m?.code==="FORBIDDEN"||m?.code==="UNAUTHORIZED"||m?.status===403||m?.status===401,S=this.getSessionOutbox(e);if(g){const y=S.map(w=>w.id===d.id?{...w,phase:"rejected"}:w);this.setSessionOutboxItems(e,y),setTimeout(()=>{const w=this.getSessionOutbox(e),x=w.filter(I=>!(I.id===d.id&&I.phase==="rejected"));x.length!==w.length&&this.setSessionOutboxItems(e,x)},6e3)}else{const y=S.map(w=>w.id===d.id?{...d,phase:"pending",attempted:!0}:w);this.setSessionOutboxItems(e,y)}throw this.dispatch({type:"ui/status",text:m?.message||String(m)}),m}).finally(()=>{this.outboxFlushPromises.delete(e),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e)});return this.outboxFlushPromises.set(e,h),await h}async flushQueuedOutbox(e){return await this.dispatchPendingOutbox(e)}maybeFlushQueuedOutbox(e){return!e||this.getPendingOutboxItems(e).length===0?!1:(this.scheduleOutboxDispatch(e),!0)}getPromptReferenceContext(){const e=this.getState();return oo(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=it(s),i=n?.sessionId||s.sessions.activeSessionId||null,r=n?.filename||null;if(!i||!r)return!1;const o=ro(r),l=ao(s.ui.prompt,e,o),c=this.getPromptAttachments(),d=c.findIndex(f=>f?.sessionId===i&&f?.filename===r),u={...d>=0?c[d]:{},id:`${i}/${r}`,sessionId:i,filename:r,resolvedPath:r,token:o},p=d>=0?c.map((f,h)=>h===d?u:f):[...c,u];return this.setPrompt(l.prompt,l.cursor),this.setPromptAttachments(p),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=Ht(s)[0]||null,r=i?.sessionId&&s.sessions.byId[i.sessionId]||null;if(!r?.sessionId)return!1;const o=dh(r),l=ao(s.ui.prompt,e,o);return this.setPrompt(l.prompt,l.cursor),this.setFocus(T.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${Ae(r.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}openSessionOwnerFilter(){const e=this.getState(),s=to(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=rh(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=to(e),i=Array.isArray(s.items)?s.items:[];if(i.length===n.length&&i.every((d,u)=>d?.id===n[u]?.id))return;const o=i[Math.max(0,Number(s.selectedIndex)||0)]?.id,l=o!=null?n.findIndex(d=>d.id===o):-1,c=l>=0?l: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=oo(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(Gs(this.getState(),"selectedSession")),l=ht(this.getState()).filter(c=>r.has(c.sessionId))[0]||null;l?.filename&&(this.dispatch({type:"files/select",sessionId:l.sessionId,filename:l.filename}),await this.ensureFilePreview(l.sessionId,l.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:Ws(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:Xr})})},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&&(Yt(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===Xr,r=this.getState().sessions.activeSessionId;let o=(await Vf(this.transport)).map(Cn),l=null;if(typeof this.transport.listSessionGroups=="function")try{const f=await this.transport.listSessionGroups();l=(Array.isArray(f)?f:[]).map(Kf).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,Cn(f)]:this.dispatch({type:"sessions/navigationIntentFailed",sessionId:c.sessionId,errorKind:"not_found"})}catch(f){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:c.sessionId,errorKind:Tn(f)})}const d=r;if(d&&!Yt(d)&&!o.some(f=>f?.sessionId===d)&&typeof this.transport.getSession=="function"){const f=await this.transport.getSession(d).catch(()=>null);f?.sessionId&&(o=[...o,Cn(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"}:{}}),l&&this.dispatch({type:"sessions/groupsLoaded",groups:l,sessions:o}),this.dispatch({type:"sessions/loaded",sessions:o}),this.refreshOpenSessionOwnerFilterModal();const u=this.getState().sessions.activeSessionId,p=new Set;if(u){if(u!==r){if(!this.getState().sessions.byId[u]?.isGroup){const g=this.getState().sessions.navigationIntent;if(g&&g.sessionId===u&&g.status!=="failed")try{await this.loadSession(u)}catch(S){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:u,errorKind:Tn(S)})}else await this.loadSession(u)}return}if(this.getState().sessions.byId[u]?.isGroup)return;this.getState().history.bySessionId.get(u)?.events?.length||await this.ensureSessionHistory(u,{force:!0}).catch(()=>{}),this.activeSessionSubscriptionId!==u&&this.attachActiveSession(u),await this.syncSessionDetail(u).catch(()=>{}),await this.syncSessionEvents(u).catch(()=>{}),p.add(u);const h=this.getState(),m=h.sessions.byId[u]||null;if(m?.parentSessionId&&typeof this.transport.getSession=="function"){const g=Object.values(h.sessions.byId).filter(S=>S?.parentSessionId===m.parentSessionId).map(S=>S.sessionId).filter(S=>S&&S!==u).slice(0,6);await Promise.all(g.map(S=>this.syncSessionDetail(S).catch(()=>{})));for(const S of g)p.add(S)}}await this.syncVisibleSessionDetails(p).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 u=o.filter(([p,f])=>p!==s&&!f?.loading).sort((p,f)=>(p[1]?.fetchedAt||0)-(f[1]?.fetchedAt||0)).slice(0,o.length-r).filter(([,p])=>n-(p?.fetchedAt||0)>i);u.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:u.map(([p])=>p)})}const l=Object.entries(e.executionHistory?.bySessionId||{});if(l.length>r){const u=l.filter(([p,f])=>p!==s&&!f?.loading).sort((p,f)=>(p[1]?.fetchedAt||0)-(f[1]?.fetchedAt||0)).slice(0,l.length-r).filter(([,p])=>n-(p?.fetchedAt||0)>i);u.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:u.map(([p])=>p)})}const c=Object.entries(e.files.bySessionId||{});if(c.length>r){const u=c.filter(([p])=>p!==s).slice(0,c.length-r);u.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:u.map(([p])=>p)})}const d=[...e.history.bySessionId.entries()];if(d.length>r*2){const u=d.filter(([p])=>p!==s).slice(0,d.length-r*2).map(([p])=>p);u.length>0&&this.dispatch({type:"history/evict",sessionIds:u})}}async syncVisibleSessionDetails(e=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=ns({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??$t(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),r=Kn(s,i),o=[...new Set(r.map(l=>l.sessionId).filter(l=>l&&!Yt(l)&&!e.has(l)))];o.length!==0&&await Promise.all(o.map(l=>this.syncSessionDetail(l).catch(()=>{})))}async catchUpSessionHistory(e,s,n){let r;try{r=await this.transport.getSessionEvents(e,n,1e3)}catch(u){return Xt(u)&&this.handleSessionGone(e),null}if(!Array.isArray(r)||r.length>=1e3)return null;if(r.length===0)return s;let o=s;for(const u of r)o=ar(o,u);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 u of r)this.reconcileOutboxAgainstEvent(e,u);const l=Xn(r),c=this.getState().sessions.byId[e]||{},d=Jr(c.contextUsage,r);return(l||d)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...l||{},...d?{contextUsage:d}:{}}}),o}async ensureSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),i=Math.min(Nh,Math.max(ae,Number(n?.loadedEventLimit??ae)||ae));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 l=await this.catchUpSessionHistory(e,n,r);if(l)return l}const o=(async()=>{let l;try{l=await this.transport.getSessionEvents(e,void 0,i)}catch(f){if(Xt(f))return this.handleSessionGone(e),null;throw f}const c={...fs(l,{requestedLimit:i}),lastSeq:l[l.length-1]?.seq||0};this.dispatch({type:"history/set",sessionId:e,history:c});for(const f of l||[])this.reconcileOutboxAgainstEvent(e,f);const d=Xn(l),u=this.getState().sessions.byId[e]||{},p=Jr(u.contextUsage,l);return(d||p)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...d||{},...p?{contextUsage:p}:{}}}),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=ns({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??$t(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),r=Kn(s,i),o=[...new Set(r.map(l=>l.sessionId).filter(Boolean))];if(o.length===0)return;await Promise.allSettled(o.map(l=>this.ensureSessionHistory(l)));return}if(e==="files"&&await this.ensureFilesForScope(He(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<Ff)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 Xt(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<Bf)){this.dispatch({type:"sessionStats/loading",sessionId:s});try{const[r,o,l,c,d,u,p]=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:l,skillUsage:c,treeSkillUsage:d,factsStats:u,treeFactsStats:p})}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<Df)){this.dispatch({type:"fleetStats/loading"});try{const r={since:new Date(Date.now()-Hf*864e5),includeDeleted:!0},[o,l,c,d,u,p]=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:l,skillUsage:c,retrievalUsage:d,sharedFactsStats:u,factsTombstoneStats:p})}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}),s?.files?.some(r=>r.path==="CHANGELOG.md")&&typeof this.transport.getAgentPackageFile=="function"?(async()=>{try{const r=await this.transport.getAgentPackageFile(e,null,"CHANGELOG.md");if(this.getState().admin?.packages?.selectedName!==e)return;this.dispatch({type:"admin/packages/changelog/loaded",name:e,content:typeof r=="string"?r:r?.content??r?.text??""})}catch{}})():this.dispatch({type:"admin/packages/changelog/loaded",name:e,content:null});const i=s?.files?.find(r=>r.path==="plugin.json")??s?.files?.[0];i&&this.selectAdminPackageFile(i.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=ma(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:l}=await ou(s,{token:r,tokenKind:o,onProgress:d=>this.dispatch({type:"admin/packages/addDialog/progress",message:d})});if(e.updateName){const d=au(l);if(d&&d!==e.updateName){this.dispatch({type:"admin/packages/addDialog/failed",error:`That folder builds "${d}", not "${e.updateName}". Use Add package to publish it as its own package.`});return}}this.dispatch({type:"admin/packages/addDialog/progress",message:`publishing ${l.length} file(s)…`});const c=await this.transport.uploadAgentPackage(l,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=rt(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=xt(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=He(this.getState()),{force:s=!1}={}){const n=Gs(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=it(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<Th)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 l=this.getState().files.bySessionId[e];return l?.selectedFilename&&await this.ensureFilePreview(e,l.selectedFilename).catch(()=>{}),l}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=Hu(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 l=o?.isBinary===!0?po(s,"",o.contentType||"",o):po(s,await this.transport.downloadArtifact(e,s),o?.contentType||"",o);return this.dispatch({type:"files/previewLoaded",sessionId:e,filename:s,...l}),l}catch(l){return this.dispatch({type:"files/previewError",sessionId:e,filename:s,error:l?.message||String(l)}),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(l=>l.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=it(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||He(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:i}=s,r=He(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 ${Ae(n)} ${i} in the default app`:`Opened ${i} in the default app`})}catch(l){this.dispatch({type:"ui/status",text:`Open failed: ${l?.message||String(l)}`})}}async downloadSelectedArtifact(){const e=it(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=ht(this.getState()),n=this.getState().files.markedIds||[],i=n.length>0?n[n.length-1]:this.getState().files.selectedArtifactId,r=s.findIndex(u=>u.id===i),o=s.findIndex(u=>u.id===e.id);if(o<0)return;if(r<0){this.dispatch({type:"files/toggleMark",artifactId:e.id});return}const[l,c]=r<=o?[r,o]:[o,r],d=s.slice(l,c+1).map(u=>u.id);this.dispatch({type:"files/setMarks",artifactIds:[...new Set([...n,...d])]})}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 l of n){const c=String(l).indexOf("/");if(c<=0)continue;const d=l.slice(0,c),u=l.slice(c+1);try{await this.transport.deleteArtifact(d,u),this.dispatch({type:"files/deleted",sessionId:d,filename:u}),i.add(d),r+=1}catch(p){o.push(`${u}: ${p?.message||String(p)}`)}}for(const l of i)await this.ensureFilesForSession(l,{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=it(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const i=He(s),r=i==="allSessions"?`${Ae(n.sessionId)} ${n.filename}`:n.filename;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifact",message:`Delete artifact "${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=it(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 ${Ae(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=qd(e),i=Yd(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,l=this.buildArtifactPickerModal({artifactLinks:n,httpLinks:i,previousFocus:e.ui.focusRegion,selectedId:o});if(!l){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:l}),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=He(this.getState());await this.ensureFilesForScope(s);const n=ht(this.getState());if(n.length===0)return;const i=it(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)),l=n[o];!l?.sessionId||!l?.filename||(s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:l.id}):this.dispatch({type:"files/select",sessionId:l.sessionId,filename:l.filename}),await this.ensureFilePreview(l.sessionId,l.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${Ae(l.sessionId)} ${l.filename}`:`Previewing ${l.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;this.dispatch({type:"files/previewOrigin",origin:"list"});const s=He(this.getState());s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:e.id}):this.dispatch({type:"files/select",sessionId:e.sessionId,filename:e.filename}),await this.ensureFilePreview(e.sessionId,e.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${Ae(e.sessionId)} ${e.filename}`:`Previewing ${e.filename}`})}toggleFilePreviewFullscreen(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.files.bySessionId[s],i=!!e.files.fullscreen;if(!i&&!n?.selectedFilename){this.dispatch({type:"ui/status",text:"Select a file before entering fullscreen"});return}const 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(!Wf.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=He(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:Tn(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:ar(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=Jf(s),o=this.getState().sessions.byId[e]||{sessionId:e},l=zo(o.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(r||l)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...r||{},...l?{contextUsage:l}:{}}}),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(Xt(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||Yt(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||Yt(e))return;let s=null;try{s=await this.transport.getSession(e)}catch(r){if(Xt(r)){this.handleSessionGone(e);return}throw r}if(!s)return;const n=this.getState().sessions.byId[e]||null,i=sh(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 ${so(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}))],l=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:l>=0?l: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(p=>String(p||"").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,l=o?o.filter(p=>p.placed!==!0):[],c=o?o.filter(p=>p.placed===!0).length:i.length;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&c>0&&await this.loadSession(`group:${e}`).catch(()=>{});const d=e?`group ${n||e}`:"No Group",u=l.length>0?` · skipped ${l.length} (${zf(l)})`:"";return this.dispatch({type:"ui/status",text:c>0?`Moved ${c} session${c===1?"":"s"} to ${d}${u}`:`No sessions moved to ${d}${u}`}),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=It(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=rt(s.value||"",s.cursorIndex||0,It(e,s.maxLength||80));this.setSessionGroupNameValue(n.prompt,n.cursor)}deleteSessionGroupNameChar(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=xt(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;if(!n?.isGroup)return e;const i=n.groupId||vs(n.sessionId);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={},s=null){const n=s??this.getState().ui.focusRegion,i=()=>{this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n)};let r=[];try{r=typeof this.transport.listCreatableAgents=="function"?await this.transport.listCreatableAgents():[]}catch(h){i(),this.dispatch({type:"ui/status",text:`Could not load agents: ${h?.message||h}`});return}const l=(typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0;if(!Array.isArray(r)||r.length===0){if(i(),!l){this.dispatch({type:"ui/status",text:"No user-creatable agents are available for this app"});return}await this.createSession(e);return}const c=[];for(const h of r){const m=String(h?.name||"").trim();m&&c.push({id:m,kind:"agent",agentName:m,title:so(m,h?.title),description:String(h?.description||"").trim(),tools:Array.isArray(h?.tools)?h.tools.filter(Boolean):[],splash:typeof h?.splash=="string"&&h.splash.trim()?h.splash:null,splashMobile:typeof h?.splashMobile=="string"&&h.splashMobile.trim()?h.splashMobile:null,initialPrompt:typeof h?.initialPrompt=="string"&&h.initialPrompt.trim()?h.initialPrompt:null,group:h?.source==="package"&&h?.scope==="user"&&h?.mine!==!1?"mine":"shared",packageName:h?.packageName||null,packageTitle:h?.packageTitle||null,packageSemver:h?.packageSemver||null,packageScope:h?.scope||null,ownerLabel:h?.ownerLabel||null,startedBy:Array.isArray(h?.startedBy)?h.startedBy.filter(Boolean):[],supportsDirectStart:typeof h?.supportsDirectStart=="boolean"?h.supportsDirectStart:void 0,builtin:h?.source!=="package"})}const d=[...c.filter(h=>h.group==="shared"),...c.filter(h=>h.group==="mine")],u=l?{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,supportsDirectStart:!0}:null,p=[ss,ul,dl,...new Set(d.filter(h=>!h.builtin).map(h=>pl(h)))],f=io(d,p,u);this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",catalog:d,genericItem:u,collapsed:p,items:f,selectedIndex:lh(f),previousFocus:n,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={},n=null){const i=n??this.getState().ui.focusRegion,r=qn(e?.supportedReasoningEfforts),o=s?.reasoningEffort||Qr(e);if(!r.length||!o){await this.openContextTierPicker(e,s,i);return}const l=r.map(d=>({id:d,effort:d,label:d,isDefault:o===d})),c=Math.max(0,l.findIndex(d=>d.id===o));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:l,selectedIndex:c,previousFocus:i,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a reasoning effort and press Enter"})}async openContextTierPicker(e,s={},n=null){const i=n??this.getState().ui.focusRegion,r=Yn(e?.supportedContextTiers),o=s?.contextTier||Yf(e);if(!r.length||!o){if(s?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i),await this.switchSessionModel({...s,model:e?.id});return}await this.openSessionAgentPicker(s,i);return}const l=r.map(d=>({id:d,tier:d,tokenLimit:e?.contextWindowSizes?.[d]||null,label:Qf(d,e?.contextWindowSizes?.[d]),isDefault:o===d})),c=Math.max(0,l.findIndex(d=>d.id===o));this.dispatch({type:"ui/modal",modal:{type:"contextTierPicker",title:`Context window for ${e?.modelName||e?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:i,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():qf(s),r=await this._resolveGhcpUserKeySet(),o=[],l=i.map(u=>({providerId:u.providerId,providerType:u.type||u.providerType,models:(u.models||[]).map(p=>{const f=p.providerType||u.type||u.providerType,h=f==="github"&&p.credentialAvailable===!1&&r===!1,m={id:p.qualifiedName,qualifiedName:p.qualifiedName,modelName:p.modelName||p.qualifiedName,providerId:p.providerId||u.providerId,providerType:f,description:p.description||"",cost:p.cost||null,supportedReasoningEfforts:qn(p.supportedReasoningEfforts),defaultReasoningEffort:p.defaultReasoningEffort||null,supportedContextTiers:Yn(p.supportedContextTiers),defaultContextTier:p.defaultContextTier||null,contextWindowSizes:p.contextWindowSizes||null,isDefault:n===p.qualifiedName,ghcpKeyMissing:h,disabled:h};return o.push(m),m})})).filter(u=>u.models.length>0),c=e?.model||n;let d=o.findIndex(u=>u.qualifiedName===c&&!u.disabled);d<0&&(d=o.findIndex(u=>!u.disabled)),d<0&&(d=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:l,selectedIndex:d,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?` · ${al[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=Fu().map(i=>({id:i.id,label:i.label,description:i.description,group:i.group,page:i.page,terminal:i.terminal,tui:i.tui}));if(e.length===0){this.dispatch({type:"ui/status",text:"No themes available"});return}const s=this.getState().ui.themeId,n=Math.max(0,e.findIndex(i=>i.id===s));this.dispatch({type:"ui/modal",modal:{type:"themePicker",title:"Theme Picker",items:e,selectedIndex:n,previousFocus:this.getState().ui.focusRegion,currentThemeId:s}}),this.dispatch({type:"ui/status",text:"Select a theme and press Enter"})}getPromptDraftSessionId(){return this.getPromptAttachments()[0]?.sessionId||null||this.getState().sessions.activeSessionId||null}openArtifactUploadModal(){if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}const e=this.getState(),s=this.getPromptDraftSessionId();this.dispatch({type:"ui/modal",modal:{type:"artifactUpload",title:s?`Upload Artifact (${Ae(s)})`:"Upload Artifact",sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0}}),this.dispatch({type:"ui/status",text:s?"Paste a local file path and press Enter to upload it into this session's artifacts":"Paste a local file path and press Enter to upload it; a new session will be created if needed"})}updateArtifactUploadModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setArtifactUploadValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="artifactUpload")return;const i=String(e||"").replace(/\r?\n/g,""),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=rt(s.value||"",s.cursorIndex||0,String(e||"").replace(/\r?\n/g,""));this.setArtifactUploadValue(n.prompt,n.cursor)}deleteArtifactUploadChar(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=xt(e.value||"",e.cursorIndex||0);this.setArtifactUploadValue(s.prompt,s.cursor)}moveArtifactUploadCursor(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",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=Mr(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 l=n[o],c=l.indexOf("/");if(c<=0)return;const d=l.slice(0,c),u=l.slice(c+1);this.dispatch({type:"files/select",sessionId:d,filename:u}),await this.ensureFilePreview(d,u).catch(()=>{})}canStepArtifactPreview(e){const s=this.getState(),n=s.files.previewOrigin==="chat"?Mr(s):ht(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=ro(e.filename),o=this.getState().ui.prompt,l=this.getState().ui.promptCursor,c=this.getPromptAttachments(),d=c.findIndex(p=>p?.sessionId===i&&p?.filename===e.filename);if(this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),d===-1||!o.includes(c[d]?.token||r)){const p=rt(o,l,`${r} `);this.setPrompt(p.prompt,p.cursor)}const u=d>=0?c.map((p,f)=>f===d?{...p,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:r}:p):[...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(u),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:d>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:i,existingAttachmentIndex:d,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,l=null;for(const c of n)try{const d=await this.transport.uploadArtifactFromFile(i,c);r.push(d),await this.finalizeArtifactUpload(d,{sessionId:i,suppressStatus:!0})}catch(d){o+=1,l=d}return r.length>0?this.dispatch({type:"ui/status",text:o>0?`Uploaded ${r.length}/${n.length} file(s); last error: ${l?.message||String(l)}`:r.length===1?`Uploaded ${r[0].filename}`:`Uploaded ${r.length} files`}):l&&this.dispatch({type:"ui/status",text:`Upload failed: ${l?.message||String(l)}`}),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=ah(n),r=$i(n),o=oh(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:`Rename (${Ae(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:i,cursorIndex:i.length,agentTitlePrefix: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 (${Ae(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=It(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=rt(s.value||"",s.cursorIndex||0,It(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=xt(e.value||"",e.cursorIndex||0);this.setRenameSessionValue(s.prompt,s.cursor)}moveRenameSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",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||vs(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 l=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),l&&this.setFocus(l),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 ${Ae(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${Ae(s)}`})}catch(l){this.dispatch({type:"ui/status",text:`Rename failed: ${l?.message||String(l)}`})}}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=bt(["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 (${Ae(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0,shares:Array.isArray(i)?i:[],visibility:n.visibility||"private"}}),this.dispatch({type:"ui/status",text:"name [r|w] grants · -name revokes · Enter apply"})}updateShareSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setShareSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="shareSession")return;const i=It(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=rt(s.value||"",s.cursorIndex||0,It(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=xt(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 h=r.toLowerCase(),m=(e.shares||[]).find(g=>g.subject&&String(g.subject).toLowerCase()===h||g.email&&String(g.email).toLowerCase()===h||g.displayName&&String(g.displayName).toLowerCase()===h);if(!m){this.dispatch({type:"ui/status",text:`No grant matching "${r}"`});return}this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.revokeSessionShare(s,{provider:m.provider,subject:m.subject}),this.dispatch({type:"ui/status",text:`Revoked ${r}`})}catch(g){this.dispatch({type:"ui/status",text:g?.message||String(g)})}return}const o=n.split(/\s+/),l={r:"read",read:"read",w:"write",write:"write"},c=o.length>1?o[o.length-1].toLowerCase():null,d=c&&l[c]?l[c]:"read",u=c&&l[c]?o.slice(0,-1).join(" "):n,p=u.toLowerCase();let f=null;if(typeof this.transport.listKnownUsers=="function"){let h=[];try{h=await this.transport.listKnownUsers({limit:500})}catch{h=[]}const m=Array.isArray(h)?h:[];if(f=m.find(g=>g.displayName&&g.displayName.toLowerCase()===p||g.email&&g.email.toLowerCase()===p||g.subject&&g.subject.toLowerCase()===p)||null,!f){const g=m.filter(S=>S.displayName&&S.displayName.toLowerCase().includes(p)||S.email&&S.email.toLowerCase().includes(p)||S.subject&&S.subject.toLowerCase().includes(p));if(g.length===1)f=g[0];else if(g.length>1){this.dispatch({type:"ui/status",text:`"${u}" is ambiguous (${g.length} matches)`});return}}}f||(f={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:u,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},d),this.dispatch({type:"ui/status",text:`Granted ${d} to ${u}`})}catch(h){this.dispatch({type:"ui/status",text:h?.message||String(h)})}}closeModal(){const e=this.getState().ui.modal;e&&(this.dispatch({type:"ui/modal",modal:null}),e.type==="themePicker"&&e.currentThemeId&&this.dispatch({type:"ui/theme",themeId:e.currentThemeId}),e.previousFocus&&this.setFocus(e.previousFocus),this.dispatch({type:"ui/status",text:"Connected"}))}toggleAgentPickerSection(e,s=null){const n=this.getState().ui.modal;if(!n||n.type!=="sessionAgentPicker"||!e)return;const i=new Set(n.collapsed||[]),r=s===null?!i.has(e):s;if(r===i.has(e))return;r?i.add(e):i.delete(e);const o=[...i],l=io(n.catalog||[],o,n.genericItem||null),c=n.items?.[n.selectedIndex||0]?.id;let d=l.findIndex(u=>u.id===c);d<0&&(d=Math.max(0,l.findIndex(u=>u.sectionKey===e))),this.dispatch({type:"ui/modal",modal:{...n,collapsed:o,items:l,selectedIndex:d}})}moveAgentPickerSection(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionAgentPicker")return!1;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Math.min(Number(s.selectedIndex)||0,n.length-1)),r=n[i];if(!r)return!1;if(e>0)return r.kind==="section"&&r.collapsed?(this.toggleAgentPickerSection(r.sectionKey,!1),!0):!1;if(r.kind==="section"&&!r.collapsed)return this.toggleAgentPickerSection(r.sectionKey,!0),!0;for(let o=i-1;o>=0;o-=1)if(n[o].kind==="section"&&n[o].depth<r.depth)return this.dispatch({type:"ui/modalSelection",index:o}),!0;return!1}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 l=o.options.map(p=>p.id).filter(Boolean);if(l.length===0)return;const c=s.type==="filesFilter"?this.getState().files.filter?.[o.id]||l[0]:s.type==="historyFormat"?this.getState().executionHistory?.format||l[0]:this.getState().logs.filter?.[o.id]||l[0],d=bt(l,c,e),u=o.options.find(p=>p.id===d)||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]:d},...s.type==="historyFormat"?{format:d}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(d).catch(()=>{}),this.ensureSelectedFilePreview().catch(()=>{})),this.dispatch({type:"ui/status",text:`${s.type==="filesFilter"?"Files":s.type==="historyFormat"?"History":"Log"} filter updated: ${o.label} = ${u?.label||d}`});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?.type==="sessionAgentPicker"){this.moveAgentPickerSection(e);return}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,l=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}: ${l?.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=st(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(!s){if(e.sessionOptions?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),this.dispatch({type:"ui/status",text:"No model selected"});return}await this.openSessionAgentPicker({},n);return}const i=Qr(s);if(e.sessionOptions?.mode==="switchModel"){await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,reasoningEffort:i??null},n);return}await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,...i?{reasoningEffort:i}:{}},n);return}if(e.type==="reasoningEffortPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};await this.openContextTierPicker(e.modelItem,{...i,...s?.id?{reasoningEffort:s.id}:{}},n);return}if(e.type==="contextTierPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{},r={...i,...s?.id?{contextTier:s.id}:{}};if(i?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),await this.switchSessionModel({...r,model:e.modelItem?.id||i.model});return}await this.openSessionAgentPicker(r,n);return}if(e.type==="sessionAgentPicker"){const s=e.items?.[e.selectedIndex||0];if(s?.kind==="section"){this.toggleAgentPickerSection(s.sectionKey);return}if(s&&s.kind!=="generic"&&s.supportsDirectStart===!1){this.dispatch({type:"ui/status",text:`${s.title||s.agentName} is created by another agent and cannot be started on its own`});return}const 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=fh(s,n);let o=e.sessions.activeSessionId;i&&(o=i,e.sessions.activeSessionId!==i&&await this.loadSession(i));let l=o&&e.sessions.byId[o]||null;if(o&&!l&&(l=this.getState().sessions.byId[o]||null),!o){const g=await this.createSession({});if(!g?.sessionId)return;o=g.sessionId,l=this.getState().sessions.byId[o]||null}const c=n.some(g=>g?.kind==="image");if(!r.trim()&&!c){o&&this.getPendingOutboxItems(o).length>0&&await this.dispatchPendingOutbox(o).catch(()=>{});return}const d=l?.pendingQuestion||null,u=!!d?.question,p=this.getPromptEditSessionMatch(o);if(p){const g=this.getSessionOutbox(o).find(S=>S.id===p.itemId);if(g?.phase==="queued"||g?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(o).catch(()=>{});return}if(u&&typeof this.transport.sendAnswer=="function"){const g=Date.now(),S={...d,answer:r,answeredAt:g,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:null,answeredPendingQuestion:S}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(o,r),this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:{...S,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(o,100),this.syncSessionEvents(o).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(y){this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:d}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(r,String(r||"").length),this.dispatch({type:"ui/status",text:y?.message||String(y)})}return}const f=n.filter(g=>g?.kind==="image");let h=null;if(f.length>0){if(f.some(y=>y.file)&&typeof this.transport.uploadArtifactFromFile!="function"){this.dispatch({type:"ui/status",text:"This transport does not support image attachments."});return}const S=this.buildOutboxItem("","pending");this.dispatch({type:"ui/status",text:`Uploading ${f.length} image${f.length>1?"s":""}...`});try{h=await this.uploadPendingImageAttachments(o,f,S.id),this.dispatch({type:"ui/status",text:""})}catch(y){this.dispatch({type:"ui/status",text:`Image upload failed: ${y?.message||y}`});return}}const m=r.trim()?r:h&&h.length>0?"See the attached image(s).":r;this.queuePromptInOutbox(o,m,h?{attachments:h}: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 l=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,l)}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=rt(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=xt(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=Sh(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,ml(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=bh(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 ns({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??$t(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,l=Je(o,r);l!==o&&this.setFocus(l)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:Je(e,this.getCurrentLayout())})}focusNext(){const e=this.getCurrentLayout(),s=Je(this.getState().ui.focusRegion,e),n=Bn(e);this.setFocus(bt(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=Je(this.getState().ui.focusRegion,e),n=Bn(e);this.setFocus(bt(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=Je(this.getState().ui.focusRegion,e);this.setFocus(Qc(s,e))}focusRight(){const e=this.getCurrentLayout(),s=Je(this.getState().ui.focusRegion,e);this.setFocus(Jc(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,l=Je(o,r);l!==o&&this.setFocus(l)}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}),l=this.getState().ui.focusRegion,c=Je(l,o);c!==l&&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}),l=this.getState().ui.focusRegion,c=Je(l,o);c!==l&&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=(l,c,d,u)=>{const p=Math.max(d,u);return Math.max(d,Math.min(p,(l||0)+c))};if(s===T.SESSIONS||s===T.CHAT){const l=fa(i),c=Bt+1,d=Math.min(ha(r,i),i-Vs-1),u=s===T.CHAT?-e:e,p=o(n.sessionPaneAdjust,u,c-l,d-l);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:p})}else if(s===T.INSPECTOR||s===T.ACTIVITY){const l=Math.max(Rt,Math.floor(i*pa)),c=Rt+1,d=i-Ps-1,u=s===T.INSPECTOR?-e:e,p=o(n.activityPaneAdjust,u,c-l,d-l);this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:p})}}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 l=Number(o?.data?.turnIndex??o?.data?.iteration);!Number.isFinite(l)||r.has(l)||(r.add(l),i.push(l))}return i.sort((o,l)=>o-l),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=bt(Ve,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=bt(Ve,this.getState().ui.inspectorTab,-1);this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),this.ensureInspectorData(e).catch(()=>{})}cycleInspectorTab(){this.nextInspectorTab()}toggleStatsView(){const e=["session","fleet","users"],s=this.getState().ui.statsViewMode,n=e.includes(s)?e.indexOf(s):0,i=e[(n+1)%e.length];this.setStatsViewMode(i)}setStatsViewMode(e){this.dispatch({type:"ui/statsViewMode",statsViewMode:e}),this.getState().ui.inspectorTab==="stats"&&this.ensureInspectorData("stats").catch(()=>{})}async selectInspectorTab(e){Ve.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=Ht(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)),l=n[o].sessionId;this.navigateToSession(l)}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(()=>{})},Mh))}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 wh.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 l=n.followBottom!==void 0?!!n.followBottom:n.atBottom!==void 0?!!n.atBottom:o>=r;return this.dispatch({type:"ui/followBottom",pane:e,followBottom:l}),this.dispatch({type:"ui/scroll",pane:e,offset:l?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 l=this.getPaneVisualScrollOffset(e,n),c=Math.max(0,Math.min(l-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:Gf,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=Ei(e,n),o=[...vi(e,n),...Ii(e)],l=Math.min(Math.max(0,Math.floor(i*.34)),Et(o,n)),c=Et(r,n);return{contentWidth:n,contentHeight:Math.max(1,i-l),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}},l=Ai(o);return{contentWidth:n,contentHeight:i,totalLines:Et(l.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},l=lt(o,{width:n}),c=l.tabs.map(f=>({text:f===l.activeTab?`[${f}] `:`${f} `,color:f===l.activeTab?"magenta":"gray",bold:f===l.activeTab})),d=(l.lines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f),u=l.activeTab==="sequence"?[c,...(l.stickyLines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f)]:[],p=l.activeTab==="sequence"?d:[c,...d];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:Et(u,n),totalLines:Et(p,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),l=Math.max(8,o-4),c=e.sessions.activeSessionId,d=c&&e.sessions.byId[c]||null,u={sessions:{activeSessionId:c,byId:c&&d?{[c]:d}:{},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}}},p=Ci(u,{listWidth:l,previewWidth:l}),f=Math.max(9,r-4),h=Math.max(5,Math.min(10,Math.floor(f*.35)));let m=Math.max(5,Math.min(h,(p.listBodyLines||[]).length+2)),g=Math.max(5,f-m-1);const S=8;if(g<S){const y=S-g;m=Math.max(5,m-y),g=Math.max(5,f-m-1)}return{contentWidth:l,contentHeight:Math.max(1,g-2),totalLines:Et(p.previewLines,l)}}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)>=Qn){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:l,totalLines:c}=this.getActiveChatRenderMetrics(n),d=Math.max(0,c-l);if(e<d)return}await this.expandSessionHistory(i,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages,eventTypes:vc})}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(ae,Number(i?.loadedEventLimit??ae)||ae),o=ae,l=Array.isArray(i?.events)&&i.events.length>0?Number(i.events[0]?.seq||0):0;if(!i?.hasOlderEvents||l<=1){this.dispatch({type:"ui/status",text:"Already showing the oldest loaded history"});return}const c=e===n.sessions.activeSessionId,d=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),u=c?this.getActiveChatRenderMetrics(n).totalLines:0,p=(async()=>{let f;const h=Math.max(1,Math.floor(Number(s.pages)||1)),m=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&l>0){f=i||fs([],{requestedLimit:r});for(let y=0;y<h;y+=1){const w=Array.isArray(f?.events)&&f.events.length>0?Number(f.events[0]?.seq||0):0;if(!f?.hasOlderEvents||w<=1){f={...f,hasOlderEvents:!1};break}if(Number(f.loadedEventCount||0)>=Qn)break;const x=await this.transport.getSessionEventsBefore(e,w,o,m);if(!Array.isArray(x)||x.length===0){f={...f,hasOlderEvents:!1};break}const I=fs(x,{requestedLimit:o}),E=[...I.events||[],...f?.events||[]];if(f={chat:Pt([...I.chat||[],...f?.chat||[]]),activity:[...I.activity||[],...f?.activity||[]],events:E,lastSeq:f?.lastSeq||f?.events?.[f?.events?.length-1]?.seq||x[x.length-1]?.seq||0,loadedEventLimit:E.length,loadedEventCount:E.length,hasOlderEvents:x.length>=o&&Number(x[0]?.seq||0)>1},!f.hasOlderEvents)break}}else{const y=Wc(r);if(y<=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 w=await this.transport.getSessionEvents(e,void 0,y);f={...fs(w,{requestedLimit:y}),lastSeq:w[w.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:f});for(const y of f?.events||[])this.reconcileOutboxAgainstEvent(e,y);const g=Array.isArray(i?.chat)&&i.chat.length>0;if(c&&!g)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(c&&d>0){const y=this.getState(),w=this.getActiveChatRenderMetrics(y).totalLines,x=Math.max(0,w-u);x>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:d+x})}const S=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:S}),f.hasOlderEvents?s.autoTriggered&&c&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,p),p}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:l}=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"}?${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Cancel Sessions",action:"cancelSession",previousFocus:s.ui.focusRegion}});return}let c=0;const d=[];for(const p of o)try{await this.transport.cancelSession(p.sessionId),c+=1}catch(f){d.push(`${p.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const u=d.length===0?`Cancelled ${c} session${c===1?"":"s"}`:`Cancelled ${c}/${o.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),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 l=r?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Session",message:`Cancel session "${l}"? 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 l=this.getState(),c=l.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 d=l.sessions.byId[c];if(d?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; regenerate sessions individually."});return}if(d?.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be regenerated."});return}if(d?.serviceKind){this.dispatch({type:"ui/status",text:"Service sessions are runtime machinery and cannot be regenerated."});return}if(!e){const u=d?.title||c.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Regenerate Session",message:`Regenerate context for "${u}"? 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:l.ui.focusRegion,extras:{instructions:"",distillMode:"llm",distillerModel:"",distillerEffort:"",distillerContextTier:"",distillerModelOptions:await this._loadDistillerModelOptions()}}});return}try{const u=String(s||"").trim();await this.transport.regenerateSession(c,{force:!0,...u?{instructions:u.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(u){this.dispatch({type:"ui/status",text:`Regenerate failed: ${u?.message||String(u)}`});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:l,skippedCount:c}=this.getBulkSelectedSessionActions(n);if(l.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 ${l.length} selected session${l.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 d=0;const u=[];for(const f of l)try{await this.transport.completeSession(f.sessionId,e),d+=1}catch(h){u.push(`${f.sessionId.slice(0,8)}: ${h?.message||String(h)}`)}this.dispatch({type:"sessions/selectClear"});const p=u.length===0?`Completed ${d} session${d===1?"":"s"}`:`Completed ${d}/${l.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:p}),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 l=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 "${l}" 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 l=o?.title||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Session",message:`Complete session "${l}"? 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(l){await this.loadSession(r).catch(()=>{}),this.dispatch({type:"ui/status",text:`Failed to send /done: ${l?.message||String(l)}`})}}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:l}=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.${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Hard Delete Sessions",action:"deleteSession",previousFocus:s.ui.focusRegion}});return}let c=0;const d=[];for(const p of o)try{await this.transport.deleteSession(p.sessionId),this.handleSessionGone(p.sessionId),c+=1}catch(f){d.push(`${p.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const u=d.length===0?`Deleted ${c} session${c===1?"":"s"}`:`Deleted ${c}/${o.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),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||vs(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 l=r?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Session",message:`Delete session "${l}"? 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 Js=0;function Le(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 Nn(){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 _h(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 Rh(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 $h(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 Oh(t=2e3){const[e,s]=a.useState(()=>Nn());return a.useEffect(()=>{if(Nn()==null)return;const n=()=>{const r=Nn();r!=null&&s(o=>o===r?o:r)};n();const i=setInterval(n,t);return()=>clearInterval(i)},[t]),a.useMemo(()=>_h(e),[e])}function Kt(t,e){return t&&e?{[t]:e}:{}}function fo(t){return typeof t=="string"?{text:t,color:"white"}:t}function ds(t,e,s,n,i,r){const o=(e.tabs||Ve).map(p=>({text:p===e.activeTab?`[${p}] `:`${p} `,color:p===e.activeTab?"magenta":"gray",bold:p===e.activeTab})),l=(e.lines||[]).map(fo),c=(e.stickyLines||[]).map(fo),d=e.activeTab==="sequence"?[o,...c]:[],u=e.activeTab==="sequence"?l:[o,...l];return a.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:i,stickyLines:d,marginBottom:Js,lines:u,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 ho(t,e){const s=String(t||"");return e<=0?"":s.length<=e?s:e===1?s.slice(0,1):`${s.slice(0,e-1)}...`}a.memo(function({controller:e,maxRows:s,width:n,height:i,frame:r,versionLabel:o=null}){const l=We(),c=Oh(),d=ee(e,m=>({sessions:m.sessions,mode:m.connection?.mode||"local",brandingTitle:m.branding?.title||"PilotSwarm",focused:m.ui.focusRegion==="sessions",identityLabel:Rh(m.auth)}),Le),u=a.useMemo(()=>$h(c,o,d.identityLabel),[c,o,d.identityLabel]),p=a.useMemo(()=>({sessions:d.sessions,connection:{mode:d.mode},branding:{title:d.brandingTitle}}),[d.brandingTitle,d.mode,d.sessions]),f=a.useMemo(()=>Kn(p,s),[p,s]),h=a.useMemo(()=>f.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:f.map(m=>m.active?Aa(m.runs,{preserveColors:!0}):m.runs),[f]);return a.createElement(l.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:u,color:"yellow",focused:d.focused,width:n,height:i,marginBottom:Js,lines:h,paneId:"sessions",paneLabel:"Sessions",frame:r})});a.memo(function({controller:e,width:s,height:n,frame:i}){const r=We(),o=ee(e,x=>{const I=x.sessions.activeSessionId;return{activeSessionId:I,activeSession:I&&x.sessions.byId[I]||null,activeHistory:I&&x.history.bySessionId.get(I)||null,activeOutbox:I&&x.outbox?.bySessionId?.[I]||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"}},Le),l=Math.max(20,s-4),c=a.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:Kt(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]),d=a.useMemo(()=>za(c,{width:l}),[l,c]),u=Uo(!!d?.animateTitleRight),p=a.useMemo(()=>Wo(d?.titleRight,u),[u,d?.titleRight]),f=!o.activeSessionId&&o.connectionError,h=a.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"}]:Ei(c,l),[o.branding.splash,o.connectionError,l,c,f]),m=String(o.activeSession?.status||"").toLowerCase()==="running",g=jo(m),S=a.useMemo(()=>f?[]:Ii(c,{spinnerFrame:g,maxWidth:l}),[c,f,g,l]),y=a.useMemo(()=>f?[]:vi(c,l),[c,f,l]),w=a.useMemo(()=>y.length>0||S.length>0?[...y,...S]:[],[y,S]);return a.createElement(r.Panel,{title:d.title,titleRight:p,color:d.color,focused:o.focused,width:s,height:n,lines:h,bottomStickyLines:w,scrollOffset:o.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:i})});const Lh=a.memo(function({controller:e,width:s,height:n,shellTitle:i,focused:r=!1,frame:o,showFullscreenTitle:l=!1,embedded:c=!1}){const d=We(),u=ee(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}),Le),p=Math.max(20,s-4),f=a.useMemo(()=>({sessions:{activeSessionId:u.activeSessionId,byId:u.activeSessionId&&u.activeSession?{[u.activeSessionId]:u.activeSession}:{},flat:u.sessionsFlat},files:{bySessionId:u.filesBySessionId,fullscreen:u.filesFullscreen,selectedArtifactId:u.selectedArtifactId,filter:u.filesFilter},ui:{scroll:{filePreview:u.filePreviewScroll}}}),[u]),h=a.useMemo(()=>Ci(f,{listWidth:Math.max(8,p-4),previewWidth:Math.max(8,p-4)}),[p,f]),m=i||(l?h.fullscreenTitle:h.panelTitle||h.listTitle)||[{text:"Files",color:"magenta",bold:!0}],g=Math.max(9,n-4),S=Math.max(5,Math.min(10,Math.floor(g*.35)));let y=Math.max(5,Math.min(S,(h.listBodyLines||[]).length+2)),w=Math.max(5,g-y-1);const x=8;if(w<x){const B=x-w;y=Math.max(5,y-B),w=Math.max(5,g-y-1)}const I=Math.max(1,y-2),E=Math.max(0,h.selectedIndex-Math.floor(I/2)),b=!c&&o?{x:o.x+2,y:o.y+2,width:p,height:y}:null,k=!c&&o?{x:o.x+2,y:o.y+2+y+1,width:p,height:w}:null,M=Ve.map(B=>({text:B==="files"?`[${B}] `:`${B} `,color:B==="files"?"magenta":"gray",bold:B==="files"})),N=a.createElement(d.Column,{width:p},a.createElement(d.Lines,{lines:[M]}),a.createElement(d.Panel,{title:h.listTitle,color:"gray",focused:!1,width:p,height:y,lines:h.listBodyLines||h.listLines.slice(1),scrollOffset:E,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:b}),a.createElement(d.Panel,{title:h.previewTitle,color:"gray",focused:!1,width:p,height:w,lines:h.previewLines,scrollOffset:h.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:k}));return c?N:a.createElement(d.Panel,{title:m,color:"magenta",focused:r,width:s,height:n,marginBottom:Js,paneId:"inspector",paneLabel:"Inspector",frame:o},N)}),Fh=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=We(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null}),Le),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Kt(c.activeSessionId,c.activeSession)},ui:{inspectorTab:"files"}}),[c.activeSession,c.activeSessionId]),u=a.useMemo(()=>lt(d,{width:l}),[l,d]);return a.createElement(o.Panel,{title:u.title,color:"magenta",focused:r.focused,width:s,height:n,marginBottom:Js,paneId:"inspector",paneLabel:"Inspector",frame:i},a.createElement(Lh,{controller:e,width:s,height:n,frame:i,focused:r.focused,embedded:!0}))}),Bh=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=We(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,activeOrchestration:p.sessions.activeSessionId&&p.orchestration.bySessionId?.[p.sessions.activeSessionId]||null,histories:p.history.bySessionId,expandedTurns:p.ui.sequenceExpandedTurns,selectedTurn:p.ui.sequenceSelectedTurn}),Le),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Kt(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]),u=a.useMemo(()=>lt(d,{width:l,sequenceExpansion:{expandedTurns:c.expandedTurns||[],selectedTurn:c.selectedTurn??null}}),[l,d,c.expandedTurns,c.selectedTurn]);return ds(o,u,r,s,n,i)}),Dh=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=We(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,logs:p.logs}),Le),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Kt(c.activeSessionId,c.activeSession)},logs:c.logs,ui:{inspectorTab:"logs"}}),[c.activeSession,c.activeSessionId,c.logs]),u=a.useMemo(()=>lt(d,{width:l}),[l,d]);return ds(o,u,r,s,n,i)}),Hh=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=We(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,executionHistory:p.executionHistory}),Le),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Kt(c.activeSessionId,c.activeSession)},executionHistory:c.executionHistory,ui:{inspectorTab:"history"}}),[c.activeSession,c.activeSessionId,c.executionHistory]),u=a.useMemo(()=>lt(d,{width:l}),[l,d]);return ds(o,u,r,s,n,i)}),Gh=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=We(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,sessionsById:p.sessions.byId,sessionsFlat:p.sessions.flat,histories:p.history.bySessionId}),Le),d=a.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]),u=a.useMemo(()=>lt(d,{width:l}),[l,d]);return ds(o,u,r,s,n,i)}),jh=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=We(),l=Math.max(20,s-4),c=ee(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,sessionStats:p.sessionStats,fleetStats:p.fleetStats,statsViewMode:p.ui.statsViewMode}),Le),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Kt(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]),u=a.useMemo(()=>lt(d,{width:l}),[l,d]);return ds(o,u,r,s,n,i)});a.memo(function({controller:e,width:s,height:n,frame:i}){const r=ee(e,o=>({inspectorTab:o.ui.inspectorTab,inspectorScroll:o.ui.scroll.inspector,inspectorFollowBottom:o.ui.followBottom?.inspector!==!1,focused:o.ui.focusRegion==="inspector"}),Le);return r.inspectorTab==="files"?a.createElement(Fh,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="sequence"?a.createElement(Bh,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="logs"?a.createElement(Dh,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="history"?a.createElement(Hh,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="stats"?a.createElement(jh,{controller:e,width:s,height:n,frame:i,meta:r}):a.createElement(Gh,{controller:e,width:s,height:n,frame:i,meta:r})});a.memo(function({controller:e,width:s,height:n,maxLines:i,frame:r}){const o=We(),l=ee(e,p=>{const f=p.sessions.activeSessionId;return{sessionsById:p.sessions.byId,activeSessionId:f,activeSession:f&&p.sessions.byId[f]||null,activeHistory:f&&p.history.bySessionId.get(f)||null,scroll:p.ui.scroll.activity,followBottom:p.ui.followBottom?.activity!==!1,focused:p.ui.focusRegion==="activity",inspectorTab:p.ui.inspectorTab,nodeMapSelectedNode:p.ui.nodeMapSelectedNode,adminWorkers:p.admin?.workers,branding:p.branding,historyBySessionId:p.history.bySessionId,sessionsFlat:p.sessions.flat}},Le),c=l.inspectorTab==="nodes",d=a.useMemo(()=>{const p=new Map;return l.activeSessionId&&l.activeHistory&&p.set(l.activeSessionId,l.activeHistory),{branding:l.branding,admin:{workers:l.adminWorkers},ui:{nodeMapSelectedNode:l.nodeMapSelectedNode},sessions:{activeSessionId:l.activeSessionId,byId:l.sessionsById,flat:l.sessionsFlat},history:{bySessionId:c?l.historyBySessionId:p}}},[l.activeHistory,l.activeSessionId,l.sessionsById,l.adminWorkers,l.branding,l.historyBySessionId,l.nodeMapSelectedNode,l.sessionsFlat,c]),u=a.useMemo(()=>c?Va(d):Ai(d,i),[i,c,d]);return a.createElement(o.Panel,{title:u.title,color:"gray",focused:l.focused,width:s,height:n,lines:u.lines,scrollOffset:l.scroll,scrollMode:l.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:r})});a.memo(function({controller:e,rows:s}){const n=We(),i=ee(e,r=>{const o=r.sessions.activeSessionId,l=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:!!l?.pendingQuestion?.question,editingPending:r.ui.promptEdit?.sessionId===o,hasOutbox:c.length>0,hasPendingOutbox:c.some(d=>d?.phase==="pending")}},Le);return a.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})});a.memo(function({controller:e}){const s=We(),n=ee(e,u=>({connected:u.connection.connected,workersOnline:u.connection.workersOnline,focusRegion:u.ui.focusRegion,inspectorTab:u.ui.inspectorTab,chatViewMode:u.ui.chatViewMode||"transcript",fullscreenPane:u.ui.fullscreenPane||null,logsAvailable:u.logs.available,logsTailing:u.logs.tailing,filesFullscreen:!!u.files.fullscreen,mode:u.connection.mode,statusText:u.ui.statusText,modal:u.ui.modal,activeSessionId:u.sessions.activeSessionId,activeSession:u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]||null,selectedIds:u.sessions.selectedIds,selectMode:u.sessions.selectMode}),Le),i=a.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=a.useMemo(()=>up(i),[i]),o=typeof s.getViewport=="function"?s.getViewport():{width:120},l=Math.max(20,(o.width||120)-4),c=Math.min(Math.max(18,Math.floor(l*.45)),l-8),d=Math.max(8,l-c-3);return a.createElement(s.StatusLine,{left:ho(r.left,d),right:ho(r.right,c)})});const Uh="modulepreload",Wh=function(t){return"/"+t},mo={},yl=function(e,s,n){let i=Promise.resolve();if(s&&s.length>0){let c=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");i=c(s.map(d=>{if(d=Wh(d),d in mo)return;mo[d]=!0;const u=d.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":Uh,u||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),u)return new Promise((h,m)=>{f.addEventListener("load",h),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${d}`)))})}))}function r(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&r(l.reason);return e().catch(r)})};var Sl=Ql();const Kh=920,bl=7,wl=19,Oi=.24,Il=16,El=8,zh=224,Vh=190,qh=48,et=16,xl=.5,Qt=xl,Yh=24,Xh=700,Qh=5e3,Jh=new Set(["low","medium","high","xhigh"]),Zh=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],em=["pilotswarm_theme","pilotswarm_session_owner_filter"],tm={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"Duroxide Event History",files:"Files",stats:"Stats"},go={sequence:Bg,logs:Hg,nodes:Gg,history:Kg,files:zg,stats:Vg};function sm(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 nm(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function im(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function rm(t){return typeof t?.transport?.listArtifacts=="function"}function om(t){return typeof t?.transport?.deleteArtifact=="function"}function am(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const lm="Session link copied to clipboard",cm=140,um="Only people with access can open this link.";function dm(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function yo(t){navigator?.clipboard?.writeText&&navigator.clipboard.writeText(t).catch(()=>{})}async function pm(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 fm(){if(!(typeof window>"u")){try{for(const t of Zh)window.localStorage.removeItem(t)}catch{}try{for(const t of em)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function gt(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()),typeof e.touchScale=="boolean"&&(s.touchScale=e.touchScale),Ce(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=Ce(n,"includeShared")?n:{...n,includeShared:!0}}if(Ce(e,"layoutAdjustments")&&(s.layoutAdjustments=di(e.layoutAdjustments)),Ce(e,"pinnedSessionIds")&&(s.pinnedSessionIds=Ls(e.pinnedSessionIds)),Ce(e,"sessionOrder")&&(s.sessionOrder=pi(e.sessionOrder)),Ce(e,"collapsedSessionIds")&&(s.collapsedSessionIds=hm(e.collapsedSessionIds)),Ce(e,"activeSessionId")){const n=e.activeSessionId==null?null:String(e.activeSessionId).trim();s.activeSessionId=n||null}return os(e.chatViewMode)&&(s.chatViewMode=e.chatViewMode),os(e.chatViewModeMobile)&&(s.chatViewModeMobile=e.chatViewModeMobile),s}function os(t){return t==="summary"||t==="transcript"||t==="rich"}function vl(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches}function Ks(){return vl()?"chatViewModeMobile":"chatViewMode"}function zs(){return vl()?"chatViewMode":"chatViewModeMobile"}function hm(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 Ce(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function Pn(t,e=null){return gt({themeId:t.themeId,touchScale:t.touchScale,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,[Ks()]:t.chatViewMode,...os(e)?{[zs()]:e}:{}})}function So(t,e=null){return gt({themeId:t?.ui?.themeId,touchScale:t?.ui?.touchScale,sessionOwnerFilter:Ws(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,sessionOrder:t?.sessions?.manualOrder,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,[Ks()]:t?.ui?.chatViewMode,...os(e)?{[zs()]:e}:{}})}function mm(t,e){const s=gt(t),n=gt(e);return gt({themeId:Ce(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:Ce(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:Ce(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:Ce(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,sessionOrder:Ce(s,"sessionOrder")?s.sessionOrder:n.sessionOrder,...Ce(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...Ce(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...Ce(s,Ks())?{chatViewMode:s[Ks()]}:{}})}async function gm(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:gt(e)})}function Li(t){return rm(t)?Ve:Ve.filter(e=>e!=="files")}function Ue(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 Jn(t,e,s){return Math.max(e,Math.min(s,t))}function Zn(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-Il-El*2),n=s*Oi,i=Math.max(0,s-zh);return{minAdjust:-n,maxAdjust:i-n}}function ym(t,e){const s=Zn(t),n=Math.max(0,Number(t)||0),r=Math.max(0,n-Il-El*2)*Oi;return Jn(r+(Number(e)||0),0,r+s.maxAdjust)}function Sm(t){return t<=qh?"hidden":t<=Vh?"compact":"wrap"}function kl(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:$t(t?.ui?.prompt||"")}function Zs(t){return ns({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,kl(t),t.ui.layout?.sessionPaneAdjust??0)}function bm(t,e){return Math.max(20,t-4)}function Me(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 Vo(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 l=o.split(`
|
|
88
|
+
`);for(const c of l)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 Oe(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function Al(t=[]){return t.map(e=>String(e?.text||"")).join("")}function bo(t){return Array.isArray(t)?Al(t):String(t||"")}function wo(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 l=String(r?.text||"");if(!l)continue;if(n(r)&&i<l.length+2)break;const c=l.length>i&&i>1?`${l.slice(0,i-1)}…`:l.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 wm(t){typeof document>"u"||(t?document.documentElement.dataset.psTouch="1":delete document.documentElement.dataset.psTouch)}function Im(t){const e=st(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 Io(t){const[e,s]=a.useState({width:0,height:0});return a.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 Em(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/bl)),height:Math.max(18,Math.floor(s/wl))}}function xm(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function vm(t){return xm(t)<=xl}function km(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)*et;return s==="bottom"?Math.max(0,i-r):Math.min(i,r)}function Am(t,e,s,n,i,r,{stickyBottom:o=!1}={}){const l=a.useMemo(()=>Me(e),[e]),c=a.useRef(null),d=a.useRef({scrollMode:n,scrollOffset:s}),u=a.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),p=a.useRef({width:null,height:null}),[f,h]=a.useState(0);a.useLayoutEffect(()=>{const E=t.current;if(!E||typeof ResizeObserver>"u")return;p.current={width:E.clientWidth,height:E.clientHeight};const b=new ResizeObserver(()=>{const k={width:E.clientWidth,height:E.clientHeight},M=p.current;k.width===M.width&&k.height===M.height||(p.current=k,h(N=>N+1))});return b.observe(E),()=>b.disconnect()},[t]),a.useLayoutEffect(()=>{const E=t.current;if(!E)return;const b=d.current,k=u.current,M=typeof performance<"u"?performance.now():Date.now(),N=k.touching||M-(k.lastUserScrollAt||0)<Xh,B=k.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-k.lastDispatchedOffset)<2;if(N&&n===b?.scrollMode&&(s===b?.scrollOffset||B)){d.current={scrollMode:n,scrollOffset:s};return}const _=o&&n==="top"&&b?.scrollMode==="top"&&b?.scrollOffset===s,P=km(E,s,n,_);if(Math.abs(E.scrollTop-P)>Qt){const j={target:P};c.current=j,E.scrollTop=P,window.requestAnimationFrame(()=>{c.current===j&&(c.current=null)})}d.current={scrollMode:n,scrollOffset:s}},[l,t,n,s,o,f]);const m=Tm(E=>{r.dispatch({type:"ui/scroll",pane:i,offset:E})}),g=a.useCallback(()=>{const E=t.current;if(!E||!i)return;const b=c.current;if(b){if(Math.abs(E.scrollTop-b.target)<=Qt)return;c.current=null}u.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const k=Math.max(0,E.scrollHeight-E.clientHeight);if(k<=0)return;if(o&&typeof r.updatePaneScrollFromViewport=="function"){const N=Math.max(0,E.scrollTop)/et;u.current.lastDispatchedOffset=N,r.updatePaneScrollFromViewport(i,N,{atBottom:vm(E)});return}const M=n==="bottom"?Math.max(0,k-E.scrollTop):Math.max(0,E.scrollTop);u.current.lastDispatchedOffset=M/et,m(M/et),i==="chat"&&n==="bottom"&&E.scrollTop<=Qt&&r.armChatTopHistoryLoad?.()},[r,m,i,t,n,o]),S=a.useCallback(E=>{const b=t.current;if(!b||i!=="chat"||n!=="bottom"||E.deltaY>=0||b.scrollTop>Qt)return;const k=Math.max(0,b.scrollHeight-b.clientHeight);r.handleChatTopHistoryScrollIntent?.(k/et)},[r,i,t,n]),y=a.useRef({startY:null,fired:!1}),w=a.useCallback(E=>{u.current.touching=!0,!(i!=="chat"||n!=="bottom")&&(y.current={startY:E.touches?.[0]?.clientY??null,fired:!1})},[i,n]),x=a.useCallback(()=>{u.current.touching=!1,u.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),I=a.useCallback(E=>{const b=t.current,k=y.current;if(!b||i!=="chat"||n!=="bottom"||k.fired||k.startY==null||b.scrollTop>Qt)return;const M=E.touches?.[0]?.clientY;if(M==null||M-k.startY<Yh)return;k.fired=!0;const N=Math.max(0,b.scrollHeight-b.clientHeight);r.handleChatTopHistoryScrollIntent?.(N/et+1,{force:!0})},[r,i,t,n]);return{normalizedLines:l,onScroll:g,onWheel:S,onTouchStart:w,onTouchMove:I,onTouchEnd:x}}function Pe({runs:t,theme:e}){return a.createElement(a.Fragment,null,(t||[]).map((s,n)=>{const i={color:Oe(e,s.color),backgroundColor:Oe(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"};if(s?.trailingRule)return a.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),l=Pl(r);return l?a.createElement(Rl,{key:`${n}:${s.text||""}`,label:s.text||"",artifactRef:l,style:i}):o?a.createElement("a",{key:`${n}:${s.text||""}`,className:"ps-md-link",href:r,target:"_blank",rel:"noreferrer",style:i},s.text||""):a.createElement("span",{key:`${n}:${s.text||""}`,style:i},s.text||"")}))}function Cm({line:t,theme:e}){const s=String(t?.body||"").trim();return a.createElement("details",{className:"ps-system-notice"},a.createElement("summary",{className:"ps-system-notice-summary",style:{color:Oe(e,t?.color)||"var(--ps-muted)"}},a.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),s?a.createElement("div",{className:"ps-system-notice-body"},a.createElement(Di,{content:s,theme:e})):null)}function Tm(t){const e=a.useRef(0),s=a.useRef(null),n=a.useRef(t);return n.current=t,a.useEffect(()=>()=>{e.current&&cancelAnimationFrame(e.current)},[]),a.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 Ne=a.memo(function({line:e,theme:s,className:n=""}){const i=n?`ps-line ${n}`:"ps-line";return e?e.kind==="systemNotice"?a.createElement(Cm,{line:e,theme:s}):e.kind==="runs"?a.createElement("div",{className:i},a.createElement(Pe,{runs:e.runs,theme:s})):a.createElement("div",{className:i,style:{color:Oe(s,e.color),backgroundColor:Oe(s,e.backgroundColor),fontWeight:e.bold?700:400,textDecoration:e.underline?"underline":"none"}},e.text||" "):a.createElement("div",{className:i}," ")});function De(t){return t?t.kind==="runs"?Al(t.runs):String(t.text||""):""}function Cl(t,e,s,n){const i=a.useRef(!1);return a.useLayoutEffect(()=>{const r=t.current;if(!r||!s)return;const o=Math.max(0,r.scrollHeight-r.clientHeight),l=Math.min(o,Math.max(0,Number(e)||0)*et);Math.abs(r.scrollTop-l)>2&&(i.current=!0,r.scrollTop=l,window.requestAnimationFrame(()=>{i.current=!1}))},[t,e,s]),a.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)/et})},[n,s,t])}const Mm={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"},Nm=new Set(["diff","patch","udiff"]),Pm=/\.(patch|diff)$/i,Tl=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,Ml=/\.(png|jpe?g|gif|webp|avif|bmp|svg|ico)$/i,_m={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 Rm(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 $m=/\.(csv|tsv)$/i;function Om(t,e){return $m.test(String(t||""))?!0:/^text\/(csv|tab-separated-values)$/i.test(String(e||"").trim())}const _n=2e3;function Lm(t){const e=String(t??"");return/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Fm({content:t,filename:e}){const[s,n]=a.useState(null),i=a.useRef(null),r=a.useRef(null),o=a.useRef(null);a.useEffect(()=>{let I=!1;return n(null),yl(()=>import("./papaparse.min-Ddflu8oC.js").then(E=>E.p),[]).then(E=>{if(I)return;const b=E.default||E,k=/\.tsv$/i.test(String(e||""))?" ":"",M=b.parse(String(t||"").trim(),{delimiter:k,skipEmptyLines:"greedy"});n({rows:M.data||[],errors:M.errors||[]})}).catch(()=>{I||n({rows:null,errors:[{message:"parser unavailable"}]})}),()=>{I=!0}},[t,e]),a.useEffect(()=>{const I=()=>{o.current=null};return window.addEventListener("mouseup",I),()=>window.removeEventListener("mouseup",I)},[]);const l=a.useCallback((I,E)=>{if(!I||!E)return;const b=window.getSelection();if(!b)return;const k=!!(I.compareDocumentPosition(E)&Node.DOCUMENT_POSITION_PRECEDING),M=document.createRange();M.setStartBefore(k?E:I),M.setEndAfter(k?I:E),b.removeAllRanges(),b.addRange(M)},[]),c=I=>I.target?.closest?I.target.closest("td,th"):null,d=a.useCallback(I=>{if(I.button!==0)return;const E=c(I);E&&(I.preventDefault(),i.current?.focus(),o.current=E,l(E,E))},[l]),u=a.useCallback(I=>{if(!o.current||!(I.buttons&1))return;const E=c(I);E&&l(o.current,E)},[l]),p=a.useCallback(I=>{if(!(I.metaKey||I.ctrlKey)||I.altKey||I.key!=="a"&&I.key!=="A")return;const E=r.current,b=window.getSelection();if(!E||!b)return;I.preventDefault(),I.stopPropagation();const k=document.createRange();k.selectNodeContents(E),b.removeAllRanges(),b.addRange(k)},[]),f=a.useCallback(I=>{const E=r.current,b=window.getSelection();if(!E||!b||b.rangeCount===0)return;const k=b.getRangeAt(0),M=new Map;for(const N of E.querySelectorAll("th,td")){if(!k.intersectsNode(N))continue;const B=N.parentElement;M.has(B)||M.set(B,[]),M.get(B).push(Lm(N.textContent))}M.size!==0&&(I.clipboardData.setData("text/plain",Array.from(M.values(),N=>N.join(" ")).join(`
|
|
91
|
+
`)),I.preventDefault())},[]);if(!s)return a.createElement("div",{className:"ps-csv-status"},"Parsing…");if(!s.rows||s.rows.length===0)return a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,String(t||"")));const[h,...m]=s.rows,g=m.reduce((I,E)=>Math.max(I,E.length),h.length),S=Array.from({length:g},(I,E)=>h[E]??""),y=m.length>_n,w=y?m.slice(0,_n):m,x=[];return y&&x.push(`showing first ${_n} of ${m.length} rows`),s.errors.length&&x.push(`${s.errors.length} parse warning${s.errors.length===1?"":"s"}`),a.createElement("div",{className:"ps-csv-wrap",ref:i,tabIndex:0,onMouseDown:d,onMouseMove:u,onKeyDown:p,onCopy:f},a.createElement("table",{className:"ps-csv-table",ref:r},a.createElement("thead",null,a.createElement("tr",null,S.map((I,E)=>a.createElement("th",{key:`h${E}`},String(I??""))))),a.createElement("tbody",null,w.map((I,E)=>a.createElement("tr",{key:`r${E}`},S.map((b,k)=>a.createElement("td",{key:`c${k}`},String(I[k]??""))))))),x.length?a.createElement("div",{className:"ps-csv-status"},x.join(" · ")):null)}function Nl(t){const e=/\.([A-Za-z0-9]+)$/.exec(String(t||""));return e&&_m[e[1].toLowerCase()]||null}function Fi(t,e){return Pm.test(String(t||""))?!0:/^text\/x-(patch|diff)$/i.test(String(e||"").trim())}function Pl(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 _l=a.createContext(null);function Rl({label:t,artifactRef:e,style:s}){const n=a.useContext(_l),i=Fi(e.filename),r=a.useCallback(o=>{if(o.preventDefault(),o.stopPropagation(),!n?.revealArtifact)return;const l=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;Promise.resolve(n.revealArtifact(e.sessionId,e.filename,{fullscreen:l})).catch(()=>{})},[n,e.sessionId,e.filename]);return a.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?a.createElement("span",{className:"ps-artifact-link-glyph","aria-hidden":"true"},"±"):null,a.createElement("span",{className:"ps-artifact-link-label"},t||e.filename))}function $l(t){return Nm.has(String(t||"").trim().toLowerCase())}const Bm=/^(?: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 Dm(t){return Bm.test(t)?"meta":t.startsWith("@@")?"hunk":t.startsWith("+")?"add":t.startsWith("-")?"del":"context"}const Hm={add:"green",del:"red",hunk:"cyan",meta:"gray"};function Bi(t,e){return String(t||"").replace(/\n$/,"").split(`
|
|
92
|
+
`).map((n,i)=>{const r=Dm(n),o=Hm[r],l=r==="add"||r==="del"||r==="context"&&n.startsWith(" "),c=l?n.slice(0,1):"",d=l?n.slice(1):n;return a.createElement("span",{key:`d:${i}`,className:`ps-diff-line is-${r}`,style:o?{color:Oe(e,o)||void 0}:void 0},a.createElement("span",{className:"ps-diff-marker","aria-hidden":"true"},c.trim()),a.createElement("span",{className:"ps-diff-text"},d))})}function Ol(t){return String(t||"").trim().toLowerCase()==="mermaid"}const Eo={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 Gm(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},l={type:"string",re:/'(?:\\.|[^'\\])*'?/y},c={type:"string",re:/`(?:\\.|[^`\\])*`?/y},d={type:"string",re:/"""[\s\S]*?"""|'''[\s\S]*?'''/y};switch(t){case"python":return[e,d,o,l,i,r];case"shell":return[e,o,l,i,r];case"sql":return[n,l,o,i,r];case"yaml":return[e,o,l,i,r];case"json":return[o,i,r];case"css":return[{type:"comment",re:/\/\*[\s\S]*?\*\//y},o,l,i,r];default:return[s,o,l,c,i,r]}}const jm={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},Um=2e4,pt=new Map,Wm=120;function Km(t,e){const s=`${e||""}\0${t}`,n=pt.get(s);if(n)return pt.delete(s),pt.set(s,n),n;const i=zm(t,e);return pt.set(s,i),pt.size>Wm&&pt.delete(pt.keys().next().value),i}function zm(t,e){const s=Mm[String(e||"").trim().toLowerCase()]||"default",n=Eo[s]||Eo.js,i=Gm(s),r=[];let o=0,l=0;const c=d=>{d>l&&r.push({type:"plain",text:t.slice(l,d)})};for(;o<t.length;){let d=null;for(const p of i){p.re.lastIndex=o;const f=p.re.exec(t);if(f&&f.index===o&&f[0].length>0){d={type:p.type,text:f[0]};break}}if(!d){o+=1;continue}let u=d.type;if(u==="identifier")if(n.has(d.text))u="keyword";else{const p=t.slice(o+d.text.length);u=/^\s*\(/.test(p)?"fn":"plain"}if(u==="plain"){o+=d.text.length;continue}c(o),r.push({type:u,text:d.text}),o+=d.text.length,l=o}return c(t.length),r}function as(t,e,s){const n=String(t||"");if(!n||n.length>Um)return n;let i;try{i=Km(n,e)}catch{return n}return i.map((r,o)=>{const l=jm[r.type];return l?a.createElement("span",{key:`t:${o}`,className:`ps-code-token is-${r.type}`,style:{color:Oe(s,l)||void 0}},r.text):a.createElement(a.Fragment,{key:`t:${o}`},r.text)})}let Is=null;function Vm(){return Is||(Is=yl(()=>import("./mermaid.core-okRCGPQQ.js").then(t=>t.bp),[]).then(t=>t.default||t).catch(t=>{throw Is=null,t})),Is}function qm(t,e){return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"default":"dark",fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"}),t}let xo=0,vo=Promise.resolve();function Ym(t){const e=vo.then(t,t);return vo=e.then(()=>{},()=>{}),e}function Ll({code:t,theme:e,fallback:s}){const[n,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState(""),d=a.useMemo(()=>mu(e),[e]);return a.useEffect(()=>{let u=!0;const p=String(t||"").trim();if(p)return o(!1),Vm().then(f=>Ym(async()=>{if(!u)return;qm(f,d),xo+=1;const h=`ps-mermaid-${xo}`;await f.parse(p);const{svg:m}=await f.render(h,p);u&&i(m)})).catch(f=>{u&&(i(null),o(!0),c(String(f?.message||f)))}),()=>{u=!1}},[t,d]),n&&!r?a.createElement("div",{className:"ps-mermaid",dangerouslySetInnerHTML:{__html:n}}):r&&l?a.createElement("div",{className:"ps-mermaid-failed"},a.createElement("div",{className:"ps-mermaid-error"},`Diagram could not be rendered — ${String(l).split(`
|
|
93
|
+
`)[0]}`),s):s}function Qe(t,e,s="md"){return oi(t).map((n,i)=>{const r=`${s}:${i}`;if(n.type==="code")return a.createElement("code",{key:r,className:"ps-md-inline-code"},n.text);if(n.type==="strong")return a.createElement("strong",{key:r,className:"ps-md-strong"},Qe(n.text,e,`${r}:strong`));if(n.type==="em")return a.createElement("em",{key:r,className:"ps-md-em"},Qe(n.text,e,`${r}:em`));if(n.type==="link"){const o=Pl(n.href);return o?a.createElement(Rl,{key:r,label:n.text,artifactRef:o,style:{color:Oe(e,"cyan")}}):/^https?:\/\//i.test(String(n.href||"").trim())?a.createElement("a",{key:r,className:"ps-md-link",href:n.href,target:"_blank",rel:"noreferrer",style:{color:Oe(e,"cyan")}},n.text):a.createElement("span",{key:r,style:{color:Oe(e,"cyan")}},n.text)}return a.createElement(a.Fragment,{key:r},n.text)})}function ei(t=""){return String(t||"").replace(/\s+/g," ").trim()}const Xm=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],Qm=24,Jm=32,Zm=6,ko=30,eg=56,Rn=.4,tg=1.4,sg=2;function Fl(t=[]){const e=Math.max(0,...t.map(m=>m.length));if(e<=0)return null;const s=t[0]||[],n=Math.max(1,t.length-1),i=Array.from({length:e},()=>({max:0,spaceCells:0}));for(let m=0;m<t.length;m+=1){const g=t[m];for(let S=0;S<e;S+=1){const y=ei(g[S]||"");y.length>i[S].max&&(i[S].max=y.length),m>0&&/\s/.test(y)&&(i[S].spaceCells+=1)}}let r=-1,o=0;for(let m=0;m<e;m+=1){const g=i[m];if(g.max<Qm||g.spaceCells/n<.4)continue;const y=ei(s[m]||"").toLowerCase(),w=Xm.some(I=>y.includes(I))?60:0,x=g.max+w;x>o&&(o=x,r=m)}if(r<0)return null;const l=i.map((m,g)=>g===r?0:Math.max(Zm,Math.min(m.max+2,Jm))),c=l.reduce((m,g)=>m+g,0),d=i[r],u=Math.max(ko,Math.min(d.max*.45,eg,Math.max(ko,c*tg))),p=l.map((m,g)=>g===r?u:m),f=p.reduce((m,g)=>m+g,0);if(f>0&&p[r]/f<Rn){const m=f-p[r];p[r]=m*(Rn/(1-Rn))}const h=p.reduce((m,g)=>m+g,0);return h>0?{widths:p.map(m=>`${(m/h*100).toFixed(2)}%`),flexIndex:r,minWidth:`${Math.ceil(h+sg)}ch`}:null}function Bl(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(r=>ei(r?.[n]||"")).filter(Boolean).join(" / ")||null)}function Ao(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 ng(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 l=/^```(\S*)\s*$/.exec(o);if(l){const p=l[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:p,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 p=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:p,rows:f});continue}if(/^\s*>/.test(r)){const p=[];for(;i<s.length&&/^\s*>/.test(s[i]);)p.push(s[i].replace(/^\s*>\s?/,"")),i+=1;n.push({type:"blockquote",text:p.join(`
|
|
97
|
+
`).trim()});continue}const d=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(r);if(d){const p=/\d+\./.test(d[2]),f=[];for(;i<s.length;){const h=s[i],m=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(h);if(!m||/\d+\./.test(m[2])!==p)break;const g=[m[3].trim()];for(i+=1;i<s.length&&s[i].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[i])&&!Ao(s[i],s[i+1]||"");)g.push(s[i].trim()),i+=1;if(f.push(g.join(" ")),!s[i]?.trim())break}n.push({type:"list",ordered:p,items:f});continue}const u=[r.trim()];for(i+=1;i<s.length&&s[i].trim()&&!Ao(s[i],s[i+1]||"");)u.push(s[i].trim()),i+=1;n.push({type:"paragraph",text:u.join(" ")})}return n}function Di({content:t,theme:e}){const s=a.useMemo(()=>ng(t),[t]);return s.length===0?a.createElement("div",{className:"ps-empty-state"},"No preview content."):a.createElement("div",{className:"ps-markdown-preview"},s.map((n,i)=>{if(n.type==="heading")return a.createElement("div",{key:`block:${i}`,className:`ps-md-heading is-h${n.level}`},Qe(n.text,e,`heading:${i}`));if(n.type==="code"){const r=$l(n.language),o=a.createElement("section",{key:`block:${i}`,className:`ps-md-code-block${r?" is-diff":""}`},a.createElement("div",{className:"ps-md-code-header"},n.language||"text"),a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,r?Bi(n.content,e):as(n.content,n.language,e))));return Ol(n.language)?a.createElement(Ll,{key:`block:${i}`,code:n.content,theme:e,fallback:o}):o}if(n.type==="blockquote")return a.createElement("blockquote",{key:`block:${i}`,className:"ps-md-quote"},Qe(n.text,e,`quote:${i}`));if(n.type==="list"){const r=n.ordered?"ol":"ul";return a.createElement(r,{key:`block:${i}`,className:`ps-md-list${n.ordered?" is-ordered":""}`},n.items.map((o,l)=>a.createElement("li",{key:`item:${l}`,className:"ps-md-list-item"},Qe(o,e,`list:${i}:${l}`))))}if(n.type==="table"){const r=Math.max(n.header.length||0,...n.rows.map(m=>m.length)),o=r>0&&r<=6,l=o?Fl([n.header,...n.rows]):null,c=!!l,d=l?l.flexIndex:-1,u=m=>m===d?"is-flex-column":null,p=Bl([n.header],r),f=`ps-md-table${o?" is-fit-width":""}${c?" has-flex-column":""}`,h=`ps-md-table-wrap${o?" is-fit-width":""}${c?" has-flex-column":""}`;return a.createElement("div",{key:`block:${i}`,className:h},a.createElement("table",{className:f,style:l?.minWidth?{"--ps-table-min-width":l.minWidth}:void 0},l?a.createElement("colgroup",null,l.widths.map((m,g)=>a.createElement("col",{key:`col:${g}`,className:u(g)||void 0,style:{width:m}}))):null,a.createElement("thead",null,a.createElement("tr",null,n.header.map((m,g)=>a.createElement("th",{key:`head:${g}`,className:u(g)||void 0},Qe(m,e,`table:${i}:head:${g}`))))),a.createElement("tbody",null,n.rows.map((m,g)=>a.createElement("tr",{key:`row:${g}`},m.map((S,y)=>a.createElement("td",{key:`cell:${g}:${y}`,className:u(y)||void 0,"data-label":p[y]||void 0},a.createElement("span",{className:"ps-table-cell-value"},Qe(S,e,`table:${i}:${g}:${y}`)))))))))}return a.createElement("p",{key:`block:${i}`,className:"ps-md-paragraph"},Qe(n.text,e,`para:${i}`))}))}function $n({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:r,theme:o,className:l="",focusRegion:c=null,children:d}){const u=a.useRef(null),p=Cl(u,i,r,t),f=a.useCallback(()=>{const h=Hi(r,c);h&&t?.setFocus&&t.setFocus(h)},[t,r,c]);return a.createElement(St,{title:e,color:s,focused:n,theme:o},a.createElement("div",{ref:u,className:`ps-scroll-panel is-preview ${l}`.trim(),onScroll:p,onMouseDown:f},d))}function ig({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:r,theme:o,content:l,focusRegion:c=null}){const d=a.useCallback(()=>{const f=Hi(r,c);f&&t?.setFocus&&t.setFocus(f)},[t,r,c]),u=a.useRef(null),p=Cl(u,i,r,t);return a.createElement(St,{title:e,color:s,focused:n,theme:o},a.createElement("div",{ref:u,className:"ps-scroll-panel ps-markdown-scroll",onScroll:p,onMouseDown:d},a.createElement(Di,{content:l,theme:o})))}function rg(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 To({title:t,color:e,focused:s,theme:n,filename:i,contentType:r,sizeBytes:o,source:l,uploadedAt:c,controller:d=null,sessionId:u=null}){const p=[];r&&p.push(r),o!=null&&p.push(rg(o)),l&&p.push(l);const f=c?new Date(c).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"",h=Tl.test(String(r||""))||Ml.test(String(i||"")),[m,g]=a.useState(null);return a.useEffect(()=>{if(g(null),!h||!d||!u||!i)return;let S=!1;return Hl(d,u,i).then(y=>{S||g(y)}).catch(()=>{S||g("error")}),()=>{S=!0}},[h,d,u,i]),a.createElement(St,{title:t,color:e,focused:s,theme:n},a.createElement("div",{className:"ps-binary-preview-card"},a.createElement("div",{className:"ps-binary-preview-kicker"},h?"Image artifact":"Binary artifact"),a.createElement("h3",{className:"ps-binary-preview-title"},i||"Artifact"),p.length>0?a.createElement("div",{className:"ps-binary-preview-meta"},p.join(" • ")):null,f?a.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${f}`):null,h&&m&&m!=="error"?a.createElement("img",{className:"ps-binary-preview-image",src:m,alt:i||"artifact image",onClick:()=>{try{window.open(m,"_blank","noopener")}catch{}}}):a.createElement("p",{className:"ps-binary-preview-copy"},h?m==="error"?"Could not load the image preview. Use Download to save the file.":"Loading image preview…":"Preview is intentionally disabled for non-text artifacts in the browser workspace. Use Download to save the file and open it in the default app.")))}function ks(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function On(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function og(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function is(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function ag(t){const e=String(De(t)||"").trim();return ks(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function lg(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=De(t);return is(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function cg(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 Mo(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?cg(t.runs.slice(1,-1)):[{text:De(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function ug(t){const e=String(t||"").trim();return is(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function dg(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 pg(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)=>dg(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function No(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>pg(t.map(i=>String(i[n]||"").trim()).filter(Boolean)))}function Dl(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&&De(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:Dl(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=De(n);if(ks(i)&&i.includes("┬")){const r=[],o=[];let l=[],c=!0;for(s+=1;s<t.length;){const d=t[s],u=De(d);if(On(u)){if(l.length>0){const p=No(l);p.length>0&&(c?r.push(p):o.push(p))}s+=1;break}if(og(u)){if(l.length>0){const p=No(l);p.length>0&&(c?r.push(p):o.push(p))}l=[],c=!1,s+=1;continue}if(is(u)){const p=ug(u);p.length>0&&l.push(p)}s+=1}e.push({type:"table",headerRows:r,bodyRows:o});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&ks(i)){const r=ag(n),o=[];for(s+=1;s<t.length;){const l=t[s],c=De(l);if(On(c)){s+=1;break}is(c)?o.push(lg(l)):o.push(De(l)),s+=1}s<t.length&&De(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&&ks(i)){const r=Mo(n),o=n.runs[0]?.color||"gray",l=[];for(s+=1;s<t.length;){const c=t[s],d=De(c);if(On(d)){s+=1;break}is(d)?l.push(Mo(c)):l.push(c?.kind==="runs"?c.runs:[{text:De(c),color:c?.color||null}]),s+=1}s<t.length&&De(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:r,bodyLines:l,borderColor:o});continue}e.push({type:"line",line:n}),s+=1}return e}function fg({lines:t,theme:e,controller:s=null}){const n=a.useMemo(()=>Dl(t),[t]);return a.createElement(Gl,{blocks:n,theme:e,controller:s})}const Ze=new Map,hg=60;function Hl(t,e,s){const n=`${e}/${s}`,i=Ze.get(n);if(i)return Ze.delete(n),Ze.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 l=>{if(!l?.ok)throw new Error(`download failed (${l?.status})`);const c=await l.blob();return URL.createObjectURL(c)}).catch(l=>{throw Ze.get(n)===o&&Ze.delete(n),l});for(Ze.set(n,o);Ze.size>hg;){const[l,c]=Ze.entries().next().value;Ze.delete(l),Promise.resolve(c).then(d=>URL.revokeObjectURL(d)).catch(()=>{})}return o}function mg({controller:t,sessionId:e,attachments:s}){const[n,i]=a.useState({});return a.useEffect(()=>{if(!t||!e)return;let r=!1;for(const o of s){const l=o?.filename;l&&Hl(t,e,l).then(c=>{r||i(d=>d[l]===c?d:{...d,[l]:c})}).catch(()=>{r||i(c=>c[l]==="error"?c:{...c,[l]:"error"})})}return()=>{r=!0}},[t,e,s]),a.createElement("div",{className:"ps-chat-image-strip"},s.map((r,o)=>{const l=r?.filename||`image-${o}`,c=n[l];return c&&c!=="error"?a.createElement("img",{key:`thumb:${o}:${l}`,className:"ps-chat-image-thumb",src:c,alt:l,title:`${l} — click to view full size`,onClick:()=>{try{window.open(c,"_blank","noopener")}catch{}}}):a.createElement("div",{key:`thumb:${o}:${l}`,className:`ps-chat-image-thumb is-pending${c==="error"?" is-error":""}`,title:l},c==="error"?"⚠":"🖼")}))}function Gl({blocks:t,theme:e,controller:s=null}){return a.createElement(a.Fragment,null,(t||[]).map((n,i)=>{if(n.type==="imageAttachments")return a.createElement(mg,{key:`imageAttachments:${i}`,controller:s,sessionId:n.sessionId,attachments:n.attachments});if(n.type==="preserve"){const r=n.splashVariant?` is-splash-${n.splashVariant}`:"";return a.createElement("div",{key:`preserve:${i}`,className:`ps-chat-preserve-block${r}`},n.lines.map((o,l)=>a.createElement(Ne,{key:`preserve:${i}:${l}`,line:o,theme:e,className:"ps-line-preserve"})))}if(n.type==="code"){const r=$l(n.language),o=a.createElement("section",{key:`code:${i}`,className:`ps-md-code-block ps-chat-code-block${r?" is-diff":""}`},a.createElement("div",{className:"ps-md-code-header"},n.language||"text"),a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,r?Bi(n.content||"",e):as(n.content||"",n.language,e))));return Ol(n.language)?a.createElement(Ll,{key:`code:${i}`,code:n.content||"",theme:e,fallback:o}):o}if(n.type==="card")return a.createElement("section",{key:`card:${i}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":Oe(e,n.borderColor)||"var(--ps-border)"}},a.createElement("header",{className:"ps-chat-card-header"},a.createElement(Pe,{runs:n.headerRuns,theme:e})),a.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?a.createElement(Gl,{blocks:n.blocks,theme:e,controller:s}):(n.bodyLines||[]).map((r,o)=>a.createElement("div",{key:`card:${i}:line:${o}`,className:"ps-chat-card-line"},a.createElement(Pe,{runs:r,theme:e})))));if(n.type==="table"){const r=n.headerRows||[],o=n.bodyRows||[],l=Math.max(1,...r.map(S=>S.length),...o.map(S=>S.length)),c=l<=6,d=c?Fl([...r,...o]):null,u=!!d,p=d?d.flexIndex:-1,f=S=>S===p?"is-flex-column":null,h=Bl(r,l),m=`ps-chat-table${c?" is-fit-width":""}${u?" has-flex-column":""}`,g=`ps-chat-table-wrap${c?" is-fit-width":""}${u?" has-flex-column":""}`;return a.createElement("div",{key:`table:${i}`,className:g},a.createElement("table",{className:m,style:d?.minWidth?{"--ps-table-min-width":d.minWidth}:void 0},d?a.createElement("colgroup",null,d.widths.map((S,y)=>a.createElement("col",{key:`col:${y}`,className:f(y)||void 0,style:{width:S}}))):null,r.length>0?a.createElement("thead",null,r.map((S,y)=>a.createElement("tr",{key:`thead:${y}`},Array.from({length:l},(w,x)=>a.createElement("th",{key:`th:${y}:${x}`,className:f(x)||void 0},Qe(S[x]||"",e,`chat-table:${i}:head:${y}:${x}`)))))):null,a.createElement("tbody",null,o.map((S,y)=>a.createElement("tr",{key:`tbody:${y}`},Array.from({length:l},(w,x)=>a.createElement("td",{key:`td:${y}:${x}`,className:f(x)||void 0,"data-label":h[x]||void 0},a.createElement("span",{className:"ps-table-cell-value"},Qe(S[x]||"",e,`chat-table:${i}:${y}:${x}`)))))))))}return a.createElement(Ne,{key:`line:${i}`,line:n.line,theme:e})}))}function St({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:i=null,children:r,theme:o,className:l=""}){const c=Oe(o,s),d=!!((Array.isArray(t)?t.length>0:String(t??"").trim())||e||i);return a.createElement("section",{className:`ps-panel${n?" is-focused":""}${d?"":" is-chromeless"}${l?` ${l}`:""}`,style:{"--ps-panel-accent":c||"var(--ps-border)"}},d?a.createElement("header",{className:"ps-panel-header"},a.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?a.createElement(Pe,{runs:t,theme:o}):bo(t)),e||i?a.createElement("div",{className:"ps-panel-header-right"},e?a.createElement("div",{className:"ps-panel-title-right"},Array.isArray(e)?a.createElement(Pe,{runs:e,theme:o}):bo(e)):null,i?a.createElement("div",{className:"ps-panel-actions"},i):null):null):null,a.createElement("div",{className:"ps-panel-body"},r))}function gg({lines:t,theme:e,controller:s}){return a.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(d=>d?.nodeSelect)?.nodeSelect||null,l=r.some(d=>d?.nodeSelected),c=a.createElement(Pe,{runs:r,theme:e});return o?a.createElement("button",{key:`line:${i}`,type:"button",className:`ps-nodemap__row${l?" is-selected":""}`,onPointerDown:d=>{d.preventDefault(),d.stopPropagation(),s.selectNodeMapNode(o)}},c):a.createElement("div",{key:`line:${i}`,className:"ps-nodemap__line"},c)}))}function yg({lines:t,theme:e,completionByTurn:s}){const[n,i]=a.useState(()=>new Set),r=a.useCallback(u=>{i(p=>{const f=new Set(p);return f.has(u)?f.delete(u):f.add(u),f})},[]),o=u=>Number(u||0).toLocaleString("en-US"),l=u=>{const p=Number(u||0);if(!Number.isFinite(p))return"?K";const f=p/1e3,h=Math.abs(f)>=10?1:2;return`${f.toFixed(h)}K`},c=u=>{const p=Number(u||0);return Number.isFinite(p)?`${(p/1e3).toFixed(1)}s`:"?s"},d=u=>{const p=String(u||"").trim();if(!p)return"unknown";const f=p.split(":").filter(Boolean),h=f[f.length-1]||"",m=f.length>1&&Jh.has(h.toLowerCase())?f.length-2:f.length-1;return f[Math.max(0,m)]||f[0]||"unknown"};return a.createElement(a.Fragment,null,t.map((u,p)=>{const f=u?.kind==="runs"&&Array.isArray(u.runs)?u.runs.find(k=>k?.completedTurn!=null)?.completedTurn:null,h=f!=null?s.get(Number(f)):null;if(!h)return a.createElement(Ne,{key:`line:${p}`,line:u,theme:e});const m=h.data||{},g=String(h.seq??`${m.turnIndex??f}:${h.createdAt??p}`),S=n.has(g),y=m.reasoningEffort?`${m.model||"(unknown)"}:${m.reasoningEffort}`:m.model||"(unknown)",w=d(m.model),x=m.durationMs!=null?c(m.durationMs):"duration n/a",I=m.durationMs!=null?`${o(m.durationMs)} ms`:"duration n/a",E=`${l(m.tokensInput)} / ${l(m.tokensOutput)}`,b=[["model",y],["started",m.startedAt?new Date(m.startedAt).toLocaleString():null],["ended",m.endedAt?new Date(m.endedAt).toLocaleString():null],["duration",I],["tokens",`${o(m.tokensInput)} in / ${o(m.tokensOutput)} out`],["cache",`${o(m.tokensCacheRead)} read / ${o(m.tokensCacheWrite)} write`],["tools",`${o(m.toolCalls)} calls / ${o(m.toolErrors)} errors`],["names",Array.isArray(m.toolNames)&&m.toolNames.length?m.toolNames.join(", "):null],["worker",m.workerNodeId||null],["result",m.resultType||null],["error",m.errorMessage||null]].filter(([,k])=>k!=null&&k!=="");return a.createElement(a.Fragment,{key:`seq:${p}`},a.createElement(Ne,{line:u,theme:e}),a.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>r(g)},a.createElement("span",{className:"ps-sequence-turn-caret"},S?"v":">"),a.createElement("span",{className:"ps-sequence-turn-rule"},"--- "),a.createElement("span",{className:"ps-sequence-turn-key"},"Mod: "),a.createElement("span",{className:"ps-sequence-turn-model"},w),a.createElement("span",{className:"ps-sequence-turn-rule"}," ("),a.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),a.createElement("span",{className:"ps-sequence-turn-tokens"},E),a.createElement("span",{className:"ps-sequence-turn-rule"},", "),a.createElement("span",{className:"ps-sequence-turn-key"},"dur: "),a.createElement("span",{className:"ps-sequence-turn-duration"},x),a.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),S?a.createElement("div",{className:"ps-sequence-turn-details"},b.map(([k,M])=>a.createElement("div",{key:k},a.createElement("span",{className:"ps-sequence-turn-detail-label"},`${k}: `),a.createElement("span",null,String(M))))):null)}))}const Sg={chat:"chat",activity:"activity",inspector:"inspector",filePreview:"inspector"};function Hi(t,e=null){return e||Sg[String(t||"")]||null}function en({title:t,titleRight:e=null,color:s,focused:n,actions:i,lines:r,stickyLines:o=[],bottomStickyLines:l=[],scrollOffset:c=0,scrollMode:d="top",paneKey:u,controller:p,className:f="",panelClassName:h="",topContent:m=null,bottomContent:g=null,structuredBlocks:S=!1,stickyBottom:y=!1,renderBody:w=null,focusRegion:x=null}){const I=ee(p,R=>R.ui.themeId),E=st(I),b=a.useRef(null),k=a.useRef(null),M=a.useRef(!1),{normalizedLines:N,onScroll:B,onWheel:_,onTouchStart:P,onTouchMove:j,onTouchEnd:K}=Am(b,r,c,d,u,p,{stickyBottom:y}),z=a.useMemo(()=>Me(o),[o]),se=a.useMemo(()=>Me(l),[l]),ne=f.includes("is-preserve")&&h.includes("has-preserved-sticky"),ve=a.useCallback(()=>{const R=Hi(u,x);R&&p?.setFocus&&p.setFocus(R)},[p,u,x]),oe=a.useCallback((R,C)=>{!R||!C||Math.abs((C.scrollLeft||0)-(R.scrollLeft||0))<=1||(M.current=!0,C.scrollLeft=R.scrollLeft,window.requestAnimationFrame(()=>{M.current=!1}))},[]),[be,v]=a.useState({up:!1,down:!1}),O=a.useCallback(R=>{if(!R)return;const C=R.scrollHeight-R.scrollTop-R.clientHeight>4,H=R.scrollTop>4;v(Q=>Q.up===C&&Q.down===H?Q:{up:C,down:H})},[]),G=a.useCallback(R=>{B(),O(R.currentTarget),!(!ne||M.current)&&oe(R.currentTarget,k.current)},[B,ne,oe,O]);a.useEffect(()=>{O(b.current)});const L=a.useCallback(R=>{!ne||M.current||oe(R.currentTarget,b.current)},[ne,oe]);return a.createElement(St,{title:t,titleRight:e,color:s,focused:n,actions:i,theme:E,className:h},m,z.length>0?a.createElement("div",{ref:k,className:`ps-panel-sticky${ne?" is-scroll-sync":""}`,onScroll:L},z.map((R,C)=>a.createElement(Ne,{key:`sticky:${C}`,line:R,theme:E}))):null,a.createElement("div",{ref:b,className:`ps-scroll-panel ${f}${be.down?" is-scrolled-down":""}${be.up?" is-scrolled-up":""}`.trim(),"data-session-scroll":x==="sessions"?"1":void 0,onScroll:G,onMouseDown:ve,onTouchStart:P,onWheel:_,onTouchMove:j,onTouchEnd:K,onTouchCancel:K},typeof w=="function"?w(N,E):S?a.createElement(fg,{lines:N,theme:E,controller:p}):N.map((R,C)=>a.createElement(Ne,{key:`line:${C}`,line:R,theme:E}))),se.length>0?a.createElement("div",{className:"ps-panel-bottom-sticky"},se.map((R,C)=>a.createElement(Ne,{key:`bottom-sticky:${C}`,line:R,theme:E}))):null,g)}const Po="—";function bg({session:t,childCount:e=0}){const s=(f,h,m="")=>{const g=h==null||h===""?Po:String(h),S=g===Po;return a.createElement("div",{className:`ps-session-detail-field${m?` ${m}`:""}${S?" is-none":""}`,key:f},a.createElement("span",{className:"ps-session-detail-label"},f),a.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 l=null;t&&!t.isGroup&&(l="off",t.cronActive===!0&&(l=t.cronKind==="wall-clock"?`next ${Fs(t.cronNextFireAt)}`:typeof t.cronInterval=="number"?`every ${Ct(t.cronInterval)}`:"on"));const c=t?.model?t.reasoningEffort&&!String(t.model).includes(String(t.reasoningEffort))?`${t.model}:${t.reasoningEffort}`:t.model:null,d=t?t.visibility==="shared_write"?"shared · write":t.visibility==="shared_read"?"shared · read":"private":null,u=t?.isGroup?t.memberCount==null?null:String(t.memberCount):e>0?String(e):null,p=Vu(t);return a.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",l,t?.cronActive===!0?"is-armed":""),s("Agent",t?.agentId),s("Updated",p?`${p.relative} (${p.status})`:null),s("Children",u),s("Access",d))}function wg(){const t="(pointer: coarse)",e=()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(t).matches:!1,[s,n]=a.useState(e);return a.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 jl=13,Ul=11,Wl=1.5,Ig=7;function Eg(t){return jl+(t-1)*Ul+Wl/2-Ig/2}const xg=a.memo(function({row:e,theme:s,structuredRows:n,mobile:i,onRowClick:r,setRef:o,drag:l}){const c=Math.max(0,e.depth),d=a.useMemo(()=>{if(c<1)return;const w=Array.from({length:c},(x,I)=>I);return{backgroundImage:w.map(()=>"linear-gradient(var(--ps-rail), var(--ps-rail))").join(", "),backgroundSize:w.map(()=>`${Wl}px 100%`).join(", "),backgroundPosition:w.map(x=>`${jl+x*Ul}px 0`).join(", "),backgroundRepeat:"no-repeat"}},[c]),u=a.useCallback(w=>o(e.sessionId,w),[o,e.sessionId]),p=a.useCallback(w=>r(w,e),[r,e]),f=e.groupId||null,h=!!(l?.dragging&&l.overGroupId&&f===l.overGroupId),m=h&&!!e.isGroup,g=!!(l?.dragging&&l.insertBeforeId===e.sessionId),S=!!(l?.dragging&&l.insertAfterId&&l.insertAfterId===e.sessionId),y=a.useCallback(w=>{if(l?.onPointerDown&&w.button===0){if(w.currentTarget?.setPointerCapture&&w.pointerId!=null)try{w.currentTarget.setPointerCapture(w.pointerId)}catch{}l.onPointerDown(w,e)}},[l,e]);return a.createElement("button",{type:"button",ref:u,className:`ps-list-button ps-session-list-button${e.active?" is-selected":""}${e.selected?" is-multiselected":""}${e.pinned?" is-pinned":""}${h?" is-drop-zone":""}${m?" is-drop-target":""}${g?" is-insert-before":""}${S?" is-insert-after":""}${e.depth>0?" is-nested":""}`,style:d,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":f||void 0,"data-order-container":e.orderContainer??void 0,"data-orderable":e.orderable?"1":void 0,onPointerDown:y,onClick:p,onContextMenu:w=>{w.ctrlKey&&(w.preventDefault(),r(w,e))}},a.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:c>0?`${Eg(c)}px`:"0px"}},a.createElement(vg,{row:e,theme:s,structured:n,showInlineDetail:i})))});function _o(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"&&i?.role!=="selection"){if(i?.role==="status"){s=Oe(e,i.color)||null;continue}n.push(i)}return{statusColor:s,rest:n}}function Ro({color:t,node:e=!1}){return a.createElement("span",{className:`ps-session-status-dot${e?" is-node":""}`,style:t?e?{borderColor:t}:{background:t}:void 0})}function ti({badge:t,size:e="sm"}){return t?a.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 $o(t){return Array.isArray(t)?t.filter(e=>!e?.ownerChip):t}function vg({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 u=_o($o(t.runs),e);return a.createElement(a.Fragment,null,u.statusColor?a.createElement(Ro,{color:u.statusColor,node:t.depth>0}):null,a.createElement(ti,{badge:t.ownerBadge}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(Pe,{runs:u.rest,theme:e})))}const r=_o($o(t.titleRuns),e),o=Array.isArray(t.ctxRuns)?t.ctxRuns:[],l=o.length>0,c=Array.isArray(t.detailRuns)?t.detailRuns:Array.isArray(t.selectedMetaRuns)?t.selectedMetaRuns:[],d=n&&t.active&&c.length>0;return a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-session-row-line"},a.createElement("div",{className:"ps-session-row-title"},r.statusColor?a.createElement(Ro,{color:r.statusColor,node:t.depth>0}):null,a.createElement(ti,{badge:t.ownerBadge}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(Pe,{runs:r.rest,theme:e}))),l?a.createElement("div",{className:"ps-session-row-ctx"},a.createElement(Pe,{runs:o,theme:e})):null),d?a.createElement("div",{className:"ps-session-row-detail"},a.createElement(Pe,{runs:c,theme:e})):null)}function kg(t){const e=a.useRef(t),s=a.useRef(null),n=a.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]);return(n===null||s.current!==n)&&(s.current=n,e.current=t),e.current}const Oo=10,Ag=1.6;function Cg(t){a.useEffect(()=>{const e=t.current;if(!e)return;let s=0,n=0,i=0,r=null;const o=d=>{if(d.touches.length!==1){r="y";return}const u=d.touches[0];s=i=u.clientX,n=u.clientY,r=null},l=d=>{if(r==="y"||d.touches.length!==1)return;const u=d.touches[0],p=u.clientX-s,f=u.clientY-n;r===null&&(Math.abs(p)<Oo&&Math.abs(f)<Oo||(r=Math.abs(p)>Math.abs(f)*Ag?"x":"y",i=u.clientX,r==="y"))||(e.scrollLeft-=u.clientX-i,i=u.clientX,d.cancelable&&d.preventDefault())},c=()=>{r=null};return e.addEventListener("touchstart",o,{passive:!0}),e.addEventListener("touchmove",l,{passive:!1}),e.addEventListener("touchend",c,{passive:!0}),e.addEventListener("touchcancel",c,{passive:!0}),()=>{e.removeEventListener("touchstart",o),e.removeEventListener("touchmove",l),e.removeEventListener("touchend",c),e.removeEventListener("touchcancel",c)}},[t])}function Gi({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1}){const i=String(s).includes("ps-mobile-session-pane"),r=a.useRef(null);Cg(r);const o=i||wg(),l=ee(t,$=>$.ui.themeId),c=st(l),d=a.useRef(new Map),u=ee(t,$=>({branding:$.branding,activeSessionId:$.sessions.activeSessionId,sessionsById:$.sessions.byId,sessionsFlat:$.sessions.flat,filterQuery:$.sessions.filterQuery||"",ownerFilter:$.sessions.ownerFilter,pinnedIds:$.sessions.pinnedIds,manualOrder:$.sessions.manualOrder,selectedIds:$.sessions.selectedIds,selectMode:$.sessions.selectMode,auth:$.auth,connectionMode:$.connection?.mode||"local",modalOpen:!!$.ui.modal,focused:$.ui.focusRegion==="sessions",listDeselected:!!$.sessions.listDeselected}),Ue),p=a.useMemo(()=>Ht({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]),f=kg(p),h=u.activeSessionId&&u.sessionsById[u.activeSessionId]||null,m=u.activeSessionId&&f.find($=>$.sessionId===u.activeSessionId)||null,[g,S]=a.useState(!1),[y,w]=a.useState(null),x=a.useRef(!1),I=["modelPicker","reasoningEffortPicker","contextTierPicker"],E=ee(t,$=>I.includes($.ui.modal?.type));a.useEffect(()=>{!E&&x.current&&(x.current=!1,S(!0))},[E]);const b=()=>{x.current=!0,S(!1),t.openSwitchModelPicker(()=>{x.current=!1}).then(()=>{!I.includes(t.getState().ui.modal?.type)&&x.current&&(x.current=!1,S(!0))}).catch($=>{x.current=!1,S(!0),t.dispatch({type:"ui/status",text:$?.message||String($)||"Failed to switch model"})})},k=u.auth?.principal||null,M=u.auth?.authorization?.role,N=M==="admin"||M==="anonymous",B=!!(h?.owner&&k&&String(h.owner.provider)===String(k.provider)&&String(h.owner.subject)===String(k.subject)),_=!!(h&&!h.isGroup&&(h.isSystem?N:N||B)),P=Array.isArray(u.selectedIds)?u.selectedIds.length:0,j=P>1,K=!!(h&&!h.isSystem&&(h.isGroup||!h.parentSessionId&&!h.groupId)),z=!!(h&&Array.isArray(u.pinnedIds)&&u.pinnedIds.includes(h.sessionId)),se=!!(h?.isGroup&&Number(h.memberCount||0)===0),ne=j?Array.isArray(u.selectedIds)&&u.selectedIds.some($=>{const D=u.sessionsById[$];return D&&!D.isSystem&&!D.isGroup}):h?.isGroup?!0:!!h,ve=P>0,oe=!!(h&&!u.listDeselected&&!h.isSystem&&!h.isGroup&&!h.parentSessionId),be=ve?u.selectedIds.filter($=>{const D=u.sessionsById[$];return D&&!D.isSystem&&!D.isGroup&&!D.parentSessionId}):oe?[h.sessionId]:[],v=`ps-session-pane${s?` ${s}`:""}`,O=a.useRef(null);O.current={rows:f,viewState:u,controller:t};const[G,L]=a.useState({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),R=a.useRef(null),C=a.useRef(null),H=a.useCallback(()=>{C.current!=null&&(cancelAnimationFrame(C.current),C.current=null)},[]),Q=a.useCallback(()=>{let $=r.current;for(;$&&$!==document.body;){const D=window.getComputedStyle($).overflowY;if(/(auto|scroll|overlay)/.test(D)&&$.scrollHeight-$.clientHeight>1)return $;$=$.parentElement}return null},[]),Y=a.useCallback(($,D)=>{const W=Q();if(!W){H();return}const re=W.getBoundingClientRect();let te=0;if(D<re.top+48?te=-14*Math.min(1,(re.top+48-D)/48):D>re.bottom-48&&(te=14*Math.min(1,(D-(re.bottom-48))/48)),R.current&&(R.current.autoScrollStep=te),!R.current){H();return}if(C.current!=null)return;const pe=()=>{const ke=R.current;if(!ke||!ke.autoScrollStep){H();return}W.scrollTop+=ke.autoScrollStep,C.current=requestAnimationFrame(pe)};C.current=requestAnimationFrame(pe)},[Q,H]),le=a.useCallback($=>{const D=R.current;if(R.current=null,H(),L({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),!(!$||!D?.started||D.ids.length===0)){if(D.intent==="reorder"){t.dispatch({type:"sessions/reorder",sessionId:D.ids[0],beforeSessionId:D.beforeSessionId});return}D.intent!=="file"&&D.intent!=="unfile"||t.moveSessionsToGroup(D.overGroupId,D.ids).catch(V=>{t.dispatch({type:"ui/status",text:`Move failed: ${V?.message||V}`})})}},[t,H]),ye=a.useCallback(($,D)=>typeof $!="number"||typeof D!="number"?null:(document.elementFromPoint($,D)?.closest?.("[data-drop-group]")||null)?.getAttribute("data-drop-group")||null,[]),we=a.useCallback(($,D,V,Z)=>{if(typeof $!="number"||typeof D!="number"||V==null)return;const W=Array.from(document.querySelectorAll(`[data-order-container="${CSS.escape(V)}"][data-orderable="1"]`));if(W.length===0)return;for(const pe of W){const ke=pe.getBoundingClientRect();if(D<ke.top+ke.height/2)return{before:pe.getAttribute("data-session-id")||null,after:null}}const te=W[W.length-1]?.getAttribute("data-session-id")||null;return{before:null,after:te&&te!==Z?te:null}},[]),Ie=a.useCallback(($,D,V)=>{const Z=ye($,D);if(V?.isGroup){const pe=V.ids.length===1?we($,D,V.container,V.ids[0]):void 0;return pe===void 0?{kind:"none",overGroupId:null,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:pe.before,after:pe.after}}const W=V?.ownGroupId||null;if(Z&&Z!==W)return{kind:"file",overGroupId:Z,before:void 0,after:null};if(!Z&&W)return{kind:"unfile",overGroupId:null,before:void 0,after:null};const te=V?.orderable&&V.ids.length===1?we($,D,V.container,V.ids[0]):void 0;return te===void 0?{kind:Z?"file":"none",overGroupId:Z,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:te.before,after:te.after}},[ye,we]);a.useEffect(()=>{if(!G.dragging)return;const $=W=>{const re=R.current;if(!re)return;const te=Ie(W.clientX,W.clientY,re);re.intent=te.kind,re.overGroupId=te.overGroupId,re.beforeSessionId=te.before,Y(W.clientX,W.clientY),document.body.classList.toggle("ps-drop-ok",te.kind==="file"),L(pe=>({...pe,intent:te.kind,overGroupId:te.overGroupId,insertBeforeId:te.before,insertAfterId:te.after,x:W.clientX,y:W.clientY}))},D=W=>{const re=R.current;if(re&&typeof W?.clientX=="number"){const te=Ie(W.clientX,W.clientY,re);re.intent=te.kind,re.overGroupId=te.overGroupId,re.beforeSessionId=te.before}le(!0)},V=()=>le(!1),Z=W=>{W.key==="Escape"&&le(!1)};return window.addEventListener("pointermove",$),window.addEventListener("pointerup",D),window.addEventListener("pointercancel",V),window.addEventListener("keydown",Z),document.body.classList.add("ps-dragging-sessions"),()=>{window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",D),window.removeEventListener("pointercancel",V),window.removeEventListener("keydown",Z),document.body.classList.remove("ps-dragging-sessions"),document.body.classList.remove("ps-drop-ok")}},[G.dragging,le,Ie,Y]);const Fe=a.useMemo(()=>({dragging:G.dragging,overGroupId:G.overGroupId,insertBeforeId:G.insertBeforeId,insertAfterId:G.insertAfterId,onPointerDown:($,D)=>{if(D.isSystem||!D.orderable&&!D.isGroup&&D.depth>0)return;const V=$.clientX,Z=$.clientY,W={row:D,startX:V,startY:Z,started:!1,ids:[],overGroupId:null,beforeSessionId:void 0,orderable:!!D.orderable,container:D.orderContainer??null,isGroup:!!D.isGroup,ownGroupId:D.groupId||null,intent:"none",autoScrollStep:0},re=pe=>{if(W.started||Math.hypot(pe.clientX-V,pe.clientY-Z)<5)return;W.started=!0;const ke=O.current.viewState,ct=Array.isArray(ke.selectedIds)?ke.selectedIds:[],Vt=ct.includes(D.sessionId)&&ct.length>1?ct:[D.sessionId],sn=ke.sessionsById||{};W.ids=Vt,R.current=W,L({dragging:!0,ids:Vt,titles:Vt.map(ps=>sn[ps]?.title||String(ps).slice(0,8)).slice(0,3),overGroupId:null,x:pe.clientX,y:pe.clientY})},te=()=>{window.removeEventListener("pointermove",re),window.removeEventListener("pointerup",te)};window.addEventListener("pointermove",re),window.addEventListener("pointerup",te)}}),[G.dragging,G.overGroupId,G.insertBeforeId,G.insertAfterId]),U=a.useCallback(($,D)=>{const{rows:V,viewState:Z,controller:W}=O.current;if($.metaKey||$.ctrlKey){$.preventDefault(),Z.selectMode||W.dispatch({type:"sessions/selectMode",enabled:!0}),W.dispatch({type:"sessions/selectToggle",sessionId:D.sessionId}),W.setFocus("sessions");return}if($.shiftKey&&Z.activeSessionId){$.preventDefault();const te=V.map(ct=>ct.sessionId),pe=te.indexOf(Z.activeSessionId),ke=te.indexOf(D.sessionId);if(pe>=0&&ke>=0){const[ct,Vt]=pe<=ke?[pe,ke]:[ke,pe],sn=te.slice(ct,Vt+1),ps=Array.from(new Set([...Z.selectedIds||[],...sn]));W.setSessionSelection(ps),W.setFocus("sessions");return}}if(D.hasChildren&&D.active){W.dispatch({type:D.collapsed?"sessions/expand":"sessions/collapse",sessionId:D.sessionId}),W.setFocus("sessions");return}Z.selectMode&&W.dispatch({type:"sessions/selectClear"}),W.setFocus("sessions"),D.sessionId===Z.activeSessionId?W.dispatch({type:"sessions/listReselect"}):D.active||W.loadSession(D.sessionId).catch(()=>{})},[]),Te=a.useCallback(($,D)=>{$&&(D?d.current.set($,D):d.current.delete($))},[]),$e=a.useRef(null),zt=`${u.activeSessionId||""}${u.focused?1:0}${u.modalOpen?1:0}`;a.useEffect(()=>{if(u.modalOpen||!u.focused||!u.activeSessionId){$e.current=null;return}const $=d.current.get(u.activeSessionId);if(!$||$e.current===zt)return;$e.current=zt;const D=document.activeElement,V=!!(D&&(D.tagName==="INPUT"||D.tagName==="TEXTAREA"||D.tagName==="SELECT"||D.isContentEditable));D!==$&&!V&&$.focus({preventScroll:!0}),$.scrollIntoView({block:"nearest"})},[zt,u.activeSessionId,u.focused,u.modalOpen,u.sessionsFlat]);const tn=a.createElement(a.Fragment,null,j?a.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."},`${P} selected`):null,j?a.createElement(ce,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(A.CLEAR_SESSION_SELECTION).catch(()=>{})}):a.createElement(ce,{className:"ps-mini-button ps-pin-icon",icon:a.createElement(Yg),onClick:()=>t.handleCommand(A.PIN_SESSION).catch(()=>{}),disabled:!K,active:z,label:K?z?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"}),a.createElement(ce,{className:"ps-mini-button",icon:be.length>1?a.createElement("span",{className:"ps-icon-badge"},a.createElement(Fo),a.createElement("span",{className:"ps-icon-badge__count"},String(be.length))):a.createElement(Fo),onClick:()=>t.handleCommand(A.OPEN_MOVE_TO_GROUP).catch(()=>{}),label:be.length>1?`Move ${be.length} selected sessions to a group`:be.length===1?"Move this session to a group":"New group"}),a.createElement(ce,{className:"ps-mini-button",icon:a.createElement(Mg),onClick:()=>S(!0),disabled:!_||j,label:j?"Disabled while multiple sessions are selected":h?.isSystem?"System sessions are managed by administrators":h?.isGroup?"Folders cannot be managed here — use the folder controls":_?"Manage session — rename, switch model, and sharing":"Only this session's owner or an admin can manage it"}),a.createElement(ce,{className:"ps-mini-button",icon:a.createElement(qg),onClick:()=>{const $=h?.sessionId;if(!$)return;const D=dm($);D&&(yo(D),w({url:D,warn:!1}),pm(t,$).then(V=>{w(Z=>Z&&Z.url===D?{...Z,warn:V}:Z)}).catch(()=>{}))},disabled:!h||h.isGroup||j,label:"Copy link — copy a direct link to this session"}),a.createElement(ce,{className:"ps-mini-button",icon:a.createElement(h?.isSystem?Og:si),onClick:()=>t.handleCommand(h?.isGroup?A.DELETE_SESSION:A.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!ne,label:j?`Terminate ${P} selected sessions (Mark Completed, Cancel, or Delete)`:h?.isGroup?se?"Delete this empty group":"This group cannot be deleted yet":h?.isSystem?"Restart this system session (complete, terminate, or hard delete)":"Terminate — mark completed, cancel, or delete this session"}),e),F=G.dragging?a.createElement("div",{className:"ps-drag-ghost",style:{left:`${G.x}px`,top:`${G.y}px`}},a.createElement("div",{className:`ps-drag-ghost__stack${G.ids.length>1?" is-collection":""}`},G.ids.length>1?a.createElement("span",{className:"ps-drag-ghost__count"},String(G.ids.length)):null,a.createElement("span",{className:"ps-drag-ghost__title"},G.ids.length>1?`${G.ids.length} sessions`:G.titles[0]||"session")),a.createElement("div",{className:"ps-drag-ghost__hint"},G.intent==="file"?"Release to file here":G.intent==="unfile"?"Release to remove from folder":G.intent==="reorder"?"Release to move here":"Release to cancel")):null;return a.createElement(a.Fragment,null,F,a.createElement(St,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:u.focused,theme:c,actions:tn,className:v},a.createElement("div",{ref:r,className:`ps-action-list ps-session-list${G.dragging?" is-dragging":""}`,onClick:$=>{$.target instanceof Element&&$.target.closest(".ps-session-list-button")||t.dispatch({type:"sessions/listDeselect"})}},f.length===0?a.createElement("div",{className:"ps-empty-state"},u.filterQuery?`No sessions matched "@@${u.filterQuery}".`:"No sessions yet."):f.map($=>a.createElement(xg,{key:$.sessionId,row:$,theme:c,structuredRows:n,mobile:i,onRowClick:U,setRef:Te,drag:o?null:Fe}))),i?null:a.createElement(bg,{session:h,childCount:m?.childCount||0})),g&&h&&!h.isGroup?a.createElement(Jg,{controller:t,sessionId:h.sessionId,initialTitle:h.title||"",currentModel:h.model||"",currentReasoningEffort:h.reasoningEffort||"",principal:u.auth?.principal||null,onClose:()=>S(!1),onSwitchModel:b,onChanged:()=>{}}):null,y?a.createElement(Tg,{url:y.url,warn:y.warn,onCopyAgain:()=>{yo(y.url),t.dispatch({type:"ui/status",text:lm})},onClose:()=>w(null)}):null)}function Tg({url:t,warn:e,onCopyAgain:s,onClose:n}){const i=a.useRef(null);a.useEffect(()=>{const o=i.current;o&&(o.focus(),o.select())},[]);const r=o=>o.stopPropagation();return a.createElement("div",{className:"ps-share-overlay",onClick:n},a.createElement("div",{className:"ps-link-modal",onClick:r},a.createElement("div",{className:"ps-share-modal-head"},a.createElement("span",null,"Link copied"),a.createElement("button",{className:"ps-modal-close",onClick:n,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-share-section-sub"},"Copied to your clipboard — anyone with access can open the session from this link."),a.createElement("div",{className:"ps-link-row"},a.createElement("input",{ref:i,className:"ps-link-input",readOnly:!0,value:t,onFocus:()=>i.current?.select()}),a.createElement("button",{className:"ps-mini-button",onClick:s},"Copy")),e?a.createElement("div",{className:"ps-link-warn"},um):null))}const Lo={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function Se({children:t}){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},t)}function Mg(){return a.createElement(Se,null,a.createElement("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"}))}function ji(){return a.createElement(Se,null,a.createElement("path",{d:"M21 4H3l7.2 8.5V19l3.6 2v-8.5L21 4z"}))}function Ng(){return a.createElement(Se,null,a.createElement("path",{d:"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"}),a.createElement("path",{d:"M14 3v5h5"}),a.createElement("line",{x1:"8.5",y1:"13",x2:"15.5",y2:"13"}),a.createElement("line",{x1:"8.5",y1:"17",x2:"13",y2:"17"}))}function Pg(){return a.createElement(Se,null,a.createElement("path",{d:"M21 14.5a2.5 2.5 0 0 1-2.5 2.5H8l-5 4V5.5A2.5 2.5 0 0 1 5.5 3h13A2.5 2.5 0 0 1 21 5.5z"}))}function _g(){return a.createElement(Se,null,a.createElement("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),a.createElement("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))}function Rg(){return a.createElement(Se,null,a.createElement("circle",{cx:"12",cy:"12",r:"9"}),a.createElement("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor"}))}function Kl(){return a.createElement(Se,null,a.createElement("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),a.createElement("path",{d:"M16 3h3a2 2 0 0 1 2 2v3"}),a.createElement("path",{d:"M21 16v3a2 2 0 0 1-2 2h-3"}),a.createElement("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}))}function Ui(){return a.createElement(Se,null,a.createElement("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),a.createElement("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),a.createElement("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}),a.createElement("path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}))}function $g(){return a.createElement(Se,null,a.createElement("circle",{cx:"12",cy:"12",r:"3"}),a.createElement("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"}))}function Og(){return a.createElement(Se,null,a.createElement("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"}),a.createElement("path",{d:"M21 3v5h-5"}))}function Lg(){return a.createElement(Se,null,a.createElement("path",{d:"M12 16V4"}),a.createElement("path",{d:"M7.5 8.5L12 4l4.5 4.5"}),a.createElement("path",{d:"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"}))}function Fg(){return a.createElement(Se,null,a.createElement("path",{d:"M12 4v12"}),a.createElement("path",{d:"M7.5 11.5L12 16l4.5-4.5"}),a.createElement("path",{d:"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"}))}function Bg(){return a.createElement(Se,null,a.createElement("line",{x1:"4.5",y1:"3",x2:"4.5",y2:"21"}),a.createElement("line",{x1:"19.5",y1:"3",x2:"19.5",y2:"21"}),a.createElement("path",{d:"M4.5 8.5h13"}),a.createElement("path",{d:"M15 6l2.5 2.5-2.5 2.5"}),a.createElement("path",{d:"M19.5 15.5h-13"}),a.createElement("path",{d:"M9 13l-2.5 2.5 2.5 2.5"}))}function Dg(){return a.createElement(Se,null,a.createElement("path",{d:"M3 5.5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v13a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),a.createElement("path",{d:"M9.5 3.5v17"}))}function Hg(){return a.createElement(Se,null,a.createElement("path",{d:"M4 17l6-6-6-6"}),a.createElement("line",{x1:"12",y1:"19",x2:"20",y2:"19"}))}function Gg(){return a.createElement(Se,null,a.createElement("circle",{cx:"6",cy:"6",r:"2.6"}),a.createElement("circle",{cx:"18",cy:"6",r:"2.6"}),a.createElement("circle",{cx:"12",cy:"18",r:"2.6"}),a.createElement("line",{x1:"8.6",y1:"6",x2:"15.4",y2:"6"}),a.createElement("line",{x1:"7.4",y1:"8.3",x2:"10.6",y2:"15.7"}),a.createElement("line",{x1:"16.6",y1:"8.3",x2:"13.4",y2:"15.7"}))}const jg="M12 2.3 20.4 7.15v9.7L12 21.7 3.6 16.85V7.15Z",Ug="M15.2 10.1A4.2 4.2 0 0 1 15.2 11.9L14.23 11.69A3.2 3.2 0 0 1 13.8 12.73L14.64 13.26A4.2 4.2 0 0 1 13.36 14.54L12.83 13.7A3.2 3.2 0 0 1 11.79 14.13L12 15.1A4.2 4.2 0 0 1 10.2 15.1L10.41 14.13A3.2 3.2 0 0 1 9.37 13.7L8.84 14.54A4.2 4.2 0 0 1 7.56 13.26L8.4 12.73A3.2 3.2 0 0 1 7.97 11.69L7 11.9A4.2 4.2 0 0 1 7 10.1L7.97 10.31A3.2 3.2 0 0 1 8.4 9.27L7.56 8.74A4.2 4.2 0 0 1 8.84 7.46L9.37 8.3A3.2 3.2 0 0 1 10.41 7.87L10.2 6.9A4.2 4.2 0 0 1 12 6.9L11.79 7.87A3.2 3.2 0 0 1 12.83 8.3L13.36 7.46A4.2 4.2 0 0 1 14.64 8.74L13.8 9.27A3.2 3.2 0 0 1 14.23 10.31ZM12.8 11A1.7 1.7 0 0 0 9.4 11A1.7 1.7 0 0 0 12.8 11Z",Wg="M7.23 15.01A5.7 5.7 0 0 1 17.76 14.55L19.11 15.04L15.1 16.57L14.71 13.44L16.06 13.93A3.9 3.9 0 0 0 8.87 14.25Z";function Kg(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":"true"},a.createElement("path",{d:jg,strokeWidth:"1.9",strokeLinejoin:"round"}),a.createElement("path",{d:Ug,fill:"currentColor",stroke:"none",fillRule:"evenodd"}),a.createElement("path",{d:Wg,fill:"currentColor",stroke:"none"}))}function zg(){return a.createElement(Se,null,a.createElement("path",{d:"M9 2.8h4.2L17 6.6v8.6a1.8 1.8 0 0 1-1.8 1.8H15"}),a.createElement("path",{d:"M4.5 9.4a1.8 1.8 0 0 1 1.8-1.8h4.2l3.8 3.8v8a1.8 1.8 0 0 1-1.8 1.8H6.3a1.8 1.8 0 0 1-1.8-1.8z"}),a.createElement("path",{d:"M10.5 7.6v3.8h3.8"}))}function Vg(){return a.createElement(Se,null,a.createElement("rect",{x:"4.2",y:"12",width:"3.6",height:"8",rx:"0.6",fill:"currentColor",stroke:"none"}),a.createElement("rect",{x:"10.2",y:"6.5",width:"3.6",height:"13.5",rx:"0.6",fill:"currentColor",stroke:"none"}),a.createElement("rect",{x:"16.2",y:"9.5",width:"3.6",height:"10.5",rx:"0.6",fill:"currentColor",stroke:"none"}),a.createElement("path",{d:"M3 21h18"}))}function qg(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.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"}),a.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 si(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.createElement("path",{d:"M3 6h18"}),a.createElement("path",{d:"M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"}),a.createElement("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),a.createElement("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),a.createElement("line",{x1:"14",y1:"11",x2:"14",y2:"17"}))}function Fo(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.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 Yg(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.createElement("path",{d:"M9 3h6"}),a.createElement("path",{d:"M10 3v6l-3 3v2h10v-2l-3-3V3"}),a.createElement("line",{x1:"12",y1:"14",x2:"12",y2:"21"}))}function Xg(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.createElement("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),a.createElement("path",{d:"M3 3v5h5"}),a.createElement("path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"}),a.createElement("path",{d:"M21 21v-5h-5"}))}function Qg(t,e,s){const[n,i]=a.useState({access:null,loading:!1}),r=a.useCallback(()=>{if(!e||s||typeof t.transport.getSessionAccess!="function"){i({access:null,loading:!1});return}let o=!1;return i(l=>({...l,loading:!0})),t.transport.getSessionAccess(e).then(l=>{o||i({access:l,loading:!1})}).catch(()=>{o||i({access:null,loading:!1})}),()=>{o=!0}},[t,e,s]);return a.useEffect(()=>{let o;const l=setTimeout(()=>{o=r()},cm);return()=>{clearTimeout(l),typeof o=="function"&&o()}},[r]),{access:n.access,loading:n.loading,reload:r}}function Jg({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:i,principal:r,onClose:o,onSwitchModel:l,onChanged:c}){const[d,u]=a.useState("general"),[p,f]=a.useState(null),[h,m]=a.useState(s||""),[g,S]=a.useState([]),[y,w]=a.useState([]),[x,I]=a.useState("private"),[E,b]=a.useState(""),[k,M]=a.useState("write"),[N,B]=a.useState([]),[_,P]=a.useState(!1),[j,K]=a.useState(null);a.useEffect(()=>{let F=!1;return t.transport.getSessionAccess(e).then($=>{!F&&$&&(f($),I($.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then($=>{F||B(Array.isArray($)?$:[])}).catch(()=>{}),()=>{F=!0}},[t,e]);const z=a.useCallback(()=>{t.transport.listSessionShares(e).then(F=>{const $=Array.isArray(F)?F:[];S($),w($)}).catch(()=>{S([]),w([])})},[t,e]);a.useEffect(()=>{z()},[z]);const se=async F=>{P(!0),K(null);try{await F(),c?.()}catch($){K($?.message||String($))}finally{P(!1)}},ne=()=>se(async()=>{await t.transport.renameSession(e,h.trim())}),ve=F=>{const $=F.trim().toLowerCase();if(!$)return null;const D=N.find(V=>V.displayName&&V.displayName.toLowerCase()===$||V.email&&V.email.toLowerCase()===$||V.subject&&V.subject.toLowerCase()===$);return D||{provider:r?.provider||"dev",subject:F.trim(),email:null,displayName:null}},oe=F=>`${F.provider}${F.subject}`,be=F=>{const $=oe(F);w(D=>[...D.filter(V=>oe(V)!==$),{provider:F.provider,subject:F.subject,email:F.email??null,displayName:F.displayName??null,access:k}]),b("")},v=()=>{const F=ve(E);F&&be(F)},O=F=>{const $=oe(F);w(D=>D.filter(V=>oe(V)!==$))},G=new Set(y.map(oe)),L=p?.owner?`${p.owner.provider}${p.owner.subject}`:null,R=E.trim().toLowerCase(),C=R?N.filter(F=>{const $=oe(F);return $===L||G.has($)?!1:F.displayName&&F.displayName.toLowerCase().includes(R)||F.email&&F.email.toLowerCase().includes(R)||F.subject&&F.subject.toLowerCase().includes(R)}).slice(0,25):[],H=!!p?.canManage,Q=p?.visibility||"private",Y=new Set(y.map(F=>`${oe(F)}:${F.access}`)),le=new Set(g.map(F=>`${oe(F)}:${F.access}`)),ye=Y.size!==le.size||[...Y].some(F=>!le.has(F)),we=H&&(x!==Q||ye),Ie=()=>se(async()=>{x!==Q&&await t.transport.setSessionVisibility(e,x);const F=new Map(g.map(Z=>[oe(Z),Z])),$=new Map(y.map(Z=>[oe(Z),Z]));for(const[Z,W]of $){const re=F.get(Z);(!re||re.access!==W.access)&&await t.transport.grantSessionShare(e,{provider:W.provider,subject:W.subject,email:W.email??null,displayName:W.displayName??null},W.access)}for(const[Z,W]of F)$.has(Z)||await t.transport.revokeSessionShare(e,{provider:W.provider,subject:W.subject});const D=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(D)&&(S(D),w(D));const V=await t.transport.getSessionAccess(e).catch(()=>null);V&&(f(V),I(V.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),Fe=l||(()=>{o(),t.openSwitchModelPicker().catch(F=>{t.dispatch({type:"ui/status",text:F?.message||String(F)||"Failed to switch model"})})}),U=n?i?`${n}:${i}`:n:"—",Te=[{id:"general",label:"General"},...H?[{id:"access",label:"Access"}]:[]],$e=Te.some(F=>F.id===d)?d:"general",zt=typeof t.transport?.regenerateSession=="function",tn=F=>F.stopPropagation();return a.createElement("div",{className:"ps-share-overlay",onClick:o},a.createElement("div",{className:"ps-share-modal",onClick:tn},a.createElement("div",{className:"ps-share-modal-head"},a.createElement("span",null,"Manage session"),a.createElement("button",{className:"ps-modal-close",onClick:o,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-manage-tabs",role:"tablist"},Te.map(F=>a.createElement("button",{key:F.id,type:"button",role:"tab","aria-selected":$e===F.id?"true":"false",className:`ps-manage-tab${$e===F.id?" is-active":""}`,onClick:()=>u(F.id)},F.label))),a.createElement("div",{className:"ps-share-modal-body"},$e==="general"?a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-share-section-label"},"Name"),a.createElement("div",{className:"ps-share-add-row"},a.createElement("input",{className:"ps-share-add-input",placeholder:"Session title",value:h,disabled:_,onChange:F=>m(F.target.value),onKeyDown:F=>{F.key==="Enter"&&ne()}}),a.createElement("button",{className:"ps-mini-button",disabled:_||!h.trim(),onClick:ne},"Save")),a.createElement("div",{className:"ps-share-section-label"},"Model"),a.createElement("div",{className:"ps-share-section-sub"},"The model this session uses on its next turn."),a.createElement("div",{className:"ps-share-add-row"},a.createElement("span",{className:"ps-manage-model-current"},U),a.createElement("button",{className:"ps-mini-button",disabled:_,onClick:Fe},"Switch model…")),zt?a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-share-section-label"},"Context"),a.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."),a.createElement("div",{className:"ps-share-add-row"},a.createElement("button",{className:"ps-mini-button ps-manage-regenerate",disabled:_,onClick:()=>{o(),t.handleCommand(A.REGENERATE_SESSION).catch(()=>{})}},a.createElement(Xg),a.createElement("span",null,"Regenerate context…")))):null):null,$e==="access"&&H?a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-share-section-label"},"General access"),a.createElement("div",{className:"ps-share-section-sub"},"The baseline level for everyone signed in to this workspace."),["private","shared_read","shared_write"].map(F=>a.createElement("label",{key:F,className:`ps-share-radio${x===F?" is-active":""}`},a.createElement("input",{type:"radio",name:"visibility",checked:x===F,disabled:_,onChange:()=>I(F)}),a.createElement("span",{className:"ps-share-radio-glyph"},Lo[F].glyph),a.createElement("span",null,Lo[F].label),a.createElement("span",{className:"ps-share-radio-hint"},F==="private"?"only you and admins":F==="shared_read"?"everyone here can view":"everyone here can view and send"))),a.createElement("div",{className:"ps-share-section-label"},"Special access"),a.createElement("div",{className:"ps-share-section-sub"},"Give specific people more than the general level. A person's grant wins over general access."),y.length===0?a.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):y.map(F=>a.createElement("div",{key:`${F.provider}/${F.subject}`,className:"ps-share-grant-row"},a.createElement("span",{className:"ps-share-grant-name"},F.displayName||F.subject),a.createElement("span",{className:"ps-share-grant-access"},`can ${F.access}`),a.createElement("button",{className:"ps-mini-button",disabled:_,onClick:()=>O(F)},"Remove"))),a.createElement("div",{className:"ps-share-add-wrap"},a.createElement("div",{className:"ps-share-add-row"},a.createElement("input",{className:"ps-share-add-input",placeholder:"Name, email, or id",value:E,disabled:_,autoComplete:"off",onChange:F=>b(F.target.value),onKeyDown:F=>{F.key==="Enter"&&v()}}),a.createElement("select",{className:"ps-share-add-select",value:k,disabled:_,onChange:F=>M(F.target.value)},a.createElement("option",{value:"read"},"can read"),a.createElement("option",{value:"write"},"can write")),a.createElement("button",{className:"ps-mini-button",disabled:_||!E.trim(),onClick:v},"Add")),C.length>0?a.createElement("div",{className:"ps-share-suggestions"},C.map(F=>a.createElement("button",{key:`${F.provider}/${F.subject}`,type:"button",className:"ps-share-suggestion",disabled:_,onClick:()=>be(F)},a.createElement("span",{className:"ps-share-suggestion-name"},F.displayName||F.subject),F.email?a.createElement("span",{className:"ps-share-suggestion-email"},F.email):null))):null),a.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),$e==="access"&&H?a.createElement("div",{className:"ps-manage-apply-bar is-footer"},a.createElement("span",{className:"ps-share-section-sub"},we?"Unsaved access changes.":"No changes to apply."),a.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:_||!we,onClick:Ie},"Apply")):null,j?a.createElement("div",{className:"ps-share-error"},j):null))}function Wi({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const i=ee(t,_=>_.ui.themeId),r=st(i),o=ee(t,_=>{const P=_.sessions.activeSessionId,j=Zs(_),K=s||e?j.totalWidth:j.leftWidth,z=Math.max(20,K-4);return{activeSessionId:P,activeHistory:P&&_.history.bySessionId.get(P)||null,activeOutbox:P&&_.outbox?.bySessionId?.[P]?_.outbox.bySessionId[P]:[],branding:_.branding,connection:_.connection,sessionsById:_.sessions.byId,sessionsFlat:_.sessions.flat,inspectorTab:_.ui.inspectorTab,chatViewMode:_.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(P&&_.sessions.byId[P]?.isGroup),activeSessionStatus:P?String(_.sessions.byId[P]?.status||"").toLowerCase():"",focused:_.ui.focusRegion==="chat",scroll:_.ui.scroll.chat,authPrincipal:_.auth?.principal||null,contentWidth:z}},Ue),l=a.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=a.useMemo(()=>za(l,{width:o.contentWidth}),[l,o.contentWidth]),d=Uo(!!c.animateTitleRight),u=a.useMemo(()=>Wo(c.titleRight,c.animateTitleRight?d:""),[d,c.animateTitleRight,c.titleRight]),[p,f]=a.useState(!1),h=!!(o.activeHistory?.hasOlderEvents&&Number(o.activeHistory?.loadedEventCount||0)>=Qn),m=a.useMemo(()=>Ei(l,o.contentWidth,{tableMode:"sentinel"}),[l,o.contentWidth]),g=jo(o.activeSessionStatus==="running"),y=a.useMemo(()=>Ii(l,{spinnerFrame:g,maxWidth:o.contentWidth}),[l,g,o.contentWidth]),w=a.useMemo(()=>vi(l,o.contentWidth,{tableMode:"sentinel"}),[l,o.contentWidth]),x=a.useMemo(()=>y.length>0?[...w,...y]:w,[w,y]),{access:I}=Qg(t,o.activeSessionId,o.activeSessionIsGroup),E=ee(t,pd,Ue),b=n&&!o.activeSessionIsGroup&&o.chatViewMode!=="summary",k=!!o.sessionsById?.[o.activeSessionId]?.serviceKind,M=k||!!I&&I.canWrite===!1,N=b?a.createElement("div",{className:"ps-chat-composer"},M?a.createElement("div",{className:"ps-composer-readonly"},k?"⚗ 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.`):a.createElement(ny,{controller:t,mobile:e,active:!0})):null,B=!!(o.activeSessionId&&o.sessionsById[o.activeSessionId]);return E&&!B?a.createElement(St,{title:c.title,color:c.color,focused:o.focused,theme:r,className:"ps-chat-panel"},a.createElement("div",{className:"ps-empty-state ps-nav-error-state"},a.createElement("div",{className:"ps-nav-error-message"},E.message),E.retryable?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(E.sessionId)},"Retry"):null)):a.createElement(en,{controller:t,title:e?wo(c.title,28):c.title,titleRight:e&&u?wo(u,18):u,actions:null,color:c.color,focused:o.focused,lines:m,bottomStickyLines:x,scrollOffset:o.scroll,scrollMode:"bottom",paneKey:"chat",className:"is-wrapped",panelClassName:"ps-chat-panel",bottomContent:N,topContent:h?a.createElement("div",{className:"ps-load-older-bar"},a.createElement("button",{type:"button",className:"ps-load-older-button",disabled:p,onClick:()=>{f(!0),t.handleCommand(A.EXPAND_HISTORY).catch(()=>{}).finally(()=>f(!1))}},p?"Loading older messages…":"↑ Load older messages")):null,structuredBlocks:!0,renderBody:null})}function Zg({controller:t}){const e=ee(t,o=>{const l=o.files.selectedArtifactId||"";return{filename:l?l.slice(l.indexOf("/")+1):"",origin:o.files.previewOrigin||null,canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},Ue),s=!!Nl(e.filename)||Fi(e.filename),[n,i]=a.useState(!1);a.useEffect(()=>{i(!1)},[e.filename]);const r=a.useCallback(o=>{t.stepArtifactPreview(o).catch(()=>{})},[t]);return a.createElement("div",{className:"ps-artifact-overlay"},a.createElement("header",{className:"ps-artifact-overlay-bar"},a.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"},"✕"),a.createElement("span",{className:"ps-artifact-overlay-title"},e.filename||"Artifact"),s?a.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,a.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canPrev,onClick:()=>r(-1),"aria-label":"Previous artifact"},"‹"),a.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canNext,onClick:()=>r(1),"aria-label":"Next artifact"},"›")),a.createElement("div",{className:`ps-artifact-overlay-body${n?" is-content-width":""}`},a.createElement(Ki,{controller:t,focused:!0,mobile:!0,previewOnly:!0,nativeScroll:!0})))}function ey({controller:t}){return a.createElement("div",{className:"ps-mobile-workspace"},a.createElement(Gi,{controller:t,panelClassName:"ps-mobile-session-pane"}),a.createElement("div",{className:"ps-mobile-chat-pane"},a.createElement(Wi,{controller:t,mobile:!0,fullWidth:!0})))}function zl({activeTab:t,controller:e}){const s=a.useMemo(()=>Li(e),[e]);return a.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>a.createElement(ce,{key:n,icon:go[n]?a.createElement(go[n]):"•",label:tm[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function Ki({controller:t,focused:e,mobile:s=!1,previewOnly:n=!1,nativeScroll:i=!1}){const r=ee(t,P=>P.ui.themeId),o=st(r),l=a.useRef(null),c=ee(t,P=>{const j=P.sessions.activeSessionId,K=Zs(P),z=s||P.files.fullscreen?P.ui.layout?.viewportWidth??120:K.rightWidth;return{activeSessionId:j,sessionsById:P.sessions.byId,sessionsFlat:P.sessions.flat,filesBySessionId:P.files.bySessionId,filesFilter:P.files.filter,selectedArtifactId:P.files.selectedArtifactId,markedIds:P.files.markedIds||[],previewOrigin:P.files.previewOrigin||null,focused:e,previewScroll:P.ui.scroll.filePreview,fullscreen:!!P.files.fullscreen,contentWidth:Math.max(20,z-4),canBrowserUpload:nm(t),canPathUpload:im(t),canDeleteArtifacts:om(t),canOpenLocally:am(t)}},Ue),d=a.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]),u=a.useMemo(()=>Ci(d,{listWidth:Math.max(18,c.contentWidth-4),previewWidth:Math.max(18,c.contentWidth-4),showHints:!1}),[d,c.contentWidth]),p=a.useMemo(()=>ht(d),[d]),f=p.length>0,h=a.useCallback(P=>{const j=Array.isArray(P)?P.filter(Boolean):[];j.length!==0&&t.uploadArtifactFiles(j).catch(()=>{})},[t]),m=a.useCallback(()=>{if(c.canBrowserUpload&&l.current){l.current.click();return}c.canPathUpload&&t.handleCommand(A.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,c.canBrowserUpload,c.canPathUpload]),g=a.useMemo(()=>new Set(c.markedIds||[]),[c.markedIds]),S=a.createElement(a.Fragment,null,g.size>0?a.createElement(a.Fragment,null,a.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",opacity:.85},title:"Cmd/Ctrl-click to mark, Shift-click for a range"},`${g.size} marked`),c.canDeleteArtifacts?a.createElement(ce,{icon:a.createElement(si),label:`Delete ${g.size} marked`,onClick:()=>t.deleteMarkedArtifacts().catch(()=>{})}):null,a.createElement(ce,{icon:"✕",label:"Clear marks",onClick:()=>t.clearArtifactMarks()})):null,a.createElement("input",{ref:l,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:P=>{h(Array.from(P.currentTarget.files||[])),P.currentTarget.value=""}}),a.createElement(ce,{icon:a.createElement(Lg),label:"Upload",onClick:m,disabled:!c.canBrowserUpload&&!c.canPathUpload}),a.createElement(ce,{icon:a.createElement(Fg),label:"Download",onClick:()=>t.handleCommand(A.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!f}),c.canDeleteArtifacts?a.createElement(ce,{icon:a.createElement(si),label:"Delete",onClick:()=>t.handleCommand(A.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,c.canOpenLocally?a.createElement(ce,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(A.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,a.createElement(ce,{icon:a.createElement(ji),label:"Filter",onClick:()=>t.handleCommand(A.OPEN_FILES_FILTER).catch(()=>{})}),a.createElement(ce,{icon:a.createElement(c.fullscreen?Ui:Kl),label:c.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(A.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),y=a.useRef(null);a.useEffect(()=>{const P=y.current;P&&typeof P.scrollIntoView=="function"&&P.scrollIntoView({block:"nearest"})},[u.selectedIndex,c.selectedArtifactId]);const w=p.length===0?Me(u.listBodyLines||[]).map((P,j)=>a.createElement(Ne,{key:`empty:${j}`,line:P,theme:o})):p.map((P,j)=>a.createElement("button",{key:P.id,type:"button",ref:j===u.selectedIndex?y:null,className:`ps-list-button${j===u.selectedIndex?" is-selected":""}`+(g.has(P.id)?" is-marked":""),onClick:K=>{if(t.setFocus("inspector"),K.metaKey||K.ctrlKey){t.toggleArtifactMark(P);return}if(K.shiftKey){t.markArtifactRange(P);return}t.clearArtifactMarks(),t.selectFileBrowserItem(P).then(()=>{s&&t.handleCommand(A.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})}).catch(()=>{})}},a.createElement(Ne,{line:Me([u.listBodyLines?.[j]])[0],theme:o}))),x=!u.previewLoading&&!u.previewError,I=x&&Fi(u.selectedFilename,u.previewContentType)&&!u.previewIsBinary&&!!u.previewContent,E=x&&(Tl.test(String(u.previewContentType||""))||Ml.test(String(u.selectedFilename||""))),b=x&&!u.previewIsBinary&&!I&&u.previewRenderMode!=="markdown"&&u.previewContent?Nl(u.selectedFilename):null,k=n?"activity":null,M=i?null:"filePreview",B=x&&!u.previewIsBinary&&Om(u.selectedFilename,u.previewContentType)&&!!u.previewContent?a.createElement($n,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:M,scrollOffset:c.previewScroll,className:"ps-csv-preview",focusRegion:k},a.createElement(Fm,{content:u.previewContent,filename:u.selectedFilename})):E?a.createElement(To,{title:null,color:"cyan",focused:!1,theme:o,filename:u.selectedFilename,contentType:u.previewContentType,sizeBytes:u.previewSizeBytes,source:u.previewSource,uploadedAt:u.previewUploadedAt,controller:t,sessionId:u.selectedSessionId}):b?a.createElement($n,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:M,scrollOffset:c.previewScroll,className:"ps-diff-preview",focusRegion:k},a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,as(u.previewContent,b,o)))):I?a.createElement($n,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:M,scrollOffset:c.previewScroll,className:"ps-diff-preview",focusRegion:k},a.createElement("pre",{className:"ps-md-code-pre is-diff"},a.createElement("code",null,Bi(u.previewContent,o)))):u.previewRenderMode==="markdown"&&!u.previewLoading&&!u.previewError?a.createElement(ig,{controller:t,title:null,color:"cyan",focused:!1,scrollOffset:c.previewScroll,paneKey:M,theme:o,focusRegion:k,content:Rm(u.previewContent||"")}):u.previewIsBinary&&!u.previewLoading&&!u.previewError?a.createElement(To,{title:null,color:"cyan",focused:!1,theme:o,filename:u.selectedFilename,contentType:u.previewContentType,sizeBytes:u.previewSizeBytes,source:u.previewSource,uploadedAt:u.previewUploadedAt,controller:t,sessionId:u.selectedSessionId}):a.createElement(en,{controller:t,title:null,color:"cyan",focused:!1,lines:u.previewLines,scrollOffset:c.previewScroll,scrollMode:"top",paneKey:M,focusRegion:k,className:"is-preview is-wrapped"}),_=c;return n?B:a.createElement(St,{title:_.fullscreen?u.fullscreenTitle:s&&u.panelTitleMobile?u.panelTitleMobile:u.panelTitle,color:"magenta",focused:_.focused,actions:S,theme:o},a.createElement(zl,{activeTab:"files",controller:t}),_.fullscreen?B:a.createElement("div",{className:"ps-files-grid is-list-only"},a.createElement("div",{className:"ps-action-list ps-files-list"},w)))}function vt({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const i=ee(t,f=>{const h=Zs(f),m=f.ui.inspectorTab,g=e?f.ui.layout?.viewportWidth??120:h.rightWidth;return{inspectorTab:m,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:bm(g)}},Ue),r=a.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=a.useMemo(()=>lt(r,{width:i.contentWidth,allowWideColumns:e}),[e,r,i.contentWidth]),l=a.useMemo(()=>{const f=i.activeSessionId&&i.historyBySessionId?.get(i.activeSessionId)||null,h=new Map;for(const m of f?.events||[]){if(m?.eventType!=="session.turn_completed")continue;const g=Number(m?.data?.turnIndex??m?.data?.iteration);Number.isFinite(g)&&h.set(g,m)}return h},[i.activeSessionId,i.historyBySessionId]),c=a.useCallback((f,h)=>a.createElement(yg,{lines:f,theme:h,completionByTurn:l}),[l]),d=a.useCallback((f,h)=>a.createElement(gg,{lines:f,theme:h,controller:t}),[t]);if(a.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 a.createElement(Ki,{controller:t,focused:i.focused,mobile:e});const u=[];if(i.inspectorTab==="logs")u.push(a.createElement(ce,{key:"tail",icon:i.logsTailing?"■":"⇣",label:i.logsTailing?"Stop tailing":"Tail (follow)",active:i.logsTailing,onClick:()=>t.handleCommand(A.TOGGLE_LOG_TAIL).catch(()=>{})})),u.push(a.createElement(ce,{key:"filter",icon:a.createElement(ji),label:"Filter",onClick:()=>t.handleCommand(A.OPEN_LOG_FILTER).catch(()=>{})}));else if(i.inspectorTab==="history")u.push(a.createElement(ce,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(A.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),u.push(a.createElement(ce,{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 h of["session","fleet","users"])u.push(a.createElement(ce,{key:`stats-view:${h}`,icon:f[h],label:`${h.replace(/^./u,m=>m.toUpperCase())} stats`,active:i.statsViewMode===h,onClick:()=>t.setStatsViewMode(h)}))}const p=n?u.concat(n):u;return a.createElement(en,{controller:t,title:o.title,color:"magenta",focused:i.focused,actions:p,topContent:a.createElement(zl,{activeTab:o.activeTab,controller:t}),stickyLines:o.stickyLines||[],lines:o.lines,renderBody:o.activeTab==="sequence"?c:o.activeTab==="nodes"?d: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 As({controller:t,panelClassName:e="",extraActions:s=null}){const n=ee(t,l=>{const c=l.sessions.activeSessionId,d=Zs(l),u=Math.max(3,d.activityPaneHeight-2);return{activeSessionId:c,activeSession:c&&l.sessions.byId[c]||null,activeHistory:c&&l.history.bySessionId.get(c)||null,focused:l.ui.focusRegion==="activity",scroll:l.ui.scroll.activity,followBottom:l.ui.followBottom?.activity!==!1,maxLines:u,nodeMapSelectedNode:l.ui.nodeMapSelectedNode,adminWorkers:l.admin?.workers,branding:l.branding,sessionsById:l.sessions.byId,sessionsFlat:l.sessions.flat,historyBySessionId:l.history.bySessionId,inspectorTab:l.ui.inspectorTab}},Ue),i=n.inspectorTab==="nodes",r=a.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=a.useMemo(()=>i?Va(r):Ai(r,n.maxLines),[i,r,n.maxLines]);return a.createElement(en,{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 ni=[{id:"sessions",label:"Sessions",side:"left"},{id:"inspector",label:"Inspector",side:"right"},{id:"activity",label:"Activity",side:"right"}];function ty({controller:t,pane:e,onClose:s,mobile:n=!1}){if(!e)return null;let i=null;e==="sessions"?i=a.createElement(Gi,{controller:t,panelClassName:"ps-chat-focus-pane",structuredRows:n}):e==="inspector"?i=a.createElement(vt,{controller:t,mobile:!1,panelClassName:"ps-chat-focus-pane",extraActions:a.createElement("button",{type:"button",className:"ps-mini-button ps-overlay-close",onClick:s,"aria-label":"Close",title:"Close"},"✕")}):e==="activity"&&(i=a.createElement(As,{controller:t,panelClassName:"ps-chat-focus-pane",extraActions:a.createElement("button",{type:"button",className:"ps-mini-button ps-overlay-close",onClick:s,"aria-label":"Close",title:"Close"},"✕")}));const r=ni.find(o=>o.id===e);return a.createElement("div",{className:`ps-chat-focus-overlay${r?.side==="left"?" is-left":" is-right"}`},i)}function sy({controller:t,openPane:e,onTogglePane:s,onExitFocus:n,mobile:i=!1}){const r=ee(t,l=>l.ui.focusRegion),o=i?a.createElement("div",{className:"ps-chat-focus-rail"},a.createElement(ce,{className:"ps-mini-button ps-chat-focus-button",icon:a.createElement(Ui),label:"Exit focus mode",onClick:n}),a.createElement(ce,{className:"ps-mini-button ps-chat-focus-button",icon:a.createElement(Dg),label:e==="sessions"?"Hide sessions":"Show sessions",active:e==="sessions",onClick:()=>s("sessions")})):a.createElement("div",{className:"ps-chat-focus-rail"},ni.map(l=>a.createElement("button",{key:l.id,type:"button",className:`ps-mini-button ps-chat-focus-button${e===l.id?" is-active":""}`,"aria-pressed":e===l.id?"true":"false",onClick:()=>s(l.id)},l.label)),a.createElement("div",{className:"ps-chat-focus-status"},e?`Focused: ${ni.find(l=>l.id===e)?.label||e}`:`Focused: ${r==="prompt"?"Prompt":"Chat"}`));return a.createElement("div",{className:"ps-chat-focus-shell"},o,a.createElement("div",{className:"ps-chat-focus-body"},a.createElement(Wi,{controller:t,mobile:i,fullWidth:!0}),a.createElement(ty,{controller:t,pane:e,onClose:()=>s(e),mobile:i})))}const Bo=Object.freeze([]);function Do(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 ny({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const i=ee(t,b=>{const k=b.sessions.activeSessionId,M=k&&b.sessions.byId[k]||null,N=k&&b.outbox?.bySessionId?.[k]?b.outbox.bySessionId[k]:[];return{value:b.ui.prompt,cursor:b.ui.promptCursor,focused:b.ui.focusRegion==="prompt",modalOpen:!!b.ui.modal,answerMode:!!M?.pendingQuestion?.question,canStopTurn:Ga(M),hasOutbox:N.length>0,hasPendingOutbox:N.some(B=>B?.phase==="pending"),pendingCount:N.filter(B=>B?.phase==="pending").length,editingPending:b.ui.promptEdit?.sessionId===k,selectedOutboxPhase:b.ui.promptEdit?.sessionId===k&&b.ui.promptEdit?.phase||null,promptAttachments:b.ui.promptAttachments||Bo}},Ue),r=a.useRef(null),o=a.useRef(null),[l,c]=a.useState(!1),d=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",u=d?i.promptAttachments.filter(b=>b?.kind==="image"):Bo,p=a.useRef(new Map);a.useEffect(()=>{const b=p.current,k=new Set(u.map(M=>M.file));for(const[M,N]of b)k.has(M)||(URL.revokeObjectURL(N),b.delete(M));for(const M of u)if(M.file&&!b.has(M.file))try{b.set(M.file,URL.createObjectURL(M.file))}catch{}},[u]),a.useEffect(()=>()=>{for(const b of p.current.values())URL.revokeObjectURL(b);p.current.clear()},[]);const f=a.useCallback(b=>{if(!d)return 0;const k=Array.from(b||[]).filter(N=>N&&typeof N.type=="string"&&N.type.startsWith("image/"));return k.length===0?0:t.addPendingImageFiles(k)?.accepted||0},[t,d]);a.useEffect(()=>{const b=r.current;if(!(!s||i.modalOpen||!i.focused||!b)){if(document.activeElement!==b)try{b.focus({preventScroll:!0})}catch{b.focus()}b.setSelectionRange(i.cursor,i.cursor)}},[s,i.cursor,i.focused,i.modalOpen]);const h=a.useCallback(()=>{t.handleCommand(A.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[m,g]=a.useState(!1),S=a.useCallback(()=>{g(!0),t.handleCommand(A.STOP_TURN).catch(()=>{}).finally(()=>g(!1))},[t]),y=a.useCallback(()=>{if(t.getState().ui.promptEdit){typeof t.cancelSelectedOutboxPrompt=="function"?t.cancelSelectedOutboxPrompt().catch(()=>{}):t.cancelSelectedPendingPrompt();return}typeof t.cancelLatestQueuedOutbox=="function"&&t.cancelLatestQueuedOutbox().catch(()=>{})},[t]),w=i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"⇪":i.hasOutbox?"+":"❯",x=i.selectedOutboxPhase==="queued",I=i.selectedOutboxPhase==="cancelling",E=x||I;return a.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}${l?" is-drag-over":""}`,...d?{onDragOver:b=>{b.dataTransfer?.types?.includes?.("Files")&&(b.preventDefault(),c(!0))},onDragLeave:b=>{b.currentTarget.contains(b.relatedTarget)||c(!1)},onDrop:b=>{c(!1),b.dataTransfer?.files?.length&&(b.preventDefault(),f(b.dataTransfer.files))}}:{}},u.length>0?a.createElement("div",{className:"ps-prompt-attachments"},u.map((b,k)=>{const M=b.file?p.current.get(b.file):null;return a.createElement("div",{key:`attach:${k}:${b.filename}`,className:"ps-attach-chip",title:`${b.filename} · ${Do(b.sizeBytes)}`},M?a.createElement("img",{className:"ps-attach-thumb",src:M,alt:b.filename}):a.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),a.createElement("div",{className:"ps-attach-size"},Do(b.sizeBytes)),a.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${b.filename}`,"aria-label":`Remove attachment ${b.filename}`,onClick:()=>t.removePendingImageAttachment(k)},"✕"))})):null,(()=>{const b=i.answerMode?"answer":I?"cancelling":x?"queued":i.editingPending?"pending":"you";return a.createElement("label",{className:`ps-prompt-label${b==="you"?" is-default":""}`},b)})(),a.createElement("textarea",{ref:r,className:"ps-prompt-input",rows:e?2:Math.max(2,$t(i.value)),value:i.value,readOnly:E,placeholder:i.answerMode?"Type an answer and press Enter":i.editingPending?I?"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:b=>t.setPromptCursor(b.currentTarget.selectionStart||0),onChange:b=>t.setPrompt(b.currentTarget.value,b.currentTarget.selectionStart||b.currentTarget.value.length),onPaste:d?b=>{const M=Array.from(b.clipboardData?.items||[]).filter(N=>N.kind==="file"&&N.type.startsWith("image/")).map(N=>N.getAsFile()).filter(Boolean);M.length>0&&f(M)>0&&b.preventDefault()}:void 0,onKeyDown:b=>{if(b.key==="Tab"&&!b.shiftKey&&t.acceptPromptReferenceAutocomplete()){b.preventDefault();return}if(b.key==="ArrowUp"&&!b.shiftKey&&!b.metaKey&&!b.altKey){b.preventDefault(),t.movePromptCursorVertical(-1);return}if(b.key==="ArrowDown"&&!b.shiftKey&&!b.metaKey&&!b.altKey){b.preventDefault(),t.movePromptCursorVertical(1);return}if(b.key==="Escape"&&i.editingPending){if(b.preventDefault(),E){t.exitPendingPromptEdit({restoreDraft:!0});return}y();return}b.key==="Enter"&&!b.shiftKey&&!b.metaKey&&!e&&(b.preventDefault(),h())}}),a.createElement("div",{className:"ps-prompt-actions"},d?a.createElement(a.Fragment,null,a.createElement("input",{ref:o,type:"file",accept:"image/*",multiple:!0,className:"ps-hidden-file-input","aria-hidden":!0,tabIndex:-1,onChange:b=>{f(b.currentTarget.files),b.currentTarget.value=""}}),a.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&&!I?a.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:y},x?"Delete":"Cancel"):null,i.canStopTurn||m?a.createElement("button",{type:"button",className:`ps-stop-button${m?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:m,onClick:S},"■"):null,a.createElement("button",{type:"button",className:`ps-send-button${e?" is-inline":""}`,title:i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"Send all queued prompts":i.hasOutbox?"Queue prompt behind the pending batch":"Send prompt","aria-label":i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"Send queued prompts":i.hasOutbox?"Queue prompt":"Send prompt",onClick:h},w)))}const iy=1e3;function ce({icon:t,label:e,onClick:s,disabled:n=!1,active:i=!1,className:r="ps-toolbar-button"}){const[o,l]=a.useState(null),c=a.useRef(null),d=a.useRef(null),u=a.useRef(null),p=a.useRef(!1);a.useLayoutEffect(()=>{if(!o||!d.current||typeof window>"u")return;const k=d.current.offsetWidth/2,M=6,N=Math.max(k+M,Math.min(o.x,window.innerWidth-k-M));d.current.style.left=`${N}px`},[o]);const f=(k=!1)=>{const M=c.current;if(!M||typeof window>"u")return;const N=M.getBoundingClientRect(),B=k?N.top-44<0:N.bottom+44<window.innerHeight;l({x:N.left+N.width/2,y:B?N.bottom+6:N.top-6,placement:B?"below":"above"})},h=a.useRef(null),m=a.useRef(null),g=k=>{k.pointerType==="mouse"&&(clearTimeout(u.current),clearTimeout(h.current),u.current=setTimeout(f,iy))},S=k=>{k.pointerType==="mouse"&&(clearTimeout(u.current),clearTimeout(h.current),l(null))},y=k=>{k.pointerType!=="mouse"&&(p.current=!1,m.current={x:k.clientX,y:k.clientY},clearTimeout(u.current),clearTimeout(h.current),u.current=setTimeout(()=>{p.current=!0,f(!0)},450))},w=k=>{if(k.pointerType==="mouse"||!m.current)return;const M=k.clientX-m.current.x,N=k.clientY-m.current.y;M*M+N*N>100&&(m.current=null,clearTimeout(u.current),l(null))},x=k=>{k.pointerType!=="mouse"&&(m.current=null,clearTimeout(u.current),p.current?(clearTimeout(h.current),h.current=setTimeout(()=>l(null),3e3),setTimeout(()=>{p.current=!1},250)):l(null))};a.useEffect(()=>()=>{clearTimeout(u.current),clearTimeout(h.current)},[]);const I=k=>{if(p.current){p.current=!1,k.preventDefault?.();return}n||s?.(k)},E=k=>{k.preventDefault?.()},b=o&&typeof document<"u"&&document.body?Sl.createPortal(a.createElement("span",{ref:d,className:`ps-icon-tooltip is-${o.placement}`,role:"tooltip",style:{left:`${o.x}px`,top:`${o.y}px`}},e),document.body):null;return a.createElement("button",{ref:c,type:"button",className:`${r} ps-icon-button${i?" is-active":""}`,onClick:I,disabled:n,"aria-label":e,onPointerEnter:g,onPointerLeave:S,onPointerDown:y,onPointerMove:w,onPointerUp:x,onPointerCancel:x,onContextMenu:E},a.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),b)}function ry({controller:t,mobile:e,chatFocusMode:s=!1,onToggleChatFocus:n=null,chatFocusDisabled:i=!1}){const[r,o]=a.useState(null);a.useEffect(()=>{typeof document>"u"||o(e?null:document.getElementById("ps-header-toolbar-slot"))},[e]);const l=ee(t,f=>!!f.admin?.visible),c=ee(t,f=>({mode:f.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]?.isGroup)}),Ue),d=[{key:"new",icon:a.createElement(_g),label:"New session — choose model and agent",onClick:()=>t.handleCommand(A.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:a.createElement(ji),label:"Filter sessions",onClick:()=>t.handleCommand(A.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:a.createElement(Rg),label:"Theme",onClick:()=>t.handleCommand(A.OPEN_THEME_PICKER).catch(()=>{})},{key:"summary",icon:a.createElement(c.mode==="summary"?Pg:Ng),label:c.activeSessionIsGroup?"Groups show group details":c.mode==="summary"?"Show chat transcript":"Show summary",onClick:()=>t.setChatViewMode(c.mode==="summary"?"transcript":"summary"),disabled:c.activeSessionIsGroup,active:c.mode==="summary"},...n?[{key:"focus",icon:a.createElement(s?Ui:Kl),label:s?"Exit focus mode":"Focus the chat pane",onClick:n,disabled:i,active:s}]:[],...e?[]:[{key:"admin",icon:a.createElement($g),label:l?"Close admin console":"Admin console",onClick:()=>t.handleCommand(l?A.CLOSE_ADMIN_CONSOLE:A.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:l}]],u=f=>a.createElement(ce,{key:f.key,icon:f.icon,label:f.label,onClick:f.onClick,disabled:!!f.disabled,active:!!f.active});if(e)return a.createElement("div",{className:"ps-toolbar is-mobile"},a.createElement("div",{className:"ps-toolbar-row ps-toolbar-row-primary"},a.createElement("div",{className:"ps-toolbar-row-actions"},d.map(u))));const p=a.createElement("div",{className:"ps-toolbar"},a.createElement("div",{className:"ps-toolbar-actions"},d.map(u)));return r?Sl.createPortal(p,r):p}function oy({controller:t,paneAdjust:e=0}){const s=a.useRef(null),[n,i]=a.useState(!1);return a.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")};let o=0,l=0;const c=()=>{o=0;const u=s.current;if(!u)return;const p=Math.round((l-u.startX)/bl),f=p-u.appliedCells;f&&(t.adjustPaneSplit(f),u.appliedCells=p)},d=u=>{s.current&&(l=u.clientX,!o&&(o=requestAnimationFrame(c)))};return window.addEventListener("pointermove",d),window.addEventListener("pointerup",r),window.addEventListener("pointercancel",r),()=>{o&&(cancelAnimationFrame(o),o=0),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",r),window.removeEventListener("pointercancel",r),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),a.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(()=>{}))}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function ay({controller:t,portalSessionColumnAdjust:e=0}){const s=a.useRef(null),[n,i]=a.useState(!1);return a.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")},o=l=>{const c=s.current;if(!c)return;const d=Jn(c.startAdjust+(l.clientX-c.startX),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:d})};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]),a.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"),l=Zn(o?.getBoundingClientRect?.().width);s.current={startX:r.clientX,startAdjust:Number(e)||0,minAdjust:l.minAdjust,maxAdjust:l.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"),l=Zn(o?.getBoundingClientRect?.().width),c=d=>{const u=Jn((Number(e)||0)+d,l.minAdjust,l.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:u})};if(r.key==="ArrowLeft"){r.preventDefault(),c(-24);return}r.key==="ArrowRight"&&(r.preventDefault(),c(24))}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function ly({controller:t,activityPaneAdjust:e=0}){const s=a.useRef(null),[n,i]=a.useState(!1);return a.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-y")},o=l=>{const c=s.current;if(!c)return;const d=Math.round((l.clientY-c.startY)/wl),u=d-c.appliedCells;u&&(t.adjustActivityPaneSplit(-u),c.appliedCells=d)};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]),a.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))}},a.createElement("span",{className:"ps-row-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-row-resizer-dot"}),a.createElement("span",{className:"ps-row-resizer-dot"}),a.createElement("span",{className:"ps-row-resizer-dot"})))}function cy({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 a.createElement("div",{className:"ps-mobile-nav"},n.map(i=>a.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 uy({controller:t}){const e=ee(t,y=>y.ui.themeId),s=ee(t,y=>!!y.ui.touchScale),n=st(e),i=ee(t,y=>({rawModal:y.ui.modal,themePicker:mf(y),modelPicker:Hp(y),reasoningEffortPicker:jp(y),contextTierPicker:Up(y),sessionAgentPicker:Gp(y),sessionGroupPicker:Wp(y),sessionGroupName:zp(y),artifactPicker:Qp(y),logFilter:Yp(y),filesFilter:Xp(y),historyFormat:hf(y),renameSession:Kp(y),sessionOwnerFilter:qp(y),artifactUpload:Vp(y),confirm:gf(y),logsFilter:y.logs.filter,filesFilterState:y.files.filter,historyFormatState:y.executionHistory?.format||"pretty"}),Ue),r=i.rawModal,o=a.useRef(null),l=a.useRef(null),c=a.useRef(null),[d,u]=a.useState(""),p=r?.type==="sessionOwnerFilter";if(a.useEffect(()=>{p||u("")},[p]),a.useEffect(()=>{if(r?.type!=="renameSession"||!i.renameSession)return;const y=o.current;if(y){if(document.activeElement!==y)try{y.focus({preventScroll:!0})}catch{y.focus()}y.setSelectionRange(i.renameSession.cursorIndex,i.renameSession.cursorIndex)}},[r?.type,i.renameSession?.cursorIndex,i.renameSession?.value]),a.useEffect(()=>{if(r?.type!=="sessionGroupName"||!i.sessionGroupName)return;const y=l.current;if(y){if(document.activeElement!==y)try{y.focus({preventScroll:!0})}catch{y.focus()}y.setSelectionRange(i.sessionGroupName.cursorIndex,i.sessionGroupName.cursorIndex)}},[r?.type,i.sessionGroupName?.cursorIndex,i.sessionGroupName?.value]),a.useEffect(()=>{if(!r||!["themePicker","modelPicker","reasoningEffortPicker","contextTierPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(r.type))return;const y=c.current;if(!y)return;const w=y.querySelector(".ps-list-button.is-selected");w&&typeof w.scrollIntoView=="function"&&w.scrollIntoView({block:"nearest"})},[r?.type,r?.selectedIndex,i.themePicker?.selectedRowIndex,i.modelPicker?.selectedRowIndex,i.reasoningEffortPicker?.selectedRowIndex,i.contextTierPicker?.selectedRowIndex,i.sessionAgentPicker?.selectedRowIndex,i.sessionGroupPicker?.selectedRowIndex,i.artifactPicker?.selectedRowIndex,i.sessionOwnerFilter?.selectedRowIndex,i.logFilter?.selectedRowIndex,i.filesFilter?.selectedRowIndex,i.historyFormat?.selectedRowIndex]),!r)return null;const f=()=>t.handleCommand(A.CLOSE_MODAL).catch(()=>{}),h=()=>a.createElement("label",{className:"ps-modal-toggle",title:"Larger type and bigger hit targets, for phones and touch screens."},a.createElement("input",{type:"checkbox",checked:s,onChange:y=>t.dispatch({type:"ui/touchScale",enabled:y.target.checked})}),a.createElement("span",null,"Mobile")),m=(y,w="Apply",x=null)=>{const I=Array.isArray(y.rows)?y.rows:[],E=Array.isArray(y.rowItemIndexes)?y.rowItemIndexes:null,b=r.type==="modelPicker"||r.type==="reasoningEffortPicker"||r.type==="contextTierPicker"||r.type==="sessionAgentPicker",k=E&&E.length===I.length?I.map((M,N)=>{const B=E[N],_=Array.isArray(M)?M:Me([M])[0]?.runs||[{text:M?.text||"",color:M?.color}];if(B==null||B<0)return a.createElement("div",{key:`row:${N}`,className:"ps-line ps-modal-list-heading-line"},a.createElement(Pe,{runs:_,theme:n}));const P=r.items?.[B];return a.createElement("button",{key:P?.id||`row:${N}`,type:"button",className:`ps-list-button ps-modal-list-button${B===r.selectedIndex?" is-selected":""}${b?" is-hanging":""}${P?.disabled?" is-disabled":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:B}),P?.kind==="section"&&t.toggleAgentPickerSection(P.sectionKey)}},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Pe,{runs:_,theme:n})))}):(r.items||[]).flatMap((M,N,B)=>{const _=a.createElement("button",{key:M.id||N,type:"button",className:`ps-list-button ps-modal-list-button${N===r.selectedIndex?" is-selected":""}${b?" is-hanging":""}${M?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:N})},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Pe,{runs:Array.isArray(I?.[N])?I[N]:Me([I?.[N]])[0]?.runs||[{text:I?.[N]?.text||"",color:I?.[N]?.color}],theme:n})));return M?.group&&M.group!==B[N-1]?.group?[a.createElement("div",{key:`group:${M.group}`,className:"ps-modal-list-group","aria-hidden":"true"},M.group),_]:[_]});return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:`ps-modal is-list${r.type==="themePicker"?" is-theme-picker":""}`,onClick:M=>M.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},y.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:c,className:"ps-modal-list"},k),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),Me(y.detailsLines||[]).map((M,N)=>a.createElement(Ne,{key:`detail:${N}`,line:M,theme:n,className:"ps-modal-detail-line"})))),a.createElement("div",{className:"ps-modal-footer"},x,a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(A.MODAL_CONFIRM).catch(()=>{})},w))))};if(r.type==="confirm"&&i.confirm){const y=!!r.alert,w=!y&&r.action==="deleteSession",x=r.action==="regenerateSession",I=r.extras||{};return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:E=>E.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},i.confirm.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},a.createElement("p",{style:{color:"#94a3b8",margin:0}},i.confirm.message)),x?a.createElement("div",{className:"ps-modal-body",style:{padding:"0 20px 12px",display:"flex",flexDirection:"column",gap:10}},a.createElement("label",{style:{color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8}},"Distillation",a.createElement("select",{className:"ps-modal-input",style:{flex:"1",padding:"4px 8px"},value:I.distillMode||"llm",onChange:E=>t.updateConfirmExtras({distillMode:E.currentTarget.value})},a.createElement("option",{value:"llm"},"Intelligent (LLM reads the whole transcript)"),a.createElement("option",{value:"deterministic"},"Fast (no LLM — tail + pointers)"))),(I.distillMode||"llm")==="llm"?a.createElement(dy,{controller:t,extras:I}):null,(I.distillMode||"llm")==="llm"?a.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:I.instructions||"",maxLength:4e3,onChange:E=>t.updateConfirmExtras({instructions:E.currentTarget.value})}):null):null,a.createElement("div",{className:"ps-modal-footer"},y?null:a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:`ps-modal-button ${w?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(A.MODAL_CONFIRM).catch(()=>{})},i.confirm.confirmLabel))))}if(r.type==="themePicker"&&i.themePicker)return m(i.themePicker,"Apply Theme",h());const g=r.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(r.type==="modelPicker"&&i.modelPicker)return m(i.modelPicker,g);if(r.type==="reasoningEffortPicker"&&i.reasoningEffortPicker)return m(i.reasoningEffortPicker,g);if(r.type==="contextTierPicker"&&i.contextTierPicker)return m(i.contextTierPicker,g);if(r.type==="sessionAgentPicker"&&i.sessionAgentPicker){const y=r.items?.[r.selectedIndex||0],w=y?.kind==="section"?y.collapsed?"Open":"Close":"Create Session";return m(i.sessionAgentPicker,w)}if(r.type==="sessionGroupPicker"&&i.sessionGroupPicker)return m(i.sessionGroupPicker,"Move");if(r.type==="artifactPicker"&&i.artifactPicker)return m(i.artifactPicker,i.artifactPicker.confirmLabel||"Open / Download");if(r.type==="sessionOwnerFilter"&&i.sessionOwnerFilter){const y=i.sessionOwnerFilter,w=Array.isArray(y.rows)?y.rows:[],x=d.trim().toLowerCase(),I=b=>{const k=w?.[b];return(Array.isArray(k)?k:Me([k])[0]?.runs||[]).map(N=>N?.text||"").join("")||String(k?.text||"")},E=(r.items||[]).map((b,k)=>k).filter(b=>{if(!x)return!0;const k=(r.items||[])[b]||{};return`${I(b)} ${k.label||""} ${k.description||""}`.toLowerCase().includes(x)});return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-list",onClick:b=>b.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},y.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{className:"ps-modal-input ps-modal-search",value:d,placeholder:"Search people…",autoFocus:!0,onChange:b=>u(b.currentTarget.value),onKeyDown:b=>{b.key==="Escape"&&d&&(b.stopPropagation(),u(""))}}),a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:c,className:"ps-modal-list"},E.length===0?a.createElement("div",{className:"ps-empty-state"},`No one matches "${d}".`):null,E.map(b=>(k=>a.createElement("button",{key:k.id||b,type:"button",className:`ps-list-button ps-modal-list-button${b===r.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(b)},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Pe,{runs:Array.isArray(w?.[b])?w[b]:Me([w?.[b]])[0]?.runs||[{text:w?.[b]?.text||"",color:w?.[b]?.color}],theme:n}))))((r.items||[])[b]||{}))),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),Me(y.detailsLines||[]).map((b,k)=>a.createElement(Ne,{key:`detail:${k}`,line:b,theme:n,className:"ps-modal-detail-line"})))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:f},"Done"))))}if(r.type==="renameSession"&&i.renameSession)return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},i.renameSession.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{ref:o,className:"ps-modal-input",value:i.renameSession.value,placeholder:i.renameSession.placeholder,onChange:y=>t.setRenameSessionValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),t.handleCommand(A.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Me(i.renameSession.helpLines||[]).map((y,w)=>a.createElement(Ne,{key:`help:${w}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(A.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(r.type==="sessionGroupName"&&i.sessionGroupName)return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},i.sessionGroupName.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{ref:l,className:"ps-modal-input",value:i.sessionGroupName.value,placeholder:i.sessionGroupName.placeholder,onChange:y=>t.setSessionGroupNameValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),t.handleCommand(A.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Me(i.sessionGroupName.helpLines||[]).map((y,w)=>a.createElement(Ne,{key:`help:${w}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(A.MODAL_CONFIRM).catch(()=>{})},"Create and Move"))));if(r.type==="terminatePicker"){const y=Number(r.bulkCount)>1,w=!!r.systemRestart,x=String(r.sessionTitle||"").trim()||"this session",I=Number(r.bulkCount)||0,E=y?`What should happen to the ${I} selected sessions? Choose an action; you'll be asked to confirm.`:w?`How should "${x}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${x}"? Choose an action; you'll be asked to confirm.`,b=k=>()=>{t.pickTerminateAction(k).catch(()=>{})};return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:k=>k.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},r.title||"Session Lifecycle"),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},a.createElement("p",{style:{color:"#94a3b8",margin:0}},E)),a.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},r.canRegenerate?a.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:b("regenerate")},"Regenerate Context"):null,a.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:b("complete")},y?`Mark ${I} Completed`:w?"Complete & Restart":"Mark Completed"),a.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:b("cancel")},y?`Cancel ${I} Sessions`:w?"Terminate & Restart":"Cancel Session"),a.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:b("delete")},y?`Hard Delete ${I} Sessions`:w?"Hard Delete & Restart":"Delete Session")),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Close"))))}if(r.type==="artifactUpload"&&i.artifactUpload)return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},i.artifactUpload.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{className:"ps-modal-input",value:i.artifactUpload.value,placeholder:i.artifactUpload.placeholder,onChange:y=>t.setArtifactUploadValue(y.currentTarget.value,y.currentTarget.selectionStart||y.currentTarget.value.length),autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Me(i.artifactUpload.helpLines||[]).map((y,w)=>a.createElement(Ne,{key:`help:${w}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(A.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const S=r.type==="logFilter"?i.logFilter:r.type==="filesFilter"?i.filesFilter:r.type==="historyFormat"?i.historyFormat:null;return S?a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-wide",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},S.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-filter-grid"},(r.items||[]).map((y,w)=>{const x=r.type==="filesFilter"?i.filesFilterState?.[y.id]||y.options?.[0]?.id:r.type==="historyFormat"?i.historyFormatState:i.logsFilter?.[y.id]||y.options?.[0]?.id;return a.createElement("div",{key:y.id||w,className:"ps-filter-column"},a.createElement("div",{className:"ps-filter-title"},y.label),(y.options||[]).map(I=>a.createElement("button",{key:I.id,type:"button",className:`ps-filter-option${I.id===x?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:w}),r.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:I.id}):r.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[y.id]:I.id}}),t.ensureFilesForScope(I.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[y.id]:I.id}})}},I.label)))})),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:f},"Done")))):null}function dy({controller:t,extras:e}){const s=Array.isArray(e.distillerModelOptions)?e.distillerModelOptions:[],n=s.find(d=>d.qualifiedName===e.distillerModel)||null,i=n?.supportedReasoningEfforts||[],r=n?.supportedContextTiers||[],o={color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8},l={flex:"1",padding:"4px 8px"},c=d=>t.updateConfirmExtras(d);return a.createElement(a.Fragment,null,a.createElement("label",{style:o},"Distiller model",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerModel||"",onChange:d=>c({distillerModel:d.currentTarget.value,distillerEffort:"",distillerContextTier:""})},a.createElement("option",{value:""},"Deployment default"),s.map(d=>a.createElement("option",{key:d.qualifiedName,value:d.qualifiedName},d.qualifiedName)))),i.length>0?a.createElement("label",{style:o},"Reasoning",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerEffort||"",onChange:d=>c({distillerEffort:d.currentTarget.value})},a.createElement("option",{value:""},"Model default"),i.map(d=>a.createElement("option",{key:d,value:d},d)))):null,r.length>0?a.createElement("label",{style:o},"Context",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerContextTier||"",onChange:d=>c({distillerContextTier:d.currentTarget.value})},a.createElement("option",{value:""},"Model default"),r.map(d=>a.createElement("option",{key:d,value:d},d==="long_context"?"long context (fits a larger transcript)":d)))):null)}function py(t,e){a.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,l=Li(t),c=t.getState().ui.inspectorTab,d=t.getState().ui.focusRegion,u=!n.metaKey&&!n.ctrlKey&&!n.altKey,p=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="T"&&n.shiftKey,f=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="N"&&n.shiftKey,h=m=>{const g=sm(l,c,m);t.selectInspectorTab(g).catch(()=>{})};if(!r&&p){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(o.type==="sessionAgentPicker"&&(n.key==="ArrowRight"||n.key==="ArrowLeft")){n.preventDefault(),t.handleCommand(n.key==="ArrowRight"?A.MODAL_PANE_NEXT:A.MODAL_PANE_PREV).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"&&u&&d!=="prompt"){n.preventDefault(),t.handleCommand(A.REFRESH).catch(()=>{});return}if(d==="chat"&&n.key==="s"&&u){n.preventDefault(),t.handleCommand(A.TOGGLE_CHAT_VIEW).catch(()=>{});return}if(n.key==="n"&&u){n.preventDefault(),t.handleCommand(A.NEW_SESSION).catch(()=>{});return}if(d==="inspector"&&c==="files"&&(n.key==="u"&&u||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(A.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="a"&&u){n.preventDefault(),t.handleCommand(A.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="x"&&u){n.preventDefault(),t.handleCommand(A.DELETE_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="o"&&u){n.preventDefault(),t.handleCommand(A.OPEN_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(A.OPEN_FILES_FILTER).catch(()=>{});return}if(d==="inspector"&&c==="stats"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(A.TOGGLE_STATS_VIEW).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="v"&&u){n.preventDefault(),t.handleCommand(A.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(d==="inspector"&&c==="logs"&&n.key==="t"&&u){n.preventDefault(),t.handleCommand(A.TOGGLE_LOG_TAIL).catch(()=>{});return}if(d==="inspector"&&c==="logs"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(A.OPEN_LOG_FILTER).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="f"&&u){n.preventDefault(),t.handleCommand(A.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="r"&&u){n.preventDefault(),t.handleCommand(A.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="a"&&u){n.preventDefault(),t.handleCommand(A.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&u){n.preventDefault(),t.handleCommand(A.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&u){n.preventDefault(),t.handleCommand(A.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&u){n.preventDefault(),t.handleCommand(A.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&u){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"&&u&&d==="inspector"){n.preventDefault(),h(1);return}if(n.key==="["&&u){n.preventDefault(),t.handleCommand(A.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&u){n.preventDefault(),t.handleCommand(A.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&u){n.preventDefault(),t.handleCommand(A.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&u){n.preventDefault(),t.handleCommand(A.GROW_SESSION_PANE).catch(()=>{});return}if(d==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),h(-1);return}if(d==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),h(1);return}if(d==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(A.MOVE_SESSION_UP).catch(()=>{});return}if(d==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(A.MOVE_SESSION_DOWN).catch(()=>{});return}if(d==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(A.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(d==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(A.PAGE_UP).catch(()=>{});return}if(d==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(A.PAGE_DOWN).catch(()=>{});return}if(d==="sessions"&&n.key==="t"&&u){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"&&u){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(d!=="prompt"&&n.key==="h"&&u){n.preventDefault(),t.handleCommand(A.FOCUS_LEFT).catch(()=>{});return}if(d!=="prompt"&&n.key==="l"&&u){n.preventDefault(),t.handleCommand(A.FOCUS_RIGHT).catch(()=>{});return}if(!e&&d==="inspector"&&c==="files"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(A.MOVE_FILE_UP).catch(()=>{});return}if(!e&&d==="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 fy(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 hy({controller:t,mobile:e=!1}){const s=ee(t,cp,Ue),n=a.useRef(null),i=s.packages||{},r=s.section==="packages",o=s.section==="workers",[l,c]=a.useState(()=>{const N={wsWidth:440,treePct:44,navWidth:240};try{return{...N,...JSON.parse(window.localStorage.getItem("ps-admin-ws-layout")||"{}")}}catch{return N}}),d=a.useCallback(N=>{c(B=>{const _={...B,...N};_.wsWidth=Math.min(900,Math.max(300,Math.round(_.wsWidth))),_.treePct=Math.min(85,Math.max(15,_.treePct)),_.navWidth=Math.min(420,Math.max(170,Math.round(_.navWidth??240)));try{window.localStorage.setItem("ps-admin-ws-layout",JSON.stringify(_))}catch{}return _})},[]),u=a.useCallback(N=>{N.preventDefault(),document.body.style.cursor="col-resize";const B=N.clientX,_=l.navWidth??240,P=K=>d({navWidth:_+(K.clientX-B)}),j=()=>{window.removeEventListener("pointermove",P),window.removeEventListener("pointerup",j),window.removeEventListener("pointercancel",j),document.body.style.cursor=""};window.addEventListener("pointermove",P),window.addEventListener("pointerup",j),window.addEventListener("pointercancel",j)},[l.navWidth,d]);a.useEffect(()=>{if(s.ghcpKey.editing){const N=window.requestAnimationFrame(()=>{n.current&&n.current.focus()});return()=>window.cancelAnimationFrame(N)}},[s.ghcpKey.editing]);const p=a.useCallback(()=>{t.closeAdminConsole()},[t]),f=a.useCallback(()=>{t.refreshAdminProfile().catch(()=>{})},[t]),h=a.useCallback(()=>{t.beginAdminEditGhcpKey()},[t]),m=a.useCallback(()=>{t.cancelAdminEditGhcpKey()},[t]),g=a.useCallback(()=>{t.clearAdminGhcpKey().catch(()=>{})},[t]),S=a.useCallback(N=>{N.preventDefault(),t.saveAdminGhcpKey().catch(()=>{})},[t]),y=a.useCallback(N=>{t.setAdminGhcpKeyDraft(N.target.value)},[t]),w=fy(s.principal),x=a.createElement("header",{className:"ps-admin-console__header"},a.createElement("h2",null,"Admin Console"),a.createElement("span",{className:"ps-admin-console__who"},w),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:p},"Close")),I=a.createElement(Iy,{view:s,draftRef:n,onBeginEdit:h,onCancelEdit:m,onClear:g,onSubmit:S,onDraftChange:y,onRefresh:f,controller:t}),E=a.createElement(my,{controller:t,view:s}),b=a.createElement(gy,{controller:t,view:s}),k=r&&i.selectedName?a.createElement(yy,{controller:t,view:s,layout:l,onLayout:d}):null,M=i.addDialog?.open?a.createElement(wy,{controller:t,dialog:i.addDialog}):null;if(e){let N;return r&&i.selectedName?N=a.createElement("div",{className:"ps-admin-mobile-stack"},a.createElement("button",{type:"button",className:"ps-mini-button ps-admin-back",onClick:()=>t.selectAdminPackage(null)},"← All packages"),b,k):r?N=E:o?N=a.createElement("div",{className:"ps-admin-mobile-stack"},E,a.createElement(Ho,{controller:t,view:s})):N=a.createElement("div",{className:"ps-admin-mobile-stack"},E,I),a.createElement("div",{className:"ps-admin-console is-mobile"},x,s.loadError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,N,M)}return a.createElement("div",{className:"ps-admin-console is-workspace"},x,s.loadError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,a.createElement("div",{className:"ps-admin-workspace",style:k?{gridTemplateColumns:`${l.navWidth}px minmax(0, 1fr) minmax(0, ${l.wsWidth}px)`}:{gridTemplateColumns:`${l.navWidth}px minmax(0, 1fr)`}},a.createElement("div",{className:"ps-admin-nav"},E,a.createElement("div",{className:"ps-admin-nav__resize",onPointerDown:u,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings column"})),a.createElement("div",{className:"ps-admin-main"},r?b:o?a.createElement(Ho,{controller:t,view:s}):I),k),M)}function Ho({controller:t,view:e}){const s=e.workers||{},n=s.rows||[],i=s.counts||{};return a.useEffect(()=>{const r=window.setInterval(()=>{t.refreshAdminWorkers()},25e3);return()=>window.clearInterval(r)},[t]),a.createElement("div",{className:"ps-admin-detail ps-admin-workers"},a.createElement("div",{className:"ps-admin-workers__head"},a.createElement("h3",null,"Workers"),s.summaryText?a.createElement("span",{className:"ps-admin-workers__summary"},`${s.summaryText}${i.pools>1?` · ${i.pools} pools`:""}${i.draining?` · ${i.draining} draining`:""}`):null,a.createElement("button",{type:"button",className:"ps-mini-button",disabled:!!s.loading,onClick:()=>t.refreshAdminWorkers()},s.loading?"Refreshing…":"Refresh")),s.error?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.error):null,s.empty?a.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."):a.createElement("div",{className:"ps-admin-workers__scroll"},a.createElement("table",{className:"ps-admin-workers__table"},a.createElement("thead",null,a.createElement("tr",null,["Worker","Pool","Phase","Heartbeat","Uptime","RSS","Sessions","Loop p99","Packages","SDK"].map(r=>a.createElement("th",{key:r},r)))),a.createElement("tbody",null,n.map(r=>a.createElement("tr",{key:r.id,className:r.live?"is-live":"is-stale"},a.createElement("td",{className:"ps-admin-workers__id",title:r.owner?`owner: ${r.owner}`:void 0},a.createElement("span",{className:`ps-worker-dot${r.live?" is-live":""}`}),r.id,r.substrate&&r.substrate!=="kubernetes"?a.createElement("span",{className:"ps-admin-workers__substrate"},r.substrate):null),a.createElement("td",null,r.pool),a.createElement("td",null,a.createElement("span",{className:`ps-worker-phase is-${r.phase}`},r.phase)),a.createElement("td",null,r.agoText),a.createElement("td",null,r.uptimeText??"—"),a.createElement("td",null,r.rssText??"—"),a.createElement("td",null,r.sessions??"—"),a.createElement("td",null,r.eventLoopText??"—"),a.createElement("td",{title:r.pkgEpoch!=null?`epoch ${r.pkgEpoch}`:void 0},r.pkgText??"—"),a.createElement("td",null,r.sdkVersion??"—")))))))}function my({controller:t,view:e}){const s=e.packages||{};return a.createElement("nav",{className:"ps-admin-tree"},a.createElement("div",{className:"ps-admin-tree__label"},"Settings"),(e.settingsTree||[]).map(n=>{if(n.kind==="group")return a.createElement("div",{key:n.id,className:"ps-admin-tree__group"},`${n.label}`,a.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 a.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?a.createElement(ti,{badge:n.ownerBadge}):a.createElement("span",{className:"ps-scope-badge is-shared",title:"shared with the whole deployment"},"S"):null,a.createElement("span",{className:"ps-admin-tree__name"},n.label),n.kind==="package"&&n.semver?a.createElement("span",{className:"ps-admin-tree__ver"},n.semver):null)}),s.loading?a.createElement("div",{className:"ps-admin-tree__hint"},"Loading packages…"):null,s.error?a.createElement("div",{className:"ps-admin-tree__hint is-error"},s.error):null,a.createElement("button",{type:"button",className:"ps-admin-tree__add",onClick:()=>t.openAdminAddPackage()},"+ Add package"))}function gy({controller:t,view:e}){const s=e.packages||{},n=s.detail;if(!s.selectedName)return a.createElement("div",{className:"ps-admin-detail is-empty"},a.createElement("h3",null,"Agents"),a.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=(l,c)=>()=>t.runAdminPackageAction(l,c),o=n.actionPending;return a.createElement("div",{className:"ps-admin-detail"},n.error?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},`Package load failed: ${n.error}`):null,n.loading?a.createElement("p",{className:"ps-admin-console__hint"},"Loading package…"):null,a.createElement("div",{className:"ps-admin-detail__head"},a.createElement("h3",null,n.name),a.createElement("span",{className:`ps-scope-badge is-${n.scope}`},n.scope),n.enabled?null:a.createElement("span",{className:"ps-scope-badge is-off"},"disabled")),n.description?a.createElement("p",{className:"ps-admin-detail__desc"},n.description):null,a.createElement("dl",{className:"ps-admin-detail__meta"},a.createElement("dt",null,"Version"),a.createElement("dd",null,n.activeSemver?`${n.activeSemver} · sha ${n.activeSha12||"?"} · ${n.sizeText}`:"no active version"),n.fleet?[a.createElement("dt",{key:"fk"},"Fleet"),a.createElement("dd",{key:"fv",className:"is-ok"},n.fleet.text)]:null,a.createElement("dt",null,"Created"),a.createElement("dd",null,`${n.createdBy||"unknown"} · ${n.createdAtText}`)),n.agents.length?a.createElement("div",null,a.createElement("div",{className:"ps-admin-detail__label"},"Agents in this package"),a.createElement("div",{className:"ps-admin-detail__chips"},n.agents.map(l=>a.createElement("span",{key:l.name,className:"ps-agent-chip",title:l.description},l.name,l.toolCount?a.createElement("i",null,` · ${l.toolCount} tools`):null)))):null,n.versions.length?a.createElement("div",null,a.createElement("div",{className:"ps-admin-detail__label"},"Versions"),a.createElement("div",{className:"ps-admin-versions"},n.versions.map(l=>a.createElement("div",{key:l.semver,className:`ps-admin-version${l.active?" is-active":""}`},a.createElement("b",null,l.semver),a.createElement("span",null,l.sha12),a.createElement("span",null,l.dateText),l.active?a.createElement("span",{className:"is-ok"},"● active"):n.canManage?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:r("pin",l.semver),disabled:!!o},"Pin"):null)))):null,n.canManage?a.createElement("div",{className:"ps-admin-detail__actions"},n.source?a.createElement("button",{type:"button",className:"ps-primary-button",onClick:r("sync"),disabled:!!o},o==="sync"?"Syncing…":"Sync now"):null,a.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"),a.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"),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:r(n.enabled?"disable":"enable"),disabled:!!o},n.enabled?"Disable":"Enable"),a.createElement("button",{type:"button",className:"ps-mini-button is-danger",onClick:i,disabled:!!o},"Delete")):a.createElement("p",{className:"ps-admin-console__hint"},"Read-only: only the package creator or an admin can modify it."),n.actionError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},n.actionError):null)}function yy({controller:t,view:e,layout:s=null,onLayout:n=null}){const i=ee(t,p=>p.ui.themeId),r=st(i),o=e.packages?.workspace,l=a.useRef(null),c=a.useCallback((p,f)=>{if(!n)return;p.preventDefault();const h=p.clientX,m=p.clientY,g={...s},S=w=>f(g,w.clientX-h,w.clientY-m),y=()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),document.body.style.cursor=""};window.addEventListener("pointermove",S),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)},[s,n]),d=a.useCallback(p=>{document.body.style.cursor="col-resize",c(p,(f,h)=>n({wsWidth:f.wsWidth-h}))},[c,n]),u=a.useCallback(p=>{document.body.style.cursor="row-resize";const f=l.current?.getBoundingClientRect().height||600;c(p,(h,m,g)=>n({treePct:h.treePct+g/f*100}))},[c,n]);return o?a.createElement("div",{className:"ps-admin-ws",ref:l,style:s?{gridTemplateRows:`auto minmax(80px, ${s.treePct}%) auto minmax(0, 1fr)`}:void 0},n?a.createElement("div",{className:"ps-admin-ws__vdivider",title:"Drag to resize the workspace",onPointerDown:d}):null,a.createElement("div",{className:"ps-admin-ws__head"},`Package workspace${o.semver?` · ${e.packages.selectedName}@${o.semver}`:""}`),a.createElement("div",{className:"ps-admin-ws__tree"},o.loading?a.createElement("div",{className:"ps-admin-tree__hint"},"Loading files…"):null,o.error?a.createElement("div",{className:"ps-admin-tree__hint is-error"},o.error):null,o.treeRows.map(p=>a.createElement("button",{key:`${p.type}:${p.path}`,type:"button",style:{paddingLeft:`${8+(p.depth||0)*16}px`},className:`ps-admin-ws__row is-${p.type}${p.selected?" is-selected":""}`,onClick:p.type==="dir"?()=>t.toggleAdminPackageDir(p.path):()=>t.selectAdminPackageFile(p.path)},a.createElement("span",{className:"ps-admin-ws__caret"},p.type==="dir"?p.expanded?"▾":"▸":""),a.createElement("span",{className:"ps-admin-ws__name"},p.label),p.sizeText?a.createElement("span",{className:"ps-admin-ws__size"},p.sizeText):null))),a.createElement("div",{className:`ps-admin-ws__preview-head${n?" is-resizable":""}`,title:n?"Drag to resize file list vs preview":void 0,onPointerDown:n?u:void 0},o.selectedPath?`Preview · ${o.selectedPath}`:"Preview"),a.createElement("div",{className:"ps-admin-ws__preview"},o.fileLoading?a.createElement("div",{className:"ps-admin-tree__hint"},"Loading…"):null,o.fileError?a.createElement("div",{className:"ps-admin-tree__hint is-error"},o.fileError):null,o.file?o.file.isBinary?a.createElement("div",{className:"ps-admin-tree__hint"},`Binary file · ${o.file.sizeText}`):a.createElement(by,{file:o.file,theme:r}):null)):null}function Sy(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 by({file:t,theme:e}){const s=t.language||"text",n=t.truncated?a.createElement("div",{className:"ps-admin-tree__hint"},"… truncated preview"):null;if(s==="markdown"){const{meta:i,body:r}=Sy(t.text||"");return a.createElement("div",{className:"ps-admin-ws__doc"},i?a.createElement("div",{className:"ps-admin-ws__frontmatter"},i.map(o=>a.createElement("div",{key:o.key,className:"ps-admin-ws__fm-row"},a.createElement("span",{className:"ps-admin-ws__fm-key"},o.key),a.createElement("span",{className:"ps-admin-ws__fm-val"},o.value)))):null,a.createElement(Di,{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 a.createElement("div",{className:"ps-admin-ws__doc"},a.createElement("pre",{className:"ps-admin-ws__code lang-json"},a.createElement("code",null,as(i,"json",e))),n)}return a.createElement("div",{className:"ps-admin-ws__doc"},a.createElement("pre",{className:`ps-admin-ws__code lang-${s}`},a.createElement("code",null,as(t.text||"",s,e))),n)}function wy({controller:t,dialog:e}){const s=ee(t,p=>p.docs?.agentPackageGuideUrl||null),n=p=>f=>t.setAdminAddPackageField(p,f.target.value),i=[["repo","GitHub / Azure DevOps"],["upload","Upload folder"]],r=e.kind==="repo"||e.kind==="github"||e.kind==="ado",o=a.useRef(null),[l,c]=a.useState(!1),d=2*1024*1024,u=p=>{if(p.preventDefault(),!(l||e.submitting)){if(e.kind==="upload"){const f=o.current;if(!f?.files?.length){t.failAdminAddPackage("Choose a package folder first.");return}const h=[...f.files].map(g=>({file:g,path:g.webkitRelativePath.split("/").slice(1).join("/")||g.name})).filter(({path:g})=>g&&!g.split("/").includes("node_modules")&&!g.split("/").includes(".git")),m=h.reduce((g,{file:S})=>g+S.size,0);if(h.length===0){t.failAdminAddPackage("The chosen folder has no uploadable files.");return}if(m>d){t.failAdminAddPackage(`Folder is ${(m/(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(h.map(({file:g,path:S})=>new Promise((y,w)=>{const x=new FileReader;x.onerror=()=>w(new Error(`could not read ${S}`)),x.onload=()=>y({path:S,contentBase64:String(x.result).split(",",2)[1]||""}),x.readAsDataURL(g)}))).then(g=>t.submitAdminUploadPackage(g,e.scope)).catch(g=>t.failAdminAddPackage(g?.message||"Could not read the chosen folder.")).finally(()=>c(!1));return}t.submitAdminAddPackage().catch(()=>{})}};return a.createElement("div",{className:"ps-modal-backdrop",onClick:()=>t.closeAdminAddPackage()},a.createElement("form",{className:"ps-modal ps-admin-add",onClick:p=>p.stopPropagation(),autoComplete:"off",onSubmit:u},a.createElement("div",{className:"ps-modal-header"},a.createElement("span",null,e.updateName?`Update ${e.updateName}`:"Add agent package"),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage()},"✕")),a.createElement("div",{className:"ps-admin-add__body"},a.createElement("div",{className:"ps-admin-add__tabs"},i.map(([p,f])=>a.createElement("button",{key:p,type:"button",className:`ps-admin-add__tab${e.kind===p?" is-on":""}`,onClick:()=>t.setAdminAddPackageField("kind",p)},f))),r?[a.createElement("label",{key:"u",className:"ps-admin-add__field"},"Link to plugin.json (or the folder containing it)",a.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"})),a.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."),a.createElement("label",{key:"t",className:"ps-admin-add__field"},"PAT (only for private GitHub repos, or to override — used here, never stored)",a.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"}))]:a.createElement("label",{className:"ps-admin-add__field"},"Package folder with plugin.json — the manifest (≤ 2 MB; node_modules skipped)",a.createElement("input",{ref:o,type:"file",webkitdirectory:"",directory:"",multiple:!0})),a.createElement("div",{className:"ps-admin-add__scope"},a.createElement("label",null,a.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="shared",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","shared")})," Shared — everyone can use it"),a.createElement("label",null,a.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?a.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?a.createElement("p",{className:"ps-admin-console__hint"},"New to this? ",a.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,a.createElement("p",{className:"ps-admin-console__hint"},"Same thing from a terminal: pilotswarm agents push ./my-agents --shared"),e.progress&&!e.error?a.createElement("p",{className:"ps-admin-add__progress"},e.progress):null,e.error?a.createElement("pre",{className:"ps-admin-add__error",role:"alert"},e.error):null),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage(),disabled:e.submitting},"Cancel"),a.createElement("button",{type:"submit",className:"ps-primary-button",disabled:e.submitting||l},l?"Reading folder…":e.submitting?"Importing…":e.updateName?"Import & update":"Import & publish"))))}function Iy({view:t,draftRef:e,onBeginEdit:s,onCancelEdit:n,onClear:i,onSubmit:r,onDraftChange:o,onRefresh:l,controller:c}){return a.createElement("section",{className:"ps-admin-console__section"},a.createElement("h3",null,"GitHub Copilot key"),t.ghcpKey.storeAsSystem?a.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."):a.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?a.createElement("label",{className:"ps-admin-console__system-toggle"},a.createElement("input",{type:"checkbox",checked:t.ghcpKey.storeAsSystem,disabled:t.ghcpKey.saving,onChange:d=>c.setAdminGhcpKeyStoreAsSystem(d.target.checked)}),"Store as System key"):null,a.createElement("p",{className:`ps-admin-console__status${t.ghcpKey.error?" is-error":""}`},t.ghcpKey.error||t.ghcpKey.statusText),t.ghcpKey.editing?a.createElement("form",{className:"ps-admin-console__form",onSubmit:r},a.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}),a.createElement("div",{className:"ps-admin-console__actions"},a.createElement("button",{type:"submit",className:"ps-primary-button",disabled:t.ghcpKey.saving},t.ghcpKey.saving?"Saving...":"Save"),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:n,disabled:t.ghcpKey.saving},"Cancel"))):a.createElement("div",{className:"ps-admin-console__actions"},a.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?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:i},t.ghcpKey.storeAsSystem?"Clear System key":"Clear key"):null,a.createElement("button",{type:"button",className:"ps-mini-button",onClick:l},t.loading?"Refreshing...":"Refresh")))}function xy({transport:t,mode:e="remote",branding:s=null,docs:n=null}={}){fm();const i=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches,r=Lf(Of,Gn({mode:e,branding:s,docs:n,chatViewMode:i?"transcript":"rich"}));return new Ph({store:r,transport:t})}function vy({controller:t}){const e=a.useRef(null),s=a.useRef(null),n=Io(e),i=Io(s),r=Em(n);a.useEffect(()=>{const L=()=>{const H=document.createElement("span");H.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const Q=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");Q&&(H.style.font=window.getComputedStyle(Q).font),H.textContent="0".repeat(100),(Q?.parentElement||document.body).appendChild(H);const Y=H.getBoundingClientRect().width/100||8;H.remove(),t.dispatch({type:"ui/viewport",width:Math.floor(window.innerWidth/Y),height:Math.floor(window.innerHeight/et)})};L();let R;const C=()=>{clearTimeout(R),R=setTimeout(L,150)};return window.addEventListener("resize",C),window.addEventListener("orientationchange",C),()=>{clearTimeout(R),window.removeEventListener("resize",C),window.removeEventListener("orientationchange",C)}},[t]);const[o,l]=a.useState(!1),[c,d]=a.useState(null),u=ee(t,L=>({themeId:L.ui.themeId,touchScale:!!L.ui.touchScale,ownerFilter:L.sessions.ownerFilter,pinnedIds:L.sessions.pinnedIds,manualOrder:L.sessions.manualOrder,collapsedSessionIds:L.sessions.collapsedIds,activeSessionId:L.sessions.activeSessionId||null,promptRows:kl(L),chatViewMode:L.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(L.sessions.activeSessionId&&L.sessions.byId[L.sessions.activeSessionId]?.isGroup),paneAdjust:L.ui.layout?.paneAdjust??0,sessionPaneAdjust:L.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:L.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:L.ui.layout?.activityPaneAdjust??0,focusRegion:L.ui.focusRegion,inspectorTab:L.ui.inspectorTab,filesFullscreen:!!L.files.fullscreen,selectedArtifactId:L.files.selectedArtifactId||null,adminVisible:!!L.admin?.visible}),Ue),p=a.useRef(!1),f=a.useRef(null),h=a.useRef(null),m=a.useRef(null),g=a.useRef(null),S=a.useRef(!1),y=a.useRef(!1),w=a.useRef(null),x=a.useRef(null),[I,E]=a.useState("workspace"),b=(n.width||window.innerWidth||0)<Kh,M=u.activeSessionIsGroup||u.chatViewMode==="summary"?0:u.promptRows;py(t,b),a.useEffect(()=>{t.setViewport(r)},[t,r.height,r.width]),a.useEffect(()=>{let L=!0;p.current=!1,f.current=null,w.current=null,x.current=So(t.getState()),m.current&&(clearTimeout(m.current),m.current=null),g.current&&(clearInterval(g.current),g.current=null),S.current=!1,y.current=!1;const R=t.transport;if(typeof R?.getCurrentUserProfile!="function"||typeof R?.setCurrentUserProfileSettings!="function")return p.current=!0,()=>{L=!1};const C=async()=>{if(!(!L||S.current)){S.current=!0;try{const H=await R.getCurrentUserProfile();if(!L)return;const Q=gt(H?.profileSettings);os(Q[zs()])&&(h.current=Q[zs()]),x.current=So(t.getState(),h.current);const Y=mm(H?.profileSettings,x.current),le=JSON.stringify(Y),ye=Pn(t.getState(),h.current),we=JSON.stringify(ye),Ie=p.current&&f.current!=null&&we!==f.current,Fe=!!m.current||y.current||Ie;if(!Fe&&w.current!==le&&(t.dispatch({type:"profileSettings/apply",settings:Y}),w.current=le),!p.current||!Fe){const U=Pn(t.getState(),h.current);f.current=JSON.stringify(U)}p.current=!0}catch{if(!L)return;p.current=!0}finally{S.current=!1}}};return C().catch(()=>{}),g.current=setInterval(()=>{C().catch(()=>{})},Qh),()=>{L=!1,m.current&&(clearTimeout(m.current),m.current=null),g.current&&(clearInterval(g.current),g.current=null),S.current=!1}},[t]),a.useEffect(()=>{if(!p.current)return;const L=Pn(u,h.current),R=JSON.stringify(L);f.current!==R&&(f.current=R,m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{m.current=null,y.current=!0,gm(t,L).catch(()=>{}).finally(()=>{y.current=!1})},400))},[t,u.activeSessionId,u.activityPaneAdjust,u.chatViewMode,u.collapsedSessionIds,u.ownerFilter,u.paneAdjust,u.manualOrder,u.pinnedIds,u.portalSessionColumnAdjust,u.sessionPaneAdjust,u.themeId,u.touchScale]),a.useEffect(()=>{Im(u.themeId),wm(u.touchScale)},[u.themeId,u.touchScale]);const N=a.useRef(null);a.useEffect(()=>{const L=N.current;N.current=u.focusRegion,L!==null&&L!==u.focusRegion&&b&&u.focusRegion!=="prompt"&&E(u.focusRegion==="activity"?"activity":u.focusRegion==="inspector"?"inspector":"workspace")},[b,u.focusRegion]),a.useEffect(()=>{const L=Li(t);!L.includes(u.inspectorTab)&&L.length>0&&t.selectInspectorTab(L[0]).catch(()=>{})},[t,u.inspectorTab]);const B=a.useMemo(()=>ns(r,u.paneAdjust,M,u.sessionPaneAdjust,u.activityPaneAdjust),[r,u.activityPaneAdjust,u.paneAdjust,M,u.sessionPaneAdjust]),_=u.filesFullscreen&&u.inspectorTab==="files",P=u.inspectorTab==="files"&&!!u.selectedArtifactId&&!_;a.useEffect(()=>{!_||!o||(l(!1),d(null))},[o,_]);const j=a.useCallback(()=>{l(L=>{const R=!L;return R?t.setFocus("chat"):d(null),R})},[t]),K=a.useCallback(L=>{d(R=>{const C=R===L?null:L;return t.setFocus(C||"chat"),C})},[t]),z=Math.max(0,(n.width||0)*.68),se=i.width||z,ne=ym(se,u.portalSessionColumnAdjust),ve=Sm(ne),oe=ve==="hidden"?"0px":`clamp(0px, calc(${Oi*100}% + ${Number(u.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,be=a.createElement("div",{className:"ps-workspace-grid",style:{gridTemplateColumns:`minmax(0, ${B.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${B.rightWidth}fr)`}},a.createElement("div",{ref:s,className:`ps-workspace-main-grid is-session-${ve}`,style:{gridTemplateColumns:`${oe} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},ve!=="hidden"?a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},a.createElement(Gi,{controller:t,structuredRows:!0})):null,a.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},a.createElement(ay,{controller:t,portalSessionColumnAdjust:u.portalSessionColumnAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},a.createElement(Wi,{controller:t}))),a.createElement(oy,{controller:t,paneAdjust:u.paneAdjust}),a.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`${B.inspectorPaneHeight}fr var(--ps-resizer-track, 16px) ${B.activityPaneHeight}fr`}},a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},B.inspectorHidden?null:a.createElement(vt,{controller:t,mobile:!1})),a.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},a.createElement(ly,{controller:t,activityPaneAdjust:u.activityPaneAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},P?a.createElement(Ki,{controller:t,focused:!1,previewOnly:!0}):B.activityHidden?null:a.createElement(As,{controller:t})))),v=a.createElement(sy,{controller:t,openPane:c,onTogglePane:K,onExitFocus:j,mobile:b}),O=a.createElement("div",{className:"ps-workspace-full"},a.createElement(vt,{controller:t,mobile:!1}));let G=null;return _&&!b?G=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(vt,{controller:t,mobile:!0})):I==="inspector"?G=u.inspectorTab==="nodes"?a.createElement("div",{className:"ps-mobile-pane-fill ps-mobile-node-split"},a.createElement(vt,{controller:t,mobile:!0}),a.createElement(As,{controller:t,panelClassName:"ps-mobile-node-detail"})):a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(vt,{controller:t,mobile:!0})):I==="activity"?G=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(As,{controller:t})):G=a.createElement(ey,{controller:t}),a.createElement(_l.Provider,{value:t},a.createElement("div",{ref:e,className:"ps-web-shell"},b&&(o||I==="inspector"||I==="activity")?null:a.createElement(ry,{controller:t,mobile:b,chatFocusMode:o,onToggleChatFocus:j,chatFocusDisabled:_}),a.createElement("div",{className:"ps-workspace"},u.adminVisible?a.createElement(hy,{controller:t,mobile:b}):_?O:o?v:b?G:be),b&&!o?a.createElement(cy,{activePane:I,setActivePane:E,controller:t}):null,b&&_?a.createElement(Zg,{controller:t}):null,a.createElement(uy,{controller:t})))}export{vy as P,a as R,yl as _,Ql as a,st as b,xy as c,up as d,Vl as g,Go as r,Ey as s};
|