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
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
function Gl(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Js={exports:{}},Y={};var Fi;function jl(){if(Fi)return Y;Fi=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"),u=Symbol.for("react.memo"),d=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 g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},m=Object.assign,y={};function S(v,O,D){this.props=v,this.context=O,this.refs=y,this.updater=D||g}S.prototype.isReactComponent={},S.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")},S.prototype.forceUpdate=function(v){this.updater.enqueueForceUpdate(this,v,"forceUpdate")};function E(){}E.prototype=S.prototype;function I(v,O,D){this.props=v,this.context=O,this.refs=y,this.updater=D||g}var w=I.prototype=new E;w.constructor=I,m(w,S.prototype),w.isPureReactComponent=!0;var b=Array.isArray;function x(){}var k={H:null,A:null,T:null,S:null},P=Object.prototype.hasOwnProperty;function N(v,O,D){var U=D.ref;return{$$typeof:t,type:v,key:O,ref:U!==void 0?U:null,props:D}}function B(v,O){return N(v.type,O,v.props)}function $(v){return typeof v=="object"&&v!==null&&v.$$typeof===t}function _(v){var O={"=":"=0",":":"=2"};return"$"+v.replace(/[=:]/g,function(D){return O[D]})}var L=/\/+/g;function j(v,O){return typeof v=="object"&&v!==null&&v.key!=null?_(""+v.key):O.toString(36)}function q(v){switch(v.status){case"fulfilled":return v.value;case"rejected":throw v.reason;default:switch(typeof v.status=="string"?v.then(x,x):(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,D,U,M){var A=typeof v;(A==="undefined"||A==="boolean")&&(v=null);var F=!1;if(v===null)F=!0;else switch(A){case"bigint":case"string":case"number":F=!0;break;case"object":switch(v.$$typeof){case t:case e:F=!0;break;case d:return F=v._init,se(F(v._payload),O,D,U,M)}}if(F)return M=M(v),F=U===""?"."+j(v,0):U,b(M)?(D="",F!=null&&(D=F.replace(L,"$&/")+"/"),se(M,O,D,"",function(le){return le})):M!=null&&($(M)&&(M=B(M,D+(M.key==null||v&&v.key===M.key?"":(""+M.key).replace(L,"$&/")+"/")+F)),O.push(M)),1;F=0;var X=U===""?".":U+":";if(b(v))for(var z=0;z<v.length;z++)U=v[z],A=X+j(U,z),F+=se(U,O,D,A,M);else if(z=h(v),typeof z=="function")for(v=z.call(v),z=0;!(U=v.next()).done;)U=U.value,A=X+j(U,z++),F+=se(U,O,D,A,M);else if(A==="object"){if(typeof v.then=="function")return se(q(v),O,D,U,M);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 F}function ne(v,O,D){if(v==null)return v;var U=[],M=0;return se(v,U,"","",function(A){return O.call(D,A,M++)}),U}function Re(v){if(v._status===-1){var O=v._result;O=O(),O.then(function(D){(v._status===0||v._status===-1)&&(v._status=1,v._result=D)},function(D){(v._status===0||v._status===-1)&&(v._status=2,v._result=D)}),v._status===-1&&(v._status=0,v._result=O)}if(v._status===1)return v._result.default;throw v._result}var re=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,D){ne(v,function(){O.apply(this,arguments)},D)},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 Y.Activity=p,Y.Children=be,Y.Component=S,Y.Fragment=s,Y.Profiler=i,Y.PureComponent=I,Y.StrictMode=n,Y.Suspense=c,Y.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=k,Y.__COMPILER_RUNTIME={__proto__:null,c:function(v){return k.H.useMemoCache(v)}},Y.cache=function(v){return function(){return v.apply(null,arguments)}},Y.cacheSignal=function(){return null},Y.cloneElement=function(v,O,D){if(v==null)throw Error("The argument must be a React element, but you passed "+v+".");var U=m({},v.props),M=v.key;if(O!=null)for(A in O.key!==void 0&&(M=""+O.key),O)!P.call(O,A)||A==="key"||A==="__self"||A==="__source"||A==="ref"&&O.ref===void 0||(U[A]=O[A]);var A=arguments.length-2;if(A===1)U.children=D;else if(1<A){for(var F=Array(A),X=0;X<A;X++)F[X]=arguments[X+2];U.children=F}return N(v.type,M,U)},Y.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},Y.createElement=function(v,O,D){var U,M={},A=null;if(O!=null)for(U in O.key!==void 0&&(A=""+O.key),O)P.call(O,U)&&U!=="key"&&U!=="__self"&&U!=="__source"&&(M[U]=O[U]);var F=arguments.length-2;if(F===1)M.children=D;else if(1<F){for(var X=Array(F),z=0;z<F;z++)X[z]=arguments[z+2];M.children=X}if(v&&v.defaultProps)for(U in F=v.defaultProps,F)M[U]===void 0&&(M[U]=F[U]);return N(v,A,M)},Y.createRef=function(){return{current:null}},Y.forwardRef=function(v){return{$$typeof:l,render:v}},Y.isValidElement=$,Y.lazy=function(v){return{$$typeof:d,_payload:{_status:-1,_result:v},_init:Re}},Y.memo=function(v,O){return{$$typeof:u,type:v,compare:O===void 0?null:O}},Y.startTransition=function(v){var O=k.T,D={};k.T=D;try{var U=v(),M=k.S;M!==null&&M(D,U),typeof U=="object"&&U!==null&&typeof U.then=="function"&&U.then(x,re)}catch(A){re(A)}finally{O!==null&&D.types!==null&&(O.types=D.types),k.T=O}},Y.unstable_useCacheRefresh=function(){return k.H.useCacheRefresh()},Y.use=function(v){return k.H.use(v)},Y.useActionState=function(v,O,D){return k.H.useActionState(v,O,D)},Y.useCallback=function(v,O){return k.H.useCallback(v,O)},Y.useContext=function(v){return k.H.useContext(v)},Y.useDebugValue=function(){},Y.useDeferredValue=function(v,O){return k.H.useDeferredValue(v,O)},Y.useEffect=function(v,O){return k.H.useEffect(v,O)},Y.useEffectEvent=function(v){return k.H.useEffectEvent(v)},Y.useId=function(){return k.H.useId()},Y.useImperativeHandle=function(v,O,D){return k.H.useImperativeHandle(v,O,D)},Y.useInsertionEffect=function(v,O){return k.H.useInsertionEffect(v,O)},Y.useLayoutEffect=function(v,O){return k.H.useLayoutEffect(v,O)},Y.useMemo=function(v,O){return k.H.useMemo(v,O)},Y.useOptimistic=function(v,O){return k.H.useOptimistic(v,O)},Y.useReducer=function(v,O,D){return k.H.useReducer(v,O,D)},Y.useRef=function(v){return k.H.useRef(v)},Y.useState=function(v){return k.H.useState(v)},Y.useSyncExternalStore=function(v,O,D){return k.H.useSyncExternalStore(v,O,D)},Y.useTransition=function(){return k.H.useTransition()},Y.version="19.2.4",Y}var Bi;function Po(){return Bi||(Bi=1,Js.exports=jl()),Js.exports}var Ul=Po();const a=Gl(Ul);var Zs={exports:{}},ve={};var Di;function Wl(){if(Di)return ve;Di=1;var t=Po();function e(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)u+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+c+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(){}var n={d:{f:s,r:function(){throw Error(e(522))},D:s,C:s,L:s,m:s,X:s,S:s,M:s},p:0,findDOMNode:null},i=Symbol.for("react.portal");function r(c,u,d){var p=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:p==null?null:""+p,children:c,containerInfo:u,implementation:d}}var o=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return ve.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,ve.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(e(299));return r(c,u,null,d)},ve.flushSync=function(c){var u=o.T,d=n.p;try{if(o.T=null,n.p=2,c)return c()}finally{o.T=u,n.p=d,n.d.f()}},ve.preconnect=function(c,u){typeof c=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,n.d.C(c,u))},ve.prefetchDNS=function(c){typeof c=="string"&&n.d.D(c)},ve.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,p=l(d,u.crossOrigin),f=typeof u.integrity=="string"?u.integrity:void 0,h=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;d==="style"?n.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:p,integrity:f,fetchPriority:h}):d==="script"&&n.d.X(c,{crossOrigin:p,integrity:f,fetchPriority:h,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},ve.preinitModule=function(c,u){if(typeof c=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var d=l(u.as,u.crossOrigin);n.d.M(c,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&n.d.M(c)},ve.preload=function(c,u){if(typeof c=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var d=u.as,p=l(d,u.crossOrigin);n.d.L(c,d,{crossOrigin:p,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},ve.preloadModule=function(c,u){if(typeof c=="string")if(u){var d=l(u.as,u.crossOrigin);n.d.m(c,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else n.d.m(c)},ve.requestFormReset=function(c){n.d.r(c)},ve.unstable_batchedUpdates=function(c,u){return c(u)},ve.useFormState=function(c,u,d){return o.H.useFormState(c,u,d)},ve.useFormStatus=function(){return o.H.useHostTransitionStatus()},ve.version="19.2.4",ve}var Hi;function Kl(){if(Hi)return Zs.exports;Hi=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(),Zs.exports=Wl(),Zs.exports}const Vl=a.createContext(null);function je(){const t=a.useContext(Vl);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 u=n.current(c);i.current(l.current,u)||(l.current=u,o(u))}),[t]),r}const Gi=[". ",".. ","..."],ji=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function _o(t,e=120){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(r=>(r+1)%ji.length)},e);return()=>clearInterval(i)},[t,e]),t?ji[s]:""}function Ro(t,e=360){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(r=>(r+1)%Gi.length)},e);return()=>clearInterval(i)},[t,e]),t?Gi[s]:""}function Oo(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"},ze=["sequence","logs","nodes","history","files","stats"],C={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 St(t,e,s){const n=t.indexOf(e),r=((n===-1?0:n)+s+t.length)%t.length;return t[r]}function Jn(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 Nn(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 ql(t){const e=Jn(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function zl(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=Jn(t);return e==null?null:{text:`ctx ${Nn(t.currentTokens)}/${Nn(t.tokenLimit)} ${e}%`,color:ql(t)}}function Yl(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 $o(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function Xl(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function Lo(t,e,s={},n={}){if(!e)return null;const i=$o(t)||{},r=Xl(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 Ql(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 ${Nn(s.tokensRemoved)}`,color:"gray"}]:[]]}const Pn=/\{(\/?)([a-z-]+)\}/g,Jl={color:null,bold:!1,underline:!1},Is=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,Ui=/session:\/\/([A-Za-z0-9-]+)/g,Zl={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function gs(t){return{color:t.color,bold:t.bold,underline:t.underline}}function ec(t,e,s){const n=gs(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:Zl[i]||null,n}return n}function Zn(t){return String(t||"").replace(Pn,"")}function Fo(t){const e=[],n=String(t||"").split(`
|
|
2
|
-
`);for(const i of n){const r=[];let o=gs(Jl),l=0,c;for(;(c=Pn.exec(i))!==null;){const[u,d,p]=c;c.index>l&&r.push({text:i.slice(l,c.index),...gs(o)}),o=ec(o,p,d==="/"),l=c.index+u.length}(l<i.length||r.length===0)&&r.push({text:i.slice(l),...gs(o)}),e.push(r),Pn.lastIndex=0}return e}function de(t){return String(t||"").slice(0,8)}function Bo(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}let en=null,tn=null,sn=null,nn=null;function tc(){return en||(en=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})),en}function Do(){return tn||(tn=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})),tn}function sc(){return sn||(sn=new Intl.DateTimeFormat("en-GB",{month:"short"})),sn}function nc(){return nn||(nn=new Intl.DateTimeFormat("en-GB",{month:"short",day:"numeric"})),nn}function Ho(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 Do().format(s);const i=tc().format(s),r=String(s.getDate()),o=sc().format(s),l=s.getFullYear()===e.getFullYear()?"":String(s.getFullYear()).slice(-2);return`${r}${o}${l} ${i}`}catch{return""}}function Pe(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t),n=Do().format(s);if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return n;const r=nc().format(s),o=s.getFullYear()===e.getFullYear()?"":` ${s.getFullYear()}`;return`${r}${o} ${n}`}catch{return""}}function At(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 ic(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function rc(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function xs(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function Wi(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!(xs(i)&&xs(n))}function oc(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!(xs(n)&&xs(i))}function Ki(t,e,s){let n=s;for(;n<t.length;){const i=t.indexOf(e,n);if(i<0)return-1;if(oc(t,i,e))return i;n=i+e.length}return-1}function ac(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 lc(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function Wt(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 st(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 Go(t){return(t||[]).map(e=>e?.text||"").join("")}function ys(t){return Be(Go(t))}function cc(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=ns(o,i);l&&(n.push({...r,text:l}),i-=Be(l))}return n}function jo(t,e){const s=Math.max(0,Number(e)||0),n=cc(t,s),i=ys(n),r=Math.max(0,s-i);return r>0&&n.push({text:" ".repeat(r),color:null,bold:!1,underline:!1}),n}function Uo(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 u=Math.max(1,s-r),d=ns(c,u);if(!d)break;if(d.length===c.length||Be(d)<u){i.push({...l,text:d}),r+=Be(d),c=c.slice(d.length),r>=s&&o();continue}const p=d.lastIndexOf(" ");if(p>0&&(r>0||p>0)){const f=d.slice(0,p+1);i.push({...l,text:f}),r+=Be(f),c=c.slice(f.length),o()}else i.push({...l,text:d}),r+=Be(d),c=c.slice(d.length),r>=s&&o()}}return(i.length>0||n.length===0)&&o(),n}function Vi(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function Wo(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 uc(t){const e=String(t||"");return Is.lastIndex=0,[...e.matchAll(Is)].map(s=>{const n=s[1],i=Wo(s[2]);return!n||!i?null:{sessionId:n,filename:i,uri:`artifact://${n}/${i}`}}).filter(Boolean)}function ft(t){const e=String(t||"");if(!e)return e;Is.lastIndex=0;const s=e.replace(Is,(n,i,r,o,l)=>{if(l.slice(Math.max(0,o-2),o)==="](")return n;const c=Wo(r);return!i||!c?n:`[artifact: ${c}](artifact://${i}/${c}) (press a to download)`});return Ui.lastIndex=0,s.replace(Ui,(n,i)=>i?`[session: ${de(i)}](session://${i})`:n)}function ei(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const r=lc(e,"`",n),o="`".repeat(r),l=rc(e,o,n+r);if(l>n+r-1){st(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=Wi(e,n,r)?Ki(e,r,n+2):-1;if(o>n+2){st(s,{type:"strong",text:e.slice(n+2,o)}),n=o+2;continue}}if(e[n]==="["){const r=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(r){st(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);st(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}=ac(e.slice(n,r));if(o){st(s,{type:"link",text:o,href:o}),l&&st(s,{type:"text",text:l}),n=r;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&Wi(e,n,e[n])){const r=e[n],o=Ki(e,r,n+1);if(o>n+1){st(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)}st(s,{type:"text",text:e.slice(n,i)}),n=i}return s.length>0?s:[{type:"text",text:""}]}function dc(t=""){return ei(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 zt(t){const e=ei(t),s=[];for(const n of e){if(n.type==="code"){Wt(s,n.text,{color:"cyan"});continue}if(n.type==="strong"){Wt(s,n.text,{bold:!0});continue}if(n.type==="em"){Wt(s,n.text,{underline:!0});continue}if(n.type==="link"){Wt(s,n.text,{color:"cyan",underline:!0,href:n.href});continue}Wt(s,n.text)}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function Ct(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function Tt(t){const e=String(t||"").trim().replace(/^\|/,"").replace(/\|$/,""),s=[];let n="",i=!1;for(const 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 Es(t){return t.length>0&&t.every(e=>/^:?-+:?$/.test(String(e||"").replace(/\s+/g,"")))}function Be(t){return Array.from(String(t||"")).length}function ns(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 Ko(t,e){const s=String(t||""),n=Math.max(0,e-Be(s));return s+" ".repeat(n)}function Vo(t){return Go(zt(t))}function pc(t,e){const s=Vo(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),i=[];let r="";const o=l=>{let c=l;for(;Be(c)>e;){const u=ns(c,e);if(!u)break;r&&(i.push(r),r=""),i.push(u),c=c.slice(u.length)}return c};for(const l of n){const c=o(l);if(!c)continue;if(!r){r=c;continue}const u=`${r} ${c}`;Be(u)<=e?r=u:(i.push(r),r=c)}return r&&i.push(r),i.length>0?i:[""]}function fc(t,e){const s=Math.max(1,...t.map(d=>d.length)),n=Math.max(s*3,e-(s*3+1)),i=Array.from({length:s},(d,p)=>Math.max(3,...t.map(f=>Be(f[p]||"")))),r=Array.from({length:s},(d,p)=>Math.max(3,...t.map(f=>Math.max(0,...String(f[p]||"").split(/\s+/).filter(Boolean).map(h=>Be(h)))))),o=Array.from({length:s},(d,p)=>Math.max(3,Math.min(Math.max(Be(t[0]?.[p]||"")||3,r[p]),24)));if(i.reduce((d,p)=>d+p,0)<=n)return i;const c=o.slice();let u=n-c.reduce((d,p)=>d+p,0);if(u<0){const d=Math.max(3,Math.floor(n/s));return c.map((p,f)=>f===s-1?Math.max(3,n-d*(s-1)):d)}for(;u>0;){let d=0,p=-1/0;for(let f=0;f<s;f++){const h=i[f]-c[f];h>p&&(p=h,d=f)}if(p<=0){c[s-1]+=u;break}c[d]+=1,u-=1}return c}function hc(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,g)=>f[g]||"")).map(f=>f.map(h=>Vo(h))),r=fc(i,e),o=[],l=`┌${r.map(f=>"─".repeat(f+2)).join("┬")}┐`,c=`├${r.map(f=>"─".repeat(f+2)).join("┼")}┤`,u=`└${r.map(f=>"─".repeat(f+2)).join("┴")}┘`,d=f=>{const h=f.map((m,y)=>pc(m,r[y])),g=Math.max(...h.map(m=>m.length));for(let m=0;m<g;m++){const y=h.map((S,E)=>Ko(S[m]||"",r[E]));o.push(`│ ${y.join(" │ ")} │`)}};o.push(l),d(i[0]),o.push(c);const p=i.slice(1);for(const f of p)d(f);return o.push(u),o.join(`
|
|
3
|
-
`)}function mc(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(!Ct(o)||!Ct(c)){n.push(o);continue}const u=Tt(o),d=Tt(c);if(!Es(d)||u.length!==d.length){n.push(o);continue}const p=[u];for(r+=1;r+1<s.length&&Ct(s[r+1]);){r+=1;const f=Tt(s[r]);Es(f)||p.push(f)}n.push(hc(p,e))}return n.join(`
|
|
5
|
-
`)}function gc(t,e){const s=String(t||"");if(!s)return[""];const n=[];let i=s;for(;i.length>0;){const r=ns(i,e);if(!r)break;n.push(r),i=i.slice(r.length)}return n.length>0?n:[""]}function qi(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",i=ns(n,Math.max(1,s-4)),r=Math.max(0,s-i.length-2);return[{text:`┌${i}${"─".repeat(r)}┐`,color:"gray"}]}function zi(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function Yi(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),i=[];for(const r of t){const o=gc(r,n);for(const l of o)i.push([{text:"│",color:"gray"},{text:Ko(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 $t(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),i=e.tableMode==="sentinel"?"sentinel":"boxArt",o=(i==="boxArt"?mc(String(t||""),n):String(t||"")).split(`
|
|
6
|
-
`);let l=!1,c="",u=[];for(let d=0;d<o.length;d+=1){const p=o[d],f=p.trim();if(f.startsWith("```")){l?(s.push(qi(c,Math.max(8,n))),s.push(...Yi(u,Math.max(8,n))),s.push(zi(Math.max(8,n))),l=!1,c="",u=[]):(l=!0,c=f.slice(3).trim(),u=[]);continue}if(l){u.push(p);continue}if(i==="sentinel"&&p&&Ct(p)){const S=o[d+1]||"";if(Ct(S)){const E=Tt(p),I=Tt(S);if(Es(I)&&E.length===I.length){const w=[];let b=d+2;for(;b<o.length&&Ct(o[b]);){const x=Tt(o[b]);Es(x)||w.push(x),b+=1}s.push({kind:"markdownTable",header:E,rows:w}),d=b-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 g=/^>\s?(.*)$/.exec(p);if(g){s.push([{text:"> ",color:"gray"},...zt(g[1]).map(S=>({...S,color:S.color||"gray"}))]);continue}const m=/^\s*[-*]\s+(.*)$/.exec(p);if(m){s.push([{text:"• ",color:"gray"},...zt(m[1])]);continue}const y=/^\s*(\d+)\.\s+(.*)$/.exec(p);if(y){s.push([{text:`${y[1]}. `,color:"gray"},...zt(y[2])]);continue}s.push(zt(p))}return l&&(s.push(qi(c,Math.max(8,n))),s.push(...Yi(u,Math.max(8,n))),s.push(zi(Math.max(8,n)))),s}function he({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 u=Math.max(l?12:20,Number(n)||(l?12:20)),d=Math.max(1,u-4),p=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:i,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]];if(c==="sentinel"){const I=$t(String(s||""),{width:d,tableMode:c}),w=o?I.map(b=>Array.isArray(b)?Vi(b,o):b):I;return[{kind:"cardStart",runs:p,borderColor:r},...w,{kind:"cardEnd"},[{text:"",color:null}]]}const f=$t(String(s||""),{width:d}),h=f.length>0?f.flatMap(I=>Uo(I,d)):[[{text:"",color:null}]],g=o?h.map(I=>Vi(I,o)):h,m=g.reduce((I,w)=>Math.max(I,ys(w)),0),y=l?Math.min(u,Math.max(12,ys(p)+3,m+4)):u,S=Math.max(1,y-4),E=Math.max(0,y-ys(p)-3);return[[{text:"┌─",color:r},...p,{text:`${"─".repeat(E)}┐`,color:r}],...g.map(I=>[{text:"│ ",color:r},...jo(I,S),{text:" │",color:r}]),[{text:`└${"─".repeat(Math.max(1,y-2))}┘`,color:r}],[{text:"",color:null}]]}function Ht(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 qo(t){const e=Ht(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}const ae=300,yc=[ae,1e3,3e3,1e4],Sc=["user.message","assistant.message","system.message","session.epoch_committed","session.regenerate_refused","session.regenerate_failed"];function zo(t){const e=t?.data&&typeof t.data=="object"?t.data:{},s=Number.isFinite(e.toEpoch)?e.toEpoch:Number(e.epoch)||0,n=Number.isFinite(e.turnsArchived)?e.turnsArchived:null;return{id:`${t.sessionId}:${t.seq}:epoch`,kind:"epoch-divider",role:"epoch-divider",epoch:s,turnsArchived:n,time:Pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Yo(t){const e=t?.data&&typeof t.data=="object"?t.data:{};return{id:`${t.sessionId}:${t.seq}:regen-refused`,kind:"regen-refused",role:"regen-refused",reason:typeof e.reason=="string"?e.reason:"unknown",time:Pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Xo(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:Pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function $e(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 Xi(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 Qo=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,bc=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function ti(t){return Qo.test(tt(t))}function rt(t){const e=String(t||"").replace(/\r\n/g,`
|
|
8
|
-
`).trim();if(!e)return"";const s=e.replace(bc,"").trimStart();return s!==e?s.trim():ti(e)?e.replace(Qo,"").trim():e}function Jo(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 u=-1;for(let d=r+1;d<e.length;d+=1){const p=e[d];if(p.trim()==="]"){u=d;break}if(/\]\s*$/.test(p.trim())){const f=p.replace(/\]\s*$/,"");f.trim()&&c.push(f),u=d;break}c.push(p)}if(u===-1){n.push(o),r+=1;continue}i(),s.push({kind:"system",text:c.join(`
|
|
12
|
-
`).trim()}),r=u+1}return i(),s}function Zo(t,e){const s=String(t||"").replace(/\r\n/g,`
|
|
13
|
-
`);return e==="user"||e==="assistant"?Jo(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
|
|
14
|
-
`).trim():s.trim()}function wc(t,e){return e!=="user"&&e!=="assistant"?[]:Jo(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function Qi(t){const e=tt(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=Zo(e,t.role);if(s)return s}return rt(e)}function Hs(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 Ic(t){return tt(Zn(t)).length>0}function xc(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 Ec(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(tt(t))}function bt(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 u=r.indexOf(c);u>=0&&(l=Math.min(l,u))}return r.slice(0,l).trim()}function vc(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(),u=bt(r,"request_id"),d=bt(r,"from"),p=bt(r,"subject"),f=/\bexpects_response=true\b/i.test(r),h=[d?`From: session-${de(d)}`:"",u?`Request ID: ${u}`:"",p?`Subject: ${p}`:"",f?"Response: required":"Response: not required","",c].filter((g,m)=>m===4||String(g||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:h.join(`
|
|
19
|
-
`),time:Pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle: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=bt(r,"request_id"),u=bt(r,"from"),d=bt(r,"verdict")||"answered",p=[u?`From: session-${de(u)}`:"",c?`Request ID: ${c}`:"",`Verdict: ${d}`,"",l].filter((f,h)=>h===3||String(f||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:p.join(`
|
|
20
|
-
`),time:Pe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:"Session Reply",cardTitleColor:"green",cardBorderColor:"green"}}return null}function kc(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&xc(s)?"system":e}function Ac(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 Cc(t,e){if(!t||!e||t.role!==e.role)return!1;const s=Qi(t),n=Qi(e);if(!s||!n||s!==n)return!1;const i=Ac(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 Mt(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!Cc(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 Tc(t){return typeof t=="string"?t.replace(/^\[FROM:[^\]\n]*\]\n?/,""):t}function Nt(t,e){const s=Gt(t),n=vc(t,s);if(n)return n;const i=Tc(Zo(s,e));if(!Ic(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:kc(t,e,i),text:i,time:Pe(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 ea(t){return t?.eventType!=="system.message"?!1:!Ec(Gt(t))}function vs(t,e){return wc(Gt(t),e).map((s,n)=>es({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function Mc(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=tt(e.text),n=Hs(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 Gt(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 ic(e)}function Nc(t){return(t||[]).map(e=>e?.text||"").join("")}function Pc(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function si(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 _c(t,e=""){return si([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function Rc(t,e=""){return si([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function Oc(t,e=""){const s=Gt(t),n=rt(e);return si([rt(s),n,t?.data?.detail,t?.data?.message])}function $c(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 Lc(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}=${$c(r)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function ni(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function pe(t,e,s,n="",i="white"){return[...ni(t),{text:e,color:s},...n?[{text:` ${n}`,color:i}]:[]]}function Fc(t,e=96){return Pc(Zn(Gt(t)),e)||""}function rn(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=Lc(r,o),u=s==="start"?"▶":s==="partial"?"…":"✓",d=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...ni(t),{text:`${u} ${r}${c}`,color:d},...l?[{text:` [sess ${de(l)}]`,color:"gray"}]:[]]}function es(t){const e=Pe(t.createdAt),s=Fc(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=rn(e,t,"start");break;case"tool.execution_complete":n=rn(e,t,"complete");break;case"tool.execution_partial_result":n=rn(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=pe(e,"[tool]","cyan",`${r} ${o}`,"white");break}case"assistant.reasoning":n=pe(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=pe(e,"[intent]","gray",r||"…","white");break}case"assistant.turn_start":n=pe(e,"[turn start]","gray",s);break;case"session.turn_completed":n=pe(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=pe(e,"[lossy handoff]","yellow",Rc(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=pe(e,"[dehydrated]","cyan",_c(t,s));break;case"session.hydrated":case"session.rehydrated":n=pe(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=pe(e,"[wait]","yellow",`${i}${o}${r}`.trim());break}case"session.input_required_started":n=pe(e,"[input]","yellow",s);break;case"session.agent_spawned":n=pe(e,"[spawn]","cyan",t?.data?.agentId||de(t?.data?.childSessionId),"white");break;case"session.cron_started":n=pe(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=pe(e,"[cron]","magenta",`scheduled${t?.data?.nextFireAt?` ${Xi(t.data.nextFireAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_fired":n=pe(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=pe(e,"[cron]","magenta",`fired${t?.data?.scheduledAt?` ${Xi(t.data.scheduledAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_cancelled":case"session.cron_at_cancelled":n=pe(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=pe(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=pe(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=pe(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.compaction_start":case"session.compaction_complete":n=Ql(e,t.eventType,t.data||{});break;case"session.error":n=pe(e,"[error]","red",s||"session error","white");break;case"system.message":ti(Gt(t))?n=pe(e,"[rehydrated]","green",Oc(t,s)||"conversation preserved"):n=pe(e,"[system]","gray",s||"system message");break;default:n=[...ni(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:Nc(n),line:n}}function Bc(t=ae){const e=Math.max(ae,Number(t)||ae);return yc.find(n=>n>e)||Math.min(1e5,e*2)}function ls(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(...vs(o,"user"));const c=Nt(o,"user");c&&n.push(c);continue}if(o.eventType==="assistant.message"){i.push(...vs(o,"assistant"));const c=Nt(o,"assistant");c&&n.push(c);continue}if(o.eventType==="system.message"){if(ea(o)){const c=es(o);c&&i.push(c)}else{const c=Nt(o,"system");c&&n.push(c)}continue}if(o.eventType==="session.epoch_committed"){n.push(zo(o));continue}if(o.eventType==="session.regenerate_refused"){n.push(Yo(o));continue}if(o.eventType==="session.regenerate_failed"){n.push(Xo(o));continue}const l=es(o);l&&i.push(l)}return{chat:Mt(n),activity:i,events:r.slice(-s),loadedEventLimit:s,loadedEventCount:r.length,hasOlderEvents:r.length>=s}}function Ji(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:$e(t?.chat||[],n),activity:$e(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(u=>Array.isArray(u.clientMessageIds)&&u.clientMessageIds.some(d=>c.has(d))?{...u,stopped:!0}:u)}return r}if(e.eventType==="user.message"){r.activity.push(...vs(e,"user")),r.activity=$e(r.activity,n);const l=Nt(e,"user");return l&&(Array.isArray(l.clientMessageIds)&&l.clientMessageIds.some(c=>r.stoppedMessageIds.includes(c))&&(l.stopped=!0),r.chat=Mc(r.chat,l),r.chat.push(l),r.chat=$e(Mt(r.chat),n)),r}if(e.eventType==="assistant.message"){r.activity.push(...vs(e,"assistant")),r.activity=$e(r.activity,n);const l=Nt(e,"assistant");return l&&(r.chat.push(l),r.chat=$e(Mt(r.chat),n)),r}if(e.eventType==="system.message"){if(ea(e)){const l=es(e);l&&(r.activity.push(l),r.activity=$e(r.activity,n))}else{const l=Nt(e,"system");if(!l)return r;r.chat.push(l),r.chat=$e(Mt(r.chat),n)}return r}if(e.eventType==="session.epoch_committed")return r.chat.push(zo(e)),r.chat=$e(r.chat,n),r;if(e.eventType==="session.regenerate_refused")return r.chat.push(Yo(e)),r.chat=$e(r.chat,n),r;if(e.eventType==="session.regenerate_failed")return r.chat.push(Xo(e)),r.chat=$e(r.chat,n),r;const o=es(e);return o&&(r.activity.push(o),r.activity=$e(r.activity,n)),r}function on(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?Ht(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 Dc=.7,Hc=30,Zi=36,an=18,ln=18,cn=0,ta=3,Lt=6,Gs=10,Gc=.25,jc=.5,Pt=6,ks=10,sa=.336,un=Pt,dn=ks,pn=Lt,fn=Gs;function Yt(t,e,s){return Math.max(e,Math.min(s,t))}function Uc(t){return[T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY].includes(t)?t:null}function Wc(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 Yt(e,1,ta)}function na(t){return Math.max(Lt,Math.floor(t*Gc))}function ia(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*jc),n=Math.max(Lt,e-Gs);return Math.max(Lt,Math.min(n,s))}function Jt(t,e=0,s=1,n=0,i=0,r=null){const o=Wc(t),l=o.width,c=o.height,u=Yt(Number(s)||1,1,ta),d=Uc(r),p=5+u,f=Math.max(18,c-p),g=Math.floor(l*Dc)+(Number(e)||0),m=l-g-cn;let y=!1,S=!1;g<=an&&m>ln?y=!0:m<=ln&&g>an?S=!0:g<=an&&m<=ln&&(S=e>=0,y=!S);let E,I;y?(E=0,I=l):S?(E=l,I=0):(E=Yt(g,Hc,l-Zi-cn),I=Math.max(Zi,l-E-cn));const b=na(f)+(Number(n)||0),x=f-b;let k=!1,P=!1;x<=fn&&b>pn?P=!0:b<=pn&&x>fn?k=!0:x<=fn&&b<=pn&&(P=(Number(n)||0)>=0,k=!P);let N,B;if(k)N=0,B=f;else if(P)N=f,B=0;else{const Re=ia(c,f);N=Yt(b,Lt,Re),B=Math.max(Gs,f-N)}const _=Math.max(Pt,Math.floor(f*sa))+(Number(i)||0),L=f-_;let j=!1,q=!1;L<=dn&&_>un?j=!0:_<=un&&L>dn?q=!0:L<=dn&&_<=un&&(j=(Number(i)||0)>=0,q=!j);let se,ne;return j?(se=f,ne=0):q?(ne=f,se=0):(se=Yt(_,Pt,Math.max(Pt,f-ks)),ne=Math.max(ks,f-se)),{viewport:o,totalWidth:l,totalHeight:c,reservedRows:p,bodyHeight:f,promptRows:u,fullscreenPane:d,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(i)||0,leftHidden:y,rightHidden:S,inspectorHidden:j,activityHidden:q,sessionHidden:k,chatHidden:P,leftWidth:E,rightWidth:I,sessionPaneHeight:N,chatPaneHeight:B,activityPaneHeight:se,inspectorPaneHeight:ne}}function _n(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=_n(e);return s.includes(t)?t:s[0]||T.PROMPT}function Kc(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 Vc(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 ra(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,u,...d]=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.`}:u?{kind:"github",repoUrl:f,ref:u,path:d.length?`/${d.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 As=2*1024*1024,qc=new Set(["node_modules",".git"]);function Rn(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 oa(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 aa(t){return t.split("/").some(e=>qc.has(e))}function la(t){const e=String(t||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.endsWith("/plugin.json")?e.slice(0,-12):e==="plugin.json"?"":e:""}function zc(t,e){return t?`${t}/${e}`:e}function ca(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 Cs(t,e,s,n){let i;try{i=await t(e,{headers:{accept:"application/json",...s}})}catch(r){throw ca(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 ua(t,e,s,n){let i;try{i=await t(e,{headers:s})}catch(o){throw ca(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 Yc(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 Xc({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:i,onProgress:r}){const{owner:o,repo:l}=Yc(t),c="https://api.github.com",u={"x-github-api-version":"2022-11-28",...i?{authorization:`Bearer ${i}`}:{}};let d=e;d||(r("resolving the default branch…"),d=(await Cs(n,`${c}/repos/${o}/${l}`,u,"api.github.com"))?.default_branch||"main"),r(`reading the file tree of ${o}/${l}@${d}…`);const p=await Cs(n,`${c}/repos/${o}/${l}/git/trees/${encodeURIComponent(d)}?recursive=1`,u,"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=la(s),g=zc(h,"plugin.json");if(!f.some(w=>w.type==="blob"&&w.path===g))throw new Error(`no plugin.json at ${g||"the repository root"} on ${d} — link to the folder that contains the manifest`);const m=h?`${h}/`:"",y=f.filter(w=>w.type==="blob"&&(!m||w.path.startsWith(m))&&!aa(w.path.slice(m.length))),S=[];let E=0,I=0;for(const w of y){I+=1;const b=w.path.slice(m.length);r(`fetching ${I}/${y.length}: ${b}`);const x=i?await Qc(n,c,o,l,w.sha,u):await ua(n,`https://raw.githubusercontent.com/${o}/${l}/${encodeURIComponent(d)}/${w.path.split("/").map(encodeURIComponent).join("/")}`,{},"raw.githubusercontent.com");if(E+=x.length,E>As)throw new Error(`package exceeds the ${Math.round(As/1024)} KB upload limit at ${b}`);S.push({path:b,contentBase64:Rn(x)})}return S}async function Qc(t,e,s,n,i,r){const o=await Cs(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 oa(l)}function Jc(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 Zc({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:u}=Jc(t),d=`https://dev.azure.com/${encodeURIComponent(l)}/${encodeURIComponent(c)}/_apis/git/repositories/${encodeURIComponent(u)}`,f={authorization:r==="pat"?`Basic ${Rn(new TextEncoder().encode(`:${i}`))}`:`Bearer ${i}`},h=la(s),g=`/${h}`,m=e?`&versionDescriptor.version=${encodeURIComponent(e)}&versionDescriptor.versionType=branch`:"";o(`reading ${u}${h?`/${h}`:""}…`);const y=await Cs(n,`${d}/items?scopePath=${encodeURIComponent(g)}&recursionLevel=Full${m}&api-version=7.1`,f,"dev.azure.com"),E=(Array.isArray(y?.value)?y.value:[]).filter(P=>P?.gitObjectType==="blob"&&!P?.isFolder),I=h?`/${h}/`:"/";if(!E.find(P=>P.path===`${I}plugin.json`.replace("//","/")))throw new Error(`no plugin.json under ${g} — link to the folder that contains the manifest`);const b=[];let x=0,k=0;for(const P of E){const N=String(P.path||"").slice(I.length);if(!N||aa(N))continue;k+=1,o(`fetching ${k}/${E.length}: ${N}`);const B=await ua(n,`${d}/blobs/${encodeURIComponent(P.objectId)}?api-version=7.1&$format=octetStream`,{...f,accept:"application/octet-stream"},"dev.azure.com");if(x+=B.length,x>As)throw new Error(`package exceeds the ${Math.round(As/1024)} KB upload limit at ${N}`);b.push({path:N,contentBase64:Rn(B)})}return b}async function eu(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=ra(t);if(r.error)throw new Error(r.error);const o={fetchImpl:e,token:s,tokenKind:n,onProgress:i},l=r.kind==="github"?await Xc(r,o):await Zc(r,o);if(l.length===0)throw new Error("the package folder is empty");return{kind:r.kind,files:l}}function tu(t=[]){const e=(Array.isArray(t)?t:[]).find(s=>s?.path==="plugin.json");if(!e?.contentBase64)return null;try{const s=oa(e.contentBase64),n=JSON.parse(new TextDecoder().decode(s));return String(n?.name||"").trim()||null}catch{return null}}function er(t){return t?.isSystem?qo(t):Number.MAX_SAFE_INTEGER}function su(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 nu(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return su(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 iu(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 Ft(t){return!!(t&&!t.isSystem&&!t.parentSessionId)}function ru(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function tr(t,e){return!!(ru(t)&&e&&e.has(t.sessionId))}function sr(t,e){return t.isSystem?0:t.isGroup&&tr(t,e)?1:tr(t,e)?2:t.isGroup?3:4}function nr(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function ir(t,e,s,n,i){const r=sr(t,n),o=sr(e,n);if(r!==o)return r-o;const l=er(t),c=er(e);if(l!==c)return l-c;if(i&&i.size>0&&Ft(t)&&Ft(e)){const S=i.has(t.sessionId)?i.get(t.sessionId):1/0,E=i.has(e.sessionId)?i.get(e.sessionId):1/0;if(S!==E)return S-E}const u=s.get(t.sessionId),d=s.get(e.sessionId);if(typeof u=="number"&&typeof d=="number"&&u!==d)return u-d;const p=nr(t),f=nr(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 g=String(t.title||""),m=String(e.title||""),y=g.localeCompare(m);return y!==0?y:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function Ve(t=[],e=new Set,s=[],n=null,i=null){const r=new Map,o=new Map,l=nu(s),c=iu(i),u=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const m of t)r.set(m.sessionId,m);const d=[];for(const m of t){if(m.isGroup||!m.groupId||m.parentSessionId)continue;const y=`group:${m.groupId}`;if(r.has(y))continue;const S={sessionId:y,groupId:m.groupId,isGroup:!0,title:"Group",status:"group",shortSummary:"reconnecting…",createdAt:0,updatedAt:0};r.set(y,S),d.push(S)}const p=new Set(d.map(m=>m.sessionId));d.length>0&&(t=[...t,...d]);for(const m of t){const y=!m.isGroup&&m.groupId&&!m.parentSessionId&&r.has(`group:${m.groupId}`)?`group:${m.groupId}`:null,S=m.parentSessionId||y;!S||!r.has(S)||(o.has(S)||o.set(S,[]),o.get(S).push(m))}for(const m of o.values())m.sort((y,S)=>ir(y,S,l,u,c));const f=t.filter(m=>!(m.parentSessionId||!m.isGroup&&m.groupId)).sort((m,y)=>ir(m,y,l,u,c)),h=[];function g(m,y){const S=o.get(m.sessionId)||[];if(h.push({sessionId:m.sessionId,depth:y,hasChildren:S.length>0,collapsed:e.has(m.sessionId),...p.has(m.sessionId)?{standIn:m}:{}}),!e.has(m.sessionId))for(const E of S)g(E,y+1)}for(const m of f)g(m,0);return h}function ou(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function hn(t){return Number.parseInt(t,16)/255}function au(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 mn(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function lu(t){const e=au(t);if(!e)return 0;const s=mn(hn(e.slice(1,3))),n=mn(hn(e.slice(3,5))),i=mn(hn(e.slice(5,7)));return .2126*s+.7152*n+.0722*i}function cu(t){const e=t?.page?.background||t?.tui?.background||t?.terminal?.background;return lu(e)>=.5}function ye({id:t,label:e,description:s,page:n,terminal:i,tui:r={},richChat:o=!1,icon:l=null}){const c={background:n?.background||i?.background||"#000000",surface:i?.background||n?.background||"#000000",foreground:i?.foreground||n?.foreground||"#ffffff",white:i?.foreground||n?.foreground||"#ffffff",gray:n?.hintColor||i?.brightBlack||i?.white||"#999999",black:i?.black||"#000000",red:i?.red||"#ff5555",green:i?.green||"#55ff55",yellow:i?.yellow||"#ffff55",blue:i?.blue||"#5555ff",magenta:i?.magenta||"#ff55ff",cyan:i?.cyan||"#55ffff",userChat:"#ffd866",userChatLabel:"#ffec99",otherUserChatLabel:i?.brightMagenta||i?.magenta||"#c9a3ff",activeHighlightBackground:i?.blue||"#5555ff",activeHighlightForeground:i?.background||"#000000",selectionBackground:i?.cursor||i?.blue||"#5555ff",selectionForeground:i?.cursorAccent||i?.background||"#000000",promptCursorBackground:i?.cursor||i?.green||"#55ff55",promptCursorForeground:i?.cursorAccent||i?.background||"#000000"};return ou({id:t,label:e,description:s,richChat:!!o,icon:l||null,page:n,terminal:i,tui:{...c,...r}})}const uu=ye({id:"github-dark",label:"GitHub Dark",description:"GitHub dark palette with soft blue accents and cool neutrals.",page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#30363d",modalForeground:"#e6edf3",modalMuted:"#8b949e",modalSelectedBackground:"#1f6feb33",modalSelectedBorder:"#2f81f7",modalSelectedForeground:"#79c0ff"},terminal:{background:"#0d1117",foreground:"#e6edf3",cursor:"#2f81f7",cursorAccent:"#0d1117",selectionBackground:"rgba(56, 139, 253, 0.28)",black:"#484f58",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"},tui:{surface:"#0d1117",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),du=ye({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",page:{background:"#f6f8fa",foreground:"#1f2328",overlayBackground:"#ffffff",overlayForeground:"#1f2328",hintColor:"#57606a",modalBackdrop:"rgba(31, 35, 40, 0.34)",modalBackground:"#ffffff",modalBorder:"#d0d7de",modalForeground:"#1f2328",modalMuted:"#57606a",modalSelectedBackground:"#ddf4ff",modalSelectedBorder:"#0969da",modalSelectedForeground:"#0550ae"},terminal:{background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",cursorAccent:"#ffffff",selectionBackground:"#ddf4ff",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#116329",brightYellow:"#7d4e00",brightBlue:"#0550ae",brightMagenta:"#6639ba",brightCyan:"#0f6f78",brightWhite:"#1f2328"},tui:{surface:"#ffffff",border:"#d0d7de",userChat:"#0969da",userChatLabel:"#0550ae",activeHighlightBackground:"#ddf4ff",activeHighlightForeground:"#0550ae",selectionBackground:"#0969da",selectionForeground:"#ffffff",promptCursorBackground:"#0969da",promptCursorForeground:"#ffffff"}}),pu=ye({id:"workspace-dark",label:"Workspace Dark",description:"Flat workspace chrome: tone surfaces and hairlines instead of panel borders.",page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#272e37",modalForeground:"#e6edf3",modalMuted:"#8b949e",modalSelectedBackground:"#1f6feb33",modalSelectedBorder:"#2f81f7",modalSelectedForeground:"#79c0ff"},terminal:{background:"#0d1117",foreground:"#e6edf3",cursor:"#2f81f7",cursorAccent:"#0d1117",selectionBackground:"rgba(56, 139, 253, 0.28)",black:"#484f58",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"},tui:{surface:"#161b22",border:"#272e37",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),fu=ye({id:"workspace-dark-rich",label:"Workspace Dark — Rich Text",description:"Workspace Dark with the rich desktop-style chat transcript (portal only).",richChat:!0,page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#272e37",modalForeground:"#e6edf3",modalMuted:"#8b949e",modalSelectedBackground:"#1f6feb33",modalSelectedBorder:"#2f81f7",modalSelectedForeground:"#79c0ff"},terminal:{background:"#0d1117",foreground:"#e6edf3",cursor:"#2f81f7",cursorAccent:"#0d1117",selectionBackground:"rgba(56, 139, 253, 0.28)",black:"#484f58",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"},tui:{surface:"#161b22",border:"#272e37",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),hu=ye({id:"cobalt2",label:"Cobalt2",description:"Electric blue shell with bright yellow accents and saturated syntax colors.",page:{background:"#193549",foreground:"#ffffff",overlayBackground:"#193549",overlayForeground:"#ffffff",hintColor:"#a8c5e6",modalBackdrop:"rgba(7, 17, 28, 0.68)",modalBackground:"#224b68",modalBorder:"#2e6c99",modalForeground:"#ffffff",modalMuted:"#a8c5e6",modalSelectedBackground:"#ffc600",modalSelectedBorder:"#ffc600",modalSelectedForeground:"#193549"},terminal:{background:"#193549",foreground:"#ffffff",cursor:"#ffc600",cursorAccent:"#193549",selectionBackground:"rgba(255, 255, 255, 0.18)",black:"#000000",red:"#ff628c",green:"#3ad900",yellow:"#ff9d00",blue:"#0088ff",magenta:"#ff628c",cyan:"#80ffbb",white:"#ffffff",brightBlack:"#666666",brightRed:"#ff628c",brightGreen:"#3ad900",brightYellow:"#ff9d00",brightBlue:"#0088ff",brightMagenta:"#ff9d00",brightCyan:"#80ffbb",brightWhite:"#ffffff"},tui:{surface:"#193549",activeHighlightBackground:"#0f5f91",activeHighlightForeground:"#ffffff",selectionBackground:"#ffc600",selectionForeground:"#193549",promptCursorBackground:"#ffc600",promptCursorForeground:"#193549"}}),mu=ye({id:"dracula",label:"Dracula",description:"Classic Dracula contrast with neon green, pink, and violet accents.",page:{background:"#282a36",foreground:"#f8f8f2",overlayBackground:"#282a36",overlayForeground:"#f8f8f2",hintColor:"#bd93f9",modalBackdrop:"rgba(24, 25, 33, 0.72)",modalBackground:"#313442",modalBorder:"#6272a4",modalForeground:"#f8f8f2",modalMuted:"#bd93f9",modalSelectedBackground:"#44475a",modalSelectedBorder:"#bd93f9",modalSelectedForeground:"#f8f8f2"},terminal:{background:"#282a36",foreground:"#f8f8f2",cursor:"#f8f8f2",cursorAccent:"#282a36",selectionBackground:"rgba(189, 147, 249, 0.24)",black:"#21222c",red:"#ff5555",green:"#50fa7b",yellow:"#f1fa8c",blue:"#bd93f9",magenta:"#ff79c6",cyan:"#8be9fd",white:"#f8f8f2",brightBlack:"#6272a4",brightRed:"#ff6e6e",brightGreen:"#69ff94",brightYellow:"#ffffa5",brightBlue:"#d6acff",brightMagenta:"#ff92df",brightCyan:"#a4ffff",brightWhite:"#ffffff"},tui:{surface:"#282a36",activeHighlightBackground:"#44475a",activeHighlightForeground:"#f8f8f2",selectionBackground:"#bd93f9",selectionForeground:"#282a36",promptCursorBackground:"#f8f8f2",promptCursorForeground:"#282a36"}}),gu=ye({id:"catppuccin-mocha",label:"Catppuccin Mocha",description:"Creamy dark palette with soft pastels and high legibility.",page:{background:"#1e1e2e",foreground:"#cdd6f4",overlayBackground:"#1e1e2e",overlayForeground:"#cdd6f4",hintColor:"#bac2de",modalBackdrop:"rgba(17, 17, 27, 0.74)",modalBackground:"#313244",modalBorder:"#585b70",modalForeground:"#cdd6f4",modalMuted:"#bac2de",modalSelectedBackground:"#45475a",modalSelectedBorder:"#89b4fa",modalSelectedForeground:"#cdd6f4"},terminal:{background:"#1e1e2e",foreground:"#cdd6f4",cursor:"#f5e0dc",cursorAccent:"#1e1e2e",selectionBackground:"rgba(137, 180, 250, 0.22)",black:"#45475a",red:"#f38ba8",green:"#a6e3a1",yellow:"#f9e2af",blue:"#89b4fa",magenta:"#f5c2e7",cyan:"#94e2d5",white:"#bac2de",brightBlack:"#585b70",brightRed:"#f38ba8",brightGreen:"#a6e3a1",brightYellow:"#f9e2af",brightBlue:"#89b4fa",brightMagenta:"#f5c2e7",brightCyan:"#94e2d5",brightWhite:"#f5e0dc"},tui:{surface:"#1e1e2e",activeHighlightBackground:"#45475a",activeHighlightForeground:"#cdd6f4",selectionBackground:"#89b4fa",selectionForeground:"#1e1e2e",promptCursorBackground:"#f5e0dc",promptCursorForeground:"#1e1e2e"}}),yu=ye({id:"hacker-x-matrix",label:"Hacker X - Matrix",description:"Black-and-phosphor terminal palette with vivid green glow and CRT-style contrast.",page:{background:"#030603",foreground:"#c8ffc8",overlayBackground:"#030603",overlayForeground:"#c8ffc8",hintColor:"#59a659",modalBackdrop:"rgba(0, 6, 0, 0.82)",modalBackground:"#081208",modalBorder:"#1f5f1f",modalForeground:"#d6ffd6",modalMuted:"#6dbb6d",modalSelectedBackground:"#0f240f",modalSelectedBorder:"#39ff14",modalSelectedForeground:"#dfffdf"},terminal:{background:"#000000",foreground:"#c8ffc8",cursor:"#39ff14",cursorAccent:"#000000",selectionBackground:"rgba(57, 255, 20, 0.2)",black:"#031003",red:"#39ff14",green:"#2a7a22",yellow:"#4a8a30",blue:"#1a6a4a",magenta:"#2a7a3a",cyan:"#2a8a5a",white:"#b7f7b7",brightBlack:"#59a659",brightRed:"#9aff86",brightGreen:"#7dff66",brightYellow:"#e0ff8a",brightBlue:"#61ffc2",brightMagenta:"#b4ffb4",brightCyan:"#98ffe0",brightWhite:"#e8ffe8"},tui:{surface:"#030603",activeHighlightBackground:"#1a3a1a",activeHighlightForeground:"#e8ffe8",selectionBackground:"#39ff14",selectionForeground:"#000000",promptCursorBackground:"#39ff14",promptCursorForeground:"#000000"}}),Su=ye({id:"hacker-x-orion-prime",label:"Hacker X - Orion Prime",description:"Deep-space navy palette with electric cyan, violet, and amber accents.",page:{background:"#0a0f1e",foreground:"#e8f2ff",overlayBackground:"#0a0f1e",overlayForeground:"#e8f2ff",hintColor:"#7e90b5",modalBackdrop:"rgba(6, 10, 24, 0.76)",modalBackground:"#121a30",modalBorder:"#2d4a73",modalForeground:"#edf5ff",modalMuted:"#93a7cc",modalSelectedBackground:"#19365f",modalSelectedBorder:"#55c2ff",modalSelectedForeground:"#f3fbff"},terminal:{background:"#0a0f1e",foreground:"#e8f2ff",cursor:"#55c2ff",cursorAccent:"#0a0f1e",selectionBackground:"rgba(85, 194, 255, 0.22)",black:"#10182b",red:"#ff6b88",green:"#67f5c2",yellow:"#ffd36b",blue:"#55c2ff",magenta:"#c79bff",cyan:"#7ceeff",white:"#c3d4ef",brightBlack:"#7e90b5",brightRed:"#ff8aa2",brightGreen:"#8cffd8",brightYellow:"#ffe28f",brightBlue:"#8fdcff",brightMagenta:"#d8b6ff",brightCyan:"#a2f5ff",brightWhite:"#ffffff"},tui:{surface:"#0c1325",activeHighlightBackground:"#173052",activeHighlightForeground:"#f3fbff",selectionBackground:"#55c2ff",selectionForeground:"#0a0f1e",promptCursorBackground:"#55c2ff",promptCursorForeground:"#0a0f1e"}}),bu=ye({id:"gruvbox-dark",label:"Gruvbox Dark",description:"Retro warm palette with earthy browns, oranges, and high readability.",page:{background:"#282828",foreground:"#ebdbb2",overlayBackground:"#282828",overlayForeground:"#ebdbb2",hintColor:"#a89984",modalBackdrop:"rgba(40, 40, 40, 0.74)",modalBackground:"#3c3836",modalBorder:"#504945",modalForeground:"#ebdbb2",modalMuted:"#a89984",modalSelectedBackground:"#504945",modalSelectedBorder:"#fabd2f",modalSelectedForeground:"#fbf1c7"},terminal:{background:"#282828",foreground:"#ebdbb2",cursor:"#ebdbb2",cursorAccent:"#282828",selectionBackground:"rgba(250, 189, 47, 0.22)",black:"#282828",red:"#cc241d",green:"#98971a",yellow:"#d79921",blue:"#458588",magenta:"#b16286",cyan:"#689d6a",white:"#a89984",brightBlack:"#928374",brightRed:"#fb4934",brightGreen:"#b8bb26",brightYellow:"#fabd2f",brightBlue:"#83a598",brightMagenta:"#d3869b",brightCyan:"#8ec07c",brightWhite:"#ebdbb2"},tui:{surface:"#282828",activeHighlightBackground:"#504945",activeHighlightForeground:"#fbf1c7",selectionBackground:"#fabd2f",selectionForeground:"#282828",promptCursorBackground:"#ebdbb2",promptCursorForeground:"#282828"}}),wu=ye({id:"noctis",label:"Noctis",description:"Dark cyan-tinted palette with warm and cold medium contrast accents.",page:{background:"#052529",foreground:"#b2cacd",overlayBackground:"#052529",overlayForeground:"#b2cacd",hintColor:"#40d4e7",modalBackdrop:"rgba(3, 25, 27, 0.72)",modalBackground:"#073940",modalBorder:"#0e6671",modalForeground:"#b2cacd",modalMuted:"#87a7ab",modalSelectedBackground:"#0b515b",modalSelectedBorder:"#40d4e7",modalSelectedForeground:"#ebfdff"},terminal:{background:"#03191b",foreground:"#b2cacd",cursor:"#85efff",cursorAccent:"#03191b",selectionBackground:"rgba(22, 159, 177, 0.27)",black:"#324a4d",red:"#e66533",green:"#49e9a6",yellow:"#e4b781",blue:"#49ace9",magenta:"#df769b",cyan:"#49d6e9",white:"#b2cacd",brightBlack:"#5e878c",brightRed:"#e97749",brightGreen:"#60ebb1",brightYellow:"#e69533",brightBlue:"#60b6eb",brightMagenta:"#e798b3",brightCyan:"#60dbeb",brightWhite:"#c1d4d7"},tui:{surface:"#03191b",activeHighlightBackground:"#083d44",activeHighlightForeground:"#ebfdff",selectionBackground:"#169fb1",selectionForeground:"#052529",promptCursorBackground:"#85efff",promptCursorForeground:"#03191b"}}),da=ye({id:"noctis-obscuro",label:"Noctis Obscuro",description:"Deep obsidian palette with cool blue accents and restrained contrast for long sessions.",page:{background:"#0b1117",foreground:"#c7d1da",overlayBackground:"#0b1117",overlayForeground:"#c7d1da",hintColor:"#7cc6ff",modalBackdrop:"rgba(5, 9, 13, 0.74)",modalBackground:"#121a23",modalBorder:"#28455b",modalForeground:"#d7e2eb",modalMuted:"#8f9dab",modalSelectedBackground:"#173041",modalSelectedBorder:"#7cc6ff",modalSelectedForeground:"#eef6ff"},terminal:{background:"#060b10",foreground:"#c7d1da",cursor:"#9fd4ff",cursorAccent:"#060b10",selectionBackground:"rgba(72, 125, 170, 0.30)",black:"#2a3138",red:"#ef6b73",green:"#7ddc8f",yellow:"#d9b36c",blue:"#68aee8",magenta:"#b28cff",cyan:"#58c9d4",white:"#c7d1da",brightBlack:"#6e7a86",brightRed:"#f28a92",brightGreen:"#97e5a6",brightYellow:"#e4c28b",brightBlue:"#86c1f1",brightMagenta:"#c6a7ff",brightCyan:"#7ad7df",brightWhite:"#e5edf5"},tui:{surface:"#060b10",activeHighlightBackground:"#123142",activeHighlightForeground:"#eef6ff",selectionBackground:"#4a7baa",selectionForeground:"#0b1117",promptCursorBackground:"#9fd4ff",promptCursorForeground:"#060b10"}}),Iu=ye({id:"dark-high-contrast",label:"Dark High Contrast",description:"Pure black background with maximum contrast ANSI colors for accessibility.",page:{background:"#000000",foreground:"#ffffff",overlayBackground:"#000000",overlayForeground:"#ffffff",hintColor:"#3794ff",modalBackdrop:"rgba(0, 0, 0, 0.85)",modalBackground:"#0c0c0c",modalBorder:"#6fc3df",modalForeground:"#ffffff",modalMuted:"#9d9d9d",modalSelectedBackground:"#0f4a85",modalSelectedBorder:"#f38518",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#ffffff",cursor:"#ffffff",cursorAccent:"#000000",selectionBackground:"rgba(255, 255, 255, 0.3)",black:"#000000",red:"#f44747",green:"#73c991",yellow:"#e5e510",blue:"#3794ff",magenta:"#bc3fbc",cyan:"#29b8db",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#89d185",brightYellow:"#f5f543",brightBlue:"#6fc3df",brightMagenta:"#d670d6",brightCyan:"#2ee2e2",brightWhite:"#ffffff"},tui:{surface:"#000000",activeHighlightBackground:"#0f4a85",activeHighlightForeground:"#ffffff",selectionBackground:"#f38518",selectionForeground:"#000000",promptCursorBackground:"#ffffff",promptCursorForeground:"#000000"}}),xu=ye({id:"terminal-green",label:"Terminal Green",description:"Classic black terminal with phosphor green text, amber warnings, and crisp operator contrast.",page:{background:"#020503",foreground:"#c9f7d3",overlayBackground:"#020503",overlayForeground:"#d9ffe0",hintColor:"#7ee787",modalBackdrop:"rgba(0, 6, 2, 0.82)",modalBackground:"#061109",modalBorder:"#245c33",modalForeground:"#d9ffe0",modalMuted:"#83a98c",modalSelectedBackground:"#0b2a14",modalSelectedBorder:"#63e27a",modalSelectedForeground:"#ecfff0"},terminal:{background:"#020503",foreground:"#c9f7d3",cursor:"#8cff9f",cursorAccent:"#020503",selectionBackground:"#174923",black:"#061109",red:"#ff5f5f",green:"#63e27a",yellow:"#d6b95f",blue:"#5aa7ff",magenta:"#c586ff",cyan:"#5ce1d8",white:"#c9f7d3",brightBlack:"#5b7a61",brightRed:"#ff7f7f",brightGreen:"#8cff9f",brightYellow:"#f0d982",brightBlue:"#82bdff",brightMagenta:"#d9a8ff",brightCyan:"#89f4ee",brightWhite:"#effff1"},tui:{surface:"#020503",border:"#245c33",userChat:"#f0d982",userChatLabel:"#fff0a8",activeHighlightBackground:"#0b2a14",activeHighlightForeground:"#ecfff0",selectionBackground:"#63e27a",selectionForeground:"#020503",promptCursorBackground:"#8cff9f",promptCursorForeground:"#020503"}}),Eu=ye({id:"high-contrast-mono",label:"High Contrast Mono",description:"Accessibility-first monochrome theme with cobalt selection and severity colors only where they matter.",page:{background:"#000000",foreground:"#f8f8f2",overlayBackground:"#050505",overlayForeground:"#ffffff",hintColor:"#b8b8b8",modalBackdrop:"rgba(0, 0, 0, 0.88)",modalBackground:"#050505",modalBorder:"#d8d8d8",modalForeground:"#ffffff",modalMuted:"#b8b8b8",modalSelectedBackground:"#003f88",modalSelectedBorder:"#ffffff",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#f8f8f2",cursor:"#ffffff",cursorAccent:"#000000",selectionBackground:"#003f88",black:"#000000",red:"#ff4d4d",green:"#00d084",yellow:"#ffd84d",blue:"#4da3ff",magenta:"#d8d8d8",cyan:"#ffffff",white:"#f8f8f2",brightBlack:"#8a8a8a",brightRed:"#ff6b6b",brightGreen:"#28e29a",brightYellow:"#ffe173",brightBlue:"#73b8ff",brightMagenta:"#ffffff",brightCyan:"#ffffff",brightWhite:"#ffffff"},tui:{surface:"#000000",border:"#d8d8d8",userChat:"#ffffff",userChatLabel:"#d8d8d8",activeHighlightBackground:"#003f88",activeHighlightForeground:"#ffffff",selectionBackground:"#ffffff",selectionForeground:"#000000",promptCursorBackground:"#ffffff",promptCursorForeground:"#000000"}}),vu=ye({id:"win95",label:"Windows 95",description:"Authentic 3D-bevelled grey, navy title bars, teal desktop, and the 16-colour VGA terminal set.",page:{background:"#008080",foreground:"#000000",overlayBackground:"#c0c0c0",overlayForeground:"#000000",hintColor:"#5a5a5a",modalBackdrop:"rgba(0, 0, 0, 0.45)",modalBackground:"#c0c0c0",modalBorder:"#808080",modalForeground:"#000000",modalMuted:"#5a5a5a",modalSelectedBackground:"#000080",modalSelectedBorder:"#000080",modalSelectedForeground:"#ffffff"},terminal:{background:"#c0c0c0",foreground:"#000000",cursor:"#000080",cursorAccent:"#c0c0c0",selectionBackground:"#000080",black:"#000000",red:"#800000",green:"#008000",yellow:"#808000",blue:"#000080",magenta:"#800080",cyan:"#008080",white:"#c0c0c0",brightBlack:"#5a5a5a",brightRed:"#c00000",brightGreen:"#006000",brightYellow:"#7a5c00",brightBlue:"#0000c0",brightMagenta:"#a000a0",brightCyan:"#006a6a",brightWhite:"#000000"},tui:{surface:"#c0c0c0",border:"#808080",userChat:"#000080",userChatLabel:"#000080",activeHighlightBackground:"#000080",activeHighlightForeground:"#ffffff",selectionBackground:"#000080",selectionForeground:"#ffffff",promptCursorBackground:"#000080",promptCursorForeground:"#ffffff"}}),ku=ye({id:"ms-dos",label:"MS-DOS 2.0",description:"CGA light-grey on black, the 16-colour CGA palette with brown, and CP437 box framing.",page:{background:"#000000",foreground:"#aaaaaa",overlayBackground:"#000000",overlayForeground:"#aaaaaa",hintColor:"#8f8f8f",modalBackdrop:"rgba(0, 0, 0, 0.78)",modalBackground:"#000000",modalBorder:"#aaaaaa",modalForeground:"#aaaaaa",modalMuted:"#8f8f8f",modalSelectedBackground:"#aaaaaa",modalSelectedBorder:"#ffffff",modalSelectedForeground:"#000000"},terminal:{background:"#000000",foreground:"#aaaaaa",cursor:"#aaaaaa",cursorAccent:"#000000",selectionBackground:"#aaaaaa",black:"#000000",red:"#aa0000",green:"#00aa00",yellow:"#aa5500",blue:"#0000aa",magenta:"#aa00aa",cyan:"#00aaaa",white:"#aaaaaa",brightBlack:"#8f8f8f",brightRed:"#ff5555",brightGreen:"#55ff55",brightYellow:"#ffff55",brightBlue:"#5555ff",brightMagenta:"#ff55ff",brightCyan:"#55ffff",brightWhite:"#ffffff"},tui:{surface:"#000000",border:"#aaaaaa",userChat:"#ffffff",userChatLabel:"#ffffff",activeHighlightBackground:"#aaaaaa",activeHighlightForeground:"#000000",selectionBackground:"#aaaaaa",selectionForeground:"#000000",promptCursorBackground:"#aaaaaa",promptCursorForeground:"#000000"}}),Au=ye({id:"doom",label:"DOOM",description:"STBAR brown metal, bone type, and the three keycards as the status palette.",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"}}),Cu=ye({id:"winamp",label:"WinAMP",description:"Bevelled grey chrome, black glass panes, phosphor green, and the spectrum ramp as the status palette.",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"}}),pa=Object.freeze([pu,fu,mu,uu,du,hu,Su,yu,gu,bu,wu,da,Iu,xu,Eu,vu,ku,Au,Cu].sort((t,e)=>t.label.localeCompare(e.label,void 0,{sensitivity:"base"}))),Tu=new Map(pa.map(t=>[t.id,t])),Mu=da.id;function Nu(){return pa}function De(t){return t?Tu.get(t)??null:null}const Pu=new Set(["agent","user","system"]);function Ts(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 _u(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:Pu.has(t.source)?t.source:"agent"}}function Ms(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const i of e){const r=_u(i);!r||n.has(r.filename)||(n.add(r.filename),s.push(r))}return s}function Ru(t,e){const s=String(e||"").trim();return s&&Ms(t).find(n=>n.filename===s)||null}function ii(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 Ns(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 ri(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 On(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 fa(t){if(t==null)return null;const e=String(t).trim();return e||null}function $n({mode:t="local",branding:e=null,docs:s=null,themeId:n=null,chatViewMode:i=null,sessionOwnerFilter:r=null,layoutAdjustments:o=null,pinnedSessionIds:l=null,collapsedSessionIds:c=null,activeSessionId:u=null,sessionOrder:d=null}={}){const p=r!=null,f=c!=null,h=ii(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:ze[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:De(n)?.id||Mu,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:fa(u),collapsedIds:On(c),collapsedIdsExplicit:f,pinnedIds:Ns(l),manualOrder:ri(d),listingSeen:!1,groupsListingSeen:!1,selectedIds:[],selectMode:!1,listDeselected:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:p,ownerFilter:Ts(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 ha(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function Ou(t,e){return!(!ha(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const ma="activeHighlightBackground",oi="activeHighlightForeground",gn="userChat",$u="userChatLabel",Lu="otherUserChatLabel",rr=new WeakMap,or=new WeakMap;function Fu(t){return t||oi}function ga(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Fu(s?.color):oi,backgroundColor:ma,bold:s?.bold??!0}))}function Ye(t,{color:e=oi,bold:s=!0}={}){return{text:t,color:e,backgroundColor:ma,bold:s}}function qe(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Bu=72;function ya(t){const e=Number(t)||0;return e>0&&e<=Bu}function ai(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function Du(t){const e=ai(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function Hu(t){const e=Sa(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function Sa(t){return t?.rowVisualStatus||ai(t)}function ba(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function li(t){const e=ai(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&ha(t?.error)&&!ba(t?.orchestrationStatus)?"warning":null}function wa(t,e="local"){const s=li(t);if(s)return s;const n=Sa(t);if(e==="remote"&&ba(t?.orchestrationStatus)&&n!=="cron_waiting"&&n!=="waiting"&&n!=="input_required"){if(t?.orchestrationStatus==="Completed")return"completed";if(t?.orchestrationStatus==="Terminated")return"terminated"}return n==="terminated"?"terminated":n}function Rt(t,e="local"){switch(wa(t,e)){case"running":return"green";case"cron_waiting":return"yellow";case"waiting":return"yellow";case"input_required":return"cyan";case"cancelled":return"gray";case"warning":return"yellow";case"failed":return"red";case"terminated":return"gray";case"completed":return"gray";case"idle":return"white";default:return"white"}}function Ia(t,e="local"){switch(wa(t,e)){case"running":return"*";case"cron_waiting":return"~";case"waiting":return"~";case"input_required":return"?";case"cancelled":return"x";case"warning":return"!";case"failed":case"terminated":return"x";case"idle":return"";default:return""}}function ue(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function js(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const ci=ue({provider:"system",subject:"system"});function ar(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 Ln(t){return ar(t?.displayName)||ar(t?.email)||"?"}function Gu(t,e=!1){return Ft(t)?e?"pinned":t.isGroup?"folders":t.groupId?`g:${t.groupId}`:"":null}function xa(t,{isMine:e=!1}={}){if(!t)return null;const s=js(t,t?.email||"");return{initials:Ln(t),hue:Ku(Vu(t,t?.email)),name:s||"unknown user",isMine:!!e}}function ju(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=ue(n);i&&!e.has(i)&&e.set(i,n)}return e}function Uu(t,e){if(t?.owner?.displayName||t?.owner?.email)return t.owner;const s=e?.get?.(ue(t?.owner))||null;return s||(t?.createdBy?{email:t.createdBy}:null)}const Wu=8;function Ku(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%Wu}function Vu(t,e){return String(e||t?.email||t?.displayName||(t?.provider&&t?.subject?`${t.provider}:${t.subject}`:"")||"").trim().toLowerCase()}function qu(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=ue(o.owner);if(!(!l||l===ci)&&Bn(o,n,i)&&(r.add(l),r.size>=e))break}return r.size}function Fn(t){return qu(t,2)>1}function Ea(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function vt(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of Ea(t,e)){const i=ue(n?.owner);i&&!s.has(i)&&s.set(i,n.owner)}return s.size===1?s.values().next().value:null}function lr(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function cr(t,e){const s=lr(t),n=lr(e?.agentId);return!!(s&&n&&s===n)}function zu(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&&cr(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&&cr(o,t))return{displayTitle:l,agentTitle:o}}return null}function Yu(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 Xu=[[/</g,"<"],[/>/g,">"],[/"/g,'"'],[/�?39;/g,"'"],[/'/g,"'"],[/ /g," "],[/&/g,"&"]];function Qu(t){let e=String(t??"");if(!e.includes("&"))return e;for(const[s,n]of Xu)e=e.replace(s,n);return e}function Us(t){return Qu(Ju(t))}function Ju(t){const e=String(t?.title||"").trim(),s=zu(t);if(!s)return e;const n=Yu(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function va(t,e){const s=de(t?.sessionId);if(t?.isSystem)return`${Ht(t,e)} (${s})`;const n=Us(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function Bn(t,e={},s={},n=void 0){if(!e||e.all===!0||t?.isGroup)return!0;if(t?.isSystem)return e.includeSystem===!0;const i=ue(n!==void 0?n:t?.owner);if(!i)return e.includeUnowned===!0;if(i===ci)return e.includeSystem===!0;const r=ue(s?.principal);return e.includeMe&&r&&i===r||e.includeShared===!0&&i!==r?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(i)}function ka(t,e={},s={},n=null){const i=vt(t,n||{});if(Bn(t,e,s,i))return!0;if(!n)return!1;if(t?.isGroup)return Ea(t,n).some(l=>ka(l,e,s,n));let r=t,o=0;for(;r?.parentSessionId&&o<16;){const l=n[r.parentSessionId];if(!l)return!1;if(Bn(l,e,s))return!0;r=l,o+=1}return!1}function Zu(t){return(t||[]).map(e=>e?.text||"").join("")}function ui(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 ur(t){const{childMap:e}=ui(t),s=new Map;function n(i){if(s.has(i))return s.get(i);const o=(e.get(i)||[]).reduce((l,c)=>l+1+n(c),0);return s.set(i,o),o}for(const i of Object.keys(t||{}))n(i);return s}function dr(t=[],e={}){const{parentMap:s}=ui(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 di(t={}){if(!t||typeof t!="object")return ur(t);const e=rr.get(t);if(e)return e;const s=ur(t);return rr.set(t,s),s}function pi(t=[],e={}){if(!Array.isArray(t))return dr(t,e);const s=or.get(t);if(s)return s;const n=dr(t,e);return or.set(t,n),n}function Aa(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 Ps(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 ed(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${Ps(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${At(t.cronInterval)}]`,color:"magenta"}:null}function Ca(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function td(t,e){const s=[];typeof t?.regenStage=="string"&&t.regenStage&&s.push({text:`↻ regen:${t.regenStage}`,color:"magenta"});const n=Hu(t);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:Rt(t,e)}));const i=Si(t?.model,t?.reasoningEffort);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i,color:"cyan"}));const r=zl(t?.contextUsage);r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r.text,color:r.color}));const o=Yl(t?.contextUsage);return o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color})),s}function sd(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:[]),u=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),d=!!s.sessions?.selectMode,p=u.has(t.sessionId),f=c.has(t.sessionId);if(p&&r.push({text:"▌",color:"cyan",bold:!0}),t.depth===0&&Ca(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 q=Ia(e,o);r.push({text:q?`${q} `:" ",color:Rt(e,o),role:"status"})}const h=e?.isGroup?"cyan":e?.isSystem?"yellow":Rt(e,o),g=vt(e,s.sessions?.byId||{}),m=de(e?.sessionId),y=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,S=y?Up(y):"",E=Si(e?.model,e?.reasoningEffort),I=e?.isSystem?Ht(e,s.branding?.title||"PilotSwarm"):Us(e),w=!!(e?.isSystem||e?.isGroup||I&&I.trim()),b=[...r];if(Fn(s)&&!e?.isSystem&&!e?.isGroup){const q=ue(s?.auth?.principal),se=!!(q&&ue(g)===q),ne=g?Ln(g):"?";b.push({text:`[${ne}] `,color:se?"green":"cyan",bold:!0,ownerChip:!0})}w?b.push({text:I,color:h,bold:!!(e?.isSystem||e?.isGroup)}):(b.push({text:m,color:h}),S&&(b.push({text:" · ",color:"gray"}),b.push({text:S,color:"gray"})),E&&(b.push({text:" · ",color:"gray"}),b.push({text:E,color:"green"})));const x=Aa(e?.sessionId,t,n,i);x&&b.push({text:` ${x.text}`,color:x.color,bold:x.bold});const k=ed(e);k&&b.push({text:" ⏱",color:"magenta"});const P=[],N=e?.contextUsage?.compaction?.state,B=Jn(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&P.push({text:`${e.memberCount}`,color:"gray"}):N==="running"?P.push({text:"⇊",color:"magenta"}):N==="failed"?P.push({text:"!",color:"red"}):B!=null?P.push({text:`${B}%`,color:B>=85?"red":B>=70?"yellow":"green"}):P.push({text:"—",color:"gray"});const $=[];e?.isGroup&&e?.memberCount!=null&&($.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),S&&($.push({text:" · ",color:"gray"}),$.push({text:S,color:"gray"})));const _=[],L=()=>{_.length&&_.push({text:" · ",color:"gray"})};if(e?.isGroup)_.push(...$);else{w&&(_.push({text:m,color:"cyan"}),S&&(L(),_.push({text:S,color:"gray"})),E&&(L(),_.push({text:E,color:"green"})));const q=e?.contextUsage;q&&Number.isFinite(q.currentTokens)&&Number.isFinite(q.tokenLimit)&&q.tokenLimit>0&&(L(),_.push({text:`ctx ${J(q.currentTokens)}/${J(q.tokenLimit)}`,color:"gray"}));const se=n?.[e?.sessionId];se&&(L(),_.push({text:`${se} child${se===1?"":"ren"}`,color:"gray"})),k&&(L(),_.push({text:k.text,color:k.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(L(),_.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...b,...w&&S&&!e?.isGroup?[{text:" ",color:"gray"},{text:S,color:"gray"}]:[],...P.length&&!e?.isGroup?[{text:" · ",color:"gray"},...P]:[],...e?.isGroup&&$.length?[{text:" ",color:"gray"},...$]:[]],titleRuns:b,ctxRuns:P,metaRuns:$,badgeRuns:[],selectedMetaRuns:_,detailRuns:_,childCount:n?.get?.(e?.sessionId)||0,chrome:{kind:e?.isGroup?"group":e?.isSystem?"system":e?.serviceKind?"service":"session",title:w?I:m,untitled:!w,statusColor:Rt(e,o),accentColor:h,pinned:f,selectMode:d,checked:p,owner:Fn(s)&&!e?.isSystem&&!e?.isGroup?{initials:g?Ln(g):"?",isMine:!!(ue(s?.auth?.principal)&&ue(g)===ue(s?.auth?.principal))}:null,childBadge:x?{text:x.text,color:x.color}:null,cron:!!k,age:S||null,model:E||null,shortId:m,ctx:P.length>0?{text:P[0].text,color:P[0].color}:null}}}function Ta(t){return String(t||"").trim().toLowerCase()}function dt(t,e){const s=Ta(e);return s?String(t||"").toLowerCase().includes(s):!0}function nd(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 pr=new WeakMap;function id(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 Bt(t){const e=di(t.sessions.byId),s=pi(t.sessions.flat,t.sessions.byId),n=Ta(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=nd(t.sessions);let u=pr.get(t.sessions.flat);return u||(u=new Map,pr.set(t.sessions.flat,u)),t.sessions.flat.filter(d=>!!(t.sessions.byId[d.sessionId]||d.standIn)).map(d=>{const p=t.sessions.byId[d.sessionId]||d.standIn,f=d.sessionId===t.sessions.activeSessionId&&!t.sessions.listDeselected,h=o.has(d.sessionId),g=l.has(d.sessionId),m=[d,p,f,h,g,n,i,r,t.connection?.mode,t.sessions.selectMode,e,s,t.branding?.title],y=u.get(d.sessionId);if(y&&id(y.deps,m))return y.row;const S=sd(d,p,t,e,s),E={sessionId:d.sessionId,text:Zu(S.runs),...S,depth:d.depth,status:p?.status,statusColor:Rt(p,t.connection?.mode||"local"),active:f,groupId:p?.groupId||d?.groupId||null,isSystem:!!p?.isSystem,isGroup:!!p?.isGroup,hasChildren:d.hasChildren,collapsed:d.collapsed,pinned:h,selected:g,canPin:Ca(p),ownerBadge:Fn(t)&&!p?.isSystem&&!p?.isGroup&&vt(p,t.sessions.byId)?xa(vt(p,t.sessions.byId),{isMine:!!(ue(t?.auth?.principal)&&ue(vt(p,t.sessions.byId))===ue(t?.auth?.principal))}):null,orderable:Ft(p),orderContainer:Gu(p,h)};return u.set(d.sessionId,{deps:m,row:E}),E}).filter(d=>{if(c?.has(d.sessionId))return!0;const p=t.sessions.byId[d.sessionId];if(!ka(p,i,r,t.sessions.byId))return!1;const f=vt(p,t.sessions.byId),h=f?`${js(f,"")} ${f.email||""}`:"",g=`${p?.shortSummary||""} ${p?.summaryState?.intent||""} ${p?.summaryState?.summary||""}`;return dt(d.text,n)||dt(d.sessionId,n)||dt(h,n)||dt(g,n)})}function Dn(t,e=8){const s=Bt(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),u=Math.min(i.length,c+e);u>i.length&&(u=i.length,c=Math.max(0,u-e));const d=i.slice(c,u);return di(t.sessions.byId),pi(i,t.sessions.byId),s.filter(p=>d.some(f=>f.sessionId===p.sessionId))}function He(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function rd(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 dy(t){const e=t.sessions?.filterExceptionId||null;return!e||!t.sessions?.byId?.[e]?null:"Showing linked session outside your current filters."}function Ma(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function od(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 ad(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),i=String(s?.answer||"").trim();if(!n||!i||Na(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 ld(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 Na(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>Hs(n?.text||"")?.question?.trim()===s):!1}function cd(t){const e=String(t?.error||"").trim();if(!e)return null;const s=li(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 fr(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 ud(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function dd(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=ud(r.text);if(o)return{...r,summaryText:o}}return null}function pd(t,e,s=[],n=[]){if(!t||t?.pendingQuestion?.question)return null;const i=String(t?.status||"").toLowerCase();if(i==="completed"||i==="failed"||i==="cancelled")return null;const r=(s||[]).filter(b=>b?.role==="user"||b?.role==="assistant"),o=r[r.length-1]||null,l=o?.role==="user",c=l&&o?.optimistic===!0,u=(n||[]).filter(b=>b?.phase==="pending").length,d=(n||[]).filter(b=>b?.phase==="queued").length,p=(n||[]).filter(b=>b?.phase==="cancelling").length,f=Array.isArray(e?.events)?e.events:[],h=fr(f,"user.message"),g=fr(f,"assistant.message"),m=h>g;if(i==="waiting"||i==="input_required"||!l&&!m&&i!=="running"&&!c)return null;const y=Math.max(h,g),S=f.filter(b=>b?.eventType==="assistant.reasoning"&&Number(b?.seq||0)>y),E=S[S.length-1]||null,I=String(E?.data?.content||E?.data?.text||E?.data?.message||"").trim();if(I)return{kind:"thinking",label:"Thinking",text:I,createdAt:E?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:g,tokenSeq:E?.seq||0};const w=dd(e,y);return w?.summaryText?{kind:i==="running"?"working":"sending",label:i==="running"?"Working":"Sending",text:w.summaryText,createdAt:w.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:g,tokenSeq:w.seq||0}:u>0?{kind:"pending",label:u===1?"Pending":`Pending ${u}`,text:u===1?"One prompt is waiting to be sent.":`${u} prompts are waiting to be sent.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:g,tokenSeq:0}:d>0?{kind:"queued",label:d===1?"Queued":`Queued ${d}`,text:d===1?"One prompt is durably queued, waiting for the LLM to receive it.":`${d} prompts are durably queued, waiting for the LLM to receive them.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:g,tokenSeq:0}: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:g,tokenSeq:0}:c?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:o?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:g,tokenSeq:0}:i==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:g,tokenSeq:0}:null}function Ws(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return on(t.branding);if(s?.isGroup){const u=Object.values(t.sessions.byId||{}).filter(h=>h&&!h.isGroup&&h.groupId===s.groupId&&!h.parentSessionId),d=h=>String(h??"").replace(/\|/g,"\\|").replace(/[\r\n]+/g," ").trim()||" ",p=u.map(h=>`| ${d(h.title||h.sessionId)} | ${d(h.status||"unknown")} | ${d(h.shortSummary||"")} |`),f=[`# ${s.title||s.groupId}`,s.shortSummary||"","","| Metric | Count |","|---|---:|",`| Members | ${s.memberCount??u.length} |`,`| Running | ${s.runningCount??0} |`,`| Waiting | ${s.waitingCount??0} |`,`| Completed | ${s.completedCount??0} |`,`| Failed | ${s.failedCount??0} |`,`| Cancelled | ${s.cancelledCount??0} |`,"","## Members",...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,g)=>g===1||String(h||"").length>0).join(`
|
|
30
|
-
`),createdAt:s.updatedAt||Date.now()}]}if(t.ui?.chatViewMode==="summary")return fd(s);const n=t.history.bySessionId.get(e),i=n?.chat||[],r=s?.pendingQuestion?.question&&!Na(i,s.pendingQuestion.question)?od(s):null,o=ad(s,i),l=cd(s);if((!n||i.length===0)&&!r&&!o&&!l)return on(t.branding,s);const c=i.length>0?[...i]:on(t.branding,s);return r&&c.push(r),o&&c.push(o),l&&c.push(l),c}function fd(t){const e=u=>{const d=String(u||"");return d.includes("\\n")?d.replace(/\\\\n/g,`
|
|
31
|
-
`).replace(/\\n/g,`
|
|
32
|
-
`):d},s=t?.summaryState&&typeof t.summaryState=="object"&&!Array.isArray(t.summaryState)?t.summaryState:null,n=s?.state&&typeof s.state=="object"&&!Array.isArray(s.state)?s.state:null,i=Us(t)||t?.title||t?.sessionId||"Session",r=[];r.push(`# ${i}`),r.push("");const o=[],l=Du(t);if(l&&o.push(["Status",l]),s?.intent&&o.push(["Intent",String(s.intent)]),t?.summaryUpdatedAt){const u=Pe(t.summaryUpdatedAt);u&&o.push(["Updated",u])}for(const[u,d]of o)r.push(`**${u}:** ${d}`);o.length>0&&r.push("");const c=e(s?.summary||t?.shortSummary||"").trim();if(c&&(r.push(c),r.push("")),n){const u=Object.entries(n).filter(([,d])=>d!=null&&!(typeof d=="string"&&!d.trim()));if(u.length>0){r.push("## State");for(const[d,p]of u)if(Array.isArray(p))if(p.length===0)r.push(`- **${d}:** _(empty)_`);else{r.push(`- **${d}:**`);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(`- **${d}:**`);for(const[f,h]of Object.entries(p).slice(0,16)){const g=typeof h=="string"?e(h):JSON.stringify(h);r.push(` - **${f}:** ${g}`)}}else r.push(`- **${d}:** ${e(String(p))}`);r.push("")}}for(const[u,d]of[["Blockers","blockers"],["Open Questions","openQuestions"],["Next Actions","nextActions"]]){const p=Array.isArray(s?.[d])?s[d].filter(Boolean).slice(0,12):[];if(p.length!==0){r.push(`## ${u}`);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 hd(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>ld(e,s)).filter(Boolean):[]:[]}function yn(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function Pa(t,e={}){const s=Pe(t?.createdAt||t?.time),n=t?.sender,i=n?.kind==="user"?ue(n):null,r=e?.viewerKey||null,o=e?.ownerKey||null,l=e?.sharedContext===!0,c=t?.role==="user",d=l&&c&&i&&!(c&&i&&r&&i===r),f=l&&c&&o&&(i&&i===o||!i&&r&&r===o)?" (owner)":"",h=c?(d?n.display||n.subject||"User":"You")+f:t?.role==="assistant"?"Agent":t?.role==="system"?"System":"PilotSwarm";let g=null,m=null;t?.pendingPhase==="pending"?(g="○",m="yellow"):t?.pendingPhase==="queued"?(g="✓",m="cyan"):t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?(g="x",m="red"):t?.role==="user"&&!t?.optimistic&&!t?.pendingPhase&&(t?.stopped?(g="⊘",m="yellow"):t?.redelivered?(g="✓✓↻",m="yellow"):(g="✓✓",m="green"));const y=t?.pendingPhase==="pending"?"yellow":t?.pendingPhase==="queued"?"cyan":t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?"red":d?Lu:t?.role==="user"?$u:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white";return{time:s,glyph:g,glyphColor:m,roleLabel:h,roleColor:y,fromOtherPerson:d}}function md(t,e={}){const{time:s,glyph:n,glyphColor:i,roleLabel:r,roleColor:o}=Pa(t,e),l=s?`[${s}] `:"",c=[...yn(l,"gray")];return n&&c.push(...yn(`${n} `,i)),c.push(...yn(`${r}: `,o,{bold:!0})),c}function ot(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function _a(){return[{text:"",color:null}]}function gd(t){const e=(t||[]).find(n=>ot(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=ot(e).trimStart();return/^[┌│└]/.test(s)}function _s(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(ot(s).trim().length>0)break;e.shift()}return e}function yd(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 Sd.test(s)?{leadingText:"",systemText:s}:null}const Sd=/^(?: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 fi(t){const e=yd(t);if(e){const o=[];e.leadingText&&o.push({kind:"text",text:e.leadingText});const l=rt(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=rt(c[1].trim());if(!f){o+=1;continue}n.push({kind:"system",text:f}),o+=1;continue}const u=[l.replace(/^\s*\[SYSTEM:\s*/i,"")];let d=-1;for(let f=o+1;f<s.length;f+=1){const h=s[f];if(h.trim()==="]"){d=f;break}if(/\]\s*$/.test(h.trim())){const g=h.replace(/\]\s*$/,"");g.trim()&&u.push(g),d=f;break}u.push(h)}if(d===-1){i.push(l),o+=1;continue}r();const p=rt(u.join(`
|
|
40
|
-
`).trim());if(!p){o=d+1;continue}n.push({kind:"system",text:p}),o=d+1}return r(),n}function bd(t){return t?t?.role==="system"?!ti(t?.text||"")||!!rt(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:fi(t?.text||"").some(e=>e.kind==="system"):!1}function hr(t){return bd(t)?"system":t?.role||"other"}function Ra(t,e){return!t||!e?!1:hr(t)!==hr(e)}function wd(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 Id(t,e=""){const s=wd(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:ft(t),color:"gray"}}function mr({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:ft(s||o),color:i}}function xd(t){return t?.label?[{text:t.label,color:t.kind==="working"?"yellow":"cyan",bold:!0}]:null}function Ed(t,e){return e?(t||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||e})):s):t}function vd(t){const e=(t||[]).find(s=>ot(s).trim().length>0);return e?ot(e).trimStart().startsWith("┌"):!1}function Rs(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&vd(e)&&ot(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function kd(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 Ad(t,e,s){const n=Math.max(20,Number(s)||20),i=Pe(e?.createdAt||e?.time),r=kd(t),o=l=>{const c=String(l||"").replace(/^session-/i,"");return de(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((u,d)=>d===2||u).join(`
|
|
41
|
-
`);return[mr({title:`Sub-agent Response — ${l}`,summary:r.status||"completed",timestamp:i,body:c,color:"cyan"})]}if(r?.kind==="subAgentMulti"){const l=r.agents.map(u=>{const d=o(u.agentId),p=u.task?`**Task:** ${u.task}`:"",f=u.status?`**Status:** ${u.status}`:"";return`${[`### ${d}`,p,f].filter(Boolean).join(`
|
|
42
|
-
`)}
|
|
43
|
-
|
|
44
|
-
${u.result||"_(no result)_"}`}),c=r.agents.map(u=>`${o(u.agentId)} ${u.status||"completed"}`).join(" · ");return[mr({title:`Sub-agent Responses (${r.agents.length})`,summary:c,timestamp:i,body:l.join(`
|
|
45
|
-
|
|
46
|
-
---
|
|
47
|
-
|
|
48
|
-
`),color:"cyan"})]}return he({title:"System",timestamp:i,body:t,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function Cd(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),i=Pe(t?.createdAt||t?.time),r=String(t?.thinkingLabel||"Thinking…").trim()||"Thinking…",o=t?.progressKind==="working"?"yellow":(t?.progressKind==="sending","cyan"),l=oe([{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),u=Math.max(0,s-c-3),d=String(t?.text||"").trim()?_s($t(ft(t.text),{width:n})).flatMap(f=>Uo(f,n)):[],p=[[{text:"┌─",color:"gray"},...l,{text:`${"─".repeat(u)}┐`,color:"gray"}]];for(const f of d)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 Td(t){return String(t||"").split(`
|
|
49
|
-
`).reduce((e,s)=>Math.max(e,Zn(s).length),0)}function Dt(t,e,s={}){if(t?.splash){const u=t.mobileText&&Td(t.text)>e;return[{kind:"markup",value:u?t.mobileText:t.text,splashAlt:!u&&t.mobileText?t.mobileText:null}]}if(t?.thinking)return Cd(t,e);if(t?.noChrome)return _s($t(ft(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const u=Hs(t?.text||"");if(u)return[...he({title:"Question",timestamp:Pe(t?.createdAt||t?.time),body:u.question,width:Math.max(20,e),titleColor:gn,borderColor:gn,tableMode:s.tableMode}),...Dt({...t,text:u.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const u=fi(t?.text||"");if(u.some(d=>d.kind==="system")){const d=[];let p=!1;for(const h of u)h.kind!=="system"&&h.text.trim()&&(Rs(d,Dt({...t,text:h.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:p})),p=!0);if(d.length>0)return d;const f=[];for(const h of u)h.kind!=="system"||!h.text.trim()||Rs(f,Ad(h.text,t,e));if(f.length>0)return f}}if(t?.role!=="user"&&t?.role!=="assistant"){const u=rt(t?.text||"");if(t?.role==="system"&&!u)return[];const d=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!d)return[Id(u||t?.text||"",Pe(t?.createdAt||t?.time))];const p=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return he({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:Pe(t?.createdAt||t?.time),body:ft(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=_s($t(ft(t?.text||""),{width:e,tableMode:s.tableMode})),i=Ed(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?gn:null),r=s.skipPrefix?[]:md(t,s),o=Oa(t,s);if(i.length===0){const u=r.length>0?[r]:[];return o.length>0?[...u,...o]:u}if(gd(i)){const u=r.length>0?[r,...i]:i;return o.length>0?[...u,...o]:u}const l=[];let c=r.length===0;for(const u of i){if(!Array.isArray(u)){c||(l.push(r),c=!0),l.push(u);continue}c?l.push(u):(l.push([...r,...u]),c=!0)}return l.push(...o),l}function Oa(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 Md=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 Nd(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 Pd=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),_d=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function Rd(t,e){const s=String(t||"").toLowerCase();return s==="search_skills"||s.includes("skill")?e?"loading skills…":"loaded skills":Pd.has(s)?e?"reading facts…":"read facts":_d.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 Od(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=Rd(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 hi(t,e={}){if(t?.ui?.chatViewMode==="summary")return[];const s=He(t);if(!s||s.isGroup)return[];if(String(s?.status||"").toLowerCase()!=="running")return[];const i=t.history?.bySessionId?.get(s.sessionId)||null,r=Array.isArray(i?.chat)?i.chat:[];let o=0;for(let E=r.length-1;E>=0;E-=1)if(r[E]?.role==="user"){o=Number(r[E]?.createdAt||0);break}const l=Array.isArray(i?.activity)?i.activity:[];let c=0,u=0;for(let E=l.length-1;E>=0;E-=1){const I=l[E],w=I?.eventType,b=Number(I?.createdAt||0);if(!c&&w==="assistant.turn_start"&&(c=b),!u&&(w==="assistant.turn_end"||w==="session.turn_completed")&&(u=b),c&&u)break}let d=0;o>u?d=o:c>u&&(d=c);let p=null;for(let E=l.length-1;E>=0;E-=1){const I=l[E];if(!(!I||Md.has(I.eventType))){if(Number(I.createdAt||0)<=u)break;p=I;break}}const f=Number.isFinite(e.now)?e.now:Date.now(),h=d>0?Nd(f-d):"",g=String(e.spinnerFrame||"").trim()||"●",m=p?Od(p):"",y=[{text:`${g} `,color:"cyan"},{text:"Working",color:"cyan"},...h?[{text:` · ${h}`,color:"gray"}]:[],...m?[{text:` — ${m}`,color:"gray"}]:[]],S=Math.max(24,Math.min(120,Math.floor(Number(e.maxWidth)||80)));return[oe(y,S)]}const gr=4;let cs=[];function mi(t,e=80,s={}){const n=t?.sessions?.activeSessionId??null,i={sessionId:n,session:n?t?.sessions?.byId?.[n]??null:null,byId:t?.sessions?.byId??null,chat:t?.history?.bySessionId?.get?.(n)?.chat??null,viewMode:t?.ui?.chatViewMode??null,branding:t?.branding??null,principal:t?.auth?.principal??null,maxWidth:e,tableMode:s?.tableMode??null};for(const g of cs)if(g.sessionId===i.sessionId&&g.session===i.session&&g.byId===i.byId&&g.chat===i.chat&&g.viewMode===i.viewMode&&g.branding===i.branding&&g.principal===i.principal&&Object.is(g.maxWidth,i.maxWidth)&&g.tableMode===i.tableMode)return g.lines;const r=g=>(cs.unshift({...i,lines:g}),cs.length>gr&&(cs.length=gr),g),o=Ws(t);if(!o||o.length===0)return r([{text:"No messages yet.",color:"gray"}]);const l=ue(t?.auth?.principal),c=t?.sessions?.activeSessionId,u=c?t?.sessions?.byId?.[c]:null,d=ue(u?.owner),p=!!(u&&(u.visibility&&u.visibility!=="private"||d&&l&&d!==l)),f={...s?.tableMode?{tableMode:s.tableMode}:{},...l?{viewerKey:l}:{},...d?{ownerKey:d}:{},...p?{sharedContext:!0}:{}},h=[];for(const[g,m]of o.entries()){if(m?.kind==="epoch-divider")h.push($a(m,e));else if(m?.kind==="regen-refused")h.push(La(m,e));else if(m?.kind==="regen-failed")h.push(Fa(m,e));else{const S=Dt(m,e,f);Rs(h,S)}const y=o[g+1];y&&Ra(m,y)&&ot(h[h.length-1]).trim().length>0&&h.push(_a())}return r(h.length>0?h:[{text:"No messages yet.",color:"gray"}])}function $d(t){return!(!t||t.kind==="epoch-divider"||t.kind==="regen-refused"||t.kind==="regen-failed"||t.splash||t.thinking||t.noChrome||t.role!=="user"&&t.role!=="assistant"||t.role==="user"&&Hs(t?.text||"")||fi(t?.text||"").some(s=>s.kind==="system"))}const yr=new WeakMap;function Ld(t,e=80,s={}){const n=Ws(t);if(!n||n.length===0)return[];const i=ue(t?.auth?.principal),r=t?.sessions?.activeSessionId,o=r?t?.sessions?.byId?.[r]:null,l=ue(o?.owner),c=!!(o&&(o.visibility&&o.visibility!=="private"||l&&i&&l!==i)),u={...s?.tableMode?{tableMode:s.tableMode}:{},...i?{viewerKey:i}:{},...l?{ownerKey:l}:{},...c?{sharedContext:!0}:{}},d=[];for(const p of n){const f=p?yr.get(p):null;if(f&&Object.is(f.text,p.text)&&Object.is(f.kind,p.kind)&&Object.is(f.role,p.role)&&Object.is(f.id,p.id)&&Object.is(f.pendingPhase,p.pendingPhase)&&Object.is(f.stopped,p.stopped)&&Object.is(f.createdAt,p.createdAt)&&Object.is(f.time,p.time)&&Object.is(f.sender,p.sender)&&Object.is(f.attachments,p.attachments)&&Object.is(f.tableMode,u.tableMode)&&Object.is(f.viewerKey,u.viewerKey)&&Object.is(f.ownerKey,u.ownerKey)&&Object.is(f.sharedContext,u.sharedContext)){d.push(f.block);continue}if(p?.kind==="epoch-divider"){d.push({kind:"lines",variant:"divider",lines:[$a(p,e)]});continue}if(p?.kind==="regen-failed"){d.push({kind:"lines",variant:"divider",lines:[Fa(p,e)]});continue}if(p?.kind==="regen-refused"){d.push({kind:"lines",variant:"divider",lines:[La(p,e)]});continue}if($d(p)){const m=Oa(p,{tableMode:"sentinel"}).find(S=>S?.kind==="imageAttachments")||null,y={kind:"message",id:p?.id??null,role:p.role,header:Pa(p,u),text:ft(p?.text||""),pendingPhase:p?.pendingPhase||null,attachments:m?{sessionId:m.sessionId,attachments:m.attachments}:null};yr.set(p,{block:y,text:p.text,kind:p.kind,createdAt:p.createdAt,time:p.time,sender:p.sender,attachments:p.attachments,role:p.role,id:p.id,pendingPhase:p.pendingPhase,stopped:p.stopped,tableMode:u.tableMode,viewerKey:u.viewerKey,ownerKey:u.ownerKey,sharedContext:u.sharedContext}),d.push(y);continue}const h=Fd(p,e,u);h&&d.push(h)}return d}const Sr=new WeakMap;function Fd(t,e,s){if(!t||typeof t!="object"){const o=Dt(t,e,s);return o.length>0?{kind:"lines",variant:"event",lines:o}:null}const n=Sr.get(t);if(n&&Object.is(n.maxWidth,e)&&Object.is(n.text,t.text)&&Object.is(n.mobileText,t.mobileText)&&Object.is(n.role,t.role)&&Object.is(n.time,t.time)&&Object.is(n.createdAt,t.createdAt)&&Object.is(n.splash,t.splash)&&Object.is(n.thinking,t.thinking)&&Object.is(n.thinkingLabel,t.thinkingLabel)&&Object.is(n.progressKind,t.progressKind)&&Object.is(n.noChrome,t.noChrome)&&Object.is(n.cardTitle,t.cardTitle)&&Object.is(n.cardTitleColor,t.cardTitleColor)&&Object.is(n.cardBorderColor,t.cardBorderColor)&&Object.is(n.stopped,t.stopped)&&Object.is(n.tableMode,s.tableMode)&&Object.is(n.viewerKey,s.viewerKey)&&Object.is(n.ownerKey,s.ownerKey)&&Object.is(n.sharedContext,s.sharedContext))return n.block;const i=Dt(t,e,s),r=i.length>0?{kind:"lines",variant:"event",lines:i}:null;return Sr.set(t,{block:r,maxWidth:e,text:t.text,mobileText:t.mobileText,role:t.role,time:t.time,createdAt:t.createdAt,splash:t.splash,thinking:t.thinking,thinkingLabel:t.thinkingLabel,progressKind:t.progressKind,noChrome:t.noChrome,cardTitle:t.cardTitle,cardTitleColor:t.cardTitleColor,cardBorderColor:t.cardBorderColor,stopped:t.stopped,tableMode:s.tableMode,viewerKey:s.viewerKey,ownerKey:s.ownerKey,sharedContext:s.sharedContext}),r}function gi(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 $a(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 gi(n,"magenta",e)}const Bd={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 La(t,e){const s=String(t?.reason||"unknown"),i=` ↻ regeneration refused · ${Bd[s]||s.replace(/_/g," ")} `;return gi(i,"yellow",e)}function Fa(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 gi(r,"red",e)}function yi(t,e=80,s={}){const n=hd(t);if(!n||n.length===0)return[];const i=Math.max(20,Number(e)||80),r=n.filter(g=>g.pendingPhase==="queued").length,o=n.filter(g=>g.pendingPhase==="pending").length,l=n.filter(g=>g.pendingPhase==="cancelling").length,c=n.filter(g=>g.pendingPhase==="rejected").length,u=[];o>0&&u.push(`${o} pending`),r>0&&u.push(`${r} queued`),l>0&&u.push(`${l} cancelling`),c>0&&u.push(`${c} rejected`);const f=[[{text:` queued prompts: ${u.length>0?u.join(" · "):"queued prompts"} `,color:"gray",trailingRule:!0}]],h=s?.tableMode?{tableMode:s.tableMode}:{};for(const[g,m]of n.entries()){Rs(f,Dt(m,i,h));const y=n[g+1];y&&Ra(m,y)&&ot(f[f.length-1]).trim().length>0&&f.push(_a())}return f}function Dd(t){const e=Ws(t),s=[],n=new Set;for(const i of e||[])for(const r of uc(i?.text||"")){const o=`${r.sessionId}/${r.filename}`;n.has(o)||(n.add(o),s.push(r))}return s}function Hd(t){const e=Ws(t),s=[],n=new Set;for(const i of e||[])for(const r of dc(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 Si(t,e){const s=Bo(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function Gd(t){return Bo(t)||"(unknown)"}function Ba(t,e={}){const s=He(t),n=t.sessions?.byId||{},i=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],r=di(n),o=pi(i,n),l=ya(e?.width);if(!s)return{color:"cyan",title:qe("Chat","cyan"),titleRight:null,animateTitleRight:!1};const c=de(s.sessionId),u=s.isSystem?"yellow":"cyan",d=qe(s.isSystem?`⚙ ${Ht(s,t.branding?.title||"PilotSwarm")}`:Us(s)||"Chat",u),p=i.find(w=>w.sessionId===s.sessionId),f=Aa(s.sessionId,p,r,o);f&&d.push({text:` ${f.text}`,color:f.color}),l||d.push({text:` [${c}]`,color:"gray"});const h=t.history?.bySessionId?.get(s.sessionId)||null,g=Array.isArray(t.outbox?.bySessionId?.[s.sessionId])?t.outbox.bySessionId[s.sessionId]:[],m=t.ui?.chatViewMode==="summary"?null:pd(s,h,h?.chat||[],g),y=t.connection?.mode||"local",S=td(s,y),E=xd(m),I=E?[...S,...S.length?[{text:" · ",color:"gray"}]:[],...E]:S;return{color:s.isSystem?"yellow":"cyan",title:d,titleRight:I.length?I:null,animateTitleRight:!!m}}function jd(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function Da(t){const e=qa(t),s=e.selected?e.nodes.find(o=>o.label===e.selected):null,n=qe("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 bi(t,e=12){const s=jd(t),n=He(t),i=qe("Activity","gray");return n?.isGroup?{title:i,disabled:!0,lines:[{text:Qa,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 Ha(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 Ga(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":Ha(e)}function Ud(t){return t==="raw"?"raw summary":"pretty text"}function Wd(t){return t?.sessionId?`session-${t.sessionId}`:null}function Kd(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},i=Wd(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 Vd(t){const e=is(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:Ga(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${de(s)}] `,color:"gray"}]:[],{text:`${n} `,color:Ha(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function qd(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${de(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:Ga(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function zd(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:Ud(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=Kd(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"?Vd(o):qd(o))]}function br(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function Yd(t){return/\.(json|jsonl)$/i.test(String(t||""))}function Xd(t){return ze.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function Qd(t=""){const e=String(t||"").split(`
|
|
51
|
-
`);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function wr(t,{selected:e=!1,width:s=24,label:n=null}={}){const i=Math.max(8,s),r=br(t)?"# ":Yd(t)?"{ ":"• ",o=ja(`${r}${n||t}`,i).padEnd(i," ");return e?Ye(o):{text:o,color:br(t)?"cyan":"white",bold:!1}}function Fe(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function Jd(t,e={}){if(!t)return new Set;const{childMap:s}=ui(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 Os(t,e=Fe(t)){const s=He(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=Jd(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 Ir(t){const s=He(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 u=typeof c?.data?.content=="string"?c.data.content:"";if(!u)continue;l.lastIndex=0;let d;for(;(d=l.exec(u))!==null;){const p=`${d[1]}/${d[2]}`;r.has(p)||(r.add(p),o.push(p))}}return o}function pt(t){const e=Fe(t);He(t)?.sessionId;const s=t.files?.filter?.query||"",n=Os(t,e),i=e==="allSessions"||n.length>1,r=[];for(const o of n){const l=Ms(t.files?.bySessionId?.[o]?.entries);for(const c of l){const u=c.filename;r.push({id:`${o}/${u}`,sessionId:o,filename:u,entry:c,label:i?`[${de(o)}] ${u}`:u})}}return r.filter(o=>dt(o.filename,s)||dt(o.sessionId,s)||dt(o.label,s))}function nt(t){const e=pt(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(Fe(t)==="allSessions"){const o=He(t)?.sessionId||null,l=o&&t.files?.bySessionId?.[o]?.selectedFilename||null;if(o&&l){const c=e.find(u=>u.sessionId===o&&u.filename===l);if(c)return c}return e[0]}const i=He(t)?.sessionId||null,r=i&&t.files?.bySessionId?.[i]?.selectedFilename||null;return e.find(o=>o.sessionId===i&&o.filename===r)||e[0]}function wi(t,e={}){const s=He(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=Fe(t),c=t.files?.filter?.query||"",u=pt(t),d=nt(t),p=d?.filename||null,f=Math.max(0,u.findIndex(_=>_.id===d?.id)),h=d?.sessionId&&p&&t.files?.bySessionId?.[d.sessionId]?.previews?.[p]||null,g=h||d?.entry||null,m=s?de(s.sessionId):"",y=Os(t,l),S=l!=="allSessions"&&y.some(_=>_&&_!==o),E=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(_=>_?.sessionId||_):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),I=l==="allSessions"&&E.some(_=>!t.files?.bySessionId?.[_]?.loaded||t.files?.bySessionId?.[_]?.loading),w=l==="allSessions"&&E.map(_=>t.files?.bySessionId?.[_]?.error).find(Boolean)||null,b=[Xd("files"),...s||l==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(l==="allSessions")I&&u.length===0?b.push({text:"Loading exported files across all sessions…",color:"gray"}):w&&u.length===0?b.push({text:w,color:"red"}):u.length===0?(b.push({text:c?`No artifacts matched "${c}" across any session.`:"No exported files across any session yet.",color:"gray"}),b.push({text:c?"Clear the query or switch back to the selected session.":"Switch the filter back to the selected session or wait for agents to export artifacts.",color:"gray"})):b.push(...u.map((_,L)=>wr(_.filename,{selected:L===f,width:n,label:_.label})));else if(s){const _=o?t.files?.bySessionId?.[o]:null;Array.isArray(_?.entries)&&_.entries;const L=u.filter(j=>y.includes(j.sessionId));_?.loading?b.push({text:"Loading exported files…",color:"gray"}):_?.error?b.push({text:_.error,color:"red"}):L.length===0&&y.every(j=>{const q=t.files?.bySessionId?.[j]?.entries;return!Array.isArray(q)||q.length===0})?(b.push({text:c?`No artifacts matched "${c}" for this ${S?"session tree":"session"}.`:`No exported files for this ${S?"session tree":"session"} yet.`,color:"gray"}),b.push({text:c?"Clear the query or upload an artifact to this session.":S?"Artifacts exported by this session or any child session will appear here.":"Agents must write/export artifacts before they appear here.",color:"gray"})):b.push(...L.map((j,q)=>wr(j.filename,{selected:q===f,width:n,label:j.label})))}let x,k;!s&&l!=="allSessions"?(k=[{text:"Preview",color:"cyan",bold:!0}],x=[{text:"No session selected.",color:"gray"}]):p?h?.loading?(k=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||d?.sessionId&&d.sessionId!==o)&&d?.sessionId?[{text:` · ${de(d.sessionId)}`,color:"gray"}]:[]],x=[{text:"Loading file preview…",color:"gray"}]):h?.error?(k=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||d?.sessionId&&d.sessionId!==o)&&d?.sessionId?[{text:` · ${de(d.sessionId)}`,color:"gray"}]:[]],x=[{text:h.error,color:"red"}]):(k=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||d?.sessionId&&d.sessionId!==o)&&d?.sessionId?[{text:` · ${de(d.sessionId)}`,color:"gray"}]:[],...h?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:h?.isBinary===!0?[{text:" [file]",color:"gray"}]:h?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],x=h?.renderMode==="markdown"?_s($t(h?.content||"",{width:i})):Qd(h?.content||"")):(k=[{text:"Preview",color:"cyan",bold:!0}],x=[{text:"Select a file to preview it here.",color:"gray"}]);const P=l==="allSessions"?"Files: all sessions":s?`Files: ${m}${S?" tree":""}`:"Files",N=l==="allSessions"?"all sessions":s?`${m}${S?" tree":""}`:"Files",B=l==="allSessions"?`Artifacts${u.length>0?` [${u.length}]`:""}`:`Artifacts${S?" tree":""}${u.length>0?` [${u.length}]`:""}`,$=c?` · @${c}`:"";return{panelTitle:[{text:`${P}${$}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${N}${$}`,color:"magenta",bold:!0}],listTitle:[{text:`${B}${$}`,color:"cyan",bold:!0}],listLines:b,listBodyLines:b.slice(1),selectedIndex:f,selectedFilename:p,selectedSessionId:d?.sessionId||null,scope:l,previewTitle:k,previewLines:x,previewContent:h?.content||"",previewContentType:h?.contentType||"",previewRenderMode:h?.renderMode||null,previewIsBinary:g?.isBinary===!0,previewSizeBytes:g?.sizeBytes??null,previewUploadedAt:g?.uploadedAt||"",previewSource:g?.source||null,previewError:h?.error||null,previewLoading:!!h?.loading,previewScrollOffset:t.ui.scroll.filePreview||0,fullscreen:!!t.files?.fullscreen,fullscreenTitle:[{text:P,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 xr(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);return Number.isNaN(e.getTime())?"—":e.toISOString().slice(0,10)}function kt(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 Zd(t){const e=String(t||"").toLowerCase();return e.endsWith(".md")?"markdown":e.endsWith(".json")?"json":/\.(mjs|cjs|js)$/.test(e)?"javascript":"text"}function ep(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,u=l?"System key":"key",d=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${d}`:"System key not configured — ownerless system sessions fall back to env GITHUB_TOKEN":s?.githubCopilotKeySet?"Configured (overrides env GITHUB_TOKEN for this user)":"Not configured (using env GITHUB_TOKEN fallback)",f=e.packages||{},h=Array.isArray(f.list)?f.list:[],g=A=>!!(o||A?.owner&&i&&A.owner.provider===i.provider&&A.owner.subject===i.subject),m=ju(t?.sessions?.byId),y=new Set;for(const A of h){if(A?.scope==="shared")continue;const F=ue(A?.owner)||String(A?.createdBy||"").trim().toLowerCase();!F||F===ci||y.add(F)}const S=y.size>1,E=A=>({name:A.name,scope:A.scope==="shared"?"shared":"user",enabled:!!A.enabled,semver:A.active?.semver||null,sha7:A.active?.sha256?String(A.active.sha256).slice(0,7):null,agentCount:Array.isArray(A.active?.manifest?.agents)?A.active.manifest.agents.length:0,canManage:g(A),ownerBadge:A.scope==="shared"||!S?null:xa(Uu(A,m)),selected:e.section==="packages"&&f.selectedName===A.name}),I=A=>!!(A?.owner&&i&&A.owner.provider===i.provider&&A.owner.subject===i.subject),w=t.sessions?.ownerFilter,b=A=>{if(!w||w.all===!0)return!0;const F=ue(A?.owner);return F?Array.isArray(w.ownerKeys)&&w.ownerKeys.includes(F):w.includeUnowned===!0},x=h.filter(A=>A.scope==="shared").map(E),k=h.filter(A=>A.scope!=="shared"&&I(A)).map(E),P=h.filter(A=>A.scope!=="shared"&&!I(A)&&b(A)).map(A=>({...E(A),ownerLabel:A?.createdBy||A?.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:x.length},...x.map(A=>({id:`pkg:${A.name}`,kind:"package",depth:2,label:A.name,...A})),{id:"group:user",kind:"group",depth:1,label:"User",count:k.length},...k.map(A=>({id:`pkg:${A.name}`,kind:"package",depth:2,label:A.name,...A})),...P.length>0?[{id:"group:others",kind:"group",depth:1,label:"Other users",count:P.length},...P.map(A=>({id:`pkg:${A.name}`,kind:"package",depth:2,label:A.name,...A}))]:[],...o?[{id:"workers",kind:"section",depth:0,label:"Workers",selected:N==="workers"}]:[]],$=f.detail||null;let _=null;if(f.selectedName){const A=h.find(K=>K.name===f.selectedName)||null,F=$?.versions?.find(K=>K.versionId===$.activeVersionId)||null,X=F?.manifest||A?.active?.manifest||{},le=Date.now()-9e4,ge=(Array.isArray(f.workerState)?f.workerState:[]).filter(K=>{const Ee=K?.updatedAt instanceof Date?K.updatedAt:new Date(K?.updatedAt??0);return!Number.isNaN(Ee.getTime())&&Ee.getTime()>=le}),we=ge.length,ke=F?ge.filter(K=>K.installed?.[f.selectedName]?.semver===F.semver&&K.installed?.[f.selectedName]?.status==="ok").length:0,Ue=$?g($):A?g(A):!1;_={name:f.selectedName,loading:!!f.detailLoading,error:f.detailError||null,scope:($?.scope||A?.scope)==="shared"?"shared":"user",enabled:$?!!$.enabled:!!A?.enabled,canManage:Ue,createdBy:$?.createdBy||A?.createdBy||null,createdAtText:xr($?.createdAt||A?.createdAt),description:typeof X.description=="string"?X.description:"",activeSemver:F?.semver||A?.active?.semver||null,activeSha12:F?.sha256?String(F.sha256).slice(0,12):null,sizeText:kt(F?.sizeBytes??A?.active?.sizeBytes),agents:Array.isArray(X.agents)?X.agents.map(K=>({name:K.name,description:K.description||"",toolCount:Array.isArray(K.tools)?K.tools.length:0,skillCount:Array.isArray(K.skills)?K.skills.length:0})):[],versions:($?.versions||[]).map(K=>({semver:K.semver,sha12:String(K.sha256||"").slice(0,12),dateText:xr(K.createdAt),active:K.versionId===$?.activeVersionId})),fleet:we>0&&F?{current:ke,total:we,text:`${ke}/${we} workers current`}:null,actionPending:f.action?.pending||null,actionError:f.action?.error||null}}const L=f.workspace||{};let j=null;if(f.selectedName){const A=L.tree,F=new Set(L.expandedDirs||[]),X=[];if(A){const le=K=>{const Ee=K.split("/");for(let We=1;We<Ee.length;We++)if(!F.has(Ee.slice(0,We).join("/")))return!1;return!0},ge=Array.isArray(A.dirs)?A.dirs:[],we=Array.isArray(A.files)?A.files:[],ke=K=>String(K).split("/").join("\0"),Ue=[...ge.map(K=>({type:"dir",path:K})),...we.map(K=>({type:"file",path:K.path,size:K.size}))].sort((K,Ee)=>ke(K.path)<ke(Ee.path)?-1:1);for(const K of Ue){if(!le(K.path))continue;const Ee=K.path.split("/").length-1;X.push({type:K.type,path:K.path,label:K.path.split("/").pop()+(K.type==="dir"?"/":""),depth:Ee,expanded:K.type==="dir"?F.has(K.path):void 0,sizeText:K.type==="file"?kt(K.size):null,selected:L.selectedPath===K.path})}}const z=L.file;j={loading:!!L.treeLoading,error:L.treeError||null,semver:L.tree?.semver||null,treeRows:X,file:z?{path:z.path,sizeText:kt(z.size),truncated:!!z.truncated,isBinary:z.encoding==="base64",text:z.encoding==="base64"?null:String(z.content||""),language:Zd(z.path)}:null,fileLoading:!!L.fileLoading,fileError:L.fileError||null,selectedPath:L.selectedPath||null}}const q=e.workers||{},se=Array.isArray(q.list)?q.list:[],ne=9e4,Re=Date.now(),re=A=>!Number.isFinite(A)||A<0?"—":A<6e4?`${Math.round(A/1e3)}s ago`:A<36e5?`${Math.round(A/6e4)}m ago`:`${Math.round(A/36e5)}h ago`,be=A=>{if(!Number.isFinite(A)||A<0)return null;if(A<60)return`${Math.round(A)}s`;if(A<3600)return`${Math.floor(A/60)}m`;const F=Math.floor(A/3600);return F<48?`${F}h ${Math.floor(A%3600/60)}m`:`${Math.floor(F/24)}d ${F%24}h`},v=se.map(A=>{const F=A?.updatedAt instanceof Date?A.updatedAt:new Date(A?.updatedAt??0),X=Number.isNaN(F.getTime())?Number.NaN:Re-F.getTime(),z=A?.health||{},le=A?.info||{},ge=A?.state?.["agent-packages"]||null,we=ge?.installed&&typeof ge.installed=="object"?Object.values(ge.installed):[],ke=we.filter(Ue=>Ue?.status==="error").length;return{id:String(A?.workerNodeId??""),pool:String(A?.pool??"default"),phase:["starting","ready","draining"].includes(A?.phase)?A.phase:"ready",live:Number.isFinite(X)&&X<=ne,agoText:re(X),uptimeText:be(z.uptimeS),rssText:kt(z.rssBytes),sessions:Number.isFinite(z.activeSessions)?z.activeSessions:null,eventLoopText:Number.isFinite(z.eventLoopDelayP99Ms)?`${z.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:A?.owner?.subject?String(A.owner.subject):null,pkgEpoch:Number.isFinite(ge?.epoch)?ge.epoch:null,pkgText:ge?`${we.length-ke} ok${ke?` · ${ke} error`:""}`:null}}).sort((A,F)=>A.pool===F.pool?A.id<F.id?-1:1:A.pool<F.pool?-1:1),O=v.filter(A=>A.live),D={loading:!!q.loading,error:q.error||null,empty:v.length===0&&!q.loading,rows:v,counts:{registered:v.length,live:O.length,ready:O.filter(A=>A.phase==="ready").length,starting:O.filter(A=>A.phase==="starting").length,draining:O.filter(A=>A.phase==="draining").length,pools:[...new Set(O.map(A=>A.pool))].length},summaryText:v.length?`${O.length} live / ${v.length} registered`:null},U={loading:!!f.loading,error:f.error||null,empty:h.length===0&&!f.loading,sharedCount:x.length,userCount:k.length,selectedName:f.selectedName||null,detail:_,workspace:j,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}},M=[];return N==="workers"?(M.push({id:"workersRefresh",label:"Refresh workers",key:"r"}),M.push({id:"showPackages",label:"Agents",key:"a"}),M.push({id:"showGhcp",label:"GitHub Keys",key:"g"}),M.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:U,workers:D,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:M}):N==="packages"?(M.push({id:"packagesRefresh",label:"Refresh packages",key:"r"}),M.push({id:"packagesNext",label:"Next package",key:"j"}),M.push({id:"packagesPrev",label:"Previous package",key:"k"}),M.push({id:"showGhcp",label:"GitHub Keys",key:"g"}),M.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:U,workers:D,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:M}):(n.editing?(M.push({id:"save",label:"Save",key:"Enter"}),M.push({id:"cancel",label:"Cancel",key:"Esc"})):(M.push({id:"edit",label:c?`Replace ${u}`:`Set ${u}`,key:"e"}),c&&M.push({id:"clear",label:`Clear ${u}`,key:"c"}),M.push({id:"refresh",label:"Refresh",key:"r"})),M.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),N==="ghcp"&&M.splice(M.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:U,workers:D,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:M})}function tp(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=He(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(E=>E?.phase==="pending"),c=t.ui.promptEdit?.sessionId===n?.sessionId,u=c&&t.ui.promptEdit?.phase==="queued",d=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 · enter create · esc cancel"};if(t.ui.modal?.type==="sessionGroupPicker")return{left:"Move selected session(s) to a group",right:"up/down move · enter choose · esc cancel"};if(t.ui.modal?.type==="sessionGroupName")return{left:"Name the new group",right:"type name · left/right move · enter create · esc cancel"};if(t.ui.modal?.type==="logFilter")return{left:"Adjust log filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="filesFilter")return{left:"Adjust files browser filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="sessionOwnerFilter")return{left:"Adjust session filters",right:"up/down choose · space toggle · esc close"};const f=!!t.sessions?.selectMode,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 m=(t.ui?.chatViewMode==="summary"?"summary":"transcript")==="summary"?"s transcript":"s summary",y={[T.SESSIONS]:"up/down switch · ctrl-u/ctrl-d page · ctrl-g move group · f filter · P pin · V select · d done · D delete · r refresh · t title · v visibility · S share · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane · p prompt",[T.CHAT]:`${m} · 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?u?`queued prompt selected · d delete · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:d?`cancelling prompt selected · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:`edit pending prompt · enter send batch · up/down cycle pending · esc cancel · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`: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 S=y[e]||y[T.SESSIONS];return Ma(He(t))&&(S=`ctrl-x stop · ${S}`),{left:t.ui.statusText,right:S}}function gt(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function oe(t,e){if(e<=0)return[];const s=[];let n=e;for(const i of t||[]){if(n<=0)break;const r=String(i?.text||"");if(!r)continue;const o=r.length>n&&n>1?`${r.slice(0,n-1)}…`:r.slice(0,n);o&&(s.push({...i,text:o}),n-=o.length)}return s}function _e(t){return Array.from(String(t||"")).length}function ja(t,e){const s=String(t||"");return e<=0?"":_e(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function Ot(t,e){const s=ja(t,e),n=Math.max(0,e-_e(s));return s+" ".repeat(n)}function Z(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function xe(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 Er(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 Ua(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?_e(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function sp(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 Wa(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 np(t,e=""){return Wa([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function ip(t,e=""){return Wa([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function is(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 rp=300*1e3,op="last 5m";function Ii(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-rp,endMs:e,label:op}}function ap(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 Ka(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 lp=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done"]);function cp(t){return lp.has(t)}function up(t){const e=Ho(t?.createdAt),s=is(t?.workerNodeId),n=sp(t),i=Ua(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 ${At(t?.data?.seconds??0)}`};case"session.wait_completed":return{...o,type:"timer",color:"yellow",detail:`${At(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const l=ip(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 ${np(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||de(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${At(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${Ps(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 ${Ps(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 Va(t=[]){const e=[];for(const s of t||[]){const n=up(s);n&&e.push({...n,nodeLabel:cp(n.type)?"orch":n.nodeLabel||"orch"})}return e}function dp(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 pp(t){const e=String(t?.error||"").trim();if(!e)return null;const s=li(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),i=Number.isFinite(n)?n:Date.now();return{time:Ho(i),createdAtMs:i,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${Ua(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function fp(t,e){const s=pp(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 hp(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=Va(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 mp(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const i of n?.events||[]){if(!Ka(i,e))continue;const r=is(i?.workerNodeId);r&&s.add(r)}return Array.from(s).sort((n,i)=>n.localeCompare(i))}function xi(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 vr(t){return Array.isArray(t?.runs)?t.runs.reduce((e,s)=>e+_e(String(s.text??"")),0):Array.isArray(t)?t.reduce((e,s)=>e+_e(String(s.text??"")),0):_e(String(t?.text??""))}function gp(t,e,s){const n=[{text:Ot("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((i,r)=>{r>0&&n.push({text:" ",color:null}),n.push({text:Ot(i,s),color:"white",bold:!0})}),xi(n)}function yp(t,e,s,n=1/0){const i=`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`;return Z(Number.isFinite(n)?i.slice(0,Math.max(e,n)):i,"gray")}function Sp(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=xe(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(xe(r.kvTotalValueBytes)),i=s<=40?l.join(" · "):o.join(" | "),i||(i="orchestration stats unavailable")}return s<=52?[oe([{text:"Stats ",color:"cyan",bold:!0},{text:i,color:"white"}],Math.max(18,s))]:he({title:"Stats",body:i,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function bp(t,e,s,n){const i=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],r=[{text:Ot(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:Ot(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):r.push({text:Ot("│",n),color:"gray"})}),xi(r)}const wp=new Set(["none","minimal","low","medium","high","xhigh","max"]);function Ip(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&&wp.has(n)?s.length-2:s.length-1;return s[Math.max(0,i)]||s[0]||"unknown"}function kr(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 lt(t){return Number(t||0).toLocaleString("en-US")}function xp(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 Ep(t,{expanded:e,selected:s,maxWidth:n}){const i=e?"v":">",r=Ip(t?.model),o=t?.durationMs!=null?`${(Number(t.durationMs)/1e3).toFixed(1)}s`:"n/a",l=`${i} Mod: ${r} tok ${kr(t?.tokensInput)}/${kr(t?.tokensOutput)} dur ${o}`,c=[];if(s?c.push(Ye(Ot(l,Math.max(18,n)))):c.push([{text:l,color:"magenta"}]),e){const u=[["model",t?.reasoningEffort?`${t?.model||"(unknown)"}:${t.reasoningEffort}`:t?.model||"(unknown)"],["duration",t?.durationMs!=null?`${lt(t.durationMs)} ms`:null],["tokens",`${lt(t?.tokensInput)} in / ${lt(t?.tokensOutput)} out`],["cache",`${lt(t?.tokensCacheRead)} read / ${lt(t?.tokensCacheWrite)} write`],["tools",`${lt(t?.toolCalls)} calls / ${lt(t?.toolErrors)} errors`],["names",Array.isArray(t?.toolNames)&&t.toolNames.length?t.toolNames.join(", "):null],["worker",t?.workerNodeId||null],["result",t?.resultType||null],["error",t?.errorMessage||null]].filter(([,d])=>d!=null&&d!=="");for(const[d,p]of u)c.push([{text:` ${d}: `,color:"gray"},{text:String(p),color:"white"}])}return c}function vp(t,e,s,n={}){const i=!!n?.allowWideColumns,r=Sp(t,e,s),o=t.history.bySessionId.get(e.sessionId),l=fp(dp(Va(o?.events||[])),e);if(l.length===0)return{stickyLines:r,lines:[Z("No events yet - interact with this session to populate the sequence diagram.")]};const c=Ii(t),u=l.filter($=>ap($,c)),d=(u.length>0?u:l).slice(-48),p=hp(t,c.startMs,c.endMs),f=Array.from(new Set(d.map($=>$.nodeLabel).filter($=>$&&$!=="orch"))).sort(($,_)=>$.localeCompare(_)),h=p.length>0?p:f,g=Math.min(13,Math.max(8,...d.map($=>_e(String($.time||""))))),m=Math.max(18,s),y=Math.max(1,Math.floor((m-g-1)/6));let S=["orch",...h];if(!i&&S.length>y){const $=Math.max(1,y-1);S=[...S.slice(0,$),"…"]}const E=Math.max(0,S.length-1),I=Math.max(4,Math.floor((m-g-1-E)/Math.max(1,S.length))),w=n?.sequenceExpansion||null,b=w?xp(o?.events||[]):null,x=w?new Set((w.expandedTurns||[]).map(Number)):null,k=w&&w.selectedTurn!=null?Number(w.selectedTurn):null,P=[];for(const $ of d)if(P.push(bp($,S,g,I)),w&&$.completedTurn!=null){const _=Number($.completedTurn),L=b.get(_);if(L)for(const j of Ep(L,{expanded:x.has(_),selected:k===_,maxWidth:m}))P.push(j)}const N=gp(S,g,I),B=P.reduce(($,_)=>Math.max($,vr(_)),vr(N));return{stickyLines:[...r,Z(`Window: ${c.label}`,"gray"),N,yp(S,g,I,B)],lines:P}}function kp(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 Ap(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!Ka(s[n],e))continue;const i=is(s[n]?.workerNodeId);if(i)return i}return null}function Cp(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 Tp(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 Mp(t,e,s){const n=t?.isSystem?Ht(t,e):t?.title||de(t?.sessionId),i=t?.isSystem?"⚙ ":t?.serviceKind?"⚗ ":`${Ia(t)||"."} `;return{sessionId:t?.sessionId||null,text:`${i}${n}`,color:t?.isSystem?"yellow":Rt(t),bold:!!t?.isSystem,active:!!s}}function qa(t){const e=Ii(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 g=is(h?.workerNodeId);if(!g)continue;const m=h?.updatedAt instanceof Date?h.updatedAt.getTime():new Date(h?.updatedAt??0).getTime(),y=Number.isFinite(m)?r-m:Number.NaN,S=h?.health||{};l.set(g,{label:g,workerNodeId:String(h?.workerNodeId??""),registered:!0,live:Number.isFinite(y)&&y<=o,phase:["starting","ready","draining"].includes(h?.phase)?h.phase:"ready",pool:String(h?.pool??"default"),agoText:Cp(y),uptimeText:Tp(S.uptimeS),rssText:Number.isFinite(S.rssBytes)?kt(S.rssBytes):null,heapText:Number.isFinite(S.heapUsedBytes)?kt(S.heapUsedBytes):null,eventLoopText:Number.isFinite(S.eventLoopDelayP99Ms)?`${S.eventLoopDelayP99Ms}ms`:null,sessions:Number.isFinite(S.activeSessions)?S.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(([,E])=>!!E).map(([E])=>E).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(([E,I])=>({name:E,semver:I?.semver??null,status:I?.status==="error"?"error":"ok",error:I?.error?String(I.error):null})):[],pkgLastError:h?.state?.["agent-packages"]?.lastError?String(h.state["agent-packages"].lastError):null,executing:[]})}for(const h of mp(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 kp(t)){const g=t.sessions.byId[h];if(!g)continue;const m=t.history.bySessionId.get(h);m?.events||(c+=1);const y=Ap(m,e),S=y?l.get(y):null;S&&S.executing.push(Mp(g,s,h===n))}const u=Array.from(l.values()).sort((h,g)=>{if(h.registered!==g.registered)return h.registered?-1:1;if(h.live!==g.live)return h.live?-1:1;const m=String(h.pool??"~").localeCompare(String(g.pool??"~"));return m!==0?m:h.label.localeCompare(g.label)});u.forEach((h,g)=>{h.ordinal=g+1});const d=u.filter(h=>h.registered),p=t.ui?.nodeMapSelectedNode,f=p&&u.some(h=>h.label===p)?p:u[0]?.label??null;return{windowLabel:e.label,degraded:d.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:d.length,liveCount:d.filter(h=>h.live).length,executingTotal:u.reduce((h,g)=>h+g.executing.length,0),missingHistoryCount:c,selected:f,nodes:u}}function Np(t,e,s={}){const n=qa(t);if(n.nodes.length===0)return[Z(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(Z("","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",u=[{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){u.push({text:` ${(r.phase||"").padEnd(8)}`,color:c,nodeSelect:r.label}),u.push({text:` ${r.pool}`,color:"gray",nodeSelect:r.label});const d=[r.executing.length?`${r.executing.length} sess`:null,r.rssText,r.uptimeText?`up ${r.uptimeText}`:null,r.agoText].filter(Boolean).join(" · ");d&&u.push({text:` ${d}`,color:"gray",nodeSelect:r.label})}else u.push({text:" activity only",color:"gray",nodeSelect:r.label}),r.executing.length&&u.push({text:` · ${r.executing.length} sess`,color:"gray",nodeSelect:r.label});i.push(xi(u))}return i.push(Z("","gray")),i.push(Z("Click a node (or press 1-9) — its details fill the pane below.","gray")),n.missingHistoryCount>0&&i.push(Z(`Loading worker history for ${n.missingHistoryCount} session(s)…`,"gray")),i}function Pp(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 g=oe([{text:`${h.providerId}`,color:"cyan",bold:!0},{text:` (${h.providerType||"provider"})`,color:"gray"}],r);o.push(g),l.push(null);for(const m of h.models||[]){const y=Array.isArray(s.items)?s.items.findIndex(b=>b.id===m.id):-1,S=y===i,E=!!m.disabled,I=oe([{text:"· ",color:"gray"},{text:m.modelName||m.qualifiedName||m.id,color:E?"gray":"white",bold:!!m.isDefault&&!E},...m.cost?[{text:` [${m.cost}]`,color:"gray"}]:[],...E?[{text:" ⊘ needs GitHub key",color:"yellow"}]:[],...m.isDefault?[{text:" ← current default",color:"gray"}]:[]],r),w=S?Ye(I.map(b=>b.text).join("").padEnd(r," ")):I;S&&(c=o.length),o.push(w),l.push(y>=0?y:null)}}const u=Array.isArray(s.items)&&s.items[i]||null,d=Array.isArray(u?.supportedReasoningEfforts)?u.supportedReasoningEfforts.filter(Boolean):[],p=typeof u?.defaultReasoningEffort=="string"?u.defaultReasoningEffort:null,f=u?[[{text:u.modelName||u.qualifiedName||u.id,color:"white",bold:!0}],[{text:`${u.providerId} (${u.providerType||"provider"})`,color:"gray"}],...u.cost?[[{text:`Cost: ${u.cost}`,color:"gray"}]]:[],...d.length>0?[[{text:`Reasoning: ${d.join(", ")}`,color:"gray"}]]:[],...p?[[{text:`Default reasoning: ${p}`,color:"gray"}]]:[],...u.disabled?[[{text:"Unavailable: requires a GitHub Copilot key. Add yours in the Admin console, then reopen this picker.",color:"yellow"}]]:[],[{text:"",color:"gray"}],[{text:u.description||"No description available for this model.",color:u.description?"white":"gray"}]]:[[{text:"No model selected.",color:"gray"}]];return{title:s.title||"Select model for new session",rows:o,rowItemIndexes:l,selectedRowIndex:c,detailsTitle:"Model Details",detailsLines:f,idealWidth:Math.min(Math.max(46,o.reduce((h,g)=>Array.isArray(g)?Math.max(h,gt(g)):Math.max(h,String(g?.text||"").length),0)+4),e)}}function _p(t,e=76){const s=t.ui.modal;if(!s||s.type!=="sessionAgentPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(24,e-4),o={shared:"Shared",mine:"My agents",generic:""},l=n.some(y=>y?.packageName),c=[],u=[];let d=null;n.forEach((y,S)=>{const E=y?.group||"shared";if(l&&E!==d){const x=o[E]??"";c.push([{text:x?`── ${x} ──`:"──",color:"gray"}]),u.push(null),d=E}const I=S===i,w=y?.kind==="generic"?" [generic]":y?.packageName?` ${y.packageName} ${y.packageSemver||""}`.trimEnd():` (${y?.agentName||y?.id||"agent"})`,b=oe([{text:y?.kind==="generic"?"○ ":"· ",color:"gray"},{text:y?.title||y?.agentName||y?.id||"Agent",color:"white",bold:!0},{text:w,color:"gray"}],r);c.push(I?Ye(b.map(x=>x.text).join("").padEnd(r," ")):b),u.push(S)});const p=n[i]||null,f=s.sessionOptions?.model||null,h=s.sessionOptions?.reasoningEffort||null,g=p?[[{text:p.title||p.agentName||p.id||"Agent",color:"white",bold:!0}],...p.kind==="generic"?[[{text:"Open-ended session",color:"gray"}]]:[[{text:p.agentName||p.id||"agent",color:"gray"}]],...p.packageName?[[{text:`Package: ${p.packageName}@${p.packageSemver||"?"} · ${p.packageScope||"shared"}`,color:"gray"}]]:p.kind==="agent"?[[{text:"Built-in agent",color:"gray"}]]:[],...f?[[{text:`Model: ${f}`,color:"gray"}]]:[],...h?[[{text:`Reasoning: ${h}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:p.description||(p.kind==="generic"?"Create a general-purpose session without a specialized named agent.":"No description available for this agent."),color:p.description?"white":"gray"}],[{text:"",color:"gray"}],[{text:p.tools?.length?`Tools: ${p.tools.join(", ")}`:"Tools: system defaults only",color:"gray"}]]:[[{text:"No agent selected.",color:"gray"}]],m=u.indexOf(i);return{title:s.title||"Select agent for new session",rows:c,rowItemIndexes:u,selectedRowIndex:m>=0?m:0,detailsTitle:"Agent Details",detailsLines:g,idealWidth:Math.min(Math.max(52,c.reduce((y,S)=>Array.isArray(S)?Math.max(y,gt(S)):Math.max(y,String(S?.text||"").length),0)+4),e)}}function Rp(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((d,p)=>{const f=p===i,h=oe([{text:"· ",color:"gray"},{text:String(d?.label||d?.id||"effort"),color:"white",bold:!0},...d?.isDefault?[{text:" ← model default",color:"gray"}]:[]],r);return f?Ye(h.map(g=>g.text).join("").padEnd(r," ")):h}),l=n[i]||null,c=s.modelItem||null,u=[[{text:c?.modelName||c?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${c?.providerId||"provider"} (${c?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text: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:u,idealWidth:Math.min(Math.max(46,o.reduce((d,p)=>Array.isArray(p)?Math.max(d,gt(p)):Math.max(d,String(p?.text||"").length),0)+4),e)}}function Op(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,g=oe([{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(g.map(m=>m.text).join("").padEnd(r," ")):g}),l=n[i]||null,c=s.modelItem||null,u=l?.label||l?.id,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:u?`Using context window: ${u}`:"Choose a context window.",color:"white"}],[{text:"Long context costs more per token.",color:"gray"}]];return{title:s.title||"Select context window",rows:o,selectedRowIndex:i,detailsTitle:"Context Window",detailsLines:d,idealWidth:Math.min(Math.max(46,o.reduce((p,f)=>Array.isArray(f)?Math.max(p,gt(f)):Math.max(p,String(f?.text||"").length),0)+4),e)}}function $p(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((d,p)=>{const f=p===i,h=d?.kind==="noGroup"?"○ ":d?.kind==="newGroup"?"+ ":"🗂 ",g=oe([{text:h,color:d?.kind==="group"?"cyan":"gray",bold:d?.kind!=="noGroup"},{text:d?.label||d?.groupId||"Group",color:"white",bold:!0},...d?.kind==="group"?[{text:` (${d.memberCount??0})`,color:"gray"}]:[]],r);return f?Ye(g.map(m=>m.text).join("").padEnd(r," ")):g}),c=n[i]||null,u=c?[[{text:c.label||c.groupId||"Group",color:"white",bold:!0}],[{text:`${o} session${o===1?"":"s"} selected`,color:"gray"}],...c.kind==="group"?[[{text:`${c.memberCount??0} current member${c.memberCount===1?"":"s"}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:c.description||"Move selected session(s) to this group.",color:"white"}]]:[[{text:"No group selected.",color:"gray"}]];return{title:s.title||"Move to Group",rows:l,selectedRowIndex:i,detailsTitle:"Move Details",detailsLines:u,idealWidth:Math.min(Math.max(50,l.reduce((d,p)=>Array.isArray(p)?Math.max(d,gt(p)):Math.max(d,String(p?.text||"").length),0)+4),e)}}function Lp(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,_e(r||"(untitled session)")+18,_e(o)+18),e)}}function Fp(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,_e(r)+18),e)}}function Bp(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?va(r,t.branding?.title):de(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,_e(n||"~/path/to/file.md")+20,_e(o)+20),e)}}function Ei(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((u,d)=>{const p=e?.[u.id]||u.options?.[0]?.id,f=(u.options||[]).map(h=>h.id===p?Ye(h.label):{text:h.label,color:"white"});return{id:u.id,title:u.label,focused:d===o,description:u.description||"",lines:f.length>0?f:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(u.label||"").length+4,...(u.options||[]).map(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((u,d)=>u+d.idealWidth,0)+Math.max(0,c.length-1)*2+4),s)}}function za(t,e={},s={}){return t?t.kind==="all"?e?.all===!0:e?.all===!0?!1:t.kind==="system"?e?.includeSystem===!0:t.kind==="unowned"?e?.includeUnowned===!0:t.kind==="me"?e?.includeMe===!0&&!!ue(s?.principal):t.kind==="shared"?e?.includeShared===!0:t.kind==="owner"?Array.isArray(e?.ownerKeys)&&e.ownerKeys.includes(t.ownerKey):!1:!1}function Ar(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(i=>i?.kind!=="all"&&za(i,e,s)).map(i=>i.kind==="me"?"Me":i.label);return n.length>0?n.join(" + "):"All sessions"}function Dp(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((d,p)=>{const f=za(d,i,r),h=d.kind==="system"?"yellow":d.kind==="unowned"?"gray":d.kind==="all"?"cyan":"white",g=[{text:f?"[x] ":"[ ] ",color:f?"cyan":"gray",bold:f},{text:d.label||d.id,color:h,bold:f}];return p===o?ga(g,{preserveColors:!0}):g}),u=[[{text:"Active: ",color:"gray"},{text:Ar(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:u,idealWidth:Math.min(Math.max(48,c.reduce((d,p)=>Math.max(d,Array.isArray(p)?gt(p):_e(p?.text||"")),0)+8,_e(Ar(n,i,r))+16),e)}}function Hp(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:Ei(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function Gp(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:Ei(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function jp(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,g)=>{const m=t.files?.bySessionId?.[g.sessionId]?.downloads?.[g.filename];return h+(m?.localPath?1:0)},0),u=Math.max(0,o.length-c),d=n.map((h,g)=>{let m;if(h.kind==="downloadAll")m=oe([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${u} pending]`,color:"gray"}],r);else if(h.kind==="url")m=oe([{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 y=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];m=oe([{text:y?.localPath?"ok ":"dl ",color:y?.localPath?"green":"cyan",bold:!0},{text:`${de(h.sessionId)}/`,color:"gray"},{text:h.filename,color:"white"}],r)}return g!==i?m:Ye(m.map(y=>y.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:`${u} pending download`,color:"gray"}],...s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:"Press Enter to download all pending artifacts.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(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,g=t.files?.bySessionId?.[p.sessionId]?.downloads?.[p.filename]||null;f=[[{text:p.filename,color:"white",bold:!0}],[{text:h?va(h,t.branding?.title):de(p.sessionId),color:"gray"}],...g?.localPath?[[{text:`Saved to: ${g.localPath}`,color:"white"}]]:s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:g?.localPath?"Press Enter to download this artifact again.":"Press Enter to download this artifact.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]]}return{title:s.title||"Linked Items",rows:d.length>0?d:[{text:"No linked items available.",color:"gray"}],selectedRowIndex:i,detailsTitle:"Linked Item Details",detailsLines:f,confirmLabel:l.length>0?o.length>0?"Open / Download":"Open":"Download",idealWidth:Math.min(Math.max(54,d.reduce((h,g)=>Array.isArray(g)?Math.max(h,gt(g)):Math.max(h,String(g?.text||"").length),0)+4),e)}}function J(t){return t==null||!Number.isFinite(t)?"0":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e4?`${(t/1e3).toFixed(1)}K`:t>=1e3?t.toLocaleString("en-US"):String(t)}function Ya(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 Up(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 us(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 Xt(t){return["session","fleet","users"].includes(t)?t:"session"}function Ks(t,e){const s=Xt(t),n=[{text:"View ",color:"cyan",bold:!0}];for(const i of["session","fleet","users"])n.push({text:i===s?`[${i}]`:i,color:i===s?"magenta":"gray",bold:i===s}),n.push({text:" ",color:"gray"});return n.push({text:" [f cycle]",color:"gray"}),oe(n,e)}function Wp(t,e,s){if(!e)return[Z("No session selected.")];const n=t.sessionStats?.bySessionId?.[e.sessionId]||null;if(!n||n.loading&&!n.summary)return[Z("Loading session stats...")];const i=n.summary;if(!i)return[Z("Session stats unavailable.")];const r=[],o=Math.max(24,s);r.push(Ks("session",o)),r.push(Z("")),r.push(oe([{text:"Session ",color:"cyan",bold:!0},{text:de(e.sessionId),color:"white"}],o));const l=e.isSystem?"system":e.owner?"user":"unowned",c=e.isSystem?"system":e.owner?js(e.owner):"(?) unowned",u=e.owner?.email||"—";r.push(oe([{text:"Owner ",color:"cyan",bold:!0},{text:c,color:e.owner?"white":"gray"}],o)),r.push(oe([{text:"Email ",color:"cyan",bold:!0},{text:u,color:e.owner?.email?"white":"gray"}],o)),r.push(oe([{text:"Type ",color:"cyan",bold:!0},{text:l,color:l==="user"?"white":"gray"}],o)),i.agentId&&r.push(oe([{text:"Agent ",color:"cyan",bold:!0},{text:i.agentId,color:"white"}],o));const d=Si(i.model||e.model,i.reasoningEffort||e.reasoningEffort);d&&r.push(oe([{text:"Model ",color:"cyan",bold:!0},{text:d,color:"white"}],o)),e.createdAt&&r.push(oe([{text:"Created ",color:"cyan",bold:!0},{text:us(e.createdAt),color:"white"}],o)),e.updatedAt&&r.push(oe([{text:"Updated ",color:"cyan",bold:!0},{text:us(e.updatedAt),color:"white"}],o)),r.push(Z(""));const p=Array.isArray(n.tokensByModel)?n.tokensByModel:[];p.length>1&&(r.push(...he({title:"Models",body:p.map($=>`${Gd($.model)} · ${$.turnCount||0} turns · ${J($.totalTokensInput)} in / ${J($.totalTokensOutput)} out`).join(`
|
|
52
|
-
`),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),r.push(Z("")));const f=(i.tokensInput||0)+(i.tokensOutput||0),h=i.cacheHitRatio,g=h==null?"—":`${(h*100).toFixed(1)}%`;r.push(...he({title:"Tokens",body:ht([["Input",J(i.tokensInput)],["Output",J(i.tokensOutput)],["Total",J(f)],["Cache Read",J(i.tokensCacheRead)],["Cache Write",J(i.tokensCacheWrite)],["Hit Ratio",g]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0})),r.push(Z(""));const m=Number(i.regenCount)||0,y=i.lastRegenStats&&typeof i.lastRegenStats=="object"?i.lastRegenStats:null,S=Number.isFinite(y?.toEpoch)?y.toEpoch:m,E=y?y.distillMode==="deterministic"||!y.distillMode&&!y.distillerModel?"fast":String(y.distillerModel||"llm").replace(/^[^:]*:/,""):null,I=y?`${y.turnsArchived??0} turn${y.turnsArchived===1?"":"s"} · ${(Number(y.totalMs)/1e3).toFixed(1)}s${E?` · ${E}`:""}`:null;r.push(...he({title:"Persistence",body:ht([["Epoch",String(S)],["Regens",m>0?String(m):null],["Last Regen",I],["Snapshot",xe(i.snapshotSizeBytes)],["Uncompressed",i.rawSizeBytes?xe(i.rawSizeBytes):null],["Compression",Er(i.rawSizeBytes,i.snapshotSizeBytes)],["Dehydrations",String(i.dehydrationCount)],["Hydrations",String(i.hydrationCount)],["Lossy Handoffs",String(i.lossyHandoffCount)],["Last Dehydrated",i.lastDehydratedAt?us(i.lastDehydratedAt):null],["Last Hydrated",i.lastHydratedAt?us(i.lastHydratedAt):null]]),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const w=n.treeStats?.tree;if(w&&w.sessionCount>1){const $=w.cacheHitRatio,_=$==null?"—":`${($*100).toFixed(1)}%`,L=(w.totalTokensInput||0)+(w.totalTokensOutput||0);r.push(Z("")),r.push(...he({title:`Tree (${w.sessionCount} sessions)`,body:ht([["Input",J(w.totalTokensInput)],["Output",J(w.totalTokensOutput)],["Total",J(L)],["Cache Read",J(w.totalTokensCacheRead)],["Cache Write",J(w.totalTokensCacheWrite)],["Hit Ratio",_],["Snapshot",xe(w.totalSnapshotSizeBytes)],["Uncompressed",w.totalRawSizeBytes?xe(w.totalRawSizeBytes):null],["Compression",Er(w.totalRawSizeBytes,w.totalSnapshotSizeBytes)],["Dehydrations",String(w.totalDehydrationCount)],["Hydrations",String(w.totalHydrationCount)]]),width:o,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const j=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];j.length>1&&(r.push(Z("")),r.push(...he({title:"Tree By Model",body:Xp(j),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const b=Array.isArray(n.skillUsage)?n.skillUsage:[];b.length>0&&(r.push(Z("")),r.push(...he({title:`Skills (${b.length})`,body:Cr(b,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const x=n.treeSkillUsage,k=Array.isArray(x?.rolledUp)?x.rolledUp:[],P=Array.isArray(x?.perSession)?x.perSession.length:0;k.length>0&&P>1&&(r.push(Z("")),r.push(...he({title:`Tree Skills (${k.length})`,body:Cr(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(Z(""));const $=Xa(N.rows),_=$?$.split(`
|
|
53
|
-
`).length:0,L=`${N.totalCount} · ${xe(N.totalBytes)}`;let j=$;B&&B.totalCount>N.totalCount&&(j+=`
|
|
54
|
-
Tree (${B.sessionIds.length} sessions): ${B.totalCount} · ${xe(B.totalBytes)}`),_>0&&r.push(...he({title:`Facts (${L})`,body:j,width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return r}function ht(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 Vs(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 rs(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 u=l[c]==null?"":String(l[c]);u.length>r[c]&&(r[c]=u.length)}const o=" ".repeat(s);return n.map(l=>l.map((c,u)=>{const d=c==null?"":String(c);return u===0?d.padEnd(r[u]):d.padStart(r[u])}).join(o)).join(`
|
|
56
|
-
`)}function Cr(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,u=s.map((p,f)=>{const h=p.kind==="learned"?"L":"S",g=String(p.name||"(unknown)");return[Vs(`${h} ${g}`,c),n[f]]}),d=rs(u);return t.length>s.length?`${d}
|
|
57
|
-
… ${t.length-s.length} more`:d}function Xa(t){const s=t.slice().sort((n,i)=>(i.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),xe(n.totalValueBytes||0)]);return rs(s)}function Kp(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":At(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return rs([["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 Vp(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 qp(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,u=s.map((p,f)=>{const h=p.namespace?` ${p.namespace}`:"";return[Vs(`${Vp(p.operation)}${h}`,c),n[f],i[f]]}),d=rs(u);return t.length>s.length?`${d}
|
|
58
|
-
… ${t.length-s.length} more`:d}function zp(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.data)return[Z("Loading fleet stats...")];const n=s.data;if(!n)return[Z("Fleet stats unavailable.")];const i=[],r=Math.max(24,e);i.push(Ks("fleet",r)),i.push(Z(""));const o=n.windowStart?`Since: ${Ya(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(oe([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],r)),i.push(oe([{text:`Sessions: ${n.totals.sessionCount}`,color:"white"},{text:` Tokens: ${J(n.totals.totalTokensInput)} in / ${J(n.totals.totalTokensOutput)} out`,color:"white"}],r)),i.push(Z(""));const c=new Map;for(const m of n.byAgent||[]){const y=m.model||"(default)",S=c.get(y)||{totalTokensInput:0,totalTokensOutput:0,totalTokensCacheRead:0,totalTokensCacheWrite:0,totalSnapshotSizeBytes:0,turnCount:0};S.totalTokensInput+=Number(m.totalTokensInput)||0,S.totalTokensOutput+=Number(m.totalTokensOutput)||0,S.totalTokensCacheRead+=Number(m.totalTokensCacheRead)||0,S.totalTokensCacheWrite+=Number(m.totalTokensCacheWrite)||0,S.totalSnapshotSizeBytes+=Number(m.totalSnapshotSizeBytes)||0,S.turnCount+=Number(m.turnCount)||0,c.set(y,S)}if(c.size>0){const m=[];for(const[y,S]of c.entries()){const E=S.totalTokensInput>0?S.totalTokensCacheRead/S.totalTokensInput:null;m.push(y),m.push(vi(S,E)),m.push("")}i.push(...he({title:"Tokens By Model",body:m.join(`
|
|
59
|
-
`).trimEnd(),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(Z(""))}const u=n.totals.cacheHitRatio,d=u==null?"—":`${(u*100).toFixed(1)}%`;i.push(...he({title:"Fleet Totals",body:ht([["Sessions",String(n.totals.sessionCount)],["Tokens In",J(n.totals.totalTokensInput)],["Tokens Out",J(n.totals.totalTokensOutput)],["Total Tokens",J(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",J(n.totals.totalTokensCacheRead)],["Cache Write",J(n.totals.totalTokensCacheWrite)],["Hit Ratio",d],["Snapshots",xe(n.totals.totalSnapshotSizeBytes)]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0}));const p=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(m=>!(m&&m.agentId==="facts-manager"&&String(m.name||"").startsWith("skills/")));p.length>0&&(i.push(Z("")),i.push(...he({title:`Fleet Skills (${p.length})`,body:Yp(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 m=f.reduce((y,S)=>y+(Number(S.calls)||0),0);i.push(Z("")),i.push(...he({title:`Fleet Retrieval (${J(m)})`,body:qp(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(Z(""));const m=`${h.totalCount} · ${xe(h.totalBytes)}`;i.push(...he({title:`Shared Facts (${m})`,body:Xa(h.rows),width:r,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const g=s.factsTombstoneStats;return g&&Number(g.pendingTotal)>0&&(i.push(Z("")),i.push(...he({title:`Fact Tombstones (${Number(g.pendingTotal)||0})`,body:Kp(g),width:r,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),i}function Yp(t,e){const n=t.slice().sort((g,m)=>{const y=b=>b==="learned"?1:0,S=y(g.kind)-y(m.kind);if(S!==0)return S;const E=g.agentId?0:1,I=m.agentId?0:1;if(E!==I)return E-I;const w=String(g.agentId||"").localeCompare(String(m.agentId||""));return w!==0?w:String(g.name||"").localeCompare(String(m.name||""))}).slice(0,15),i=n.map(g=>`${g.invocations||0} inv`),r=n.map(g=>`${g.sessionCount||0} sess`),o=i.reduce((g,m)=>Math.max(g,m.length),0),l=r.reduce((g,m)=>Math.max(g,m.length),0),c=4,u=2,d=c+u+o+u+l,p=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-d):1/0,f=n.map((g,m)=>{const y=g.kind==="learned"?"L":"S",S=g.agentId||".",E=String(g.name||"(unknown)");return[Vs(`${y} ${S}/${E}`,p),i[m],r[m]]}),h=rs(f);return t.length>n.length?`${h}
|
|
60
|
-
… ${t.length-n.length} more`:h}function Xp(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(vi(n,i)),s.push("")}return s.join(`
|
|
61
|
-
`).trimEnd()}function vi(t,e){const s=e==null?"—":`${(e*100).toFixed(1)}%`,n=(Number(t.totalTokensInput)||0)+(Number(t.totalTokensOutput)||0),i=[["Input",J(t.totalTokensInput||0)],["Output",J(t.totalTokensOutput||0)],["Total",J(n)],["Turns",J(t.turnCount||0)],["Cache Read",J(t.totalTokensCacheRead||0)],["Cache Write",J(t.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",xe(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&i.push(["Orch",xe(t.totalOrchestrationHistorySizeBytes||0)]),ht(i).split(`
|
|
62
|
-
`).map(o=>` ${o}`).join(`
|
|
63
|
-
`)}function Hn(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":js(t?.owner,"Unknown User")}function Qp(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=Hn(t);return e&&e!==s?e:""}function Jp(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=Vs(String(r.model||"(default)"),Math.max(12,e-10));i.push(`${o} · ${r.sessionCount||0} sess · ${r.turnCount||0} turns`),i.push(vi(r,r.cacheHitRatio)),i.push("")}return s.length>n.length&&i.push(`… ${s.length-n.length} more models`),i.join(`
|
|
64
|
-
`).trimEnd()}function Zp(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.userStats)return[Z("Loading user stats...")];const n=s.userStats;if(!n)return[Z("User stats unavailable.")];const i=[],r=Math.max(24,e);i.push(Ks("users",r)),i.push(Z(""));const o=n.windowStart?`Since: ${Ya(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(oe([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],r)),i.push(oe([{text:`Users: ${Array.isArray(n.users)?n.users.length:0}`,color:"white"},{text:` Sessions: ${n.totals.sessionCount||0}`,color:"white"}],r)),i.push(Z(""));const c=n.totals.cacheHitRatio,u=c==null?"—":`${(c*100).toFixed(1)}%`;i.push(...he({title:"User Totals",body:ht([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",J(n.totals.totalTokensInput||0)],["Tokens Out",J(n.totals.totalTokensOutput||0)],["Total Tokens",J((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",J(n.totals.totalTokensCacheRead||0)],["Cache Write",J(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",u],["Snapshots",xe(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",xe(n.totals.totalOrchestrationHistorySizeBytes||0)]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0}));const d=Array.isArray(n.users)?n.users:[],p=d.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=Qp(f),g=f.cacheHitRatio,m=g==null?"—":`${(g*100).toFixed(1)}%`,y=h?`${Hn(f)} <${h}>`:Hn(f),S=ht([["Sessions",String(f.sessionCount||0)],["Tokens In",J(f.totalTokensInput||0)],["Tokens Out",J(f.totalTokensOutput||0)],["Total Tokens",J((f.totalTokensInput||0)+(f.totalTokensOutput||0))],["Cache Read",J(f.totalTokensCacheRead||0)],["Cache Write",J(f.totalTokensCacheWrite||0)],["Hit Ratio",m],["Snapshots",xe(f.totalSnapshotSizeBytes||0)],["Orch Size",xe(f.totalOrchestrationHistorySizeBytes||0)]]),E=Jp(f,r);i.push(Z("")),i.push(...he({title:`${y} (${f.sessionCount||0})`,body:E?`${S}
|
|
65
|
-
|
|
66
|
-
${E}`:S,width:r,titleColor:f.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return d.length>p.length&&(i.push(Z("")),i.push(Z(`… ${d.length-p.length} more users`))),i}function at(t,e={}){const s=He(t),n=t.ui.inspectorTab,i=Math.max(18,Number(e?.width)||36),r=!!e?.allowWideColumns,o=ya(i);if(s?.isGroup)return{title:qe("Inspector","magenta"),activeTab:n,tabs:ze,disabled:!0,stickyLines:[],lines:[Z(Qa,"gray")]};const l=s?de(s.sessionId):"",c=n==="sequence"||n==="nodes"?Ii(t):null,u=n==="nodes"?[...qe("Node Map","magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:s?n==="sequence"?[...qe(o?"Sequence":`Sequence: ${l}`,"magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:n==="logs"?[...qe(o?"Logs":`Logs: ${l}`,"magenta")]:n==="history"?[...qe(o?"Duroxide Events":`Duroxide Event History: ${l}`,"magenta")]:n==="stats"?[...qe(o?"Stats":`Stats: ${l}`,"magenta"),{text:` [${Xt(t.ui?.statsViewMode)}]`,color:"gray"}]:[...qe(o?"Files":`Files: ${l}`,"magenta")]:n==="stats"?`Stats: ${Xt(t.ui?.statsViewMode).replace(/^./u,f=>f.toUpperCase())}`:"No session selected";let d,p=[];switch(n){case"sequence":{const f=s?vp(t,s,i,{allowWideColumns:r,sequenceExpansion:e?.sequenceExpansion||null}):{stickyLines:[],lines:["No session selected."]};p=f.stickyLines||[],d=f.lines;break}case"logs":d=s?zd(t,s):["No session selected."];break;case"nodes":d=Np(t,i,{});break;case"files":d=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":d=s?nf(t,s):["No session selected."];break;case"stats":d=Xt(t.ui?.statsViewMode)==="users"?Zp(t,i):Xt(t.ui?.statsViewMode)==="fleet"?zp(t,i):s?Wp(t,s,i):[Ks("session",Math.max(24,i)),Z(""),Z("No session selected. Press f to cycle to fleet or users view.")];break;default:d=["Inspector view is scaffolded in the new architecture."];break}return{title:u,activeTab:n,tabs:ze,stickyLines:p,lines:d}}const ef={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"},Qa="Select a session to see details.";function tf(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=ef[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),u=c.length>100?c.slice(0,97)+"...":c;n.push([{text:` ${o}: `,color:"yellow"},{text:u,color:"white"}])}else n.push({text:` ${String(r).slice(0,120)}`,color:"white"})}catch{const r=t.data.length>120?t.data.slice(0,117)+"...":t.data;n.push({text:` ${r}`,color:"white"})}return n}function sf(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function nf(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=sf(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=tf(n[o]);for(const c of l)r.push(c);o<n.length-1&&r.push({text:"────────────────────────────────",color:"gray"})}return r}function rf(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:Ei(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function Tr(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 of(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,u=Math.max(24,e-4),d=n.map((f,h)=>{const g=f.id===o?" [current]":"",m=`${f.label}${g}`.slice(0,u);return h===i?Ye(m.padEnd(u," ")):[{text:m,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"}],{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"}],Tr([{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"}]),Tr([{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:d,selectedRowIndex:i,detailsTitle:"Theme Details",detailsLines:p}}function af(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 Mr(t){return new Map(t)}function Qt(t){return new Set(t)}function lf(t){return Array.isArray(t)?[...t]:[]}function cf(t){return Array.isArray(t)?[...t]:[]}const uf=5e3;function Nr(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 Ja(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function ds(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||Ja(r))&&s.push(i)}return s}function Za(t){return Qt(t)}function df(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 Pr(t,e,s){const n=Za(t);if(!s||!e?.[s])return n;for(const i of df(s,e))n.delete(i);return n}function _r(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 pf(t){return{...t||{}}}function Xe(t){return{...t||{}}}function Rr(t){return{...t||{}}}function ps(t){return{...t||{}}}function Sn(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function ff(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function hf(t){return[T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY].includes(t)?t:null}function bn(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 Gn(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(!Gn(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)||!Gn(t[i],e[i]))return!1;return!0}function Or(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 mf(t,e){const s=Or(t),n=Or(e);return s>0&&n>0&&n<=s}const gf=new Set(["completed","failed","cancelled","error"]);function yf(t,e){const s=String(e?.status??"").toLowerCase();if(t?.status!=="running"||s==="running"||gf.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:mf(t,e)}function $r(t={},e={}){let s=t||{};const n=yf(t,e);for(const[i,r]of Object.entries(e||{}))if(r!==void 0&&!(i==="status"&&n)){if(i==="pendingQuestion"&&Sf(t,r)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}Gn(t?.[i],r)||(s===t&&(s={...t||{}}),s[i]=r)}return s}function Lr(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function Fr(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=Lr(e),i=t?.rowVisualStatus||Lr(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>=uf?{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0}:e.rowVisualStatus===i&&e.rowVisualStatusCandidate===n&&Number(e.rowVisualStatusCandidateSince)===o?e:{...e,rowVisualStatus:i,rowVisualStatusCandidate:n,rowVisualStatusCandidateSince:o}}function Br(t){return String(t?.question||"").trim()}function Sf(t,e){const s=Br(t?.answeredPendingQuestion),n=Br(e);return!!(s&&n&&s===n)}function bf(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&qo(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function Dr(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 Hr(t={}){const e=String(t?.filterQuery||"").trim(),s=Ts(t?.ownerFilter);return!!e||s.all!==!0}function wf(t,e=[]){const s=Bt(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(r=>r.sessionId===n)||t.sessions?.navigationIntent||n&&t.sessions?.byId?.[n]&&!Hr(t.sessions)||n&&!t.sessions?.listingSeen)return n;if(Hr(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 bf(i)}function If(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 ct(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=Pr(s.collapsedIds,s.byId,r);_r(p,s.collapsedIds)||(s={...s,collapsedIds:p,flat:Ve(Object.values(s.byId||{}),p,s.orderById,s.pinnedIds,s.manualOrder)})}i&&s.filterExceptionId!==i&&(Bt({...t,sessions:s}).some(f=>f.sessionId===i)||(s={...s,filterExceptionId:i}));const o={...t,sessions:s},l=wf(o,Object.values(s.byId||{})),c=Pr(s.collapsedIds,s.byId,l);return{sessions:{...!_r(c,s.collapsedIds)?{...s,collapsedIds:c,flat:Ve(Object.values(s.byId||{}),c,s.orderById,s.pinnedIds,s.manualOrder)}:s,activeSessionId:l},ui:If(t,l)}}function wn(t={},e=0,s=[]){const n=pf(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 xf(t=[],e=[]){const s=Ve(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 Ef(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 Gr(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 vf(t,e){switch(e.type){case"connection/ready":return{...t,connection:{...t.connection,connected:!0,workersOnline:e.workersOnline??t.connection.workersOnline,error:null},ui:{...t.ui,statusText:e.statusText??t.ui.statusText??"Ready"}};case"connection/error":return{...t,connection:{...t.connection,connected:!1,error:e.error},ui:{...t.ui,statusText:e.statusText||e.error||"Connection error"}};case"auth/context":return{...t,auth:{principal:e.principal??null,authorization:e.authorization??null}};case"ui/status":return{...t,ui:{...t.ui,statusText:e.text}};case"ui/theme":return{...t,ui:{...t.ui,themeId:e.themeId||t.ui.themeId}};case"profileSettings/apply":{const s=e.settings&&typeof e.settings=="object"&&!Array.isArray(e.settings)?e.settings:{},n=Object.prototype.hasOwnProperty.call(s,"themeId")&&typeof s.themeId=="string"&&s.themeId.trim(),i=Object.prototype.hasOwnProperty.call(s,"sessionOwnerFilter"),r=Object.prototype.hasOwnProperty.call(s,"layoutAdjustments"),o=Object.prototype.hasOwnProperty.call(s,"chatViewMode")&&(s.chatViewMode==="summary"||s.chatViewMode==="transcript"),l=Object.prototype.hasOwnProperty.call(s,"pinnedSessionIds"),c=Object.prototype.hasOwnProperty.call(s,"collapsedSessionIds"),u=Object.prototype.hasOwnProperty.call(s,"sessionOrder"),d=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.status!=="failed"),p=Object.prototype.hasOwnProperty.call(s,"activeSessionId")&&!d,f=Object.keys(t.sessions.byId||{}).length>0,h=r?{...t.ui.layout||{},...ii(s.layoutAdjustments)}:t.ui.layout,g=l?f?ds(Ns(s.pinnedSessionIds),t.sessions.byId):Ns(s.pinnedSessionIds):t.sessions.pinnedIds,m=c?f?Za(On(s.collapsedSessionIds),t.sessions.byId):On(s.collapsedSessionIds):t.sessions.collapsedIds,y=u?ri(s.sessionOrder):t.sessions.manualOrder,S=p?fa(s.activeSessionId):t.sessions.activeSessionId,E={...t.sessions,...i?{ownerFilter:Ts(s.sessionOwnerFilter),ownerFilterExplicit:!0}:{},pinnedIds:g,manualOrder:y,collapsedIds:m,collapsedIdsExplicit:c?!0:t.sessions.collapsedIdsExplicit,activeSessionId:S,flat:l||c||u?Ve(Object.values(t.sessions.byId),m,t.sessions.orderById,g,y):t.sessions.flat},I=f&&(i||l||c||p)?ct(t,E):{sessions:E,ui:t.ui};return{...t,sessions:I.sessions,ui:{...I.ui,themeId:n?s.themeId.trim():I.ui.themeId,chatViewMode:o?s.chatViewMode:I.ui.chatViewMode,layout:h}}}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=ct(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:Ts(e.filter),navigationIntent:null,filterExceptionId:null},n=ct(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=ct(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:Ef(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:_t(e.prompt),promptAttachments:Gr(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:Gr(t.ui.prompt,e.attachments)}};case"sessions/gone":{const s=e.sessionId;if(!s)return t;const n=!!t.sessions.byId[s],i=t.sessions.activeSessionId===s;if(!n&&!i)return t;const r={...t.sessions.byId};delete r[s];const o=Array.isArray(t.sessions.selectedIds)?t.sessions.selectedIds.filter(l=>l!==s):t.sessions.selectedIds;return{...t,sessions:{...t.sessions,byId:r,selectedIds:o,activeSessionId:i?null:t.sessions.activeSessionId}}}case"sessions/loaded":{const s={};let n=!1;const i=Date.now();for(const w of t.sessions.groupRows||[])s[w.sessionId]=t.sessions.byId[w.sessionId]||w;for(const w of e.sessions){const b=t.sessions.byId[w.sessionId],x=Fr(b,$r(b,w),i);s[w.sessionId]=x,!n&&x!==b&&(n=!0)}t.sessions.activeSessionId&&t.sessions.byId[t.sessions.activeSessionId]&&!t.sessions.byId[t.sessions.activeSessionId]?.isGroup&&!s[t.sessions.activeSessionId]&&(s[t.sessions.activeSessionId]={...t.sessions.byId[t.sessions.activeSessionId]},n=!0);const r=Object.keys(t.sessions.byId),o=Object.keys(s);if(r.length!==o.length&&(n=!0),!n){for(const w of o)if(!t.sessions.byId[w]){n=!0;break}}if(!n)return t;const l=Object.values(s),c=Object.keys(t.sessions.orderById||{}).length>0,u=Dr(l),d=!!t.sessions.collapsedIdsExplicit,{orderById:p,nextOrderOrdinal:f}=c?wn(t.sessions.orderById,t.sessions.nextOrderOrdinal,l):xf(l,t.sessions.pinnedIds),h=d?Qt(t.sessions.collapsedIds):u,g=t.sessions.listingSeen===!0;if(d&&g){const w=Dr(Object.values(t.sessions.byId));for(const b of u)w.has(b)||h.add(b)}const m=ds(t.sessions.pinnedIds,s),y=Nr(t.sessions.selectedIds,s),S=Ve(l,h,p,m,t.sessions.manualOrder),E={...t.sessions,byId:s,collapsedIds:h,collapsedIdsExplicit:d,listingSeen:!0,pinnedIds:m,selectedIds:y,selectMode:t.sessions.selectMode&&y.length>0,flat:S,activeSessionId:t.sessions.activeSessionId,orderById:p,nextOrderOrdinal:f},I=ct(t,E);return{...t,sessions:I.sessions,ui:I.ui}}case"sessions/groupsLoaded":{const s=Array.isArray(e.groups)?e.groups:[],n={...t.sessions.byId},i=Array.isArray(e.sessions)?e.sessions:Object.values(t.sessions.byId),r=new Set(i.filter(g=>g&&!g.isGroup&&g.groupId&&!g.parentSessionId).map(g=>`group:${g.groupId}`)),o=[];for(const g of Object.keys(n))if(n[g]?.isGroup&&!s.some(m=>m.sessionId===g)){if(r.has(g)){o.push(n[g]);continue}delete n[g]}for(const g of s)n[g.sessionId]={...n[g.sessionId]||{},...g};const l=ds(t.sessions.pinnedIds,n),{orderById:c,nextOrderOrdinal:u}=wn(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(n)),d=t.sessions.groupsListingSeen===!0,p=Qt(t.sessions.collapsedIds);for(const g of s)d&&(t.sessions.byId[g.sessionId]||p.add(g.sessionId));const f={...t.sessions,groupRows:[...s,...o],byId:n,pinnedIds:l,orderById:c,nextOrderOrdinal:u,collapsedIds:p,groupsListingSeen:!0,flat:Ve(Object.values(n),p,c,l,t.sessions.manualOrder)},h=ct(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=Fr(s,$r(s,e.session),Date.now());if(n===s)return t;const i={...t.sessions.byId,[e.session.sessionId]:n},r=ds(t.sessions.pinnedIds,i),{orderById:o,nextOrderOrdinal:l}=wn(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(i)),c={...t.sessions,byId:i,pinnedIds:r,flat:Ve(Object.values(i),t.sessions.collapsedIds,o,r,t.sessions.manualOrder),activeSessionId:t.sessions.activeSessionId,orderById:o,nextOrderOrdinal:l},u=ct(t,c);return{...t,sessions:u.sessions,ui:u.ui}}case"sessions/selected":{t={...t,sessions:{...t.sessions,listDeselected:!1}};const s=t.sessions.activeSessionId,n={...t.ui.chatScrollBySession||{}};s&&s!==e.sessionId&&(n[s]=Number(t.ui.scroll?.chat)||0);const i=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.sessionId!==e.sessionId);return{...t,sessions:{...t.sessions,activeSessionId:e.sessionId,...i?{navigationIntent:null,filterExceptionId:null}:{}},ui:{...t.ui,chatScrollBySession:n,statusText:s!==e.sessionId?"":t.ui.statusText,scroll:{...t.ui.scroll,chat:Number(n[e.sessionId])||0,inspector:0,activity:0},followBottom:{...t.ui.followBottom||{},inspector:!0,activity:!0}}}}case"ui/fullscreenPane":{const s=hf(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=Qt(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:Ve(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds,t.sessions.manualOrder)}}}case"sessions/expand":{const s=Qt(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:Ve(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(!Ja(n))return t;const i=lf(t.sessions.pinnedIds),o=i.indexOf(s)>=0?i.filter(l=>l!==s):[...i,s];return{...t,sessions:{...t.sessions,pinnedIds:o,flat:Ve(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(!Ft(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(d=>d.sessionId).filter(d=>Ft(t.sessions.byId[d]))).filter(d=>d!==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((d,p)=>d===t.sessions.manualOrder[p])?t:{...t,sessions:{...t.sessions,manualOrder:c,flat:Ve(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=cf(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=Nr(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=bn(Mt(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,u=Mr(t.history.bySessionId);return u.set(e.sessionId,{...e.history||{},chat:r,activity:bn(e.history?.activity||[],i),events:bn(e.history?.events||[],i),loadedEventLimit:i}),{...t,history:{...t.history,bySessionId:u},ui:c?{...t.ui,scroll:{...t.ui.scroll,chat:0}}:t.ui}}case"history/evict":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=Mr(t.history.bySessionId);for(const o of s)n.delete(o);const i=Rr(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=Rr(t.outbox?.bySessionId);return n.length===0?delete i[s]:i[s]=n,{...t,outbox:{...t.outbox,bySessionId:i}}}case"orchestration/statsLoading":{const s=ps(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=ps(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=ps(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=ps(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={...$n().admin.packages.addDialog,open:!0,updateName:e.updateName||null,scope:e.scope==="shared"?"shared":"user"};return{...t,admin:{...t.admin,section:"packages",packages:{...t.admin.packages,addDialog:s}}}}case"admin/packages/addDialog/close":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...$n().admin.packages.addDialog,open:!1}}}};case"admin/packages/addDialog/setField":{const s=t.admin.packages.addDialog;return e.field in s?{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...s,[e.field]:e.value,error:null}}}}:t}case"admin/packages/addDialog/submitting":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,submitting:!0,progress:null,error:null}}}};case"admin/packages/addDialog/progress":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,progress:e.message||null}}}};case"admin/packages/addDialog/failed":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,submitting:!1,progress:null,error:e.error||"Failed to import package"}}}};case"admin/systemGhcpKey/saved":{const s=e.status||{};return{...t,admin:{...t.admin,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:Date.now(),storeAsSystem:!!t.admin.ghcpKey.storeAsSystem},systemGhcpKey:{supported:!0,loading:!1,configured:!!s.configured,changedBy:s.changedBy||null,changedAt:s.changedAt||null,error:null}}}}case"files/evictPreviews":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=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=Ms(e.entries),r=Number(e.fetchedAt)||0,o=c=>i.some(u=>u.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=Ms(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,...u}=n.downloads||{},d=e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:null;return s[e.sessionId]={...n,entries:i,previews:l,downloads:u,selectedFilename:r},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:t.files.selectedArtifactId===d?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:{...Sn(t.files.filter),...Sn(e.filter)},...Sn(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:ff(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 kf(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 Af=2e4,Cf=2e4,Tf=3e4,Mf=30,jr="Session refresh failed",Nf=3,Pf=200,_f=5,Rf=new Set([T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY]);function Of(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 In(t){return!t?.sessionId||t.isGroup?t:{...t,groupId:t.viewerGroupId??null,parentSessionId:t.parentSessionId??null}}function Ss(t){return String(t||"").startsWith("group:")?String(t).slice(6):null}function Kt(t){return Ss(t)!==null}function $f(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 xn(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 Vt(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||s==="NOT_FOUND"}async function Lf(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<_f;n+=1){const i=await t.listSessionsPage({limit:Pf,cursor:s}),r=Array.isArray(i?.sessions)?i.sessions:[];if(e.push(...r),!i?.hasMore||!i?.nextCursor)break;s=i.nextCursor}return e}function Ff(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 jn(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 Ur(t){const e=jn(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 Un(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 Bf(t){const e=Un(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 el={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function Df(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 Hf(t,e){const s=Df(e);return s?t==="long_context"?`Long context (${s} tokens, higher cost)`:`Default (${s} tokens)`:el[t]||t}function Wn(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 Gf(t){return Wn([t])}function Wr(t,e=[]){let s=$o(t);for(const n of e){const i=Lo(s,n?.eventType,n?.data,{timestamp:n?.createdAt});i&&(s=i)}return s}function $s(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i+=1)if(!$s(t[i],e[i]))return!1;return!0}if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!$s(t[i],e[i]))return!1;return!0}function Kr(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 ki(t,e){const s=Kr(t?.updatedAt),n=Kr(e?.updatedAt);return s>0&&n>0&&n<=s}function jf(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function Uf(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&jf(e?.status)&&ki(t,e)}function Wf(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!sl(e?.status)&&!tl(e?.orchestrationStatus)&&ki(t,e)}function Kf(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||$s(t?.[l],c)||(s[l]=c,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&!ki(t,e)&&(s.pendingQuestion=null,n=!0),Uf(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),Ou(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),Wf(t,e))for(const l of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[l]!=null&&($s(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((sl(e.status)||tl(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 Vr(t){return String(t||"").replace(/\r\n/g,`
|
|
68
|
-
`).trim()}function tl(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function sl(t){return t==="completed"||t==="failed"||t==="cancelled"}function Ae(t){return String(t||"").slice(0,8)}function Ls(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function fs(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Vf=Ls({provider:"system",subject:"system"});function qr(t){const e=t.auth?.principal||null,s=Ls(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=fs(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=Ls(o);!l||l===s||l===Vf||i.has(l)||i.set(l,o)}for(const[r,o]of[...i.entries()].sort((l,c)=>fs(l[1]).localeCompare(fs(c[1])))){const l=fs(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 Fs(t){return Ls(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,includeShared:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function qf(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||t?.includeShared||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function zf(t,e,s){const n=t||Fs(s);if(!e)return n;if(e.kind==="all")return n.all?Fs(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 qf(i)?i:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function Ai(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 Yf(t){const e=Ai(t);return e?Math.max(1,60-`${e}: `.length):60}function Xf(t){const e=String(t?.title||"").trim();if(!e)return"";const s=Ai(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 zr(t,e){const s=String(e||"").trim();if(s)return s;const n=String(t||"").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):"Agent"}function Yr(t){return`📎 ${String(t||"").trim()}`}function Xr(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 Qf(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 Jf(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function Zf(t){const e=String(t?.sessionId||"").trim(),s=Ae(e)||"session";return`Referenced session: ${Jf(t?.title,s)} — session://${e}`}function Qr(t,e,s){if(!e)return it(t,String(t||"").length,s);const n=String(t||""),i=n.slice(e.tokenEnd,e.tokenEnd+1),r=!i||/\s/u.test(i);return Qf(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${r?" ":""}`)}function eh(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 Jr=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Zr=4*1024*1024,En=4;function th(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=eh(t,s);return n.join(`
|
|
71
|
-
`)+(i?`
|
|
72
|
-
|
|
73
|
-
${i}`:"")}function wt(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function nl(t){return Array.from(String(t||"")).length}function sh(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=Fo(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 nh(t,e){const s=Math.max(1,Number(e)||1),n=nl(t);return Math.max(1,Math.ceil(n/s))}function It(t,e){const s=Math.max(1,Number(e)||1);return sh(t).reduce((n,i)=>{if(!i)return n+1;if(Array.isArray(i)){const r=i.reduce((o,l)=>o+nl(l?.text||""),0);return n+Math.max(1,Math.ceil(r/s))}return n+nh(i.text||"",s)},0)}function fe(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function il(t){return String(t||"").split(`
|
|
74
|
-
`)}function ih(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 rh(t,e,s){const n=il(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 it(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 hs(t){return/\s/u.test(t||"")}function rl(t,e,s){const n=String(t||"");let i=fe(n,e);if(s<0){for(;i>0&&hs(n[i-1]);)i-=1;for(;i>0&&!hs(n[i-1]);)i-=1;return i}for(;i<n.length&&hs(n[i]);)i+=1;for(;i<n.length&&!hs(n[i]);)i+=1;return i}function oh(t,e){const s=String(t||""),n=fe(s,e),i=rl(s,n,-1);return i===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,i)}${s.slice(n)}`,cursor:i}}function ah(t,e,s){const n=il(t);if(n.length<=1)return fe(t,e);const i=ih(t,e),r=Math.max(0,Math.min(i.line+s,n.length-1));return r===i.line?fe(t,e):rh(t,r,i.column)}const Kn=3e3,lh=new Set(["logs","sequence"]),ch=2e5,uh=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),dh=new Set([".json",".jsonl"]),ph=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function ol(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function fh(t,e=""){const s=ol(t),n=String(e||"").toLowerCase();return ph.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}function eo(t,e=ch){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 hh(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 mh(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${hh(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
|
|
78
|
-
`)}function to(t,e,s="",n=null){const i=String(s||"").toLowerCase(),r=ol(t);if(n?.isBinary===!0||fh(t,s))return{content:mh(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=eo(e);if(uh.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(dh.has(r)||i.includes("json"))try{return{content:eo(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 gh=1e4,yh=140,Sh=1500;class bh{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(!Jr.has(c)){o.push({name:l.name||"image",reason:"unsupported type"});continue}if((Number(l.size)||0)>Zr){o.push({name:l.name||"image",reason:"over 4 MB"});continue}if(i.length+r.length>=En){o.push({name:l.name||"image",reason:`max ${En} 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!Jr.has(n)||(Number(e?.sizeBytes)||0)>Zr||this.getPromptAttachments().filter(r=>r?.kind==="image").length>=En?!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",u=`attach-${r}-${o}.${c}`;await this.transport.uploadArtifactFromFile(e,l.file,u),i.push({filename:u})}return i}acknowledgeOutboxPrompt(e,s,n=null){if(!e)return!1;const i=this.getSessionOutbox(e);if(n){const c=i.findIndex(u=>(u?.phase==="pending"||u?.phase==="queued"||u?.phase==="cancelling")&&Array.isArray(u.clientMessageIds)&&u.clientMessageIds.includes(n));if(c!==-1){const u=i[c];return this.setSessionOutboxItems(e,i.filter((d,p)=>p!==c)),this.getPromptEditSessionMatch(e)?.itemId===u?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const r=Vr(s);if(!r)return!1;const o=i.findIndex(c=>(c?.phase==="pending"||c?.phase==="queued"||c?.phase==="cancelling")&&Vr(c.text)===r);if(o===-1)return!1;const l=i[o];return this.setSessionOutboxItems(e,i.filter((c,u)=>u!==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(d=>n.has(d)));if(r.length===i.length)return!1;const o=new Set(i.filter(c=>!r.some(u=>u.id===c.id)).map(c=>c.id));this.setSessionOutboxItems(e,r);const 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(g=>g?.attempted===!0),r=i?[i]:n.filter(g=>g?.attempted!==!0);if(r.length===0)return!1;const o=r.flatMap(g=>Array.isArray(g.clientMessageIds)&&g.clientMessageIds.length>0?g.clientMessageIds:[g.id]),l=r.map(g=>String(g.text||"")).join(`
|
|
79
|
-
|
|
80
|
-
`),c=r.flatMap(g=>Array.isArray(g.attachments)?g.attachments:[]),u={id:r[0].id,text:l,createdAt:r[0].createdAt||Date.now(),phase:"pending",attempted:!0,clientMessageIds:o,...c.length>0?{attachments:c}:{}},d=new Set(r.map(g=>g.id)),p=this.getSessionOutbox(e).filter(g=>!d.has(g.id));this.setSessionOutboxItems(e,[...p,u]);const f=this.getPromptEditSessionMatch(e);f&&d.has(f.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const h=(async()=>{await this.transport.sendMessage(e,u.text,{enqueueOnly:!0,clientMessageIds:u.clientMessageIds,...Array.isArray(u.attachments)&&u.attachments.length>0?{attachments:u.attachments}:{}});const m=this.getSessionOutbox(e).map(y=>y.id===u.id?{...y,phase:"queued"}:y);return this.setSessionOutboxItems(e,m),this.syncSessionEvents(e).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(g=>{const m=g?.code==="FORBIDDEN"||g?.code==="UNAUTHORIZED"||g?.status===403||g?.status===401,y=this.getSessionOutbox(e);if(m){const S=y.map(E=>E.id===u.id?{...E,phase:"rejected"}:E);this.setSessionOutboxItems(e,S),setTimeout(()=>{const E=this.getSessionOutbox(e),I=E.filter(w=>!(w.id===u.id&&w.phase==="rejected"));I.length!==E.length&&this.setSessionOutboxItems(e,I)},6e3)}else{const S=y.map(E=>E.id===u.id?{...u,phase:"pending",attempted:!0}:E);this.setSessionOutboxItems(e,S)}throw this.dispatch({type:"ui/status",text:g?.message||String(g)}),g}).finally(()=>{this.outboxFlushPromises.delete(e),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e)});return this.outboxFlushPromises.set(e,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 Xr(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=nt(s),i=n?.sessionId||s.sessions.activeSessionId||null,r=n?.filename||null;if(!i||!r)return!1;const o=Yr(r),l=Qr(s.ui.prompt,e,o),c=this.getPromptAttachments(),u=c.findIndex(f=>f?.sessionId===i&&f?.filename===r),d={...u>=0?c[u]:{},id:`${i}/${r}`,sessionId:i,filename:r,resolvedPath:r,token:o},p=u>=0?c.map((f,h)=>h===u?d:f):[...c,d];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=Bt(s)[0]||null,r=i?.sessionId&&s.sessions.byId[i.sessionId]||null;if(!r?.sessionId)return!1;const o=Zf(r),l=Qr(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=qr(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=zf(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=qr(e),i=Array.isArray(s.items)?s.items:[];if(i.length===n.length&&i.every((u,d)=>u?.id===n[d]?.id))return;const o=i[Math.max(0,Number(s.selectedIndex)||0)]?.id,l=o!=null?n.findIndex(u=>u.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=Xr(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(Os(this.getState(),"selectedSession")),l=pt(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:Fs(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:jr})})},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&&(Kt(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===jr,r=this.getState().sessions.activeSessionId;let o=(await Lf(this.transport)).map(In),l=null;if(typeof this.transport.listSessionGroups=="function")try{const f=await this.transport.listSessionGroups();l=(Array.isArray(f)?f:[]).map(Of).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,In(f)]:this.dispatch({type:"sessions/navigationIntentFailed",sessionId:c.sessionId,errorKind:"not_found"})}catch(f){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:c.sessionId,errorKind:xn(f)})}const u=r;if(u&&!Kt(u)&&!o.some(f=>f?.sessionId===u)&&typeof this.transport.getSession=="function"){const f=await this.transport.getSession(u).catch(()=>null);f?.sessionId&&(o=[...o,In(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 d=this.getState().sessions.activeSessionId,p=new Set;if(d){if(d!==r){if(!this.getState().sessions.byId[d]?.isGroup){const m=this.getState().sessions.navigationIntent;if(m&&m.sessionId===d&&m.status!=="failed")try{await this.loadSession(d)}catch(y){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:d,errorKind:xn(y)})}else await this.loadSession(d)}return}if(this.getState().sessions.byId[d]?.isGroup)return;this.getState().history.bySessionId.get(d)?.events?.length||await this.ensureSessionHistory(d,{force:!0}).catch(()=>{}),this.activeSessionSubscriptionId!==d&&this.attachActiveSession(d),await this.syncSessionDetail(d).catch(()=>{}),await this.syncSessionEvents(d).catch(()=>{}),p.add(d);const h=this.getState(),g=h.sessions.byId[d]||null;if(g?.parentSessionId&&typeof this.transport.getSession=="function"){const m=Object.values(h.sessions.byId).filter(y=>y?.parentSessionId===g.parentSessionId).map(y=>y.sessionId).filter(y=>y&&y!==d).slice(0,6);await Promise.all(m.map(y=>this.syncSessionDetail(y).catch(()=>{})));for(const y of m)p.add(y)}}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 d=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);d.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:d.map(([p])=>p)})}const l=Object.entries(e.executionHistory?.bySessionId||{});if(l.length>r){const d=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);d.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:d.map(([p])=>p)})}const c=Object.entries(e.files.bySessionId||{});if(c.length>r){const d=c.filter(([p])=>p!==s).slice(0,c.length-r);d.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:d.map(([p])=>p)})}const u=[...e.history.bySessionId.entries()];if(u.length>r*2){const d=u.filter(([p])=>p!==s).slice(0,u.length-r*2).map(([p])=>p);d.length>0&&this.dispatch({type:"history/evict",sessionIds:d})}}async syncVisibleSessionDetails(e=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=Jt({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=Dn(s,i),o=[...new Set(r.map(l=>l.sessionId).filter(l=>l&&!Kt(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(d){return Vt(d)&&this.handleSessionGone(e),null}if(!Array.isArray(r)||r.length>=1e3)return null;if(r.length===0)return s;let o=s;for(const d of r)o=Ji(o,d);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 d of r)this.reconcileOutboxAgainstEvent(e,d);const l=Wn(r),c=this.getState().sessions.byId[e]||{},u=Wr(c.contextUsage,r);return(l||u)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...l||{},...u?{contextUsage:u}:{}}}),o}async ensureSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),i=Math.min(Sh,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(Vt(f))return this.handleSessionGone(e),null;throw f}const c={...ls(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 u=Wn(l),d=this.getState().sessions.byId[e]||{},p=Wr(d.contextUsage,l);return(u||p)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...u||{},...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=Jt({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=Dn(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(Fe(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<Af)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 Vt(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<Cf)){this.dispatch({type:"sessionStats/loading",sessionId:s});try{const[r,o,l,c,u,d,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:u,factsStats:d,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<Tf)){this.dispatch({type:"fleetStats/loading"});try{const r={since:new Date(Date.now()-Mf*864e5),includeDeleted:!0},[o,l,c,u,d,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:u,sharedFactsStats:d,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=ra(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 eu(s,{token:r,tokenKind:o,onProgress:u=>this.dispatch({type:"admin/packages/addDialog/progress",message:u})});if(e.updateName){const u=tu(l);if(u&&u!==e.updateName){this.dispatch({type:"admin/packages/addDialog/failed",error:`That folder builds "${u}", not "${e.updateName}". Use Add package to publish it as its own package.`});return}}this.dispatch({type:"admin/packages/addDialog/progress",message:`publishing ${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=it(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=Fe(this.getState()),{force:s=!1}={}){const n=Os(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=nt(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<gh)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=Ru(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?to(s,"",o.contentType||"",o):to(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=nt(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||Fe(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:i}=s,r=Fe(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=nt(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=pt(this.getState()),n=this.getState().files.markedIds||[],i=n.length>0?n[n.length-1]:this.getState().files.selectedArtifactId,r=s.findIndex(d=>d.id===i),o=s.findIndex(d=>d.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],u=s.slice(l,c+1).map(d=>d.id);this.dispatch({type:"files/setMarks",artifactIds:[...new Set([...n,...u])]})}clearArtifactMarks(){this.dispatch({type:"files/clearMarks"})}async deleteMarkedArtifacts({confirmed:e=!1}={}){const s=this.getState(),n=s.files.markedIds||[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No artifacts marked"}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifacts",message:`Delete ${n.length} artifact${n.length===1?"":"s"}? This action cannot be undone.`,confirmLabel:`Delete ${n.length}`,action:"deleteMarkedArtifacts",previousFocus:s.ui.focusRegion}}),!1;const i=new Set;let r=0;const o=[];for(const l of n){const c=String(l).indexOf("/");if(c<=0)continue;const u=l.slice(0,c),d=l.slice(c+1);try{await this.transport.deleteArtifact(u,d),this.dispatch({type:"files/deleted",sessionId:u,filename:d}),i.add(u),r+=1}catch(p){o.push(`${d}: ${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=nt(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const i=Fe(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=nt(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=Dd(e),i=Hd(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=Fe(this.getState());await this.ensureFilesForScope(s);const n=pt(this.getState());if(n.length===0)return;const i=nt(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=Fe(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(!Rf.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=Fe(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:xn(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:Ji(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=Gf(s),o=this.getState().sessions.byId[e]||{sessionId:e},l=Lo(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(Vt(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||Kt(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||Kt(e))return;let s=null;try{s=await this.transport.getSession(e)}catch(r){if(Vt(r)){this.handleSessionGone(e);return}throw r}if(!s)return;const n=this.getState().sessions.byId[e]||null,i=Kf(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 ${zr(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 u=e?`group ${n||e}`:"No Group",d=l.length>0?` · skipped ${l.length} (${$f(l)})`:"";return this.dispatch({type:"ui/status",text:c>0?`Moved ${c} session${c===1?"":"s"} to ${u}${d}`:`No sessions moved to ${u}${d}`}),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=wt(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=it(s.value||"",s.cursorIndex||0,wt(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,i=n?.isGroup?n.groupId||Ss(n.sessionId):n?.groupId;return i?{...e,groupId:i}:e}getActiveSession(e=this.getState()){const s=e.sessions?.activeSessionId;return s&&e.sessions.byId[s]||null}toggleChatViewMode(){if(this.getActiveSession()?.isGroup){this.dispatch({type:"ui/status",text:"Session groups show group details"});return}const s=this.getState().ui?.chatViewMode==="summary"?"transcript":"summary";this.dispatch({type:"ui/chatViewMode",mode:s}),this.dispatch({type:"ui/status",text:s==="summary"?"Showing session summary":"Showing chat transcript"})}setChatViewMode(e){e!=="summary"&&e!=="transcript"||this.getActiveSession()?.isGroup||this.dispatch({type:"ui/chatViewMode",mode:e})}async openSessionAgentPicker(e={},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(d){i(),this.dispatch({type:"ui/status",text:`Could not load agents: ${d?.message||d}`});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 d of r){const p=String(d?.name||"").trim();p&&c.push({id:p,kind:"agent",agentName:p,title:zr(p,d?.title),description:String(d?.description||"").trim(),tools:Array.isArray(d?.tools)?d.tools.filter(Boolean):[],splash:typeof d?.splash=="string"&&d.splash.trim()?d.splash:null,splashMobile:typeof d?.splashMobile=="string"&&d.splashMobile.trim()?d.splashMobile:null,initialPrompt:typeof d?.initialPrompt=="string"&&d.initialPrompt.trim()?d.initialPrompt:null,group:d?.source==="package"&&d?.scope==="user"&&d?.mine!==!1?"mine":"shared",packageName:d?.packageName||null,packageSemver:d?.packageSemver||null,packageScope:d?.scope||null,builtin:d?.source!=="package"})}const u=[...c.filter(d=>d.group==="shared"),...c.filter(d=>d.group==="mine")];l&&u.push({id:"__generic__",kind:"generic",group:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,splashMobile:null,initialPrompt:null}),this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",items:u,selectedIndex:0,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=jn(e?.supportedReasoningEfforts),o=s?.reasoningEffort||Ur(e);if(!r.length||!o){await this.openContextTierPicker(e,s,i);return}const l=r.map(u=>({id:u,effort:u,label:u,isDefault:o===u})),c=Math.max(0,l.findIndex(u=>u.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=Un(e?.supportedContextTiers),o=s?.contextTier||Bf(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(u=>({id:u,tier:u,tokenLimit:e?.contextWindowSizes?.[u]||null,label:Hf(u,e?.contextWindowSizes?.[u]),isDefault:o===u})),c=Math.max(0,l.findIndex(u=>u.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():Ff(s),r=await this._resolveGhcpUserKeySet(),o=[],l=i.map(d=>({providerId:d.providerId,providerType:d.type||d.providerType,models:(d.models||[]).map(p=>{const f=p.providerType||d.type||d.providerType,h=f==="github"&&p.credentialAvailable===!1&&r===!1,g={id:p.qualifiedName,qualifiedName:p.qualifiedName,modelName:p.modelName||p.qualifiedName,providerId:p.providerId||d.providerId,providerType:f,description:p.description||"",cost:p.cost||null,supportedReasoningEfforts:jn(p.supportedReasoningEfforts),defaultReasoningEffort:p.defaultReasoningEffort||null,supportedContextTiers:Un(p.supportedContextTiers),defaultContextTier:p.defaultContextTier||null,contextWindowSizes:p.contextWindowSizes||null,isDefault:n===p.qualifiedName,ghcpKeyMissing:h,disabled:h};return o.push(g),g})})).filter(d=>d.models.length>0),c=e?.model||n;let u=o.findIndex(d=>d.qualifiedName===c&&!d.disabled);u<0&&(u=o.findIndex(d=>!d.disabled)),u<0&&(u=0),this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:e?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:o,groups:l,selectedIndex:u,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async _resolveGhcpUserKeySet(){const e=this.getState().admin?.profile;if(typeof e?.githubCopilotKeySet=="boolean")return e.githubCopilotKeySet;if(typeof this.transport.getCurrentUserProfile!="function")return null;try{const s=await this.transport.getCurrentUserProfile();return s&&typeof s.githubCopilotKeySet=="boolean"?s.githubCopilotKeySet:!1}catch{return null}}async openSwitchModelPicker(e=null){this._onSwitchModelApplied=typeof e=="function"?e:null;const s=this.getState(),n=s.sessions.activeSessionId,i=n&&s.sessions.byId[n]||null;if(!i||i.isGroup){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Select a session before switching model"});return}if(typeof this.transport.setSessionModel!="function"){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.openModelPicker({mode:"switchModel",sessionId:n,model:i.model||void 0,reasoningEffort:i.reasoningEffort||void 0})}async switchSessionModel(e={}){const s=e.sessionId||this.getState().sessions.activeSessionId,n=String(e.model||"").trim();if(!s||!n){this.dispatch({type:"ui/status",text:"Select a model before switching"});return}if(typeof this.transport.setSessionModel!="function"){this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.transport.setSessionModel(s,{model:n,..."reasoningEffort"in e?{reasoningEffort:e.reasoningEffort??null}:{},..."contextTier"in e?{contextTier:e.contextTier??null}:{},source:"ui"});const i=e.reasoningEffort?`${n}:${e.reasoningEffort}`:n,r=e.contextTier?` · ${el[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=Nu().map(i=>({id:i.id,label:i.label,description:i.description,page:i.page,terminal:i.terminal,tui:i.tui}));if(e.length===0){this.dispatch({type:"ui/status",text:"No themes available"});return}const s=this.getState().ui.themeId,n=Math.max(0,e.findIndex(i=>i.id===s));this.dispatch({type:"ui/modal",modal:{type:"themePicker",title:"Theme Picker",items:e,selectedIndex:n,previousFocus:this.getState().ui.focusRegion,currentThemeId:s}}),this.dispatch({type:"ui/status",text:"Select a theme and press Enter"})}getPromptDraftSessionId(){return this.getPromptAttachments()[0]?.sessionId||null||this.getState().sessions.activeSessionId||null}openArtifactUploadModal(){if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}const e=this.getState(),s=this.getPromptDraftSessionId();this.dispatch({type:"ui/modal",modal:{type:"artifactUpload",title:s?`Upload Artifact (${Ae(s)})`:"Upload Artifact",sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0}}),this.dispatch({type:"ui/status",text:s?"Paste a local file path and press Enter to upload it into this session's artifacts":"Paste a local file path and press Enter to upload it; a new session will be created if needed"})}updateArtifactUploadModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setArtifactUploadValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="artifactUpload")return;const i=String(e||"").replace(/\r?\n/g,""),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=it(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=Ir(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 u=l.slice(0,c),d=l.slice(c+1);this.dispatch({type:"files/select",sessionId:u,filename:d}),await this.ensureFilePreview(u,d).catch(()=>{})}canStepArtifactPreview(e){const s=this.getState(),n=s.files.previewOrigin==="chat"?Ir(s):pt(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=Yr(e.filename),o=this.getState().ui.prompt,l=this.getState().ui.promptCursor,c=this.getPromptAttachments(),u=c.findIndex(p=>p?.sessionId===i&&p?.filename===e.filename);if(this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),u===-1||!o.includes(c[u]?.token||r)){const p=it(o,l,`${r} `);this.setPrompt(p.prompt,p.cursor)}const d=u>=0?c.map((p,f)=>f===u?{...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(d),await this.ensureFilesForSession(i,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:i,filename:e.filename}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(i,e.filename,{force:!0}).catch(()=>null),this.setFocus(T.PROMPT),n||this.dispatch({type:"ui/status",text:u>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:i,existingAttachmentIndex:u,token:r}}async uploadArtifactFiles(e=[],{sessionId:s=null}={}){const n=Array.isArray(e)?e.filter(c=>c&&typeof c.name=="string"):[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No files selected"}),[];if(typeof this.transport.uploadArtifactFromFile!="function")return this.dispatch({type:"ui/status",text:"Browser file uploads are not supported by this transport"}),[];this.dispatch({type:"ui/status",text:n.length===1?`Uploading ${n[0].name}...`:`Uploading ${n.length} artifact files...`});const i=s||await this.ensurePromptAttachmentSessionId(),r=[];let o=0,l=null;for(const c of n)try{const u=await this.transport.uploadArtifactFromFile(i,c);r.push(u),await this.finalizeArtifactUpload(u,{sessionId:i,suppressStatus:!0})}catch(u){o+=1,l=u}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=Xf(n),r=Ai(n),o=Yf(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=wt(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=it(s.value||"",s.cursorIndex||0,wt(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||Ss(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=St(["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=wt(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=it(s.value||"",s.cursorIndex||0,wt(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(),g=(e.shares||[]).find(m=>m.subject&&String(m.subject).toLowerCase()===h||m.email&&String(m.email).toLowerCase()===h||m.displayName&&String(m.displayName).toLowerCase()===h);if(!g){this.dispatch({type:"ui/status",text:`No grant matching "${r}"`});return}this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.revokeSessionShare(s,{provider:g.provider,subject:g.subject}),this.dispatch({type:"ui/status",text:`Revoked ${r}`})}catch(m){this.dispatch({type:"ui/status",text:m?.message||String(m)})}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,u=c&&l[c]?l[c]:"read",d=c&&l[c]?o.slice(0,-1).join(" "):n,p=d.toLowerCase();let f=null;if(typeof this.transport.listKnownUsers=="function"){let h=[];try{h=await this.transport.listKnownUsers({limit:500})}catch{h=[]}const g=Array.isArray(h)?h:[];if(f=g.find(m=>m.displayName&&m.displayName.toLowerCase()===p||m.email&&m.email.toLowerCase()===p||m.subject&&m.subject.toLowerCase()===p)||null,!f){const m=g.filter(y=>y.displayName&&y.displayName.toLowerCase().includes(p)||y.email&&y.email.toLowerCase().includes(p)||y.subject&&y.subject.toLowerCase().includes(p));if(m.length===1)f=m[0];else if(m.length>1){this.dispatch({type:"ui/status",text:`"${d}" is ambiguous (${m.length} matches)`});return}}}f||(f={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:d,email:null,displayName:null}),this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.grantSessionShare(s,{provider:f.provider,subject:f.subject,email:f.email??null,displayName:f.displayName??null},u),this.dispatch({type:"ui/status",text:`Granted ${u} to ${d}`})}catch(h){this.dispatch({type:"ui/status",text:h?.message||String(h)})}}closeModal(){const e=this.getState().ui.modal;e&&(this.dispatch({type:"ui/modal",modal:null}),e.type==="themePicker"&&e.currentThemeId&&this.dispatch({type:"ui/theme",themeId:e.currentThemeId}),e.previousFocus&&this.setFocus(e.previousFocus),this.dispatch({type:"ui/status",text:"Connected"}))}moveModalSelection(e){const s=this.getState().ui.modal;if(!s)return;if(s.type==="help"){const 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],u=St(l,c,e),d=o.options.find(p=>p.id===u)||o.options[0];this.dispatch({type:s.type==="filesFilter"?"files/filter":s.type==="historyFormat"?"executionHistory/format":"logs/filter",filter:s.type==="historyFormat"?void 0:{[o.id]:u},...s.type==="historyFormat"?{format:u}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(u).catch(()=>{}),this.ensureSelectedFilePreview().catch(()=>{})),this.dispatch({type:"ui/status",text:`${s.type==="filesFilter"?"Files":s.type==="historyFormat"?"History":"Log"} filter updated: ${o.label} = ${d?.label||u}`});return}const n=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(0,Math.min(n+e,s.items.length-1));this.dispatch({type:"ui/modalSelection",index:i})}moveModalPane(e){const s=this.getState().ui.modal;if(!s||s.type!=="logFilter"&&s.type!=="filesFilter"&&s.type!=="historyFormat"||!Array.isArray(s.items)||s.items.length===0)return;const i=(Math.max(0,Number(s.selectedIndex)||0)+e+s.items.length)%s.items.length,r=s.items[i],o=s.type==="filesFilter"?this.getState().files.filter?.[r.id]||r.options?.[0]?.id:s.type==="historyFormat"?this.getState().executionHistory?.format||r.options?.[0]?.id:this.getState().logs.filter?.[r.id]||r.options?.[0]?.id,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=De(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=Ur(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],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=th(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 m=await this.createSession({});if(!m?.sessionId)return;o=m.sessionId,l=this.getState().sessions.byId[o]||null}const c=n.some(m=>m?.kind==="image");if(!r.trim()&&!c){o&&this.getPendingOutboxItems(o).length>0&&await this.dispatchPendingOutbox(o).catch(()=>{});return}const u=l?.pendingQuestion||null,d=!!u?.question,p=this.getPromptEditSessionMatch(o);if(p){const m=this.getSessionOutbox(o).find(y=>y.id===p.itemId);if(m?.phase==="queued"||m?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(o).catch(()=>{});return}if(d&&typeof this.transport.sendAnswer=="function"){const m=Date.now(),y={...u,answer:r,answeredAt:m,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:null,answeredPendingQuestion:y}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(o,r),this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:{...y,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(o,100),this.syncSessionEvents(o).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(S){this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:u}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(r,String(r||"").length),this.dispatch({type:"ui/status",text:S?.message||String(S)})}return}const f=n.filter(m=>m?.kind==="image");let h=null;if(f.length>0){if(f.some(S=>S.file)&&typeof this.transport.uploadArtifactFromFile!="function"){this.dispatch({type:"ui/status",text:"This transport does not support image attachments."});return}const y=this.buildOutboxItem("","pending");this.dispatch({type:"ui/status",text:`Uploading ${f.length} image${f.length>1?"s":""}...`});try{h=await this.uploadPendingImageAttachments(o,f,y.id),this.dispatch({type:"ui/status",text:""})}catch(S){this.dispatch({type:"ui/status",text:`Image upload failed: ${S?.message||S}`});return}}const g=r.trim()?r:h&&h.length>0?"See the attached image(s).":r;this.queuePromptInOutbox(o,g,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=it(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=oh(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,rl(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=ah(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 Jt({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=_n(e);this.setFocus(St(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=Je(this.getState().ui.focusRegion,e),n=_n(e);this.setFocus(St(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=Je(this.getState().ui.focusRegion,e);this.setFocus(Kc(s,e))}focusRight(){const e=this.getCurrentLayout(),s=Je(this.getState().ui.focusRegion,e);this.setFocus(Vc(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,u,d)=>{const p=Math.max(u,d);return Math.max(u,Math.min(p,(l||0)+c))};if(s===T.SESSIONS||s===T.CHAT){const l=na(i),c=Lt+1,u=Math.min(ia(r,i),i-Gs-1),d=s===T.CHAT?-e:e,p=o(n.sessionPaneAdjust,d,c-l,u-l);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:p})}else if(s===T.INSPECTOR||s===T.ACTIVITY){const l=Math.max(Pt,Math.floor(i*sa)),c=Pt+1,u=i-ks-1,d=s===T.INSPECTOR?-e:e,p=o(n.activityPaneAdjust,d,c-l,u-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=St(ze,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=St(ze,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){ze.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=Bt(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(()=>{})},yh))}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 lh.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:Nf,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=mi(e,n),o=[...yi(e,n),...hi(e)],l=Math.min(Math.max(0,Math.floor(i*.34)),It(o,n)),c=It(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=bi(o);return{contentWidth:n,contentHeight:i,totalLines:It(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=at(o,{width:n}),c=l.tabs.map(f=>({text:f===l.activeTab?`[${f}] `:`${f} `,color:f===l.activeTab?"magenta":"gray",bold:f===l.activeTab})),u=(l.lines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f),d=l.activeTab==="sequence"?[c,...(l.stickyLines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f)]:[],p=l.activeTab==="sequence"?u:[c,...u];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:It(d,n),totalLines:It(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,u=c&&e.sessions.byId[c]||null,d={sessions:{activeSessionId:c,byId:c&&u?{[c]:u}:{},flat:e.sessions.flat},files:{bySessionId:e.files.bySessionId,fullscreen:!!e.files.fullscreen,selectedArtifactId:e.files.selectedArtifactId,filter:e.files.filter},ui:{scroll:{filePreview:e.ui.scroll.filePreview}}},p=wi(d,{listWidth:l,previewWidth:l}),f=Math.max(9,r-4),h=Math.max(5,Math.min(10,Math.floor(f*.35)));let g=Math.max(5,Math.min(h,(p.listBodyLines||[]).length+2)),m=Math.max(5,f-g-1);const y=8;if(m<y){const S=y-m;g=Math.max(5,g-S),m=Math.max(5,f-g-1)}return{contentWidth:l,contentHeight:Math.max(1,m-2),totalLines:It(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)>=Kn){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),u=Math.max(0,c-l);if(e<u)return}await this.expandSessionHistory(i,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages,eventTypes:Sc})}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,u=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),d=c?this.getActiveChatRenderMetrics(n).totalLines:0,p=(async()=>{let f;const h=Math.max(1,Math.floor(Number(s.pages)||1)),g=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&l>0){f=i||ls([],{requestedLimit:r});for(let S=0;S<h;S+=1){const E=Array.isArray(f?.events)&&f.events.length>0?Number(f.events[0]?.seq||0):0;if(!f?.hasOlderEvents||E<=1){f={...f,hasOlderEvents:!1};break}if(Number(f.loadedEventCount||0)>=Kn)break;const I=await this.transport.getSessionEventsBefore(e,E,o,g);if(!Array.isArray(I)||I.length===0){f={...f,hasOlderEvents:!1};break}const w=ls(I,{requestedLimit:o}),b=[...w.events||[],...f?.events||[]];if(f={chat:Mt([...w.chat||[],...f?.chat||[]]),activity:[...w.activity||[],...f?.activity||[]],events:b,lastSeq:f?.lastSeq||f?.events?.[f?.events?.length-1]?.seq||I[I.length-1]?.seq||0,loadedEventLimit:b.length,loadedEventCount:b.length,hasOlderEvents:I.length>=o&&Number(I[0]?.seq||0)>1},!f.hasOlderEvents)break}}else{const S=Bc(r);if(S<=r){this.dispatch({type:"ui/status",text:i?.hasOlderEvents?`Already showing a large recent history window (${r} events)`:"Already showing the oldest loaded history"});return}const E=await this.transport.getSessionEvents(e,void 0,S);f={...ls(E,{requestedLimit:S}),lastSeq:E[E.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:f});for(const S of f?.events||[])this.reconcileOutboxAgainstEvent(e,S);const m=Array.isArray(i?.chat)&&i.chat.length>0;if(c&&!m)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(c&&u>0){const S=this.getState(),E=this.getActiveChatRenderMetrics(S).totalLines,I=Math.max(0,E-d);I>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:u+I})}const y=f.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${f.loadedEventCount} events loaded)`:`Loaded older history page (${f.loadedEventCount} events loaded)`:`Loaded full available history (${f.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:y}),f.hasOlderEvents?s.autoTriggered&&c&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,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 u=[];for(const p of o)try{await this.transport.cancelSession(p.sessionId),c+=1}catch(f){u.push(`${p.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const d=u.length===0?`Cancelled ${c} session${c===1?"":"s"}`:`Cancelled ${c}/${o.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:d}),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 u=l.sessions.byId[c];if(u?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; regenerate sessions individually."});return}if(u?.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be regenerated."});return}if(u?.serviceKind){this.dispatch({type:"ui/status",text:"Service sessions are runtime machinery and cannot be regenerated."});return}if(!e){const d=u?.title||c.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Regenerate Session",message:`Regenerate context for "${d}"? 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 d=String(s||"").trim();await this.transport.regenerateSession(c,{force:!0,...d?{instructions:d.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(d){this.dispatch({type:"ui/status",text:`Regenerate failed: ${d?.message||String(d)}`});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 u=0;const d=[];for(const f of l)try{await this.transport.completeSession(f.sessionId,e),u+=1}catch(h){d.push(`${f.sessionId.slice(0,8)}: ${h?.message||String(h)}`)}this.dispatch({type:"sessions/selectClear"});const p=d.length===0?`Completed ${u} session${u===1?"":"s"}`:`Completed ${u}/${l.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.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 u=[];for(const p of o)try{await this.transport.deleteSession(p.sessionId),this.handleSessionGone(p.sessionId),c+=1}catch(f){u.push(`${p.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const d=u.length===0?`Deleted ${c} session${c===1?"":"s"}`:`Deleted ${c}/${o.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:d}),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||Ss(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 C.REFRESH:await this.refreshSessions();return;case C.NEW_SESSION:await this.openNewSessionFlow();return;case C.OPEN_MODEL_PICKER:await this.openModelPicker();return;case C.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case C.OPEN_THEME_PICKER:this.openThemePicker();return;case C.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case C.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case C.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case C.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case C.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case C.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case C.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case C.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case C.TOGGLE_CHAT_VIEW:this.toggleChatViewMode();return;case C.CLOSE_MODAL:this.closeModal();return;case C.MODAL_PREV:this.moveModalSelection(-1);return;case C.MODAL_NEXT:this.moveModalSelection(1);return;case C.MODAL_PANE_PREV:this.moveModalPane(-1);return;case C.MODAL_PANE_NEXT:this.moveModalPane(1);return;case C.MODAL_CONFIRM:await this.confirmModal();return;case C.SEND_PROMPT:await this.sendPrompt();return;case C.FOCUS_NEXT:this.focusNext();return;case C.FOCUS_PREV:this.focusPrev();return;case C.FOCUS_LEFT:this.focusLeft();return;case C.FOCUS_RIGHT:this.focusRight();return;case C.FOCUS_PROMPT:this.setFocus(T.PROMPT);return;case C.FOCUS_SESSIONS:this.setFocus(T.SESSIONS);return;case C.MOVE_SESSION_UP:await this.moveSession(-1);return;case C.MOVE_SESSION_DOWN:await this.moveSession(1);return;case C.EXPAND_SESSION:this.expandActiveSession();return;case C.COLLAPSE_SESSION:this.collapseActiveSession();return;case C.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case C.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case C.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case C.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case C.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case C.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case C.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case C.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case C.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case C.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case C.OPEN_HELP:this.openHelpModal();return;case C.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case C.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case C.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case C.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case C.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case C.OPEN_LOG_FILTER:this.openLogFilter();return;case C.OPEN_FILES_FILTER:this.openFilesFilter();return;case C.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case C.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case C.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case C.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case C.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case C.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case C.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case C.SCROLL_UP:this.scrollCurrentPane(1);return;case C.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case C.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 C.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 C.EXPAND_HISTORY:await this.expandActiveHistory();return;case C.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case C.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case C.CANCEL_SESSION:await this.cancelActiveSession();return;case C.STOP_TURN:await this.stopActiveSessionTurn();return;case C.DONE_SESSION:await this.completeActiveSession();return;case C.DELETE_SESSION:await this.deleteActiveSession();return;case C.REGENERATE_SESSION:await this.regenerateActiveSession();return;case C.PIN_SESSION:this.togglePinActiveSession();return;case C.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case C.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case C.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case C.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case C.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case C.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case C.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case C.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case C.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case C.ADMIN_SHOW_GHCP:this.setAdminSection("ghcp");return;case C.ADMIN_SHOW_PACKAGES:this.setAdminSection("packages");return;case C.ADMIN_SHOW_WORKERS:this.setAdminSection("workers");return;case C.ADMIN_WORKERS_REFRESH:await this.refreshAdminWorkers();return;case C.ADMIN_PACKAGES_REFRESH:await this.refreshAdminAgentPackages();return;case C.ADMIN_PACKAGES_NEXT:await this.stepAdminPackageSelection(1);return;case C.ADMIN_PACKAGES_PREV:await this.stepAdminPackageSelection(-1);return;case C.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case C.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case C.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case C.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 qs=0;function Oe(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 vn(){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 wh(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 Ih(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 xh(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 Eh(t=2e3){const[e,s]=a.useState(()=>vn());return a.useEffect(()=>{if(vn()==null)return;const n=()=>{const r=vn();r!=null&&s(o=>o===r?o:r)};n();const i=setInterval(n,t);return()=>clearInterval(i)},[t]),a.useMemo(()=>wh(e),[e])}function jt(t,e){return t&&e?{[t]:e}:{}}function so(t){return typeof t=="string"?{text:t,color:"white"}:t}function os(t,e,s,n,i,r){const o=(e.tabs||ze).map(p=>({text:p===e.activeTab?`[${p}] `:`${p} `,color:p===e.activeTab?"magenta":"gray",bold:p===e.activeTab})),l=(e.lines||[]).map(so),c=(e.stickyLines||[]).map(so),u=e.activeTab==="sequence"?[o,...c]:[],d=e.activeTab==="sequence"?l:[o,...l];return a.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:i,stickyLines:u,marginBottom:qs,lines:d,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="sequence"||e.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:r})}function no(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=je(),c=Eh(),u=ee(e,g=>({sessions:g.sessions,mode:g.connection?.mode||"local",brandingTitle:g.branding?.title||"PilotSwarm",focused:g.ui.focusRegion==="sessions",identityLabel:Ih(g.auth)}),Oe),d=a.useMemo(()=>xh(c,o,u.identityLabel),[c,o,u.identityLabel]),p=a.useMemo(()=>({sessions:u.sessions,connection:{mode:u.mode},branding:{title:u.brandingTitle}}),[u.brandingTitle,u.mode,u.sessions]),f=a.useMemo(()=>Dn(p,s),[p,s]),h=a.useMemo(()=>f.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:f.map(g=>g.active?ga(g.runs,{preserveColors:!0}):g.runs),[f]);return a.createElement(l.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:d,color:"yellow",focused:u.focused,width:n,height:i,marginBottom:qs,lines:h,paneId:"sessions",paneLabel:"Sessions",frame:r})});a.memo(function({controller:e,width:s,height:n,frame:i}){const r=je(),o=ee(e,I=>{const w=I.sessions.activeSessionId;return{activeSessionId:w,activeSession:w&&I.sessions.byId[w]||null,activeHistory:w&&I.history.bySessionId.get(w)||null,activeOutbox:w&&I.outbox?.bySessionId?.[w]||null,authPrincipal:I.auth?.principal||null,branding:I.branding,connectionError:I.connection.error,connectionMode:I.connection.mode,chatViewMode:I.ui.chatViewMode||"transcript",chatScroll:I.ui.scroll.chat,focused:I.ui.focusRegion==="chat"}},Oe),l=Math.max(20,s-4),c=a.useMemo(()=>{const I=new Map;return o.activeSessionId&&o.activeHistory&&I.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:jt(o.activeSessionId,o.activeSession)},history:{bySessionId:I},outbox:{bySessionId:o.activeSessionId&&o.activeOutbox?{[o.activeSessionId]:o.activeOutbox}:{}}}},[o.activeHistory,o.activeSessionId,o.activeSession,o.activeOutbox,o.authPrincipal,o.branding,o.chatViewMode,o.connectionError,o.connectionMode]),u=a.useMemo(()=>Ba(c,{width:l}),[l,c]),d=Ro(!!u?.animateTitleRight),p=a.useMemo(()=>Oo(u?.titleRight,d),[d,u?.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"}]:mi(c,l),[o.branding.splash,o.connectionError,l,c,f]),g=String(o.activeSession?.status||"").toLowerCase()==="running",m=_o(g),y=a.useMemo(()=>f?[]:hi(c,{spinnerFrame:m,maxWidth:l}),[c,f,m,l]),S=a.useMemo(()=>f?[]:yi(c,l),[c,f,l]),E=a.useMemo(()=>S.length>0||y.length>0?[...S,...y]:[],[S,y]);return a.createElement(r.Panel,{title:u.title,titleRight:p,color:u.color,focused:o.focused,width:s,height:n,lines:h,bottomStickyLines:E,scrollOffset:o.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:i})});const vh=a.memo(function({controller:e,width:s,height:n,shellTitle:i,focused:r=!1,frame:o,showFullscreenTitle:l=!1,embedded:c=!1}){const u=je(),d=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}),Oe),p=Math.max(20,s-4),f=a.useMemo(()=>({sessions:{activeSessionId:d.activeSessionId,byId:d.activeSessionId&&d.activeSession?{[d.activeSessionId]:d.activeSession}:{},flat:d.sessionsFlat},files:{bySessionId:d.filesBySessionId,fullscreen:d.filesFullscreen,selectedArtifactId:d.selectedArtifactId,filter:d.filesFilter},ui:{scroll:{filePreview:d.filePreviewScroll}}}),[d]),h=a.useMemo(()=>wi(f,{listWidth:Math.max(8,p-4),previewWidth:Math.max(8,p-4)}),[p,f]),g=i||(l?h.fullscreenTitle:h.panelTitle||h.listTitle)||[{text:"Files",color:"magenta",bold:!0}],m=Math.max(9,n-4),y=Math.max(5,Math.min(10,Math.floor(m*.35)));let S=Math.max(5,Math.min(y,(h.listBodyLines||[]).length+2)),E=Math.max(5,m-S-1);const I=8;if(E<I){const B=I-E;S=Math.max(5,S-B),E=Math.max(5,m-S-1)}const w=Math.max(1,S-2),b=Math.max(0,h.selectedIndex-Math.floor(w/2)),x=!c&&o?{x:o.x+2,y:o.y+2,width:p,height:S}:null,k=!c&&o?{x:o.x+2,y:o.y+2+S+1,width:p,height:E}:null,P=ze.map(B=>({text:B==="files"?`[${B}] `:`${B} `,color:B==="files"?"magenta":"gray",bold:B==="files"})),N=a.createElement(u.Column,{width:p},a.createElement(u.Lines,{lines:[P]}),a.createElement(u.Panel,{title:h.listTitle,color:"gray",focused:!1,width:p,height:S,lines:h.listBodyLines||h.listLines.slice(1),scrollOffset:b,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:x}),a.createElement(u.Panel,{title:h.previewTitle,color:"gray",focused:!1,width:p,height:E,lines:h.previewLines,scrollOffset:h.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:k}));return c?N:a.createElement(u.Panel,{title:g,color:"magenta",focused:r,width:s,height:n,marginBottom:qs,paneId:"inspector",paneLabel:"Inspector",frame:o},N)}),kh=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=je(),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}),Oe),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:jt(c.activeSessionId,c.activeSession)},ui:{inspectorTab:"files"}}),[c.activeSession,c.activeSessionId]),d=a.useMemo(()=>at(u,{width:l}),[l,u]);return a.createElement(o.Panel,{title:d.title,color:"magenta",focused:r.focused,width:s,height:n,marginBottom:qs,paneId:"inspector",paneLabel:"Inspector",frame:i},a.createElement(vh,{controller:e,width:s,height:n,frame:i,focused:r.focused,embedded:!0}))}),Ah=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=je(),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}),Oe),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:jt(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]),d=a.useMemo(()=>at(u,{width:l,sequenceExpansion:{expandedTurns:c.expandedTurns||[],selectedTurn:c.selectedTurn??null}}),[l,u,c.expandedTurns,c.selectedTurn]);return os(o,d,r,s,n,i)}),Ch=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=je(),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}),Oe),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:jt(c.activeSessionId,c.activeSession)},logs:c.logs,ui:{inspectorTab:"logs"}}),[c.activeSession,c.activeSessionId,c.logs]),d=a.useMemo(()=>at(u,{width:l}),[l,u]);return os(o,d,r,s,n,i)}),Th=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=je(),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}),Oe),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:jt(c.activeSessionId,c.activeSession)},executionHistory:c.executionHistory,ui:{inspectorTab:"history"}}),[c.activeSession,c.activeSessionId,c.executionHistory]),d=a.useMemo(()=>at(u,{width:l}),[l,u]);return os(o,d,r,s,n,i)}),Mh=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=je(),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}),Oe),u=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]),d=a.useMemo(()=>at(u,{width:l}),[l,u]);return os(o,d,r,s,n,i)}),Nh=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=je(),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}),Oe),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:jt(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]),d=a.useMemo(()=>at(u,{width:l}),[l,u]);return os(o,d,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"}),Oe);return r.inspectorTab==="files"?a.createElement(kh,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="sequence"?a.createElement(Ah,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="logs"?a.createElement(Ch,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="history"?a.createElement(Th,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="stats"?a.createElement(Nh,{controller:e,width:s,height:n,frame:i,meta:r}):a.createElement(Mh,{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=je(),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}},Oe),c=l.inspectorTab==="nodes",u=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]),d=a.useMemo(()=>c?Da(u):bi(u,i),[i,c,u]);return a.createElement(o.Panel,{title:d.title,color:"gray",focused:l.focused,width:s,height:n,lines:d.lines,scrollOffset:l.scroll,scrollMode:l.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:r})});a.memo(function({controller:e,rows:s}){const n=je(),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(u=>u?.phase==="pending")}},Oe);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=je(),n=ee(e,d=>({connected:d.connection.connected,workersOnline:d.connection.workersOnline,focusRegion:d.ui.focusRegion,inspectorTab:d.ui.inspectorTab,chatViewMode:d.ui.chatViewMode||"transcript",fullscreenPane:d.ui.fullscreenPane||null,logsAvailable:d.logs.available,logsTailing:d.logs.tailing,filesFullscreen:!!d.files.fullscreen,mode:d.connection.mode,statusText:d.ui.statusText,modal:d.ui.modal,activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,selectedIds:d.sessions.selectedIds,selectMode:d.sessions.selectMode}),Oe),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(()=>tp(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),u=Math.max(8,l-c-3);return a.createElement(s.StatusLine,{left:no(r.left,u),right:no(r.right,c)})});const Ph="modulepreload",_h=function(t){return"/"+t},io={},al=function(e,s,n){let i=Promise.resolve();if(s&&s.length>0){let c=function(u){return Promise.all(u.map(d=>Promise.resolve(d).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(u=>{if(u=_h(u),u in io)return;io[u]=!0;const d=u.endsWith(".css"),p=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${p}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":Ph,d||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),d)return new Promise((h,g)=>{f.addEventListener("load",h),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}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 ll=Kl();const Rh=920,cl=7,ul=19,Ci=.24,dl=16,pl=8,Oh=224,$h=190,Lh=48,et=16,fl=.5,qt=fl,Fh=24,Bh=700,Dh=5e3,Hh=new Set(["low","medium","high","xhigh"]),Gh=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],jh=["pilotswarm_theme","pilotswarm_session_owner_filter"],Uh={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"Duroxide Event History",files:"Files",stats:"Stats"},ro={sequence:Tg,logs:Ng,nodes:Pg,history:$g,files:Lg,stats:Fg};function Wh(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 Kh(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function Vh(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function qh(t){return typeof t?.transport?.listArtifacts=="function"}function zh(t){return typeof t?.transport?.deleteArtifact=="function"}function Yh(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const Xh="Session link copied to clipboard",Qh=140,Jh="Only people with access can open this link.";function Zh(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function oo(t){navigator?.clipboard?.writeText&&navigator.clipboard.writeText(t).catch(()=>{})}async function em(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 tm(){if(!(typeof window>"u")){try{for(const t of Gh)window.localStorage.removeItem(t)}catch{}try{for(const t of jh)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function mt(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()),Te(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=Te(n,"includeShared")?n:{...n,includeShared:!0}}if(Te(e,"layoutAdjustments")&&(s.layoutAdjustments=ii(e.layoutAdjustments)),Te(e,"pinnedSessionIds")&&(s.pinnedSessionIds=Ns(e.pinnedSessionIds)),Te(e,"sessionOrder")&&(s.sessionOrder=ri(e.sessionOrder)),Te(e,"collapsedSessionIds")&&(s.collapsedSessionIds=sm(e.collapsedSessionIds)),Te(e,"activeSessionId")){const n=e.activeSessionId==null?null:String(e.activeSessionId).trim();s.activeSessionId=n||null}return ts(e.chatViewMode)&&(s.chatViewMode=e.chatViewMode),ts(e.chatViewModeMobile)&&(s.chatViewModeMobile=e.chatViewModeMobile),s}function ts(t){return t==="summary"||t==="transcript"||t==="rich"}function hl(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches}function Bs(){return hl()?"chatViewModeMobile":"chatViewMode"}function Ds(){return hl()?"chatViewMode":"chatViewModeMobile"}function sm(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 Te(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function kn(t,e=null){return mt({themeId:t.themeId,sessionOwnerFilter:t.ownerFilter,layoutAdjustments:{paneAdjust:t.paneAdjust,sessionPaneAdjust:t.sessionPaneAdjust,portalSessionColumnAdjust:t.portalSessionColumnAdjust,activityPaneAdjust:t.activityPaneAdjust},pinnedSessionIds:t.pinnedIds,sessionOrder:t.manualOrder,collapsedSessionIds:t.collapsedSessionIds,activeSessionId:t.activeSessionId,[Bs()]:t.chatViewMode,...ts(e)?{[Ds()]:e}:{}})}function ao(t,e=null){return mt({themeId:t?.ui?.themeId,sessionOwnerFilter:Fs(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,sessionOrder:t?.sessions?.manualOrder,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,[Bs()]:t?.ui?.chatViewMode,...ts(e)?{[Ds()]:e}:{}})}function nm(t,e){const s=mt(t),n=mt(e);return mt({themeId:Te(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:Te(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:Te(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:Te(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,sessionOrder:Te(s,"sessionOrder")?s.sessionOrder:n.sessionOrder,...Te(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...Te(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...Te(s,Bs())?{chatViewMode:s[Bs()]}:{}})}async function im(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:mt(e)})}function Ti(t){return qh(t)?ze:ze.filter(e=>e!=="files")}function Ge(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 Vn(t,e,s){return Math.max(e,Math.min(s,t))}function qn(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-dl-pl*2),n=s*Ci,i=Math.max(0,s-Oh);return{minAdjust:-n,maxAdjust:i-n}}function rm(t,e){const s=qn(t),n=Math.max(0,Number(t)||0),r=Math.max(0,n-dl-pl*2)*Ci;return Vn(r+(Number(e)||0),0,r+s.maxAdjust)}function om(t){return t<=Lh?"hidden":t<=$h?"compact":"wrap"}function ml(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:_t(t?.ui?.prompt||"")}function zs(t){return Jt({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,ml(t),t.ui.layout?.sessionPaneAdjust??0)}function am(t,e){return Math.max(20,t-4)}function Ce(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 Fo(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 me(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function gl(t=[]){return t.map(e=>String(e?.text||"")).join("")}function lo(t){return Array.isArray(t)?gl(t):String(t||"")}function co(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 lm(t){const e=De(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 uo(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 cm(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/cl)),height:Math.max(18,Math.floor(s/ul))}}function um(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function dm(t){return um(t)<=fl}function pm(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 fm(t,e,s,n,i,r,{stickyBottom:o=!1}={}){const l=a.useMemo(()=>Ce(e),[e]),c=a.useRef(null),u=a.useRef({scrollMode:n,scrollOffset:s}),d=a.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),p=a.useRef({width:null,height:null}),[f,h]=a.useState(0);a.useLayoutEffect(()=>{const b=t.current;if(!b||typeof ResizeObserver>"u")return;p.current={width:b.clientWidth,height:b.clientHeight};const x=new ResizeObserver(()=>{const k={width:b.clientWidth,height:b.clientHeight},P=p.current;k.width===P.width&&k.height===P.height||(p.current=k,h(N=>N+1))});return x.observe(b),()=>x.disconnect()},[t]),a.useLayoutEffect(()=>{const b=t.current;if(!b)return;const x=u.current,k=d.current,P=typeof performance<"u"?performance.now():Date.now(),N=k.touching||P-(k.lastUserScrollAt||0)<Bh,B=k.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-k.lastDispatchedOffset)<2;if(N&&n===x?.scrollMode&&(s===x?.scrollOffset||B)){u.current={scrollMode:n,scrollOffset:s};return}const $=o&&n==="top"&&x?.scrollMode==="top"&&x?.scrollOffset===s,_=pm(b,s,n,$);if(Math.abs(b.scrollTop-_)>qt){const L={target:_};c.current=L,b.scrollTop=_,window.requestAnimationFrame(()=>{c.current===L&&(c.current=null)})}u.current={scrollMode:n,scrollOffset:s}},[l,t,n,s,o,f]);const g=mm(b=>{r.dispatch({type:"ui/scroll",pane:i,offset:b})}),m=a.useCallback(()=>{const b=t.current;if(!b||!i)return;const x=c.current;if(x){if(Math.abs(b.scrollTop-x.target)<=qt)return;c.current=null}d.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const k=Math.max(0,b.scrollHeight-b.clientHeight);if(k<=0)return;if(o&&typeof r.updatePaneScrollFromViewport=="function"){const N=Math.max(0,b.scrollTop)/et;d.current.lastDispatchedOffset=N,r.updatePaneScrollFromViewport(i,N,{atBottom:dm(b)});return}const P=n==="bottom"?Math.max(0,k-b.scrollTop):Math.max(0,b.scrollTop);d.current.lastDispatchedOffset=P/et,g(P/et),i==="chat"&&n==="bottom"&&b.scrollTop<=qt&&r.armChatTopHistoryLoad?.()},[r,g,i,t,n,o]),y=a.useCallback(b=>{const x=t.current;if(!x||i!=="chat"||n!=="bottom"||b.deltaY>=0||x.scrollTop>qt)return;const k=Math.max(0,x.scrollHeight-x.clientHeight);r.handleChatTopHistoryScrollIntent?.(k/et)},[r,i,t,n]),S=a.useRef({startY:null,fired:!1}),E=a.useCallback(b=>{d.current.touching=!0,!(i!=="chat"||n!=="bottom")&&(S.current={startY:b.touches?.[0]?.clientY??null,fired:!1})},[i,n]),I=a.useCallback(()=>{d.current.touching=!1,d.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),w=a.useCallback(b=>{const x=t.current,k=S.current;if(!x||i!=="chat"||n!=="bottom"||k.fired||k.startY==null||x.scrollTop>qt)return;const P=b.touches?.[0]?.clientY;if(P==null||P-k.startY<Fh)return;k.fired=!0;const N=Math.max(0,x.scrollHeight-x.clientHeight);r.handleChatTopHistoryScrollIntent?.(N/et+1,{force:!0})},[r,i,t,n]);return{normalizedLines:l,onScroll:m,onWheel:y,onTouchStart:E,onTouchMove:w,onTouchEnd:I}}function Me({runs:t,theme:e}){return a.createElement(a.Fragment,null,(t||[]).map((s,n)=>{const i={color:me(e,s.color),backgroundColor:me(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=Il(r);return l?a.createElement(El,{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 hm({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:me(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(Ys,{content:s,theme:e})):null)}function mm(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(hm,{line:e,theme:s}):e.kind==="runs"?a.createElement("div",{className:i},a.createElement(Me,{runs:e.runs,theme:s})):a.createElement("div",{className:i,style:{color:me(s,e.color),backgroundColor:me(s,e.backgroundColor),fontWeight:e.bold?700:400,textDecoration:e.underline?"underline":"none"}},e.text||" "):a.createElement("div",{className:i}," ")});function Le(t){return t?t.kind==="runs"?gl(t.runs):String(t.text||""):""}function yl(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 gm={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"},ym=new Set(["diff","patch","udiff"]),Sm=/\.(patch|diff)$/i,Sl=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,bl=/\.(png|jpe?g|gif|webp|avif|bmp|svg|ico)$/i,bm={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 wm(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 Im=/\.(csv|tsv)$/i;function xm(t,e){return Im.test(String(t||""))?!0:/^text\/(csv|tab-separated-values)$/i.test(String(e||"").trim())}const An=2e3;function Em(t){const e=String(t??"");return/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function vm({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 w=!1;return n(null),al(()=>import("./papaparse.min-DLUoV5k5.js").then(b=>b.p),[]).then(b=>{if(w)return;const x=b.default||b,k=/\.tsv$/i.test(String(e||""))?" ":"",P=x.parse(String(t||"").trim(),{delimiter:k,skipEmptyLines:"greedy"});n({rows:P.data||[],errors:P.errors||[]})}).catch(()=>{w||n({rows:null,errors:[{message:"parser unavailable"}]})}),()=>{w=!0}},[t,e]),a.useEffect(()=>{const w=()=>{o.current=null};return window.addEventListener("mouseup",w),()=>window.removeEventListener("mouseup",w)},[]);const l=a.useCallback((w,b)=>{if(!w||!b)return;const x=window.getSelection();if(!x)return;const k=!!(w.compareDocumentPosition(b)&Node.DOCUMENT_POSITION_PRECEDING),P=document.createRange();P.setStartBefore(k?b:w),P.setEndAfter(k?w:b),x.removeAllRanges(),x.addRange(P)},[]),c=w=>w.target?.closest?w.target.closest("td,th"):null,u=a.useCallback(w=>{if(w.button!==0)return;const b=c(w);b&&(w.preventDefault(),i.current?.focus(),o.current=b,l(b,b))},[l]),d=a.useCallback(w=>{if(!o.current||!(w.buttons&1))return;const b=c(w);b&&l(o.current,b)},[l]),p=a.useCallback(w=>{if(!(w.metaKey||w.ctrlKey)||w.altKey||w.key!=="a"&&w.key!=="A")return;const b=r.current,x=window.getSelection();if(!b||!x)return;w.preventDefault(),w.stopPropagation();const k=document.createRange();k.selectNodeContents(b),x.removeAllRanges(),x.addRange(k)},[]),f=a.useCallback(w=>{const b=r.current,x=window.getSelection();if(!b||!x||x.rangeCount===0)return;const k=x.getRangeAt(0),P=new Map;for(const N of b.querySelectorAll("th,td")){if(!k.intersectsNode(N))continue;const B=N.parentElement;P.has(B)||P.set(B,[]),P.get(B).push(Em(N.textContent))}P.size!==0&&(w.clipboardData.setData("text/plain",Array.from(P.values(),N=>N.join(" ")).join(`
|
|
91
|
-
`)),w.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,...g]=s.rows,m=g.reduce((w,b)=>Math.max(w,b.length),h.length),y=Array.from({length:m},(w,b)=>h[b]??""),S=g.length>An,E=S?g.slice(0,An):g,I=[];return S&&I.push(`showing first ${An} of ${g.length} rows`),s.errors.length&&I.push(`${s.errors.length} parse warning${s.errors.length===1?"":"s"}`),a.createElement("div",{className:"ps-csv-wrap",ref:i,tabIndex:0,onMouseDown:u,onMouseMove:d,onKeyDown:p,onCopy:f},a.createElement("table",{className:"ps-csv-table",ref:r},a.createElement("thead",null,a.createElement("tr",null,y.map((w,b)=>a.createElement("th",{key:`h${b}`},String(w??""))))),a.createElement("tbody",null,E.map((w,b)=>a.createElement("tr",{key:`r${b}`},y.map((x,k)=>a.createElement("td",{key:`c${k}`},String(w[k]??""))))))),I.length?a.createElement("div",{className:"ps-csv-status"},I.join(" · ")):null)}function wl(t){const e=/\.([A-Za-z0-9]+)$/.exec(String(t||""));return e&&bm[e[1].toLowerCase()]||null}function Mi(t,e){return Sm.test(String(t||""))?!0:/^text\/x-(patch|diff)$/i.test(String(e||"").trim())}function Il(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 xl=a.createContext(null);function El({label:t,artifactRef:e,style:s}){const n=a.useContext(xl),i=Mi(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 vl(t){return ym.has(String(t||"").trim().toLowerCase())}const km=/^(?: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 Am(t){return km.test(t)?"meta":t.startsWith("@@")?"hunk":t.startsWith("+")?"add":t.startsWith("-")?"del":"context"}const Cm={add:"green",del:"red",hunk:"cyan",meta:"gray"};function Ni(t,e){return String(t||"").replace(/\n$/,"").split(`
|
|
92
|
-
`).map((n,i)=>{const r=Am(n),o=Cm[r],l=r==="add"||r==="del"||r==="context"&&n.startsWith(" "),c=l?n.slice(0,1):"",u=l?n.slice(1):n;return a.createElement("span",{key:`d:${i}`,className:`ps-diff-line is-${r}`,style:o?{color:me(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"},u))})}function kl(t){return String(t||"").trim().toLowerCase()==="mermaid"}const po={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 Tm(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},u={type:"string",re:/"""[\s\S]*?"""|'''[\s\S]*?'''/y};switch(t){case"python":return[e,u,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 Mm={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},Nm=2e4,ut=new Map,Pm=120;function _m(t,e){const s=`${e||""}\0${t}`,n=ut.get(s);if(n)return ut.delete(s),ut.set(s,n),n;const i=Rm(t,e);return ut.set(s,i),ut.size>Pm&&ut.delete(ut.keys().next().value),i}function Rm(t,e){const s=gm[String(e||"").trim().toLowerCase()]||"default",n=po[s]||po.js,i=Tm(s),r=[];let o=0,l=0;const c=u=>{u>l&&r.push({type:"plain",text:t.slice(l,u)})};for(;o<t.length;){let u=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){u={type:p.type,text:f[0]};break}}if(!u){o+=1;continue}let d=u.type;if(d==="identifier")if(n.has(u.text))d="keyword";else{const p=t.slice(o+u.text.length);d=/^\s*\(/.test(p)?"fn":"plain"}if(d==="plain"){o+=u.text.length;continue}c(o),r.push({type:d,text:u.text}),o+=u.text.length,l=o}return c(t.length),r}function ss(t,e,s){const n=String(t||"");if(!n||n.length>Nm)return n;let i;try{i=_m(n,e)}catch{return n}return i.map((r,o)=>{const l=Mm[r.type];return l?a.createElement("span",{key:`t:${o}`,className:`ps-code-token is-${r.type}`,style:{color:me(s,l)||void 0}},r.text):a.createElement(a.Fragment,{key:`t:${o}`},r.text)})}let ms=null;function Om(){return ms||(ms=al(()=>import("./mermaid.core-CyzD7dTc.js").then(t=>t.bp),[]).then(t=>t.default||t).catch(t=>{throw ms=null,t})),ms}function $m(t,e){return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"default":"dark",fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"}),t}let fo=0,ho=Promise.resolve();function Lm(t){const e=ho.then(t,t);return ho=e.then(()=>{},()=>{}),e}function Al({code:t,theme:e,fallback:s}){const[n,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState(""),u=a.useMemo(()=>cu(e),[e]);return a.useEffect(()=>{let d=!0;const p=String(t||"").trim();if(p)return o(!1),Om().then(f=>Lm(async()=>{if(!d)return;$m(f,u),fo+=1;const h=`ps-mermaid-${fo}`;await f.parse(p);const{svg:g}=await f.render(h,p);d&&i(g)})).catch(f=>{d&&(i(null),o(!0),c(String(f?.message||f)))}),()=>{d=!1}},[t,u]),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 ei(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=Il(n.href);return o?a.createElement(El,{key:r,label:n.text,artifactRef:o,style:{color:me(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:me(e,"cyan")}},n.text):a.createElement("span",{key:r,style:{color:me(e,"cyan")}},n.text)}return a.createElement(a.Fragment,{key:r},n.text)})}function zn(t=""){return String(t||"").replace(/\s+/g," ").trim()}const Fm=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],Bm=24,Dm=32,Hm=6,mo=30,Gm=56,Cn=.4,jm=1.4,Um=2;function Cl(t=[]){const e=Math.max(0,...t.map(g=>g.length));if(e<=0)return null;const s=t[0]||[],n=Math.max(1,t.length-1),i=Array.from({length:e},()=>({max:0,spaceCells:0}));for(let g=0;g<t.length;g+=1){const m=t[g];for(let y=0;y<e;y+=1){const S=zn(m[y]||"");S.length>i[y].max&&(i[y].max=S.length),g>0&&/\s/.test(S)&&(i[y].spaceCells+=1)}}let r=-1,o=0;for(let g=0;g<e;g+=1){const m=i[g];if(m.max<Bm||m.spaceCells/n<.4)continue;const S=zn(s[g]||"").toLowerCase(),E=Fm.some(w=>S.includes(w))?60:0,I=m.max+E;I>o&&(o=I,r=g)}if(r<0)return null;const l=i.map((g,m)=>m===r?0:Math.max(Hm,Math.min(g.max+2,Dm))),c=l.reduce((g,m)=>g+m,0),u=i[r],d=Math.max(mo,Math.min(u.max*.45,Gm,Math.max(mo,c*jm))),p=l.map((g,m)=>m===r?d:g),f=p.reduce((g,m)=>g+m,0);if(f>0&&p[r]/f<Cn){const g=f-p[r];p[r]=g*(Cn/(1-Cn))}const h=p.reduce((g,m)=>g+m,0);return h>0?{widths:p.map(g=>`${(g/h*100).toFixed(2)}%`),flexIndex:r,minWidth:`${Math.ceil(h+Um)}ch`}:null}function Tl(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(r=>zn(r?.[n]||"")).filter(Boolean).join(" / ")||null)}function go(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 yo(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Wm(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=yo(r);i+=2;const f=[];for(;i<s.length&&s[i].includes("|")&&s[i].trim();)f.push(yo(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 u=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(r);if(u){const p=/\d+\./.test(u[2]),f=[];for(;i<s.length;){const h=s[i],g=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(h);if(!g||/\d+\./.test(g[2])!==p)break;const m=[g[3].trim()];for(i+=1;i<s.length&&s[i].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[i])&&!go(s[i],s[i+1]||"");)m.push(s[i].trim()),i+=1;if(f.push(m.join(" ")),!s[i]?.trim())break}n.push({type:"list",ordered:p,items:f});continue}const d=[r.trim()];for(i+=1;i<s.length&&s[i].trim()&&!go(s[i],s[i+1]||"");)d.push(s[i].trim()),i+=1;n.push({type:"paragraph",text:d.join(" ")})}return n}function Ys({content:t,theme:e}){const s=a.useMemo(()=>Wm(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=vl(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?Ni(n.content,e):ss(n.content,n.language,e))));return kl(n.language)?a.createElement(Al,{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(g=>g.length)),o=r>0&&r<=6,l=o?Cl([n.header,...n.rows]):null,c=!!l,u=l?l.flexIndex:-1,d=g=>g===u?"is-flex-column":null,p=Tl([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((g,m)=>a.createElement("col",{key:`col:${m}`,className:d(m)||void 0,style:{width:g}}))):null,a.createElement("thead",null,a.createElement("tr",null,n.header.map((g,m)=>a.createElement("th",{key:`head:${m}`,className:d(m)||void 0},Qe(g,e,`table:${i}:head:${m}`))))),a.createElement("tbody",null,n.rows.map((g,m)=>a.createElement("tr",{key:`row:${m}`},g.map((y,S)=>a.createElement("td",{key:`cell:${m}:${S}`,className:d(S)||void 0,"data-label":p[S]||void 0},a.createElement("span",{className:"ps-table-cell-value"},Qe(y,e,`table:${i}:${m}:${S}`)))))))))}return a.createElement("p",{key:`block:${i}`,className:"ps-md-paragraph"},Qe(n.text,e,`para:${i}`))}))}function Tn({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:r,theme:o,className:l="",focusRegion:c=null,children:u}){const d=a.useRef(null),p=yl(d,i,r,t),f=a.useCallback(()=>{const h=Pi(r,c);h&&t?.setFocus&&t.setFocus(h)},[t,r,c]);return a.createElement(yt,{title:e,color:s,focused:n,theme:o},a.createElement("div",{ref:d,className:`ps-scroll-panel is-preview ${l}`.trim(),onScroll:p,onMouseDown:f},u))}function Km({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:r,theme:o,content:l,focusRegion:c=null}){const u=a.useCallback(()=>{const f=Pi(r,c);f&&t?.setFocus&&t.setFocus(f)},[t,r,c]),d=a.useRef(null),p=yl(d,i,r,t);return a.createElement(yt,{title:e,color:s,focused:n,theme:o},a.createElement("div",{ref:d,className:"ps-scroll-panel ps-markdown-scroll",onScroll:p,onMouseDown:u},a.createElement(Ys,{content:l,theme:o})))}function Vm(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 So({title:t,color:e,focused:s,theme:n,filename:i,contentType:r,sizeBytes:o,source:l,uploadedAt:c,controller:u=null,sessionId:d=null}){const p=[];r&&p.push(r),o!=null&&p.push(Vm(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=Sl.test(String(r||""))||bl.test(String(i||"")),[g,m]=a.useState(null);return a.useEffect(()=>{if(m(null),!h||!u||!d||!i)return;let y=!1;return Pl(u,d,i).then(S=>{y||m(S)}).catch(()=>{y||m("error")}),()=>{y=!0}},[h,u,d,i]),a.createElement(yt,{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&&g&&g!=="error"?a.createElement("img",{className:"ps-binary-preview-image",src:g,alt:i||"artifact image",onClick:()=>{try{window.open(g,"_blank","noopener")}catch{}}}):a.createElement("p",{className:"ps-binary-preview-copy"},h?g==="error"?"Could not load the image preview. Use Download to save the file.":"Loading image preview…":"Preview is intentionally disabled for non-text artifacts in the browser workspace. Use Download to save the file and open it in the default app.")))}function bs(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function Mn(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function qm(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function Zt(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function zm(t){const e=String(Le(t)||"").trim();return bs(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function Ym(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=Le(t);return Zt(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function Xm(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 bo(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?Xm(t.runs.slice(1,-1)):[{text:Le(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function Qm(t){const e=String(t||"").trim();return Zt(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function Jm(t="",e=""){const s=String(t||"").trimEnd(),n=String(e||"").trimStart();if(!s||!n)return!1;const i=s.slice(-1),r=n[0];return!!(/^[,.;:!?%)\]}>]/u.test(r)||/^[._/\\-]/u.test(r)||/[([{<._/\\-]$/u.test(i)||/\.[A-Za-z0-9]{0,4}$/u.test(s)&&/^[A-Za-z0-9]/u.test(r))}function Zm(t=[]){const e=(Array.isArray(t)?t:[t]).map(s=>String(s||"").trim()).filter(Boolean);return e.length===0?"":e.slice(1).reduce((s,n)=>Jm(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function wo(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>Zm(t.map(i=>String(i[n]||"").trim()).filter(Boolean)))}function Ml(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&&Le(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:Ml(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=Le(n);if(bs(i)&&i.includes("┬")){const r=[],o=[];let l=[],c=!0;for(s+=1;s<t.length;){const u=t[s],d=Le(u);if(Mn(d)){if(l.length>0){const p=wo(l);p.length>0&&(c?r.push(p):o.push(p))}s+=1;break}if(qm(d)){if(l.length>0){const p=wo(l);p.length>0&&(c?r.push(p):o.push(p))}l=[],c=!1,s+=1;continue}if(Zt(d)){const p=Qm(d);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&&bs(i)){const r=zm(n),o=[];for(s+=1;s<t.length;){const l=t[s],c=Le(l);if(Mn(c)){s+=1;break}Zt(c)?o.push(Ym(l)):o.push(Le(l)),s+=1}s<t.length&&Le(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&&bs(i)){const r=bo(n),o=n.runs[0]?.color||"gray",l=[];for(s+=1;s<t.length;){const c=t[s],u=Le(c);if(Mn(u)){s+=1;break}Zt(u)?l.push(bo(c)):l.push(c?.kind==="runs"?c.runs:[{text:Le(c),color:c?.color||null}]),s+=1}s<t.length&&Le(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 Nl({lines:t,theme:e,controller:s=null}){const n=a.useMemo(()=>Ml(t),[t]);return a.createElement(Rl,{blocks:n,theme:e,controller:s})}const eg=a.memo(function({block:e,theme:s,controller:n,continued:i}){const r=e.header||{},o=e.role==="user"?" is-user":" is-assistant",l=e.pendingPhase?` is-${e.pendingPhase}`:"",c=String(e.text||""),u=e.role==="user"&&r.fromOtherPerson;return a.createElement("article",{className:`ps-rich-msg${o}${l}${i?" is-continued":""}`},a.createElement("header",{className:"ps-rich-msg-head"},u?a.createElement("span",{className:"ps-rich-msg-label",style:{color:me(s,r.roleColor)||void 0}},r.roleLabel):null,a.createElement("span",{className:"ps-rich-msg-meta"},r.glyph?a.createElement("span",{className:"ps-rich-msg-glyph",title:e.pendingPhase||void 0,style:{color:me(s,r.glyphColor)||void 0}},r.glyph):null,r.time?a.createElement("span",{className:"ps-rich-msg-time"},r.time):null)),c.trim()?a.createElement("div",{className:"ps-rich-msg-body"},a.createElement(Ys,{content:c,theme:s})):null,e.attachments?a.createElement(_l,{controller:n,sessionId:e.attachments.sessionId,attachments:e.attachments.attachments}):null)}),tg=a.memo(function({block:e,theme:s,controller:n}){const i=a.useMemo(()=>Ce(e.lines||[]),[e.lines]);return a.createElement("div",{className:`ps-rich-lineblock is-${e.variant||"event"}`},a.createElement(Nl,{lines:i,theme:s,controller:n}))});function sg({blocks:t,theme:e,controller:s=null}){return a.createElement("div",{className:"ps-rich-chat"},(t||[]).map((n,i)=>{if(n.kind==="message"){const r=t[i-1],o=n.header||{},l=n.role==="user"&&o.fromOtherPerson,c=!!(r&&r.kind==="message"&&r.role===n.role&&!(r.header&&r.header.fromOtherPerson)&&!l);return a.createElement(eg,{key:n.id!=null?`msg:${n.id}`:`msg:${i}`,block:n,theme:e,controller:s,continued:c})}return a.createElement(tg,{key:`lines:${i}`,block:n,theme:e,controller:s})}))}const Ze=new Map,ng=60;function Pl(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>ng;){const[l,c]=Ze.entries().next().value;Ze.delete(l),Promise.resolve(c).then(u=>URL.revokeObjectURL(u)).catch(()=>{})}return o}function _l({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&&Pl(t,e,l).then(c=>{r||i(u=>u[l]===c?u:{...u,[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 Rl({blocks:t,theme:e,controller:s=null}){return a.createElement(a.Fragment,null,(t||[]).map((n,i)=>{if(n.type==="imageAttachments")return a.createElement(_l,{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=vl(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?Ni(n.content||"",e):ss(n.content||"",n.language,e))));return kl(n.language)?a.createElement(Al,{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":me(e,n.borderColor)||"var(--ps-border)"}},a.createElement("header",{className:"ps-chat-card-header"},a.createElement(Me,{runs:n.headerRuns,theme:e})),a.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?a.createElement(Rl,{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(Me,{runs:r,theme:e})))));if(n.type==="table"){const r=n.headerRows||[],o=n.bodyRows||[],l=Math.max(1,...r.map(y=>y.length),...o.map(y=>y.length)),c=l<=6,u=c?Cl([...r,...o]):null,d=!!u,p=u?u.flexIndex:-1,f=y=>y===p?"is-flex-column":null,h=Tl(r,l),g=`ps-chat-table${c?" is-fit-width":""}${d?" has-flex-column":""}`,m=`ps-chat-table-wrap${c?" is-fit-width":""}${d?" has-flex-column":""}`;return a.createElement("div",{key:`table:${i}`,className:m},a.createElement("table",{className:g,style:u?.minWidth?{"--ps-table-min-width":u.minWidth}:void 0},u?a.createElement("colgroup",null,u.widths.map((y,S)=>a.createElement("col",{key:`col:${S}`,className:f(S)||void 0,style:{width:y}}))):null,r.length>0?a.createElement("thead",null,r.map((y,S)=>a.createElement("tr",{key:`thead:${S}`},Array.from({length:l},(E,I)=>a.createElement("th",{key:`th:${S}:${I}`,className:f(I)||void 0},Qe(y[I]||"",e,`chat-table:${i}:head:${S}:${I}`)))))):null,a.createElement("tbody",null,o.map((y,S)=>a.createElement("tr",{key:`tbody:${S}`},Array.from({length:l},(E,I)=>a.createElement("td",{key:`td:${S}:${I}`,className:f(I)||void 0,"data-label":h[I]||void 0},a.createElement("span",{className:"ps-table-cell-value"},Qe(y[I]||"",e,`chat-table:${i}:${S}:${I}`)))))))))}return a.createElement(Ne,{key:`line:${i}`,line:n.line,theme:e})}))}function ig(t){return Array.isArray(t)?t.map(e=>{const s=String(e?.text??""),n=/^(\s*)\[(.+)\](\s*)$/.exec(s);return n?{...e,text:`${n[1]}${n[2]}${n[3]}`}:e}):t}function yt({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:i=null,children:r,theme:o,className:l=""}){const c=me(o,s),u=!!((Array.isArray(t)?t.length>0:String(t??"").trim())||e||i);return a.createElement("section",{className:`ps-panel${n?" is-focused":""}${u?"":" is-chromeless"}${l?` ${l}`:""}`,style:{"--ps-panel-accent":c||"var(--ps-border)"}},u?a.createElement("header",{className:"ps-panel-header"},a.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?a.createElement(Me,{runs:t,theme:o}):lo(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(Me,{runs:e,theme:o}):lo(e)):null,i?a.createElement("div",{className:"ps-panel-actions"},i):null):null):null,a.createElement("div",{className:"ps-panel-body"},r))}function rg({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(u=>u?.nodeSelect)?.nodeSelect||null,l=r.some(u=>u?.nodeSelected),c=a.createElement(Me,{runs:r,theme:e});return o?a.createElement("button",{key:`line:${i}`,type:"button",className:`ps-nodemap__row${l?" is-selected":""}`,onPointerDown:u=>{u.preventDefault(),u.stopPropagation(),s.selectNodeMapNode(o)}},c):a.createElement("div",{key:`line:${i}`,className:"ps-nodemap__line"},c)}))}function og({lines:t,theme:e,completionByTurn:s}){const[n,i]=a.useState(()=>new Set),r=a.useCallback(d=>{i(p=>{const f=new Set(p);return f.has(d)?f.delete(d):f.add(d),f})},[]),o=d=>Number(d||0).toLocaleString("en-US"),l=d=>{const p=Number(d||0);if(!Number.isFinite(p))return"?K";const f=p/1e3,h=Math.abs(f)>=10?1:2;return`${f.toFixed(h)}K`},c=d=>{const p=Number(d||0);return Number.isFinite(p)?`${(p/1e3).toFixed(1)}s`:"?s"},u=d=>{const p=String(d||"").trim();if(!p)return"unknown";const f=p.split(":").filter(Boolean),h=f[f.length-1]||"",g=f.length>1&&Hh.has(h.toLowerCase())?f.length-2:f.length-1;return f[Math.max(0,g)]||f[0]||"unknown"};return a.createElement(a.Fragment,null,t.map((d,p)=>{const f=d?.kind==="runs"&&Array.isArray(d.runs)?d.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:d,theme:e});const g=h.data||{},m=String(h.seq??`${g.turnIndex??f}:${h.createdAt??p}`),y=n.has(m),S=g.reasoningEffort?`${g.model||"(unknown)"}:${g.reasoningEffort}`:g.model||"(unknown)",E=u(g.model),I=g.durationMs!=null?c(g.durationMs):"duration n/a",w=g.durationMs!=null?`${o(g.durationMs)} ms`:"duration n/a",b=`${l(g.tokensInput)} / ${l(g.tokensOutput)}`,x=[["model",S],["started",g.startedAt?new Date(g.startedAt).toLocaleString():null],["ended",g.endedAt?new Date(g.endedAt).toLocaleString():null],["duration",w],["tokens",`${o(g.tokensInput)} in / ${o(g.tokensOutput)} out`],["cache",`${o(g.tokensCacheRead)} read / ${o(g.tokensCacheWrite)} write`],["tools",`${o(g.toolCalls)} calls / ${o(g.toolErrors)} errors`],["names",Array.isArray(g.toolNames)&&g.toolNames.length?g.toolNames.join(", "):null],["worker",g.workerNodeId||null],["result",g.resultType||null],["error",g.errorMessage||null]].filter(([,k])=>k!=null&&k!=="");return a.createElement(a.Fragment,{key:`seq:${p}`},a.createElement(Ne,{line:d,theme:e}),a.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>r(m)},a.createElement("span",{className:"ps-sequence-turn-caret"},y?"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"},E),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"},b),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"},I),a.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),y?a.createElement("div",{className:"ps-sequence-turn-details"},x.map(([k,P])=>a.createElement("div",{key:k},a.createElement("span",{className:"ps-sequence-turn-detail-label"},`${k}: `),a.createElement("span",null,String(P))))):null)}))}const ag={chat:"chat",activity:"activity",inspector:"inspector",filePreview:"inspector"};function Pi(t,e=null){return e||ag[String(t||"")]||null}function Xs({title:t,titleRight:e=null,color:s,focused:n,actions:i,lines:r,stickyLines:o=[],bottomStickyLines:l=[],scrollOffset:c=0,scrollMode:u="top",paneKey:d,controller:p,className:f="",panelClassName:h="",topContent:g=null,bottomContent:m=null,structuredBlocks:y=!1,stickyBottom:S=!1,renderBody:E=null,focusRegion:I=null}){const w=ee(p,M=>M.ui.themeId),b=De(w),x=a.useRef(null),k=a.useRef(null),P=a.useRef(!1),{normalizedLines:N,onScroll:B,onWheel:$,onTouchStart:_,onTouchMove:L,onTouchEnd:j}=fm(x,r,c,u,d,p,{stickyBottom:S}),q=a.useMemo(()=>Ce(o),[o]),se=a.useMemo(()=>Ce(l),[l]),ne=f.includes("is-preserve")&&h.includes("has-preserved-sticky"),Re=a.useCallback(()=>{const M=Pi(d,I);M&&p?.setFocus&&p.setFocus(M)},[p,d,I]),re=a.useCallback((M,A)=>{!M||!A||Math.abs((A.scrollLeft||0)-(M.scrollLeft||0))<=1||(P.current=!0,A.scrollLeft=M.scrollLeft,window.requestAnimationFrame(()=>{P.current=!1}))},[]),[be,v]=a.useState({up:!1,down:!1}),O=a.useCallback(M=>{if(!M)return;const A=M.scrollHeight-M.scrollTop-M.clientHeight>4,F=M.scrollTop>4;v(X=>X.up===A&&X.down===F?X:{up:A,down:F})},[]),D=a.useCallback(M=>{B(),O(M.currentTarget),!(!ne||P.current)&&re(M.currentTarget,k.current)},[B,ne,re,O]);a.useEffect(()=>{O(x.current)});const U=a.useCallback(M=>{!ne||P.current||re(M.currentTarget,x.current)},[ne,re]);return a.createElement(yt,{title:t,titleRight:e,color:s,focused:n,actions:i,theme:b,className:h},g,q.length>0?a.createElement("div",{ref:k,className:`ps-panel-sticky${ne?" is-scroll-sync":""}`,onScroll:U},q.map((M,A)=>a.createElement(Ne,{key:`sticky:${A}`,line:M,theme:b}))):null,a.createElement("div",{ref:x,className:`ps-scroll-panel ${f}${be.down?" is-scrolled-down":""}${be.up?" is-scrolled-up":""}`.trim(),"data-session-scroll":I==="sessions"?"1":void 0,onScroll:D,onMouseDown:Re,onTouchStart:_,onWheel:$,onTouchMove:L,onTouchEnd:j,onTouchCancel:j},typeof E=="function"?E(N,b):y?a.createElement(Nl,{lines:N,theme:b,controller:p}):N.map((M,A)=>a.createElement(Ne,{key:`line:${A}`,line:M,theme:b}))),se.length>0?a.createElement("div",{className:"ps-panel-bottom-sticky"},se.map((M,A)=>a.createElement(Ne,{key:`bottom-sticky:${A}`,line:M,theme:b}))):null,m)}const lg={group:"🗂",system:"⚙",service:"⚗"},Io="—";function cg({session:t,childCount:e=0}){const s=(p,f,h="")=>{const g=f==null||f===""?Io:String(f),m=g===Io;return a.createElement("div",{className:`ps-session-detail-field${h?` ${h}`:""}${m?" is-none":""}`,key:p},a.createElement("span",{className:"ps-session-detail-label"},p),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?`${J(n.currentTokens)} / ${J(n.tokenLimit)} · ${r}%`:null;let l=null;t&&!t.isGroup&&(l="off",t.cronActive===!0&&(l=t.cronKind==="wall-clock"?`next ${Ps(t.cronNextFireAt)}`:typeof t.cronInterval=="number"?`every ${At(t.cronInterval)}`:"on"));const c=t?.model?t.reasoningEffort&&!String(t.model).includes(String(t.reasoningEffort))?`${t.model}:${t.reasoningEffort}`:t.model:null,u=t?t.visibility==="shared_write"?"shared · write":t.visibility==="shared_read"?"shared · read":"private":null,d=t?.isGroup?t.memberCount==null?null:String(t.memberCount):e>0?String(e):null;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("Status",t?.status),s("Children",d),s("Access",u))}function ug(){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 Ol=13,$l=11,Ll=1.5,dg=7;function pg(t){return Ol+(t-1)*$l+Ll/2-dg/2}const fg=a.memo(function({row:e,theme:s,rich:n,structuredRows:i,mobile:r,onRowClick:o,setRef:l,drag:c}){const u=Math.max(0,e.depth),d=a.useMemo(()=>{if(u<1)return;const I=Array.from({length:u},(w,b)=>b);return{backgroundImage:I.map(()=>"linear-gradient(var(--ps-rail), var(--ps-rail))").join(", "),backgroundSize:I.map(()=>`${Ll}px 100%`).join(", "),backgroundPosition:I.map(w=>`${Ol+w*$l}px 0`).join(", "),backgroundRepeat:"no-repeat"}},[u]),p=a.useCallback(I=>l(e.sessionId,I),[l,e.sessionId]),f=a.useCallback(I=>o(I,e),[o,e]),h=e.groupId||null,g=!!(c?.dragging&&c.overGroupId&&h===c.overGroupId),m=g&&!!e.isGroup,y=!!(c?.dragging&&c.insertBeforeId===e.sessionId),S=!!(c?.dragging&&c.insertAfterId&&c.insertAfterId===e.sessionId),E=a.useCallback(I=>{if(c?.onPointerDown&&I.button===0){if(I.currentTarget?.setPointerCapture&&I.pointerId!=null)try{I.currentTarget.setPointerCapture(I.pointerId)}catch{}c.onPointerDown(I,e)}},[c,e]);return a.createElement("button",{type:"button",ref:p,className:`ps-list-button ps-session-list-button${e.active?" is-selected":""}${e.selected?" is-multiselected":""}${e.pinned?" is-pinned":""}${g?" is-drop-zone":""}${m?" is-drop-target":""}${y?" 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":h||void 0,"data-order-container":e.orderContainer??void 0,"data-orderable":e.orderable?"1":void 0,onPointerDown:E,onClick:f,onContextMenu:I=>{I.ctrlKey&&(I.preventDefault(),o(I,e))}},a.createElement("div",{className:n?"ps-session-row-content is-rich":"ps-line ps-session-row-content",style:{paddingInlineStart:u>0?`${pg(u)}px`:"0px"}},n?a.createElement(hg,{row:e,theme:s,showDetail:r}):a.createElement(Fl,{row:e,theme:s,structured:i,showInlineDetail:r})))});function hg({row:t,theme:e,showDetail:s=!1}){const n=t.chrome;if(!n)return a.createElement(Fl,{row:t,theme:e,structured:!0,showInlineDetail:s});const i=lg[n.kind]||null,r=me(e,n.accentColor)||void 0,o=s&&Array.isArray(t.detailRuns)?t.detailRuns:[];return a.createElement("div",{className:"ps-rich-session-row"},a.createElement("div",{className:"ps-rich-session-main"},n.selectMode?a.createElement("span",{className:`ps-rich-session-check${n.checked?" is-checked":""}`},n.checked?"✓":""):null,i?a.createElement("span",{className:"ps-rich-session-kind"},i):a.createElement("span",{className:`ps-rich-session-dot${t.depth>0?" is-node":""}`,style:t.depth>0?{borderColor:me(e,n.statusColor)||void 0}:{background:me(e,n.statusColor)||void 0},title:t.status||void 0}),n.owner?a.createElement("span",{className:`ps-rich-session-owner${n.owner.isMine?" is-mine":""}`,title:n.owner.initials},n.owner.initials):null,a.createElement("span",{className:`ps-rich-session-title${n.untitled?" is-untitled":""}`,style:n.kind==="session"?void 0:{color:r},title:n.title},n.title),n.pinned?a.createElement("span",{className:"ps-rich-session-pin",title:"Pinned"},a.createElement(Dl)):null,n.cron?a.createElement("span",{className:"ps-rich-session-cron",title:"Scheduled"},"⏱"):null,n.childBadge?a.createElement("span",{className:"ps-rich-session-count",style:{color:me(e,n.childBadge.color)||void 0}},n.childBadge.text):null,n.ctx?a.createElement("span",{className:"ps-rich-session-ctx",style:{color:me(e,n.ctx.color)||void 0}},n.ctx.text):null),o.length>0?a.createElement("div",{className:"ps-rich-session-detail"},a.createElement(Me,{runs:o,theme:e})):null)}function xo(t,e){if(!Array.isArray(t))return{statusColor:null,rest:t};let s=null;const n=[];for(const i of t)if(i?.role!=="depth"){if(i?.role==="status"){s=me(e,i.color)||null;continue}n.push(i)}return{statusColor:s,rest:n}}function Eo({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 Yn({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 vo(t){return Array.isArray(t)?t.filter(e=>!e?.ownerChip):t}function Fl({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 d=xo(vo(t.runs),e);return a.createElement(a.Fragment,null,d.statusColor?a.createElement(Eo,{color:d.statusColor,node:t.depth>0}):null,a.createElement(Yn,{badge:t.ownerBadge}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(Me,{runs:d.rest,theme:e})))}const r=xo(vo(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:[],u=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(Eo,{color:r.statusColor,node:t.depth>0}):null,a.createElement(Yn,{badge:t.ownerBadge}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(Me,{runs:r.rest,theme:e}))),l?a.createElement("div",{className:"ps-session-row-ctx"},a.createElement(Me,{runs:o,theme:e})):null),u?a.createElement("div",{className:"ps-session-row-detail"},a.createElement(Me,{runs:c,theme:e})):null)}function mg(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 ko=10,gg=1.6;function yg(t){a.useEffect(()=>{const e=t.current;if(!e)return;let s=0,n=0,i=0,r=null;const o=u=>{if(u.touches.length!==1){r="y";return}const d=u.touches[0];s=i=d.clientX,n=d.clientY,r=null},l=u=>{if(r==="y"||u.touches.length!==1)return;const d=u.touches[0],p=d.clientX-s,f=d.clientY-n;r===null&&(Math.abs(p)<ko&&Math.abs(f)<ko||(r=Math.abs(p)>Math.abs(f)*gg?"x":"y",i=d.clientX,r==="y"))||(e.scrollLeft-=d.clientX-i,i=d.clientX,u.cancelable&&u.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 _i({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1}){const i=String(s).includes("ps-mobile-session-pane"),r=a.useRef(null);yg(r);const o=i||ug(),l=ee(t,H=>H.ui.themeId),c=De(l),u=a.useRef(new Map),d=ee(t,H=>({branding:H.branding,activeSessionId:H.sessions.activeSessionId,sessionsById:H.sessions.byId,sessionsFlat:H.sessions.flat,filterQuery:H.sessions.filterQuery||"",ownerFilter:H.sessions.ownerFilter,pinnedIds:H.sessions.pinnedIds,manualOrder:H.sessions.manualOrder,selectedIds:H.sessions.selectedIds,selectMode:H.sessions.selectMode,auth:H.auth,connectionMode:H.connection?.mode||"local",modalOpen:!!H.ui.modal,focused:H.ui.focusRegion==="sessions",rich:!!De(H.ui.themeId)?.richChat,listDeselected:!!H.sessions.listDeselected}),Ge),p=a.useMemo(()=>Bt({sessions:{activeSessionId:d.activeSessionId,byId:d.sessionsById,flat:d.sessionsFlat,filterQuery:d.filterQuery,ownerFilter:d.ownerFilter,pinnedIds:d.pinnedIds,manualOrder:d.manualOrder,selectedIds:d.selectedIds,selectMode:d.selectMode,listDeselected:d.listDeselected},auth:d.auth,connection:{mode:d.connectionMode},branding:d.branding}),[d.activeSessionId,d.auth,d.branding,d.connectionMode,d.filterQuery,d.listDeselected,d.ownerFilter,d.pinnedIds,d.manualOrder,d.selectedIds,d.selectMode,d.sessionsById,d.sessionsFlat]),f=mg(p),h=d.activeSessionId&&d.sessionsById[d.activeSessionId]||null,g=d.activeSessionId&&f.find(H=>H.sessionId===d.activeSessionId)||null,[m,y]=a.useState(!1),[S,E]=a.useState(null),I=a.useRef(!1),w=["modelPicker","reasoningEffortPicker","contextTierPicker"],b=ee(t,H=>w.includes(H.ui.modal?.type));a.useEffect(()=>{!b&&I.current&&(I.current=!1,y(!0))},[b]);const x=()=>{I.current=!0,y(!1),t.openSwitchModelPicker(()=>{I.current=!1}).then(()=>{!w.includes(t.getState().ui.modal?.type)&&I.current&&(I.current=!1,y(!0))}).catch(H=>{I.current=!1,y(!0),t.dispatch({type:"ui/status",text:H?.message||String(H)||"Failed to switch model"})})},k=d.auth?.principal||null,P=d.auth?.authorization?.role,N=P==="admin"||P==="anonymous",B=!!(h?.owner&&k&&String(h.owner.provider)===String(k.provider)&&String(h.owner.subject)===String(k.subject)),$=!!(h&&!h.isSystem&&!h.isGroup&&(N||B)),_=Array.isArray(d.selectedIds)?d.selectedIds.length:0,L=_>1,j=!!(h&&!h.isSystem&&(h.isGroup||!h.parentSessionId&&!h.groupId)),q=!!(h&&Array.isArray(d.pinnedIds)&&d.pinnedIds.includes(h.sessionId)),se=!!(h?.isGroup&&Number(h.memberCount||0)===0),ne=L?Array.isArray(d.selectedIds)&&d.selectedIds.some(H=>{const G=d.sessionsById[H];return G&&!G.isSystem&&!G.isGroup}):h?.isGroup?!0:!!h,Re=_>0,re=!!(h&&!d.listDeselected&&!h.isSystem&&!h.isGroup&&!h.parentSessionId),be=Re?d.selectedIds.filter(H=>{const G=d.sessionsById[H];return G&&!G.isSystem&&!G.isGroup&&!G.parentSessionId}):re?[h.sessionId]:[],v=`ps-session-pane${d.rich?" is-rich":""}${s?` ${s}`:""}`,O=a.useRef(null);O.current={rows:f,viewState:d,controller:t};const[D,U]=a.useState({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),M=a.useRef(null),A=a.useRef(null),F=a.useCallback(()=>{A.current!=null&&(cancelAnimationFrame(A.current),A.current=null)},[]),X=a.useCallback((H,G)=>{const te=document.elementFromPoint(H,G)?.closest?.("[data-session-scroll]")||document.querySelector("[data-session-scroll]");if(!te){F();return}const Q=te.getBoundingClientRect();let ie=0;if(G<Q.top+48?ie=-14*Math.min(1,(Q.top+48-G)/48):G>Q.bottom-48&&(ie=14*Math.min(1,(G-(Q.bottom-48))/48)),M.current&&(M.current.autoScrollStep=ie),!M.current){F();return}if(A.current!=null)return;const Ie=()=>{const Ke=M.current;if(!Ke||!Ke.autoScrollStep){F();return}te.scrollTop+=Ke.autoScrollStep,A.current=requestAnimationFrame(Ie)};A.current=requestAnimationFrame(Ie)},[F]),z=a.useCallback(H=>{const G=M.current;if(M.current=null,F(),U({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),!(!H||!G?.started||G.ids.length===0)){if(G.intent==="reorder"){t.dispatch({type:"sessions/reorder",sessionId:G.ids[0],beforeSessionId:G.beforeSessionId});return}G.intent!=="file"&&G.intent!=="unfile"||t.moveSessionsToGroup(G.overGroupId,G.ids).catch(R=>{t.dispatch({type:"ui/status",text:`Move failed: ${R?.message||R}`})})}},[t,F]),le=a.useCallback((H,G)=>typeof H!="number"||typeof G!="number"?null:(document.elementFromPoint(H,G)?.closest?.("[data-drop-group]")||null)?.getAttribute("data-drop-group")||null,[]),ge=a.useCallback((H,G,R,W)=>{if(typeof H!="number"||typeof G!="number"||R==null)return;const V=Array.from(document.querySelectorAll(`[data-order-container="${CSS.escape(R)}"][data-orderable="1"]`));if(V.length===0)return;for(const ie of V){const Ie=ie.getBoundingClientRect();if(G<Ie.top+Ie.height/2)return{before:ie.getAttribute("data-session-id")||null,after:null}}const Q=V[V.length-1]?.getAttribute("data-session-id")||null;return{before:null,after:Q&&Q!==W?Q:null}},[]),we=a.useCallback((H,G,R)=>{const W=le(H,G),V=R?.ownGroupId||null;if(W&&W!==V)return{kind:"file",overGroupId:W,before:void 0,after:null};if(!W&&V)return{kind:"unfile",overGroupId:null,before:void 0,after:null};const Q=R?.orderable&&R.ids.length===1?ge(H,G,R.container,R.ids[0]):void 0;return Q===void 0?{kind:W?"file":"none",overGroupId:W,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:Q.before,after:Q.after}},[le,ge]);a.useEffect(()=>{if(!D.dragging)return;const H=V=>{const te=M.current;if(!te)return;const Q=we(V.clientX,V.clientY,te);te.intent=Q.kind,te.overGroupId=Q.overGroupId,te.beforeSessionId=Q.before,X(V.clientX,V.clientY),document.body.classList.toggle("ps-drop-ok",Q.kind==="file"),U(ie=>({...ie,intent:Q.kind,overGroupId:Q.overGroupId,insertBeforeId:Q.before,insertAfterId:Q.after,x:V.clientX,y:V.clientY}))},G=V=>{const te=M.current;if(te&&typeof V?.clientX=="number"){const Q=we(V.clientX,V.clientY,te);te.intent=Q.kind,te.overGroupId=Q.overGroupId,te.beforeSessionId=Q.before}z(!0)},R=()=>z(!1),W=V=>{V.key==="Escape"&&z(!1)};return window.addEventListener("pointermove",H),window.addEventListener("pointerup",G),window.addEventListener("pointercancel",R),window.addEventListener("keydown",W),document.body.classList.add("ps-dragging-sessions"),()=>{window.removeEventListener("pointermove",H),window.removeEventListener("pointerup",G),window.removeEventListener("pointercancel",R),window.removeEventListener("keydown",W),document.body.classList.remove("ps-dragging-sessions"),document.body.classList.remove("ps-drop-ok")}},[D.dragging,z,we,X]);const ke=a.useMemo(()=>({dragging:D.dragging,overGroupId:D.overGroupId,insertBeforeId:D.insertBeforeId,insertAfterId:D.insertAfterId,onPointerDown:(H,G)=>{if(G.isSystem||!G.orderable&&!G.isGroup&&G.depth>0)return;const R=H.clientX,W=H.clientY,V={row:G,startX:R,startY:W,started:!1,ids:[],overGroupId:null,beforeSessionId:void 0,orderable:!!G.orderable,container:G.orderContainer??null,ownGroupId:G.groupId||null,intent:"none",autoScrollStep:0},te=ie=>{if(V.started||Math.hypot(ie.clientX-R,ie.clientY-W)<5)return;V.started=!0;const Ie=O.current.viewState,Ke=Array.isArray(Ie.selectedIds)?Ie.selectedIds:[],Ut=Ke.includes(G.sessionId)&&Ke.length>1?Ke:[G.sessionId],Qs=Ie.sessionsById||{};V.ids=Ut,M.current=V,U({dragging:!0,ids:Ut,titles:Ut.map(as=>Qs[as]?.title||String(as).slice(0,8)).slice(0,3),overGroupId:null,x:ie.clientX,y:ie.clientY})},Q=()=>{window.removeEventListener("pointermove",te),window.removeEventListener("pointerup",Q)};window.addEventListener("pointermove",te),window.addEventListener("pointerup",Q)}}),[D.dragging,D.overGroupId,D.insertBeforeId,D.insertAfterId]),Ue=a.useCallback((H,G)=>{const{rows:R,viewState:W,controller:V}=O.current;if(H.metaKey||H.ctrlKey){H.preventDefault(),W.selectMode||V.dispatch({type:"sessions/selectMode",enabled:!0}),V.dispatch({type:"sessions/selectToggle",sessionId:G.sessionId}),V.setFocus("sessions");return}if(H.shiftKey&&W.activeSessionId){H.preventDefault();const Q=R.map(Ke=>Ke.sessionId),ie=Q.indexOf(W.activeSessionId),Ie=Q.indexOf(G.sessionId);if(ie>=0&&Ie>=0){const[Ke,Ut]=ie<=Ie?[ie,Ie]:[Ie,ie],Qs=Q.slice(Ke,Ut+1),as=Array.from(new Set([...W.selectedIds||[],...Qs]));V.setSessionSelection(as),V.setFocus("sessions");return}}if(G.hasChildren&&G.active){V.dispatch({type:G.collapsed?"sessions/expand":"sessions/collapse",sessionId:G.sessionId}),V.setFocus("sessions");return}W.selectMode&&V.dispatch({type:"sessions/selectClear"}),V.setFocus("sessions"),G.sessionId===W.activeSessionId?V.dispatch({type:"sessions/listReselect"}):G.active||V.loadSession(G.sessionId).catch(()=>{})},[]),K=a.useCallback((H,G)=>{H&&(G?u.current.set(H,G):u.current.delete(H))},[]);a.useEffect(()=>{if(d.modalOpen||!d.focused||!d.activeSessionId)return;const H=u.current.get(d.activeSessionId);H&&(document.activeElement!==H&&H.focus({preventScroll:!0}),H.scrollIntoView({block:"nearest"}))},[d.activeSessionId,d.focused,d.modalOpen]);const Ee=a.createElement(a.Fragment,null,L?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."},`${_} selected`):null,L?a.createElement(ce,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(C.CLEAR_SESSION_SELECTION).catch(()=>{})}):a.createElement(ce,{className:"ps-mini-button ps-pin-icon",icon:a.createElement(Dl),onClick:()=>t.handleCommand(C.PIN_SESSION).catch(()=>{}),disabled:!j,active:q,label:j?q?"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(Co),a.createElement("span",{className:"ps-icon-badge__count"},String(be.length))):a.createElement(Co),onClick:()=>t.handleCommand(C.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(bg),onClick:()=>y(!0),disabled:!$||L,label:L?"Disabled while multiple sessions are selected":"Manage session — rename, switch model, and sharing"}),a.createElement(ce,{className:"ps-mini-button",icon:a.createElement(Bg),onClick:()=>{const H=h?.sessionId;if(!H)return;const G=Zh(H);G&&(oo(G),E({url:G,warn:!1}),em(t,H).then(R=>{E(W=>W&&W.url===G?{...W,warn:R}:W)}).catch(()=>{}))},disabled:!h||h.isGroup||L,label:"Copy link — copy a direct link to this session"}),a.createElement(ce,{className:"ps-mini-button",icon:a.createElement(h?.isSystem?kg:Xn),onClick:()=>t.handleCommand(h?.isGroup?C.DELETE_SESSION:C.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!ne,label:L?`Terminate ${_} 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),We=D.dragging?a.createElement("div",{className:"ps-drag-ghost",style:{left:`${D.x}px`,top:`${D.y}px`}},a.createElement("div",{className:`ps-drag-ghost__stack${D.ids.length>1?" is-collection":""}`},D.ids.length>1?a.createElement("span",{className:"ps-drag-ghost__count"},String(D.ids.length)):null,a.createElement("span",{className:"ps-drag-ghost__title"},D.ids.length>1?`${D.ids.length} sessions`:D.titles[0]||"session")),a.createElement("div",{className:"ps-drag-ghost__hint"},D.overGroupId?"Release to file here":"Release to remove from folder")):null;return a.createElement(a.Fragment,null,We,a.createElement(yt,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:d.focused,theme:c,actions:Ee,className:v},a.createElement("div",{ref:r,className:`ps-action-list ps-session-list${D.dragging?" is-dragging":""}`,onClick:H=>{H.target instanceof Element&&H.target.closest(".ps-session-list-button")||t.dispatch({type:"sessions/listDeselect"})}},f.length===0?a.createElement("div",{className:"ps-empty-state"},d.filterQuery?`No sessions matched "@@${d.filterQuery}".`:"No sessions yet."):f.map(H=>a.createElement(fg,{key:H.sessionId,row:H,theme:c,rich:d.rich,structuredRows:n,mobile:i,onRowClick:Ue,setRef:K,drag:o?null:ke}))),i?null:a.createElement(cg,{session:h,childCount:g?.childCount||0})),m&&h&&!h.isGroup?a.createElement(Gg,{controller:t,sessionId:h.sessionId,initialTitle:h.title||"",currentModel:h.model||"",currentReasoningEffort:h.reasoningEffort||"",principal:d.auth?.principal||null,onClose:()=>y(!1),onSwitchModel:x,onChanged:()=>{}}):null,S?a.createElement(Sg,{url:S.url,warn:S.warn,onCopyAgain:()=>{oo(S.url),t.dispatch({type:"ui/status",text:Xh})},onClose:()=>E(null)}):null)}function Sg({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"},Jh):null))}const Ao={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 bg(){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 Ri(){return a.createElement(Se,null,a.createElement("path",{d:"M21 4H3l7.2 8.5V19l3.6 2v-8.5L21 4z"}))}function wg(){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 Ig(){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 xg(){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 Eg(){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 Bl(){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 Oi(){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 vg(){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 kg(){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 Ag(){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 Cg(){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 Tg(){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 Mg(){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 Ng(){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 Pg(){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 _g="M12 2.3 20.4 7.15v9.7L12 21.7 3.6 16.85V7.15Z",Rg="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",Og="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 $g(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":"true"},a.createElement("path",{d:_g,strokeWidth:"1.9",strokeLinejoin:"round"}),a.createElement("path",{d:Rg,fill:"currentColor",stroke:"none",fillRule:"evenodd"}),a.createElement("path",{d:Og,fill:"currentColor",stroke:"none"}))}function Lg(){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 Fg(){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 Bg(){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 Xn(){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 Co(){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 Dl(){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 Dg(){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 Hg(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()},Qh);return()=>{clearTimeout(l),typeof o=="function"&&o()}},[r]),{access:n.access,loading:n.loading,reload:r}}function Gg({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:i,principal:r,onClose:o,onSwitchModel:l,onChanged:c}){const[u,d]=a.useState("general"),[p,f]=a.useState(null),[h,g]=a.useState(s||""),[m,y]=a.useState([]),[S,E]=a.useState([]),[I,w]=a.useState("private"),[b,x]=a.useState(""),[k,P]=a.useState("write"),[N,B]=a.useState([]),[$,_]=a.useState(!1),[L,j]=a.useState(null);a.useEffect(()=>{let R=!1;return t.transport.getSessionAccess(e).then(W=>{!R&&W&&(f(W),w(W.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(W=>{R||B(Array.isArray(W)?W:[])}).catch(()=>{}),()=>{R=!0}},[t,e]);const q=a.useCallback(()=>{t.transport.listSessionShares(e).then(R=>{const W=Array.isArray(R)?R:[];y(W),E(W)}).catch(()=>{y([]),E([])})},[t,e]);a.useEffect(()=>{q()},[q]);const se=async R=>{_(!0),j(null);try{await R(),c?.()}catch(W){j(W?.message||String(W))}finally{_(!1)}},ne=()=>se(async()=>{await t.transport.renameSession(e,h.trim())}),Re=R=>{const W=R.trim().toLowerCase();if(!W)return null;const V=N.find(te=>te.displayName&&te.displayName.toLowerCase()===W||te.email&&te.email.toLowerCase()===W||te.subject&&te.subject.toLowerCase()===W);return V||{provider:r?.provider||"dev",subject:R.trim(),email:null,displayName:null}},re=R=>`${R.provider}${R.subject}`,be=R=>{const W=re(R);E(V=>[...V.filter(te=>re(te)!==W),{provider:R.provider,subject:R.subject,email:R.email??null,displayName:R.displayName??null,access:k}]),x("")},v=()=>{const R=Re(b);R&&be(R)},O=R=>{const W=re(R);E(V=>V.filter(te=>re(te)!==W))},D=new Set(S.map(re)),U=p?.owner?`${p.owner.provider}${p.owner.subject}`:null,M=b.trim().toLowerCase(),A=M?N.filter(R=>{const W=re(R);return W===U||D.has(W)?!1:R.displayName&&R.displayName.toLowerCase().includes(M)||R.email&&R.email.toLowerCase().includes(M)||R.subject&&R.subject.toLowerCase().includes(M)}).slice(0,25):[],F=!!p?.canManage,X=p?.visibility||"private",z=new Set(S.map(R=>`${re(R)}:${R.access}`)),le=new Set(m.map(R=>`${re(R)}:${R.access}`)),ge=z.size!==le.size||[...z].some(R=>!le.has(R)),we=F&&(I!==X||ge),ke=()=>se(async()=>{I!==X&&await t.transport.setSessionVisibility(e,I);const R=new Map(m.map(Q=>[re(Q),Q])),W=new Map(S.map(Q=>[re(Q),Q]));for(const[Q,ie]of W){const Ie=R.get(Q);(!Ie||Ie.access!==ie.access)&&await t.transport.grantSessionShare(e,{provider:ie.provider,subject:ie.subject,email:ie.email??null,displayName:ie.displayName??null},ie.access)}for(const[Q,ie]of R)W.has(Q)||await t.transport.revokeSessionShare(e,{provider:ie.provider,subject:ie.subject});const V=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(V)&&(y(V),E(V));const te=await t.transport.getSessionAccess(e).catch(()=>null);te&&(f(te),w(te.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),Ue=l||(()=>{o(),t.openSwitchModelPicker().catch(R=>{t.dispatch({type:"ui/status",text:R?.message||String(R)||"Failed to switch model"})})}),K=n?i?`${n}:${i}`:n:"—",Ee=[{id:"general",label:"General"},...F?[{id:"access",label:"Access"}]:[]],We=Ee.some(R=>R.id===u)?u:"general",H=typeof t.transport?.regenerateSession=="function",G=R=>R.stopPropagation();return a.createElement("div",{className:"ps-share-overlay",onClick:o},a.createElement("div",{className:"ps-share-modal",onClick:G},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"},Ee.map(R=>a.createElement("button",{key:R.id,type:"button",role:"tab","aria-selected":We===R.id?"true":"false",className:`ps-manage-tab${We===R.id?" is-active":""}`,onClick:()=>d(R.id)},R.label))),a.createElement("div",{className:"ps-share-modal-body"},We==="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:R=>g(R.target.value),onKeyDown:R=>{R.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"},K),a.createElement("button",{className:"ps-mini-button",disabled:$,onClick:Ue},"Switch model…")),H?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(C.REGENERATE_SESSION).catch(()=>{})}},a.createElement(Dg),a.createElement("span",null,"Regenerate context…")))):null):null,We==="access"&&F?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(R=>a.createElement("label",{key:R,className:`ps-share-radio${I===R?" is-active":""}`},a.createElement("input",{type:"radio",name:"visibility",checked:I===R,disabled:$,onChange:()=>w(R)}),a.createElement("span",{className:"ps-share-radio-glyph"},Ao[R].glyph),a.createElement("span",null,Ao[R].label),a.createElement("span",{className:"ps-share-radio-hint"},R==="private"?"only you and admins":R==="shared_read"?"everyone here can view":"everyone here can view and send"))),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."),S.length===0?a.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):S.map(R=>a.createElement("div",{key:`${R.provider}/${R.subject}`,className:"ps-share-grant-row"},a.createElement("span",{className:"ps-share-grant-name"},R.displayName||R.subject),a.createElement("span",{className:"ps-share-grant-access"},`can ${R.access}`),a.createElement("button",{className:"ps-mini-button",disabled:$,onClick:()=>O(R)},"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:b,disabled:$,autoComplete:"off",onChange:R=>x(R.target.value),onKeyDown:R=>{R.key==="Enter"&&v()}}),a.createElement("select",{className:"ps-share-add-select",value:k,disabled:$,onChange:R=>P(R.target.value)},a.createElement("option",{value:"read"},"can read"),a.createElement("option",{value:"write"},"can write")),a.createElement("button",{className:"ps-mini-button",disabled:$||!b.trim(),onClick:v},"Add")),A.length>0?a.createElement("div",{className:"ps-share-suggestions"},A.map(R=>a.createElement("button",{key:`${R.provider}/${R.subject}`,type:"button",className:"ps-share-suggestion",disabled:$,onClick:()=>be(R)},a.createElement("span",{className:"ps-share-suggestion-name"},R.displayName||R.subject),R.email?a.createElement("span",{className:"ps-share-suggestion-email"},R.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),We==="access"&&F?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:ke},"Apply")):null,L?a.createElement("div",{className:"ps-share-error"},L):null))}function $i({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const i=ee(t,L=>L.ui.themeId),r=De(i),o=ee(t,L=>{const j=L.sessions.activeSessionId,q=zs(L),se=s||e?q.totalWidth:q.leftWidth,ne=Math.max(20,se-4);return{activeSessionId:j,activeHistory:j&&L.history.bySessionId.get(j)||null,activeOutbox:j&&L.outbox?.bySessionId?.[j]?L.outbox.bySessionId[j]:[],branding:L.branding,connection:L.connection,sessionsById:L.sessions.byId,sessionsFlat:L.sessions.flat,inspectorTab:L.ui.inspectorTab,chatViewMode:L.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(j&&L.sessions.byId[j]?.isGroup),activeSessionStatus:j?String(L.sessions.byId[j]?.status||"").toLowerCase():"",focused:L.ui.focusRegion==="chat",scroll:L.ui.scroll.chat,authPrincipal:L.auth?.principal||null,contentWidth:ne}},Ge),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(()=>Ba(l,{width:o.contentWidth}),[l,o.contentWidth]),u=Ro(!!c.animateTitleRight),d=a.useMemo(()=>Oo(c.titleRight,c.animateTitleRight?u:""),[u,c.animateTitleRight,c.titleRight]),p=!!r?.richChat&&!o.activeSessionIsGroup,[f,h]=a.useState(!1),g=!!(o.activeHistory?.hasOlderEvents&&Number(o.activeHistory?.loadedEventCount||0)>=Kn),m=a.useMemo(()=>p?Ld(l,o.contentWidth,{tableMode:"sentinel"}):null,[p,l,o.contentWidth]),y=a.useMemo(()=>m?m.map((L,j)=>({text:L.kind==="message"?`m:${L.id??j}:${(L.text||"").length}:${L.pendingPhase||""}`:`l:${j}:${(L.lines||[]).length}`})):mi(l,o.contentWidth,{tableMode:"sentinel"}),[m,l,o.contentWidth]),S=_o(o.activeSessionStatus==="running"),I=a.useMemo(()=>hi(l,{spinnerFrame:S,maxWidth:o.contentWidth}),[l,S,o.contentWidth]),w=a.useMemo(()=>yi(l,o.contentWidth,{tableMode:"sentinel"}),[l,o.contentWidth]),b=a.useMemo(()=>I.length>0?[...w,...I]:w,[w,I]),{access:x}=Hg(t,o.activeSessionId,o.activeSessionIsGroup),k=ee(t,rd,Ge),P=n&&!o.activeSessionIsGroup&&o.chatViewMode!=="summary",N=!!o.sessionsById?.[o.activeSessionId]?.serviceKind,B=N||!!x&&x.canWrite===!1,$=P?a.createElement("div",{className:"ps-chat-composer"},B?a.createElement("div",{className:"ps-composer-readonly"},N?"⚗ Service session — runtime machinery. Its transcript is a read-only trace; it does not accept messages.":`You have view access to this session. Ask ${x.owner?.displayName||x.owner?.email||"the owner"} for write access to participate.`):a.createElement(Vg,{controller:t,mobile:e,active:!0})):null,_=!!(o.activeSessionId&&o.sessionsById[o.activeSessionId]);return k&&!_?a.createElement(yt,{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"},k.message),k.retryable?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(k.sessionId)},"Retry"):null)):a.createElement(Xs,{controller:t,title:(()=>{const L=e?co(c.title,28):c.title;return p?ig(L):L})(),titleRight:e&&d?co(d,18):d,actions:null,color:c.color,focused:o.focused,lines:y,bottomStickyLines:b,scrollOffset:o.scroll,scrollMode:"bottom",paneKey:"chat",className:p?"is-wrapped is-rich":"is-wrapped",panelClassName:p?"ps-chat-panel is-rich":"ps-chat-panel",bottomContent:$,topContent:g?a.createElement("div",{className:"ps-load-older-bar"},a.createElement("button",{type:"button",className:"ps-load-older-button",disabled:f,onClick:()=>{h(!0),t.handleCommand(C.EXPAND_HISTORY).catch(()=>{}).finally(()=>h(!1))}},f?"Loading older messages…":"↑ Load older messages")):null,structuredBlocks:!0,renderBody:m?(L,j)=>a.createElement(sg,{blocks:m,theme:j,controller:t}):null})}function jg({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)}},Ge),s=!!wl(e.filename)||Mi(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(Li,{controller:t,focused:!0,mobile:!0,previewOnly:!0,nativeScroll:!0})))}function Ug({controller:t}){return a.createElement("div",{className:"ps-mobile-workspace"},a.createElement(_i,{controller:t,panelClassName:"ps-mobile-session-pane"}),a.createElement("div",{className:"ps-mobile-chat-pane"},a.createElement($i,{controller:t,mobile:!0,fullWidth:!0})))}function Hl({activeTab:t,controller:e}){const s=a.useMemo(()=>Ti(e),[e]);return a.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>a.createElement(ce,{key:n,icon:ro[n]?a.createElement(ro[n]):"•",label:Uh[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function Li({controller:t,focused:e,mobile:s=!1,previewOnly:n=!1,nativeScroll:i=!1}){const r=ee(t,_=>_.ui.themeId),o=De(r),l=a.useRef(null),c=ee(t,_=>{const L=_.sessions.activeSessionId,j=zs(_),q=s||_.files.fullscreen?_.ui.layout?.viewportWidth??120:j.rightWidth;return{activeSessionId:L,sessionsById:_.sessions.byId,sessionsFlat:_.sessions.flat,filesBySessionId:_.files.bySessionId,filesFilter:_.files.filter,selectedArtifactId:_.files.selectedArtifactId,markedIds:_.files.markedIds||[],previewOrigin:_.files.previewOrigin||null,focused:e,previewScroll:_.ui.scroll.filePreview,fullscreen:!!_.files.fullscreen,contentWidth:Math.max(20,q-4),canBrowserUpload:Kh(t),canPathUpload:Vh(t),canDeleteArtifacts:zh(t),canOpenLocally:Yh(t)}},Ge),u=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]),d=a.useMemo(()=>wi(u,{listWidth:Math.max(18,c.contentWidth-4),previewWidth:Math.max(18,c.contentWidth-4),showHints:!1}),[u,c.contentWidth]),p=a.useMemo(()=>pt(u),[u]),f=p.length>0,h=a.useCallback(_=>{const L=Array.isArray(_)?_.filter(Boolean):[];L.length!==0&&t.uploadArtifactFiles(L).catch(()=>{})},[t]),g=a.useCallback(()=>{if(c.canBrowserUpload&&l.current){l.current.click();return}c.canPathUpload&&t.handleCommand(C.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,c.canBrowserUpload,c.canPathUpload]),m=a.useMemo(()=>new Set(c.markedIds||[]),[c.markedIds]),y=a.createElement(a.Fragment,null,m.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"},`${m.size} marked`),c.canDeleteArtifacts?a.createElement(ce,{icon:a.createElement(Xn),label:`Delete ${m.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:_=>{h(Array.from(_.currentTarget.files||[])),_.currentTarget.value=""}}),a.createElement(ce,{icon:a.createElement(Ag),label:"Upload",onClick:g,disabled:!c.canBrowserUpload&&!c.canPathUpload}),a.createElement(ce,{icon:a.createElement(Cg),label:"Download",onClick:()=>t.handleCommand(C.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!f}),c.canDeleteArtifacts?a.createElement(ce,{icon:a.createElement(Xn),label:"Delete",onClick:()=>t.handleCommand(C.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,c.canOpenLocally?a.createElement(ce,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(C.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,a.createElement(ce,{icon:a.createElement(Ri),label:"Filter",onClick:()=>t.handleCommand(C.OPEN_FILES_FILTER).catch(()=>{})}),a.createElement(ce,{icon:a.createElement(c.fullscreen?Oi:Bl),label:c.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(C.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),S=a.useRef(null);a.useEffect(()=>{const _=S.current;_&&typeof _.scrollIntoView=="function"&&_.scrollIntoView({block:"nearest"})},[d.selectedIndex,c.selectedArtifactId]);const E=p.length===0?Ce(d.listBodyLines||[]).map((_,L)=>a.createElement(Ne,{key:`empty:${L}`,line:_,theme:o})):p.map((_,L)=>a.createElement("button",{key:_.id,type:"button",ref:L===d.selectedIndex?S:null,className:`ps-list-button${L===d.selectedIndex?" is-selected":""}`+(m.has(_.id)?" is-marked":""),onClick:j=>{if(t.setFocus("inspector"),j.metaKey||j.ctrlKey){t.toggleArtifactMark(_);return}if(j.shiftKey){t.markArtifactRange(_);return}t.clearArtifactMarks(),t.selectFileBrowserItem(_).then(()=>{s&&t.handleCommand(C.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})}).catch(()=>{})}},a.createElement(Ne,{line:Ce([d.listBodyLines?.[L]])[0],theme:o}))),I=!d.previewLoading&&!d.previewError,w=I&&Mi(d.selectedFilename,d.previewContentType)&&!d.previewIsBinary&&!!d.previewContent,b=I&&(Sl.test(String(d.previewContentType||""))||bl.test(String(d.selectedFilename||""))),x=I&&!d.previewIsBinary&&!w&&d.previewRenderMode!=="markdown"&&d.previewContent?wl(d.selectedFilename):null,k=n?"activity":null,P=i?null:"filePreview",B=I&&!d.previewIsBinary&&xm(d.selectedFilename,d.previewContentType)&&!!d.previewContent?a.createElement(Tn,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:P,scrollOffset:c.previewScroll,className:"ps-csv-preview",focusRegion:k},a.createElement(vm,{content:d.previewContent,filename:d.selectedFilename})):b?a.createElement(So,{title:null,color:"cyan",focused:!1,theme:o,filename:d.selectedFilename,contentType:d.previewContentType,sizeBytes:d.previewSizeBytes,source:d.previewSource,uploadedAt:d.previewUploadedAt,controller:t,sessionId:d.selectedSessionId}):x?a.createElement(Tn,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:P,scrollOffset:c.previewScroll,className:"ps-diff-preview",focusRegion:k},a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,ss(d.previewContent,x,o)))):w?a.createElement(Tn,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:P,scrollOffset:c.previewScroll,className:"ps-diff-preview",focusRegion:k},a.createElement("pre",{className:"ps-md-code-pre is-diff"},a.createElement("code",null,Ni(d.previewContent,o)))):d.previewRenderMode==="markdown"&&!d.previewLoading&&!d.previewError?a.createElement(Km,{controller:t,title:null,color:"cyan",focused:!1,scrollOffset:c.previewScroll,paneKey:P,theme:o,focusRegion:k,content:wm(d.previewContent||"")}):d.previewIsBinary&&!d.previewLoading&&!d.previewError?a.createElement(So,{title:null,color:"cyan",focused:!1,theme:o,filename:d.selectedFilename,contentType:d.previewContentType,sizeBytes:d.previewSizeBytes,source:d.previewSource,uploadedAt:d.previewUploadedAt,controller:t,sessionId:d.selectedSessionId}):a.createElement(Xs,{controller:t,title:null,color:"cyan",focused:!1,lines:d.previewLines,scrollOffset:c.previewScroll,scrollMode:"top",paneKey:P,focusRegion:k,className:"is-preview is-wrapped"}),$=c;return n?B:a.createElement(yt,{title:$.fullscreen?d.fullscreenTitle:s&&d.panelTitleMobile?d.panelTitleMobile:d.panelTitle,color:"magenta",focused:$.focused,actions:y,theme:o},a.createElement(Hl,{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"},E)))}function Et({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const i=ee(t,f=>{const h=zs(f),g=f.ui.inspectorTab,m=e?f.ui.layout?.viewportWidth??120:h.rightWidth;return{inspectorTab:g,statsViewMode:f.ui.statsViewMode,adminWorkers:f.admin?.workers,nodeMapSelectedNode:f.ui.nodeMapSelectedNode,activeSessionId:f.sessions.activeSessionId,sessionsById:f.sessions.byId,sessionsFlat:f.sessions.flat,historyBySessionId:f.history.bySessionId,sessionStats:f.sessionStats,fleetStats:f.fleetStats,connection:f.connection,orchestrationBySessionId:f.orchestration.bySessionId,executionHistoryBySessionId:f.executionHistory?.bySessionId||{},executionHistoryFormat:f.executionHistory?.format||"pretty",logs:f.logs,files:f.files,focused:f.ui.focusRegion==="inspector",scroll:f.ui.scroll.inspector,followBottom:f.ui.followBottom?.inspector!==!1,logsTailing:f.logs.tailing,filesFullscreen:!!f.files.fullscreen,contentWidth:am(m)}},Ge),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(()=>at(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 g of f?.events||[]){if(g?.eventType!=="session.turn_completed")continue;const m=Number(g?.data?.turnIndex??g?.data?.iteration);Number.isFinite(m)&&h.set(m,g)}return h},[i.activeSessionId,i.historyBySessionId]),c=a.useCallback((f,h)=>a.createElement(og,{lines:f,theme:h,completionByTurn:l}),[l]),u=a.useCallback((f,h)=>a.createElement(rg,{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(Li,{controller:t,focused:i.focused,mobile:e});const d=[];if(i.inspectorTab==="logs")d.push(a.createElement(ce,{key:"tail",icon:i.logsTailing?"■":"⇣",label:i.logsTailing?"Stop tailing":"Tail (follow)",active:i.logsTailing,onClick:()=>t.handleCommand(C.TOGGLE_LOG_TAIL).catch(()=>{})})),d.push(a.createElement(ce,{key:"filter",icon:a.createElement(Ri),label:"Filter",onClick:()=>t.handleCommand(C.OPEN_LOG_FILTER).catch(()=>{})}));else if(i.inspectorTab==="history")d.push(a.createElement(ce,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(C.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),d.push(a.createElement(ce,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(C.EXPORT_EXECUTION_HISTORY).catch(()=>{})}));else if(i.inspectorTab==="stats"){const f={session:"◉",fleet:"⬢",users:"⚇"};for(const h of["session","fleet","users"])d.push(a.createElement(ce,{key:`stats-view:${h}`,icon:f[h],label:`${h.replace(/^./u,g=>g.toUpperCase())} stats`,active:i.statsViewMode===h,onClick:()=>t.setStatsViewMode(h)}))}const p=n?d.concat(n):d;return a.createElement(Xs,{controller:t,title:o.title,color:"magenta",focused:i.focused,actions:p,topContent:a.createElement(Hl,{activeTab:o.activeTab,controller:t}),stickyLines:o.stickyLines||[],lines:o.lines,renderBody:o.activeTab==="sequence"?c:o.activeTab==="nodes"?u:null,scrollOffset:i.scroll,scrollMode:o.activeTab==="sequence"||o.activeTab==="logs"&&i.followBottom?"bottom":"top",stickyBottom:o.activeTab==="logs",paneKey:"inspector",className:o.activeTab==="history"||o.activeTab==="logs"?"is-wrapped":"is-preserve",panelClassName:`ps-inspector-pane${o.activeTab==="sequence"?" has-preserved-sticky":""}${s?` ${s}`:""}`.trim()})}function ws({controller:t,panelClassName:e="",extraActions:s=null}){const n=ee(t,l=>{const c=l.sessions.activeSessionId,u=zs(l),d=Math.max(3,u.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:d,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}},Ge),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?Da(r):bi(r,n.maxLines),[i,r,n.maxLines]);return a.createElement(Xs,{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 Qn=[{id:"sessions",label:"Sessions",side:"left"},{id:"inspector",label:"Inspector",side:"right"},{id:"activity",label:"Activity",side:"right"}];function Wg({controller:t,pane:e,onClose:s,mobile:n=!1}){if(!e)return null;let i=null;e==="sessions"?i=a.createElement(_i,{controller:t,panelClassName:"ps-chat-focus-pane",structuredRows:n}):e==="inspector"?i=a.createElement(Et,{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(ws,{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=Qn.find(o=>o.id===e);return a.createElement("div",{className:`ps-chat-focus-overlay${r?.side==="left"?" is-left":" is-right"}`},i)}function Kg({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(Oi),label:"Exit focus mode",onClick:n}),a.createElement(ce,{className:"ps-mini-button ps-chat-focus-button",icon:a.createElement(Mg),label:e==="sessions"?"Hide sessions":"Show sessions",active:e==="sessions",onClick:()=>s("sessions")})):a.createElement("div",{className:"ps-chat-focus-rail"},Qn.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: ${Qn.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($i,{controller:t,mobile:i,fullWidth:!0}),a.createElement(Wg,{controller:t,pane:e,onClose:()=>s(e),mobile:i})))}const To=Object.freeze([]);function Mo(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 Vg({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const i=ee(t,x=>{const k=x.sessions.activeSessionId,P=k&&x.sessions.byId[k]||null,N=k&&x.outbox?.bySessionId?.[k]?x.outbox.bySessionId[k]:[];return{value:x.ui.prompt,cursor:x.ui.promptCursor,focused:x.ui.focusRegion==="prompt",modalOpen:!!x.ui.modal,answerMode:!!P?.pendingQuestion?.question,canStopTurn:Ma(P),hasOutbox:N.length>0,hasPendingOutbox:N.some(B=>B?.phase==="pending"),pendingCount:N.filter(B=>B?.phase==="pending").length,editingPending:x.ui.promptEdit?.sessionId===k,selectedOutboxPhase:x.ui.promptEdit?.sessionId===k&&x.ui.promptEdit?.phase||null,promptAttachments:x.ui.promptAttachments||To}},Ge),r=a.useRef(null),o=a.useRef(null),[l,c]=a.useState(!1),u=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",d=u?i.promptAttachments.filter(x=>x?.kind==="image"):To,p=a.useRef(new Map);a.useEffect(()=>{const x=p.current,k=new Set(d.map(P=>P.file));for(const[P,N]of x)k.has(P)||(URL.revokeObjectURL(N),x.delete(P));for(const P of d)if(P.file&&!x.has(P.file))try{x.set(P.file,URL.createObjectURL(P.file))}catch{}},[d]),a.useEffect(()=>()=>{for(const x of p.current.values())URL.revokeObjectURL(x);p.current.clear()},[]);const f=a.useCallback(x=>{if(!u)return 0;const k=Array.from(x||[]).filter(N=>N&&typeof N.type=="string"&&N.type.startsWith("image/"));return k.length===0?0:t.addPendingImageFiles(k)?.accepted||0},[t,u]);a.useEffect(()=>{const x=r.current;if(!(!s||i.modalOpen||!i.focused||!x)){if(document.activeElement!==x)try{x.focus({preventScroll:!0})}catch{x.focus()}x.setSelectionRange(i.cursor,i.cursor)}},[s,i.cursor,i.focused,i.modalOpen]);const h=a.useCallback(()=>{t.handleCommand(C.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[g,m]=a.useState(!1),y=a.useCallback(()=>{m(!0),t.handleCommand(C.STOP_TURN).catch(()=>{}).finally(()=>m(!1))},[t]),S=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]),E=i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"⇪":i.hasOutbox?"+":"❯",I=i.selectedOutboxPhase==="queued",w=i.selectedOutboxPhase==="cancelling",b=I||w;return a.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}${l?" is-drag-over":""}`,...u?{onDragOver:x=>{x.dataTransfer?.types?.includes?.("Files")&&(x.preventDefault(),c(!0))},onDragLeave:x=>{x.currentTarget.contains(x.relatedTarget)||c(!1)},onDrop:x=>{c(!1),x.dataTransfer?.files?.length&&(x.preventDefault(),f(x.dataTransfer.files))}}:{}},d.length>0?a.createElement("div",{className:"ps-prompt-attachments"},d.map((x,k)=>{const P=x.file?p.current.get(x.file):null;return a.createElement("div",{key:`attach:${k}:${x.filename}`,className:"ps-attach-chip",title:`${x.filename} · ${Mo(x.sizeBytes)}`},P?a.createElement("img",{className:"ps-attach-thumb",src:P,alt:x.filename}):a.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),a.createElement("div",{className:"ps-attach-size"},Mo(x.sizeBytes)),a.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${x.filename}`,"aria-label":`Remove attachment ${x.filename}`,onClick:()=>t.removePendingImageAttachment(k)},"✕"))})):null,(()=>{const x=i.answerMode?"answer":w?"cancelling":I?"queued":i.editingPending?"pending":"you";return a.createElement("label",{className:`ps-prompt-label${x==="you"?" is-default":""}`},x)})(),a.createElement("textarea",{ref:r,className:"ps-prompt-input",rows:e?2:Math.max(2,_t(i.value)),value:i.value,readOnly:b,placeholder:i.answerMode?"Type an answer and press Enter":i.editingPending?w?"Cancellation requested":I?"Queued message selected":"Edit the pending message, then send or cancel it":i.hasOutbox?"Type a message and press Enter to queue it behind the pending batch":"Type a message and press Enter",enterKeyHint:"send",onFocus:()=>t.setFocus("prompt"),onSelect:x=>t.setPromptCursor(x.currentTarget.selectionStart||0),onChange:x=>t.setPrompt(x.currentTarget.value,x.currentTarget.selectionStart||x.currentTarget.value.length),onPaste:u?x=>{const P=Array.from(x.clipboardData?.items||[]).filter(N=>N.kind==="file"&&N.type.startsWith("image/")).map(N=>N.getAsFile()).filter(Boolean);P.length>0&&f(P)>0&&x.preventDefault()}:void 0,onKeyDown:x=>{if(x.key==="Tab"&&!x.shiftKey&&t.acceptPromptReferenceAutocomplete()){x.preventDefault();return}if(x.key==="ArrowUp"&&!x.shiftKey&&!x.metaKey&&!x.altKey){x.preventDefault(),t.movePromptCursorVertical(-1);return}if(x.key==="ArrowDown"&&!x.shiftKey&&!x.metaKey&&!x.altKey){x.preventDefault(),t.movePromptCursorVertical(1);return}if(x.key==="Escape"&&i.editingPending){if(x.preventDefault(),b){t.exitPendingPromptEdit({restoreDraft:!0});return}S();return}x.key==="Enter"&&!x.shiftKey&&!x.metaKey&&!e&&(x.preventDefault(),h())}}),a.createElement("div",{className:"ps-prompt-actions"},u?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:x=>{f(x.currentTarget.files),x.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&&!w?a.createElement("button",{type:"button",className:"ps-mini-button",title:I?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":I?"Delete selected queued prompt":"Cancel selected pending prompt",onClick:S},I?"Delete":"Cancel"):null,i.canStopTurn||g?a.createElement("button",{type:"button",className:`ps-stop-button${g?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:g,onClick:y},"■"):null,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},E)))}const qg=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),u=a.useRef(null),d=a.useRef(null),p=a.useRef(!1);a.useLayoutEffect(()=>{if(!o||!u.current||typeof window>"u")return;const k=u.current.offsetWidth/2,P=6,N=Math.max(k+P,Math.min(o.x,window.innerWidth-k-P));u.current.style.left=`${N}px`},[o]);const f=(k=!1)=>{const P=c.current;if(!P||typeof window>"u")return;const N=P.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),g=a.useRef(null),m=k=>{k.pointerType==="mouse"&&(clearTimeout(d.current),clearTimeout(h.current),d.current=setTimeout(f,qg))},y=k=>{k.pointerType==="mouse"&&(clearTimeout(d.current),clearTimeout(h.current),l(null))},S=k=>{k.pointerType!=="mouse"&&(p.current=!1,g.current={x:k.clientX,y:k.clientY},clearTimeout(d.current),clearTimeout(h.current),d.current=setTimeout(()=>{p.current=!0,f(!0)},450))},E=k=>{if(k.pointerType==="mouse"||!g.current)return;const P=k.clientX-g.current.x,N=k.clientY-g.current.y;P*P+N*N>100&&(g.current=null,clearTimeout(d.current),l(null))},I=k=>{k.pointerType!=="mouse"&&(g.current=null,clearTimeout(d.current),p.current?(clearTimeout(h.current),h.current=setTimeout(()=>l(null),3e3),setTimeout(()=>{p.current=!1},250)):l(null))};a.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(h.current)},[]);const w=k=>{if(p.current){p.current=!1,k.preventDefault?.();return}n||s?.(k)},b=k=>{k.preventDefault?.()},x=o&&typeof document<"u"&&document.body?ll.createPortal(a.createElement("span",{ref:u,className:`ps-icon-tooltip is-${o.placement}`,role:"tooltip",style:{left:`${o.x}px`,top:`${o.y}px`}},e),document.body):null;return a.createElement("button",{ref:c,type:"button",className:`${r} ps-icon-button${i?" is-active":""}`,onClick:w,disabled:n,"aria-label":e,onPointerEnter:m,onPointerLeave:y,onPointerDown:S,onPointerMove:E,onPointerUp:I,onPointerCancel:I,onContextMenu:b},a.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),x)}function zg({controller:t,mobile:e,chatFocusMode:s=!1,onToggleChatFocus:n=null,chatFocusDisabled:i=!1}){const r=ee(t,h=>!!De(h.ui.themeId)?.richChat),[o,l]=a.useState(null);a.useEffect(()=>{typeof document>"u"||l(e?null:document.getElementById("ps-header-toolbar-slot"))},[r,e]);const c=ee(t,h=>!!h.admin?.visible),u=ee(t,h=>({mode:h.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(h.sessions.activeSessionId&&h.sessions.byId[h.sessions.activeSessionId]?.isGroup)}),Ge),d=[{key:"new",icon:a.createElement(xg),label:"New session — choose model and agent",onClick:()=>t.handleCommand(C.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:a.createElement(Ri),label:"Filter sessions",onClick:()=>t.handleCommand(C.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:a.createElement(Eg),label:"Theme",onClick:()=>t.handleCommand(C.OPEN_THEME_PICKER).catch(()=>{})},{key:"summary",icon:a.createElement(u.mode==="summary"?Ig:wg),label:u.activeSessionIsGroup?"Groups show group details":u.mode==="summary"?"Show chat transcript":"Show summary",onClick:()=>t.setChatViewMode(u.mode==="summary"?"transcript":"summary"),disabled:u.activeSessionIsGroup,active:u.mode==="summary"},...n?[{key:"focus",icon:a.createElement(s?Oi:Bl),label:s?"Exit focus mode":"Focus the chat pane",onClick:n,disabled:i,active:s}]:[],...e?[]:[{key:"admin",icon:a.createElement(vg),label:c?"Close admin console":"Admin console",onClick:()=>t.handleCommand(c?C.CLOSE_ADMIN_CONSOLE:C.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:c}]],p=h=>a.createElement(ce,{key:h.key,icon:h.icon,label:h.label,onClick:h.onClick,disabled:!!h.disabled,active:!!h.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(p))));const f=a.createElement("div",{className:"ps-toolbar"},a.createElement("div",{className:"ps-toolbar-actions"},d.map(p)));return o?ll.createPortal(f,o):f}function Yg({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 d=s.current;if(!d)return;const p=Math.round((l-d.startX)/cl),f=p-d.appliedCells;f&&(t.adjustPaneSplit(f),d.appliedCells=p)},u=d=>{s.current&&(l=d.clientX,!o&&(o=requestAnimationFrame(c)))};return window.addEventListener("pointermove",u),window.addEventListener("pointerup",r),window.addEventListener("pointercancel",r),()=>{o&&(cancelAnimationFrame(o),o=0),window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",r),window.removeEventListener("pointercancel",r),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),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(C.GROW_RIGHT_PANE).catch(()=>{});return}r.key==="ArrowRight"&&(r.preventDefault(),t.handleCommand(C.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 Xg({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 u=Vn(c.startAdjust+(l.clientX-c.startX),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:u})};return window.addEventListener("pointermove",o),window.addEventListener("pointerup",r),window.addEventListener("pointercancel",r),()=>{window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",r),window.removeEventListener("pointercancel",r),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),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=qn(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=qn(o?.getBoundingClientRect?.().width),c=u=>{const d=Vn((Number(e)||0)+u,l.minAdjust,l.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:d})};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 Qg({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 u=Math.round((l.clientY-c.startY)/ul),d=u-c.appliedCells;d&&(t.adjustActivityPaneSplit(-d),c.appliedCells=u)};return window.addEventListener("pointermove",o),window.addEventListener("pointerup",r),window.addEventListener("pointercancel",r),()=>{window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",r),window.removeEventListener("pointercancel",r),document.body.classList.remove("is-resizing-pane-y")}},[t,n]),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 Jg({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 Zg({controller:t}){const e=ee(t,m=>m.ui.themeId),s=De(e),n=ee(t,m=>({rawModal:m.ui.modal,themePicker:of(m),modelPicker:Pp(m),reasoningEffortPicker:Rp(m),contextTierPicker:Op(m),sessionAgentPicker:_p(m),sessionGroupPicker:$p(m),sessionGroupName:Fp(m),artifactPicker:jp(m),logFilter:Hp(m),filesFilter:Gp(m),historyFormat:rf(m),renameSession:Lp(m),sessionOwnerFilter:Dp(m),artifactUpload:Bp(m),confirm:af(m),logsFilter:m.logs.filter,filesFilterState:m.files.filter,historyFormatState:m.executionHistory?.format||"pretty"}),Ge),i=n.rawModal,r=a.useRef(null),o=a.useRef(null),l=a.useRef(null),[c,u]=a.useState(""),d=i?.type==="sessionOwnerFilter";if(a.useEffect(()=>{d||u("")},[d]),a.useEffect(()=>{if(i?.type!=="renameSession"||!n.renameSession)return;const m=r.current;if(m){if(document.activeElement!==m)try{m.focus({preventScroll:!0})}catch{m.focus()}m.setSelectionRange(n.renameSession.cursorIndex,n.renameSession.cursorIndex)}},[i?.type,n.renameSession?.cursorIndex,n.renameSession?.value]),a.useEffect(()=>{if(i?.type!=="sessionGroupName"||!n.sessionGroupName)return;const m=o.current;if(m){if(document.activeElement!==m)try{m.focus({preventScroll:!0})}catch{m.focus()}m.setSelectionRange(n.sessionGroupName.cursorIndex,n.sessionGroupName.cursorIndex)}},[i?.type,n.sessionGroupName?.cursorIndex,n.sessionGroupName?.value]),a.useEffect(()=>{if(!i||!["themePicker","modelPicker","reasoningEffortPicker","contextTierPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(i.type))return;const m=l.current;if(!m)return;const y=m.querySelector(".ps-list-button.is-selected");y&&typeof y.scrollIntoView=="function"&&y.scrollIntoView({block:"nearest"})},[i?.type,i?.selectedIndex,n.themePicker?.selectedRowIndex,n.modelPicker?.selectedRowIndex,n.reasoningEffortPicker?.selectedRowIndex,n.contextTierPicker?.selectedRowIndex,n.sessionAgentPicker?.selectedRowIndex,n.sessionGroupPicker?.selectedRowIndex,n.artifactPicker?.selectedRowIndex,n.sessionOwnerFilter?.selectedRowIndex,n.logFilter?.selectedRowIndex,n.filesFilter?.selectedRowIndex,n.historyFormat?.selectedRowIndex]),!i)return null;const p=()=>t.handleCommand(C.CLOSE_MODAL).catch(()=>{}),f=(m,y="Apply")=>{const S=Array.isArray(m.rows)?m.rows:[],E=Array.isArray(m.rowItemIndexes)?m.rowItemIndexes:null,I=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",w=E&&E.length===S.length?S.map((b,x)=>{const k=E[x],P=Array.isArray(b)?b:Ce([b])[0]?.runs||[{text:b?.text||"",color:b?.color}];if(k==null||k<0)return a.createElement("div",{key:`row:${x}`,className:"ps-line ps-modal-list-heading-line"},a.createElement(Me,{runs:P,theme:s}));const N=i.items?.[k];return a.createElement("button",{key:N?.id||`row:${x}`,type:"button",className:`ps-list-button ps-modal-list-button${k===i.selectedIndex?" is-selected":""}${I?" is-hanging":""}${N?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:k})},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Me,{runs:P,theme:s})))}):(i.items||[]).map((b,x)=>a.createElement("button",{key:b.id||x,type:"button",className:`ps-list-button ps-modal-list-button${x===i.selectedIndex?" is-selected":""}${I?" is-hanging":""}${b?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:x})},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Me,{runs:Array.isArray(S?.[x])?S[x]:Ce([S?.[x]])[0]?.runs||[{text:S?.[x]?.text||"",color:S?.[x]?.color}],theme:s}))));return a.createElement("div",{className:"ps-modal-backdrop",onClick:p},a.createElement("div",{className:`ps-modal is-list${i.type==="themePicker"?" is-theme-picker":""}`,onClick:b=>b.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},m.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:p,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:l,className:"ps-modal-list"},w),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},m.detailsTitle||"Details"),Ce(m.detailsLines||[]).map((b,x)=>a.createElement(Ne,{key:`detail:${x}`,line:b,theme:s,className:"ps-modal-detail-line"})))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:p},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(C.MODAL_CONFIRM).catch(()=>{})},y))))};if(i.type==="confirm"&&n.confirm){const m=!!i.alert,y=!m&&i.action==="deleteSession",S=i.action==="regenerateSession",E=i.extras||{};return a.createElement("div",{className:"ps-modal-backdrop",onClick:p},a.createElement("div",{className:"ps-modal is-narrow",onClick:I=>I.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},n.confirm.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:p,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},a.createElement("p",{style:{color:"#94a3b8",margin:0}},n.confirm.message)),S?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:E.distillMode||"llm",onChange:I=>t.updateConfirmExtras({distillMode:I.currentTarget.value})},a.createElement("option",{value:"llm"},"Intelligent (LLM reads the whole transcript)"),a.createElement("option",{value:"deterministic"},"Fast (no LLM — tail + pointers)"))),(E.distillMode||"llm")==="llm"?a.createElement(ey,{controller:t,extras:E}):null,(E.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:E.instructions||"",maxLength:4e3,onChange:I=>t.updateConfirmExtras({instructions:I.currentTarget.value})}):null):null,a.createElement("div",{className:"ps-modal-footer"},m?null:a.createElement("button",{type:"button",className:"ps-modal-button",onClick:p},"Cancel"),a.createElement("button",{type:"button",className:`ps-modal-button ${y?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(C.MODAL_CONFIRM).catch(()=>{})},n.confirm.confirmLabel))))}if(i.type==="themePicker"&&n.themePicker)return f(n.themePicker,"Apply Theme");const h=i.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(i.type==="modelPicker"&&n.modelPicker)return f(n.modelPicker,h);if(i.type==="reasoningEffortPicker"&&n.reasoningEffortPicker)return f(n.reasoningEffortPicker,h);if(i.type==="contextTierPicker"&&n.contextTierPicker)return f(n.contextTierPicker,h);if(i.type==="sessionAgentPicker"&&n.sessionAgentPicker)return f(n.sessionAgentPicker,"Create Session");if(i.type==="sessionGroupPicker"&&n.sessionGroupPicker)return f(n.sessionGroupPicker,"Move");if(i.type==="artifactPicker"&&n.artifactPicker)return f(n.artifactPicker,n.artifactPicker.confirmLabel||"Open / Download");if(i.type==="sessionOwnerFilter"&&n.sessionOwnerFilter){const m=n.sessionOwnerFilter,y=Array.isArray(m.rows)?m.rows:[],S=c.trim().toLowerCase(),E=w=>{const b=y?.[w];return(Array.isArray(b)?b:Ce([b])[0]?.runs||[]).map(k=>k?.text||"").join("")||String(b?.text||"")},I=(i.items||[]).map((w,b)=>b).filter(w=>{if(!S)return!0;const b=(i.items||[])[w]||{};return`${E(w)} ${b.label||""} ${b.description||""}`.toLowerCase().includes(S)});return a.createElement("div",{className:"ps-modal-backdrop",onClick:p},a.createElement("div",{className:"ps-modal is-list",onClick:w=>w.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},m.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:p,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{className:"ps-modal-input ps-modal-search",value:c,placeholder:"Search people…",autoFocus:!0,onChange:w=>u(w.currentTarget.value),onKeyDown:w=>{w.key==="Escape"&&c&&(w.stopPropagation(),u(""))}}),a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:l,className:"ps-modal-list"},I.length===0?a.createElement("div",{className:"ps-empty-state"},`No one matches "${c}".`):null,I.map(w=>(b=>a.createElement("button",{key:b.id||w,type:"button",className:`ps-list-button ps-modal-list-button${w===i.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(w)},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Me,{runs:Array.isArray(y?.[w])?y[w]:Ce([y?.[w]])[0]?.runs||[{text:y?.[w]?.text||"",color:y?.[w]?.color}],theme:s}))))((i.items||[])[w]||{}))),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},m.detailsTitle||"Details"),Ce(m.detailsLines||[]).map((w,b)=>a.createElement(Ne,{key:`detail:${b}`,line:w,theme:s,className:"ps-modal-detail-line"})))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:p},"Done"))))}if(i.type==="renameSession"&&n.renameSession)return a.createElement("div",{className:"ps-modal-backdrop",onClick:p},a.createElement("div",{className:"ps-modal is-narrow",onClick:m=>m.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},n.renameSession.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:p,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{ref:r,className:"ps-modal-input",value:n.renameSession.value,placeholder:n.renameSession.placeholder,onChange:m=>t.setRenameSessionValue(m.currentTarget.value,m.currentTarget.selectionStart??m.currentTarget.value.length),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),t.handleCommand(C.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Ce(n.renameSession.helpLines||[]).map((m,y)=>a.createElement(Ne,{key:`help:${y}`,line:m,theme:s,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:p},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(C.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(i.type==="sessionGroupName"&&n.sessionGroupName)return a.createElement("div",{className:"ps-modal-backdrop",onClick:p},a.createElement("div",{className:"ps-modal is-narrow",onClick:m=>m.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},n.sessionGroupName.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:p,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{ref:o,className:"ps-modal-input",value:n.sessionGroupName.value,placeholder:n.sessionGroupName.placeholder,onChange:m=>t.setSessionGroupNameValue(m.currentTarget.value,m.currentTarget.selectionStart??m.currentTarget.value.length),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),t.handleCommand(C.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Ce(n.sessionGroupName.helpLines||[]).map((m,y)=>a.createElement(Ne,{key:`help:${y}`,line:m,theme:s,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:p},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(C.MODAL_CONFIRM).catch(()=>{})},"Create and Move"))));if(i.type==="terminatePicker"){const m=Number(i.bulkCount)>1,y=!!i.systemRestart,S=String(i.sessionTitle||"").trim()||"this session",E=Number(i.bulkCount)||0,I=m?`What should happen to the ${E} selected sessions? Choose an action; you'll be asked to confirm.`:y?`How should "${S}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${S}"? Choose an action; you'll be asked to confirm.`,w=b=>()=>{t.pickTerminateAction(b).catch(()=>{})};return a.createElement("div",{className:"ps-modal-backdrop",onClick:p},a.createElement("div",{className:"ps-modal is-narrow",onClick:b=>b.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},i.title||"Session Lifecycle"),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:p,"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}},I)),a.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},i.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:w("regenerate")},"Regenerate Context"):null,a.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:w("complete")},m?`Mark ${E} Completed`:y?"Complete & Restart":"Mark Completed"),a.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:w("cancel")},m?`Cancel ${E} Sessions`:y?"Terminate & Restart":"Cancel Session"),a.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:w("delete")},m?`Hard Delete ${E} Sessions`:y?"Hard Delete & Restart":"Delete Session")),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:p},"Close"))))}if(i.type==="artifactUpload"&&n.artifactUpload)return a.createElement("div",{className:"ps-modal-backdrop",onClick:p},a.createElement("div",{className:"ps-modal is-narrow",onClick:m=>m.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},n.artifactUpload.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:p,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{className:"ps-modal-input",value:n.artifactUpload.value,placeholder:n.artifactUpload.placeholder,onChange:m=>t.setArtifactUploadValue(m.currentTarget.value,m.currentTarget.selectionStart||m.currentTarget.value.length),autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Ce(n.artifactUpload.helpLines||[]).map((m,y)=>a.createElement(Ne,{key:`help:${y}`,line:m,theme:s,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:p},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(C.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const g=i.type==="logFilter"?n.logFilter:i.type==="filesFilter"?n.filesFilter:i.type==="historyFormat"?n.historyFormat:null;return g?a.createElement("div",{className:"ps-modal-backdrop",onClick:p},a.createElement("div",{className:"ps-modal is-wide",onClick:m=>m.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},g.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:p,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-filter-grid"},(i.items||[]).map((m,y)=>{const S=i.type==="filesFilter"?n.filesFilterState?.[m.id]||m.options?.[0]?.id:i.type==="historyFormat"?n.historyFormatState:n.logsFilter?.[m.id]||m.options?.[0]?.id;return a.createElement("div",{key:m.id||y,className:"ps-filter-column"},a.createElement("div",{className:"ps-filter-title"},m.label),(m.options||[]).map(E=>a.createElement("button",{key:E.id,type:"button",className:`ps-filter-option${E.id===S?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:y}),i.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:E.id}):i.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[m.id]:E.id}}),t.ensureFilesForScope(E.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[m.id]:E.id}})}},E.label)))})),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:p},"Done")))):null}function ey({controller:t,extras:e}){const s=Array.isArray(e.distillerModelOptions)?e.distillerModelOptions:[],n=s.find(u=>u.qualifiedName===e.distillerModel)||null,i=n?.supportedReasoningEfforts||[],r=n?.supportedContextTiers||[],o={color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8},l={flex:"1",padding:"4px 8px"},c=u=>t.updateConfirmExtras(u);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:u=>c({distillerModel:u.currentTarget.value,distillerEffort:"",distillerContextTier:""})},a.createElement("option",{value:""},"Deployment default"),s.map(u=>a.createElement("option",{key:u.qualifiedName,value:u.qualifiedName},u.qualifiedName)))),i.length>0?a.createElement("label",{style:o},"Reasoning",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerEffort||"",onChange:u=>c({distillerEffort:u.currentTarget.value})},a.createElement("option",{value:""},"Model default"),i.map(u=>a.createElement("option",{key:u,value:u},u)))):null,r.length>0?a.createElement("label",{style:o},"Context",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerContextTier||"",onChange:u=>c({distillerContextTier:u.currentTarget.value})},a.createElement("option",{value:""},"Model default"),r.map(u=>a.createElement("option",{key:u,value:u},u==="long_context"?"long context (fits a larger transcript)":u)))):null)}function ty(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=Ti(t),c=t.getState().ui.inspectorTab,u=t.getState().ui.focusRegion,d=!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=g=>{const m=Wh(l,c,g);t.selectInspectorTab(m).catch(()=>{})};if(!r&&p){n.preventDefault(),t.handleCommand(C.OPEN_THEME_PICKER).catch(()=>{});return}if(!r&&f){n.preventDefault(),t.handleCommand(C.OPEN_MODEL_PICKER).catch(()=>{});return}if(o&&!r){if(n.key==="Escape"||o.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(C.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||o.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(C.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(C.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(C.MODAL_PANE_NEXT).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(C.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(C.MODAL_NEXT).catch(()=>{}));return}if(!r){if(n.key==="r"&&d&&u!=="prompt"){n.preventDefault(),t.handleCommand(C.REFRESH).catch(()=>{});return}if(u==="chat"&&n.key==="s"&&d){n.preventDefault(),t.handleCommand(C.TOGGLE_CHAT_VIEW).catch(()=>{});return}if(n.key==="n"&&d){n.preventDefault(),t.handleCommand(C.NEW_SESSION).catch(()=>{});return}if(u==="inspector"&&c==="files"&&(n.key==="u"&&d||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(C.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="a"&&d){n.preventDefault(),t.handleCommand(C.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="x"&&d){n.preventDefault(),t.handleCommand(C.DELETE_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="o"&&d){n.preventDefault(),t.handleCommand(C.OPEN_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(C.OPEN_FILES_FILTER).catch(()=>{});return}if(u==="inspector"&&c==="stats"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(C.TOGGLE_STATS_VIEW).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="v"&&d){n.preventDefault(),t.handleCommand(C.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(u==="inspector"&&c==="logs"&&n.key==="t"&&d){n.preventDefault(),t.handleCommand(C.TOGGLE_LOG_TAIL).catch(()=>{});return}if(u==="inspector"&&c==="logs"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(C.OPEN_LOG_FILTER).catch(()=>{});return}if(u==="inspector"&&c==="history"&&n.key==="f"&&d){n.preventDefault(),t.handleCommand(C.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(u==="inspector"&&c==="history"&&n.key==="r"&&d){n.preventDefault(),t.handleCommand(C.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(u==="inspector"&&c==="history"&&n.key==="a"&&d){n.preventDefault(),t.handleCommand(C.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&d){n.preventDefault(),t.handleCommand(C.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&d){n.preventDefault(),t.handleCommand(C.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&d){n.preventDefault(),t.handleCommand(C.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&d){n.preventDefault(),t.handleCommand(C.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(C.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&d&&u==="inspector"){n.preventDefault(),h(1);return}if(n.key==="["&&d){n.preventDefault(),t.handleCommand(C.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&d){n.preventDefault(),t.handleCommand(C.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&d){n.preventDefault(),t.handleCommand(C.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&d){n.preventDefault(),t.handleCommand(C.GROW_SESSION_PANE).catch(()=>{});return}if(u==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),h(-1);return}if(u==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),h(1);return}if(u==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(C.MOVE_SESSION_UP).catch(()=>{});return}if(u==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(C.MOVE_SESSION_DOWN).catch(()=>{});return}if(u==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(C.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(u==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(C.PAGE_UP).catch(()=>{});return}if(u==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(C.PAGE_DOWN).catch(()=>{});return}if(u==="sessions"&&n.key==="t"&&d){n.preventDefault(),t.handleCommand(C.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(C.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(C.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&d){n.preventDefault(),t.handleCommand(C.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(C.SCROLL_BOTTOM).catch(()=>{});return}if(u!=="prompt"&&n.key==="h"&&d){n.preventDefault(),t.handleCommand(C.FOCUS_LEFT).catch(()=>{});return}if(u!=="prompt"&&n.key==="l"&&d){n.preventDefault(),t.handleCommand(C.FOCUS_RIGHT).catch(()=>{});return}if(!e&&u==="inspector"&&c==="files"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(C.MOVE_FILE_UP).catch(()=>{});return}if(!e&&u==="inspector"&&c==="files"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(C.MOVE_FILE_DOWN).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(C.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(C.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(C.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function sy(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 ny({controller:t,mobile:e=!1}){const s=ee(t,ep,Ge),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}}),u=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 $})},[]),d=a.useCallback(N=>{N.preventDefault(),document.body.style.cursor="col-resize";const B=N.clientX,$=l.navWidth??240,_=j=>u({navWidth:$+(j.clientX-B)}),L=()=>{window.removeEventListener("pointermove",_),window.removeEventListener("pointerup",L),window.removeEventListener("pointercancel",L),document.body.style.cursor=""};window.addEventListener("pointermove",_),window.addEventListener("pointerup",L),window.addEventListener("pointercancel",L)},[l.navWidth,u]);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]),g=a.useCallback(()=>{t.cancelAdminEditGhcpKey()},[t]),m=a.useCallback(()=>{t.clearAdminGhcpKey().catch(()=>{})},[t]),y=a.useCallback(N=>{N.preventDefault(),t.saveAdminGhcpKey().catch(()=>{})},[t]),S=a.useCallback(N=>{t.setAdminGhcpKeyDraft(N.target.value)},[t]),E=sy(s.principal),I=a.createElement("header",{className:"ps-admin-console__header"},a.createElement("h2",null,"Admin Console"),a.createElement("span",{className:"ps-admin-console__who"},E),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:p},"Close")),w=a.createElement(uy,{view:s,draftRef:n,onBeginEdit:h,onCancelEdit:g,onClear:m,onSubmit:y,onDraftChange:S,onRefresh:f,controller:t}),b=a.createElement(iy,{controller:t,view:s}),x=a.createElement(ry,{controller:t,view:s}),k=r&&i.selectedName?a.createElement(oy,{controller:t,view:s,layout:l,onLayout:u}):null,P=i.addDialog?.open?a.createElement(cy,{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"),x,k):r?N=b:o?N=a.createElement("div",{className:"ps-admin-mobile-stack"},b,a.createElement(No,{controller:t,view:s})):N=a.createElement("div",{className:"ps-admin-mobile-stack"},b,w),a.createElement("div",{className:"ps-admin-console is-mobile"},I,s.loadError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,N,P)}return a.createElement("div",{className:"ps-admin-console is-workspace"},I,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"},b,a.createElement("div",{className:"ps-admin-nav__resize",onPointerDown:d,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings column"})),a.createElement("div",{className:"ps-admin-main"},r?x:o?a.createElement(No,{controller:t,view:s}):w),k),P)}function No({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 iy({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(Yn,{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 ry({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 oy({controller:t,view:e,layout:s=null,onLayout:n=null}){const i=ee(t,p=>p.ui.themeId),r=De(i),o=e.packages?.workspace,l=a.useRef(null),c=a.useCallback((p,f)=>{if(!n)return;p.preventDefault();const h=p.clientX,g=p.clientY,m={...s},y=E=>f(m,E.clientX-h,E.clientY-g),S=()=>{window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",S),window.removeEventListener("pointercancel",S),document.body.style.cursor=""};window.addEventListener("pointermove",y),window.addEventListener("pointerup",S),window.addEventListener("pointercancel",S)},[s,n]),u=a.useCallback(p=>{document.body.style.cursor="col-resize",c(p,(f,h)=>n({wsWidth:f.wsWidth-h}))},[c,n]),d=a.useCallback(p=>{document.body.style.cursor="row-resize";const f=l.current?.getBoundingClientRect().height||600;c(p,(h,g,m)=>n({treePct:h.treePct+m/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:u}):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?d: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(ly,{file:o.file,theme:r}):null)):null}function ay(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 ly({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}=ay(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(Ys,{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,ss(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,ss(t.text||"",s,e))),n)}function cy({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),u=2*1024*1024,d=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(m=>({file:m,path:m.webkitRelativePath.split("/").slice(1).join("/")||m.name})).filter(({path:m})=>m&&!m.split("/").includes("node_modules")&&!m.split("/").includes(".git")),g=h.reduce((m,{file:y})=>m+y.size,0);if(h.length===0){t.failAdminAddPackage("The chosen folder has no uploadable files.");return}if(g>u){t.failAdminAddPackage(`Folder is ${(g/(1024*1024)).toFixed(1)} MB after filtering — the upload envelope is 2 MB. Use a repo/URL source or 'pilotswarm agents push' for larger packages.`);return}c(!0),Promise.all(h.map(({file:m,path:y})=>new Promise((S,E)=>{const I=new FileReader;I.onerror=()=>E(new Error(`could not read ${y}`)),I.onload=()=>S({path:y,contentBase64:String(I.result).split(",",2)[1]||""}),I.readAsDataURL(m)}))).then(m=>t.submitAdminUploadPackage(m,e.scope)).catch(m=>t.failAdminAddPackage(m?.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:d},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 uy({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:u=>c.setAdminGhcpKeyStoreAsSystem(u.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 py({transport:t,mode:e="remote",branding:s=null,docs:n=null}={}){tm();const i=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches,r=kf(vf,$n({mode:e,branding:s,docs:n,chatViewMode:i?"transcript":"rich"}));return new bh({store:r,transport:t})}function fy({controller:t}){const e=ee(t,M=>!!De(M.ui.themeId)?.richChat);a.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-rich-ui",e),()=>document.body.classList.remove("ps-rich-ui")},[e]);const s=a.useRef(null),n=a.useRef(null),i=uo(s),r=uo(n),o=cm(i);a.useEffect(()=>{const M=()=>{const X=document.createElement("span");X.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const z=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");z&&(X.style.font=window.getComputedStyle(z).font),X.textContent="0".repeat(100),(z?.parentElement||document.body).appendChild(X);const le=X.getBoundingClientRect().width/100||8;X.remove(),t.dispatch({type:"ui/viewport",width:Math.floor(window.innerWidth/le),height:Math.floor(window.innerHeight/et)})};M();let A;const F=()=>{clearTimeout(A),A=setTimeout(M,150)};return window.addEventListener("resize",F),window.addEventListener("orientationchange",F),()=>{clearTimeout(A),window.removeEventListener("resize",F),window.removeEventListener("orientationchange",F)}},[t]);const[l,c]=a.useState(!1),[u,d]=a.useState(null),p=ee(t,M=>({themeId:M.ui.themeId,ownerFilter:M.sessions.ownerFilter,pinnedIds:M.sessions.pinnedIds,manualOrder:M.sessions.manualOrder,collapsedSessionIds:M.sessions.collapsedIds,activeSessionId:M.sessions.activeSessionId||null,promptRows:ml(M),chatViewMode:M.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(M.sessions.activeSessionId&&M.sessions.byId[M.sessions.activeSessionId]?.isGroup),paneAdjust:M.ui.layout?.paneAdjust??0,sessionPaneAdjust:M.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:M.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:M.ui.layout?.activityPaneAdjust??0,focusRegion:M.ui.focusRegion,inspectorTab:M.ui.inspectorTab,filesFullscreen:!!M.files.fullscreen,selectedArtifactId:M.files.selectedArtifactId||null,adminVisible:!!M.admin?.visible}),Ge),f=a.useRef(!1),h=a.useRef(null),g=a.useRef(null),m=a.useRef(null),y=a.useRef(null),S=a.useRef(!1),E=a.useRef(!1),I=a.useRef(null),w=a.useRef(null),[b,x]=a.useState("workspace"),k=(i.width||window.innerWidth||0)<Rh,N=p.activeSessionIsGroup||p.chatViewMode==="summary"?0:p.promptRows;ty(t,k),a.useEffect(()=>{t.setViewport(o)},[t,o.height,o.width]),a.useEffect(()=>{let M=!0;f.current=!1,h.current=null,I.current=null,w.current=ao(t.getState()),m.current&&(clearTimeout(m.current),m.current=null),y.current&&(clearInterval(y.current),y.current=null),S.current=!1,E.current=!1;const A=t.transport;if(typeof A?.getCurrentUserProfile!="function"||typeof A?.setCurrentUserProfileSettings!="function")return f.current=!0,()=>{M=!1};const F=async()=>{if(!(!M||S.current)){S.current=!0;try{const X=await A.getCurrentUserProfile();if(!M)return;const z=mt(X?.profileSettings);ts(z[Ds()])&&(g.current=z[Ds()]),w.current=ao(t.getState(),g.current);const le=nm(X?.profileSettings,w.current),ge=JSON.stringify(le),we=kn(t.getState(),g.current),ke=JSON.stringify(we),Ue=f.current&&h.current!=null&&ke!==h.current,K=!!m.current||E.current||Ue;if(!K&&I.current!==ge&&(t.dispatch({type:"profileSettings/apply",settings:le}),I.current=ge),!f.current||!K){const Ee=kn(t.getState(),g.current);h.current=JSON.stringify(Ee)}f.current=!0}catch{if(!M)return;f.current=!0}finally{S.current=!1}}};return F().catch(()=>{}),y.current=setInterval(()=>{F().catch(()=>{})},Dh),()=>{M=!1,m.current&&(clearTimeout(m.current),m.current=null),y.current&&(clearInterval(y.current),y.current=null),S.current=!1}},[t]),a.useEffect(()=>{if(!f.current)return;const M=kn(p,g.current),A=JSON.stringify(M);h.current!==A&&(h.current=A,m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{m.current=null,E.current=!0,im(t,M).catch(()=>{}).finally(()=>{E.current=!1})},400))},[t,p.activeSessionId,p.activityPaneAdjust,p.chatViewMode,p.collapsedSessionIds,p.ownerFilter,p.paneAdjust,p.manualOrder,p.pinnedIds,p.portalSessionColumnAdjust,p.sessionPaneAdjust,p.themeId]),a.useEffect(()=>{lm(p.themeId)},[p.themeId]);const B=a.useRef(null);a.useEffect(()=>{const M=B.current;B.current=p.focusRegion,M!==null&&M!==p.focusRegion&&k&&p.focusRegion!=="prompt"&&x(p.focusRegion==="activity"?"activity":p.focusRegion==="inspector"?"inspector":"workspace")},[k,p.focusRegion]),a.useEffect(()=>{const M=Ti(t);!M.includes(p.inspectorTab)&&M.length>0&&t.selectInspectorTab(M[0]).catch(()=>{})},[t,p.inspectorTab]);const $=a.useMemo(()=>Jt(o,p.paneAdjust,N,p.sessionPaneAdjust,p.activityPaneAdjust),[o,p.activityPaneAdjust,p.paneAdjust,N,p.sessionPaneAdjust]),_=p.filesFullscreen&&p.inspectorTab==="files",L=p.inspectorTab==="files"&&!!p.selectedArtifactId&&!_;a.useEffect(()=>{!_||!l||(c(!1),d(null))},[l,_]);const j=a.useCallback(()=>{c(M=>{const A=!M;return A?t.setFocus("chat"):d(null),A})},[t]),q=a.useCallback(M=>{d(A=>{const F=A===M?null:M;return t.setFocus(F||"chat"),F})},[t]),se=Math.max(0,(i.width||0)*.68),ne=r.width||se,Re=rm(ne,p.portalSessionColumnAdjust),re=om(Re),be=re==="hidden"?"0px":`clamp(0px, calc(${Ci*100}% + ${Number(p.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,v=a.createElement("div",{className:"ps-workspace-grid",style:{gridTemplateColumns:`minmax(0, ${$.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${$.rightWidth}fr)`}},a.createElement("div",{ref:n,className:`ps-workspace-main-grid is-session-${re}`,style:{gridTemplateColumns:`${be} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},re!=="hidden"?a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},a.createElement(_i,{controller:t,structuredRows:!0})):null,a.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},a.createElement(Xg,{controller:t,portalSessionColumnAdjust:p.portalSessionColumnAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},a.createElement($i,{controller:t}))),a.createElement(Yg,{controller:t,paneAdjust:p.paneAdjust}),a.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`${$.inspectorPaneHeight}fr var(--ps-resizer-track, 16px) ${$.activityPaneHeight}fr`}},a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},$.inspectorHidden?null:a.createElement(Et,{controller:t,mobile:!1})),a.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},a.createElement(Qg,{controller:t,activityPaneAdjust:p.activityPaneAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},L?a.createElement(Li,{controller:t,focused:!1,previewOnly:!0}):$.activityHidden?null:a.createElement(ws,{controller:t})))),O=a.createElement(Kg,{controller:t,openPane:u,onTogglePane:q,onExitFocus:j,mobile:k}),D=a.createElement("div",{className:"ps-workspace-full"},a.createElement(Et,{controller:t,mobile:!1}));let U=null;return _&&!k?U=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(Et,{controller:t,mobile:!0})):b==="inspector"?U=p.inspectorTab==="nodes"?a.createElement("div",{className:"ps-mobile-pane-fill ps-mobile-node-split"},a.createElement(Et,{controller:t,mobile:!0}),a.createElement(ws,{controller:t,panelClassName:"ps-mobile-node-detail"})):a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(Et,{controller:t,mobile:!0})):b==="activity"?U=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(ws,{controller:t})):U=a.createElement(Ug,{controller:t}),a.createElement(xl.Provider,{value:t},a.createElement("div",{ref:s,className:"ps-web-shell"},k&&(l||b==="inspector"||b==="activity")?null:a.createElement(zg,{controller:t,mobile:k,chatFocusMode:l,onToggleChatFocus:j,chatFocusDisabled:_}),a.createElement("div",{className:"ps-workspace"},p.adminVisible?a.createElement(ny,{controller:t,mobile:k}):_?D:l?O:k?U:v),k&&!l?a.createElement(Jg,{activePane:b,setActivePane:x,controller:t}):null,k&&_?a.createElement(jg,{controller:t}):null,a.createElement(Zg,{controller:t})))}export{fy as P,a as R,al as _,Kl as a,De as b,py as c,tp as d,Gl as g,Po as r,dy as s};
|