pilotswarm 0.5.26 → 0.5.28
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 +1 -1
- package/ui/core/src/controller.js +66 -6
- package/ui/core/src/selectors.js +265 -13
- package/ui/react/src/web-app.js +527 -117
- package/web/dist/assets/{abnfDiagram-VRR7QNED-C4qRR7va.js → abnfDiagram-VRR7QNED-DLV45wH4.js} +1 -1
- package/web/dist/assets/{arc-BQw2V2pL.js → arc-CE4xAYdE.js} +1 -1
- package/web/dist/assets/{architectureDiagram-ZJ3FMSHR-DMdWnLGG.js → architectureDiagram-ZJ3FMSHR-DfzR8-9F.js} +1 -1
- package/web/dist/assets/{blockDiagram-677ZJIJ3-DZnALw8j.js → blockDiagram-677ZJIJ3-C2pZdqvH.js} +1 -1
- package/web/dist/assets/{c4Diagram-LMCZKHZV-BGGZ42iX.js → c4Diagram-LMCZKHZV-CKRspTan.js} +1 -1
- package/web/dist/assets/channel-D7p-E4El.js +1 -0
- package/web/dist/assets/{chunk-2Q5K7J3B-Dastiegd.js → chunk-2Q5K7J3B-CNjLrfHT.js} +1 -1
- package/web/dist/assets/{chunk-32BRIVSS-B4XexRzf.js → chunk-32BRIVSS-Bv5EwyaJ.js} +1 -1
- package/web/dist/assets/{chunk-5VM5RSS4-D66MNGCN.js → chunk-5VM5RSS4-NDBesEbJ.js} +1 -1
- package/web/dist/assets/{chunk-EX3LRPZG-DeqPS4Xm.js → chunk-EX3LRPZG-DHQht9ty.js} +1 -1
- package/web/dist/assets/{chunk-JWPE2WC7-DIMWiXpM.js → chunk-JWPE2WC7-r0OQpJRF.js} +1 -1
- package/web/dist/assets/{chunk-MOJQB5TN-vTyL0qgx.js → chunk-MOJQB5TN-fcwIDgtl.js} +1 -1
- package/web/dist/assets/{chunk-RYQCIY6F-C7U9MKGw.js → chunk-RYQCIY6F-x7XQlDO1.js} +1 -1
- package/web/dist/assets/{chunk-V7JOEXUC-BzPwQ7n3.js → chunk-V7JOEXUC-U8ZNVy1m.js} +1 -1
- package/web/dist/assets/{chunk-VR4S4FIN-CmDsyK3b.js → chunk-VR4S4FIN-DLEdPLcN.js} +1 -1
- package/web/dist/assets/{chunk-XXDRQBXY-ZJn6BaGL.js → chunk-XXDRQBXY-TeyAtB-i.js} +1 -1
- package/web/dist/assets/classDiagram-OUVF2IWQ-yFZ-1yMb.js +1 -0
- package/web/dist/assets/classDiagram-v2-EOCWNBFH-yFZ-1yMb.js +1 -0
- package/web/dist/assets/{cose-bilkent-JH36ORCC-CAA8JZZM.js → cose-bilkent-JH36ORCC-B3bAl1-Z.js} +1 -1
- package/web/dist/assets/{cynefin-VYW2F7L2-B6pX-lUD.js → cynefin-VYW2F7L2-DexP8nG-.js} +1 -1
- package/web/dist/assets/{cynefinDiagram-TSTJHNR4-sKTHU_UH.js → cynefinDiagram-TSTJHNR4-Doa2XnSs.js} +1 -1
- package/web/dist/assets/{dagre-VKFMJZFB-EuakJ578.js → dagre-VKFMJZFB-DZMBKQcJ.js} +1 -1
- package/web/dist/assets/{diagram-FQU43EPY-DR3M_pic.js → diagram-FQU43EPY-BkzibmSq.js} +1 -1
- package/web/dist/assets/{diagram-G47NLZAW-BlS6yM0u.js → diagram-G47NLZAW-CihyHR3a.js} +1 -1
- package/web/dist/assets/{diagram-NH7WQ7WH-CQNXe6dc.js → diagram-NH7WQ7WH-OMDUUxwW.js} +1 -1
- package/web/dist/assets/{diagram-OA4YK3LP-BizBeSQo.js → diagram-OA4YK3LP-Lc0imJba.js} +1 -1
- package/web/dist/assets/{diagram-WEI45ONY-C-_KM6Gg.js → diagram-WEI45ONY-Dlcy8hPe.js} +1 -1
- package/web/dist/assets/{ebnfDiagram-CCIWWBDH-BapWEdic.js → ebnfDiagram-CCIWWBDH-Dh3u17Dg.js} +1 -1
- package/web/dist/assets/{erDiagram-Q63AITRT-Btijn1Xj.js → erDiagram-Q63AITRT-C0OhlUC2.js} +1 -1
- package/web/dist/assets/{flowDiagram-23GEKE2U-D8zK8HkH.js → flowDiagram-23GEKE2U-CADKxT-x.js} +1 -1
- package/web/dist/assets/{ganttDiagram-NO4QXBWP-DyjkOIMW.js → ganttDiagram-NO4QXBWP-iVVdxWB7.js} +1 -1
- package/web/dist/assets/{gitGraphDiagram-IHSO6WYX-3r9_QeYN.js → gitGraphDiagram-IHSO6WYX-BwDUec_a.js} +1 -1
- package/web/dist/assets/index-BGWTu1KK.css +1 -0
- package/web/dist/assets/{index-CIt9PdC-.js → index-Djfdr7ts.js} +2 -2
- package/web/dist/assets/{infoDiagram-FWYZ7A6U-Ccd8ACUz.js → infoDiagram-FWYZ7A6U-CGPUif0s.js} +1 -1
- package/web/dist/assets/{ishikawaDiagram-FXEZZL3T-DPRUC8V2.js → ishikawaDiagram-FXEZZL3T-QYnrl-KA.js} +1 -1
- package/web/dist/assets/{journeyDiagram-5HDEW3XC-CkvayMsL.js → journeyDiagram-5HDEW3XC-CeKixxL0.js} +1 -1
- package/web/dist/assets/{kanban-definition-HUTT4EX6-CAK9Z-ha.js → kanban-definition-HUTT4EX6-CeYokFBS.js} +1 -1
- package/web/dist/assets/{linear-B-_ZjN2w.js → linear-BbA6_gnz.js} +1 -1
- package/web/dist/assets/{mermaid.core-BN9c--2r.js → mermaid.core--xGRoQTa.js} +4 -4
- package/web/dist/assets/{mindmap-definition-LN4V7U3C-DuD_AHRU.js → mindmap-definition-LN4V7U3C-D53u8h0z.js} +1 -1
- package/web/dist/assets/papaparse.min-BU0o7jXn.js +10 -0
- package/web/dist/assets/{pegDiagram-2B236MQR-Cc1v58KA.js → pegDiagram-2B236MQR-B7QSyG-3.js} +1 -1
- package/web/dist/assets/{pieDiagram-ENE6RG2P-Bc32--ur.js → pieDiagram-ENE6RG2P-XtSGL7GG.js} +1 -1
- package/web/dist/assets/pilotswarm-CtO819QH.js +94 -0
- package/web/dist/assets/{quadrantDiagram-ABIIQ3AL-DpPTc2EP.js → quadrantDiagram-ABIIQ3AL-LZoYSbTH.js} +1 -1
- package/web/dist/assets/{railroadDiagram-RFXS5EU6-DXMzwejw.js → railroadDiagram-RFXS5EU6-B5FREx2U.js} +1 -1
- package/web/dist/assets/{requirementDiagram-TGXJPOKE-B3ImAxw-.js → requirementDiagram-TGXJPOKE-1VRFkBQX.js} +1 -1
- package/web/dist/assets/{sankeyDiagram-HTMAVEWB-hmVMffE2.js → sankeyDiagram-HTMAVEWB-J456gWvu.js} +1 -1
- package/web/dist/assets/{sequenceDiagram-DBY2YBRQ-D53fk6uF.js → sequenceDiagram-DBY2YBRQ-CaCcw6KO.js} +1 -1
- package/web/dist/assets/{sizeCapture-X5ZJPWSS-4U-I5d2g.js → sizeCapture-X5ZJPWSS-DClsP3_O.js} +1 -1
- package/web/dist/assets/{stateDiagram-2N3HPSRC-0Y5TgWhW.js → stateDiagram-2N3HPSRC-D6VyrKhd.js} +1 -1
- package/web/dist/assets/stateDiagram-v2-6OUMAXLB-D7eKFhHb.js +1 -0
- package/web/dist/assets/{swimlanes-5IMT3BWC-Umhy4qUu.js → swimlanes-5IMT3BWC-q678iAuo.js} +2 -2
- package/web/dist/assets/swimlanesDiagram-G3AALYLV-DlVHQBQx.js +8 -0
- package/web/dist/assets/{timeline-definition-FHXFAJF6-D5hOg3Qu.js → timeline-definition-FHXFAJF6-WnPK_zhe.js} +1 -1
- package/web/dist/assets/{vennDiagram-L72KCM5P-QVIcE3UD.js → vennDiagram-L72KCM5P-WpumuLld.js} +1 -1
- package/web/dist/assets/{wardleyDiagram-EHGQE667-BEj1M2cB.js → wardleyDiagram-EHGQE667-CBrYLUm_.js} +1 -1
- package/web/dist/assets/{xychartDiagram-FW5EYKEG-xojRIXIf.js → xychartDiagram-FW5EYKEG-DbX1rnDW.js} +1 -1
- package/web/dist/index.html +3 -3
- package/web/dist/assets/channel-CB157dQ5.js +0 -1
- package/web/dist/assets/classDiagram-OUVF2IWQ-B6JwBYlv.js +0 -1
- package/web/dist/assets/classDiagram-v2-EOCWNBFH-B6JwBYlv.js +0 -1
- package/web/dist/assets/index-CT2_MRcC.css +0 -1
- package/web/dist/assets/pilotswarm-BgzdDy09.js +0 -93
- package/web/dist/assets/stateDiagram-v2-6OUMAXLB-DqIcGfAY.js +0 -1
- package/web/dist/assets/swimlanesDiagram-G3AALYLV-DA9txLi6.js +0 -8
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
function Ya(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ps={exports:{}},j={};var ci;function Qa(){if(ci)return j;ci=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),r=Symbol.for("react.consumer"),o=Symbol.for("react.context"),a=Symbol.for("react.forward_ref"),l=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),p=Symbol.iterator;function h(b){return b===null||typeof b!="object"?null:(b=p&&b[p]||b["@@iterator"],typeof b=="function"?b:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,S={};function y(b,O,G){this.props=b,this.context=O,this.refs=S,this.updater=G||m}y.prototype.isReactComponent={},y.prototype.setState=function(b,O){if(typeof b!="object"&&typeof b!="function"&&b!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,b,O,"setState")},y.prototype.forceUpdate=function(b){this.updater.enqueueForceUpdate(this,b,"forceUpdate")};function A(){}A.prototype=y.prototype;function x(b,O,G){this.props=b,this.context=O,this.refs=S,this.updater=G||m}var v=x.prototype=new A;v.constructor=x,g(v,y.prototype),v.isPureReactComponent=!0;var I=Array.isArray;function w(){}var C={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function R(b,O,G){var P=G.ref;return{$$typeof:t,type:b,key:O,ref:P!==void 0?P:null,props:G}}function F(b,O){return R(b.type,O,b.props)}function L(b){return typeof b=="object"&&b!==null&&b.$$typeof===t}function M(b){var O={"=":"=0",":":"=2"};return"$"+b.replace(/[=:]/g,function(G){return O[G]})}var $=/\/+/g;function D(b,O){return typeof b=="object"&&b!==null&&b.key!=null?M(""+b.key):O.toString(36)}function K(b){switch(b.status){case"fulfilled":return b.value;case"rejected":throw b.reason;default:switch(typeof b.status=="string"?b.then(w,w):(b.status="pending",b.then(function(O){b.status==="pending"&&(b.status="fulfilled",b.value=O)},function(O){b.status==="pending"&&(b.status="rejected",b.reason=O)})),b.status){case"fulfilled":return b.value;case"rejected":throw b.reason}}throw b}function z(b,O,G,P,k){var B=typeof b;(B==="undefined"||B==="boolean")&&(b=null);var H=!1;if(b===null)H=!0;else switch(B){case"bigint":case"string":case"number":H=!0;break;case"object":switch(b.$$typeof){case t:case e:H=!0;break;case f:return H=b._init,z(H(b._payload),O,G,P,k)}}if(H)return k=k(b),H=P===""?"."+D(b,0):P,I(k)?(G="",H!=null&&(G=H.replace($,"$&/")+"/"),z(k,O,G,"",function(Se){return Se})):k!=null&&(L(k)&&(k=F(k,G+(k.key==null||b&&b.key===k.key?"":(""+k.key).replace($,"$&/")+"/")+H)),O.push(k)),1;H=0;var V=P===""?".":P+":";if(I(b))for(var X=0;X<b.length;X++)P=b[X],B=V+D(P,X),H+=z(P,O,G,B,k);else if(X=h(b),typeof X=="function")for(b=X.call(b),X=0;!(P=b.next()).done;)P=P.value,B=V+D(P,X++),H+=z(P,O,G,B,k);else if(B==="object"){if(typeof b.then=="function")return z(K(b),O,G,P,k);throw O=String(b),Error("Objects are not valid as a React child (found: "+(O==="[object Object]"?"object with keys {"+Object.keys(b).join(", ")+"}":O)+"). If you meant to render a collection of children, use an array instead.")}return H}function Y(b,O,G){if(b==null)return b;var P=[],k=0;return z(b,P,"","",function(B){return O.call(G,B,k++)}),P}function Ie(b){if(b._status===-1){var O=b._result;O=O(),O.then(function(G){(b._status===0||b._status===-1)&&(b._status=1,b._result=G)},function(G){(b._status===0||b._status===-1)&&(b._status=2,b._result=G)}),b._status===-1&&(b._status=0,b._result=O)}if(b._status===1)return b._result.default;throw b._result}var Z=typeof reportError=="function"?reportError:function(b){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var O=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof b=="object"&&b!==null&&typeof b.message=="string"?String(b.message):String(b),error:b});if(!window.dispatchEvent(O))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",b);return}console.error(b)},xe={map:Y,forEach:function(b,O,G){Y(b,function(){O.apply(this,arguments)},G)},count:function(b){var O=0;return Y(b,function(){O++}),O},toArray:function(b){return Y(b,function(O){return O})||[]},only:function(b){if(!L(b))throw Error("React.Children.only expected to receive a single React element child.");return b}};return j.Activity=d,j.Children=xe,j.Component=y,j.Fragment=s,j.Profiler=i,j.PureComponent=x,j.StrictMode=n,j.Suspense=l,j.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=C,j.__COMPILER_RUNTIME={__proto__:null,c:function(b){return C.H.useMemoCache(b)}},j.cache=function(b){return function(){return b.apply(null,arguments)}},j.cacheSignal=function(){return null},j.cloneElement=function(b,O,G){if(b==null)throw Error("The argument must be a React element, but you passed "+b+".");var P=g({},b.props),k=b.key;if(O!=null)for(B in O.key!==void 0&&(k=""+O.key),O)!N.call(O,B)||B==="key"||B==="__self"||B==="__source"||B==="ref"&&O.ref===void 0||(P[B]=O[B]);var B=arguments.length-2;if(B===1)P.children=G;else if(1<B){for(var H=Array(B),V=0;V<B;V++)H[V]=arguments[V+2];P.children=H}return R(b.type,k,P)},j.createContext=function(b){return b={$$typeof:o,_currentValue:b,_currentValue2:b,_threadCount:0,Provider:null,Consumer:null},b.Provider=b,b.Consumer={$$typeof:r,_context:b},b},j.createElement=function(b,O,G){var P,k={},B=null;if(O!=null)for(P in O.key!==void 0&&(B=""+O.key),O)N.call(O,P)&&P!=="key"&&P!=="__self"&&P!=="__source"&&(k[P]=O[P]);var H=arguments.length-2;if(H===1)k.children=G;else if(1<H){for(var V=Array(H),X=0;X<H;X++)V[X]=arguments[X+2];k.children=V}if(b&&b.defaultProps)for(P in H=b.defaultProps,H)k[P]===void 0&&(k[P]=H[P]);return R(b,B,k)},j.createRef=function(){return{current:null}},j.forwardRef=function(b){return{$$typeof:a,render:b}},j.isValidElement=L,j.lazy=function(b){return{$$typeof:f,_payload:{_status:-1,_result:b},_init:Ie}},j.memo=function(b,O){return{$$typeof:u,type:b,compare:O===void 0?null:O}},j.startTransition=function(b){var O=C.T,G={};C.T=G;try{var P=b(),k=C.S;k!==null&&k(G,P),typeof P=="object"&&P!==null&&typeof P.then=="function"&&P.then(w,Z)}catch(B){Z(B)}finally{O!==null&&G.types!==null&&(O.types=G.types),C.T=O}},j.unstable_useCacheRefresh=function(){return C.H.useCacheRefresh()},j.use=function(b){return C.H.use(b)},j.useActionState=function(b,O,G){return C.H.useActionState(b,O,G)},j.useCallback=function(b,O){return C.H.useCallback(b,O)},j.useContext=function(b){return C.H.useContext(b)},j.useDebugValue=function(){},j.useDeferredValue=function(b,O){return C.H.useDeferredValue(b,O)},j.useEffect=function(b,O){return C.H.useEffect(b,O)},j.useEffectEvent=function(b){return C.H.useEffectEvent(b)},j.useId=function(){return C.H.useId()},j.useImperativeHandle=function(b,O,G){return C.H.useImperativeHandle(b,O,G)},j.useInsertionEffect=function(b,O){return C.H.useInsertionEffect(b,O)},j.useLayoutEffect=function(b,O){return C.H.useLayoutEffect(b,O)},j.useMemo=function(b,O){return C.H.useMemo(b,O)},j.useOptimistic=function(b,O){return C.H.useOptimistic(b,O)},j.useReducer=function(b,O,G){return C.H.useReducer(b,O,G)},j.useRef=function(b){return C.H.useRef(b)},j.useState=function(b){return C.H.useState(b)},j.useSyncExternalStore=function(b,O,G){return C.H.useSyncExternalStore(b,O,G)},j.useTransition=function(){return C.H.useTransition()},j.version="19.2.4",j}var ui;function Xr(){return ui||(ui=1,Ps.exports=Qa()),Ps.exports}var Xa=Xr();const c=Ya(Xa);var Os={exports:{}},ce={};var di;function Ja(){if(di)return ce;di=1;var t=Xr();function e(l){var u="https://react.dev/errors/"+l;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var f=2;f<arguments.length;f++)u+="&args[]="+encodeURIComponent(arguments[f])}return"Minified React error #"+l+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(){}var n={d:{f:s,r:function(){throw Error(e(522))},D:s,C:s,L:s,m:s,X:s,S:s,M:s},p:0,findDOMNode:null},i=Symbol.for("react.portal");function r(l,u,f){var d=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:d==null?null:""+d,children:l,containerInfo:u,implementation:f}}var o=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function a(l,u){if(l==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return ce.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,ce.createPortal=function(l,u){var f=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(e(299));return r(l,u,null,f)},ce.flushSync=function(l){var u=o.T,f=n.p;try{if(o.T=null,n.p=2,l)return l()}finally{o.T=u,n.p=f,n.d.f()}},ce.preconnect=function(l,u){typeof l=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,n.d.C(l,u))},ce.prefetchDNS=function(l){typeof l=="string"&&n.d.D(l)},ce.preinit=function(l,u){if(typeof l=="string"&&u&&typeof u.as=="string"){var f=u.as,d=a(f,u.crossOrigin),p=typeof u.integrity=="string"?u.integrity:void 0,h=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;f==="style"?n.d.S(l,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:d,integrity:p,fetchPriority:h}):f==="script"&&n.d.X(l,{crossOrigin:d,integrity:p,fetchPriority:h,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},ce.preinitModule=function(l,u){if(typeof l=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var f=a(u.as,u.crossOrigin);n.d.M(l,{crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&n.d.M(l)},ce.preload=function(l,u){if(typeof l=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var f=u.as,d=a(f,u.crossOrigin);n.d.L(l,f,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},ce.preloadModule=function(l,u){if(typeof l=="string")if(u){var f=a(u.as,u.crossOrigin);n.d.m(l,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else n.d.m(l)},ce.requestFormReset=function(l){n.d.r(l)},ce.unstable_batchedUpdates=function(l,u){return l(u)},ce.useFormState=function(l,u,f){return o.H.useFormState(l,u,f)},ce.useFormStatus=function(){return o.H.useHostTransitionStatus()},ce.version="19.2.4",ce}var fi;function Za(){if(fi)return Os.exports;fi=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(),Os.exports=Ja(),Os.exports}const el=c.createContext(null);function Me(){const t=c.useContext(el);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function q(t,e,s=Object.is){const n=c.useRef(e),i=c.useRef(s);n.current=e,i.current=s;const[r,o]=c.useState(()=>e(t.getState())),a=c.useRef(r);return c.useEffect(()=>{a.current=r},[r]),c.useEffect(()=>t.subscribe(l=>{const u=n.current(l);i.current(a.current,u)||(a.current=u,o(u))}),[t]),r}const pi=[". ",".. ","..."],hi=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function Jr(t,e=120){const[s,n]=c.useState(0);return c.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(r=>(r+1)%hi.length)},e);return()=>clearInterval(i)},[t,e]),t?hi[s]:""}function Zr(t,e=360){const[s,n]=c.useState(0);return c.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(r=>(r+1)%pi.length)},e);return()=>clearInterval(i)},[t,e]),t?pi[s]:""}function eo(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",ADMIN:"admin"},Ne=["sequence","logs","nodes","history","files","stats"],E={REFRESH:"refresh",NEW_SESSION:"newSession",OPEN_MODEL_PICKER:"openModelPicker",OPEN_SWITCH_MODEL_PICKER:"openSwitchModelPicker",OPEN_THEME_PICKER:"openThemePicker",OPEN_RENAME_SESSION:"openRenameSession",OPEN_SESSION_FILTER:"openSessionFilter",OPEN_TERMINATE_PICKER:"openTerminatePicker",OPEN_MOVE_TO_GROUP:"openMoveToGroup",CREATE_SESSION_GROUP:"createSessionGroup",OPEN_ARTIFACT_UPLOAD:"openArtifactUpload",TOGGLE_CHAT_VIEW:"toggleChatView",CLOSE_MODAL:"closeModal",MODAL_PREV:"modalPrev",MODAL_NEXT:"modalNext",MODAL_PANE_PREV:"modalPanePrev",MODAL_PANE_NEXT:"modalPaneNext",MODAL_CONFIRM:"modalConfirm",SEND_PROMPT:"sendPrompt",FOCUS_NEXT:"focusNext",FOCUS_PREV:"focusPrev",FOCUS_LEFT:"focusLeft",FOCUS_RIGHT:"focusRight",FOCUS_PROMPT:"focusPrompt",FOCUS_SESSIONS:"focusSessions",MOVE_SESSION_UP:"moveSessionUp",MOVE_SESSION_DOWN:"moveSessionDown",EXPAND_SESSION:"expandSession",COLLAPSE_SESSION:"collapseSession",NEXT_INSPECTOR_TAB:"nextInspectorTab",PREV_INSPECTOR_TAB:"prevInspectorTab",CYCLE_INSPECTOR_TAB:"cycleInspectorTab",GROW_LEFT_PANE:"growLeftPane",GROW_RIGHT_PANE:"growRightPane",GROW_SESSION_PANE:"growSessionPane",SHRINK_SESSION_PANE:"shrinkSessionPane",GROW_FOCUSED_PANE:"growFocusedPane",SHRINK_FOCUSED_PANE:"shrinkFocusedPane",OPEN_ARTIFACT_PICKER:"openArtifactPicker",OPEN_HELP:"openHelp",SEQUENCE_SELECT_PREV:"sequenceSelectPrev",SEQUENCE_SELECT_NEXT:"sequenceSelectNext",TOGGLE_SEQUENCE_TURN:"toggleSequenceTurn",TOGGLE_LOG_TAIL:"toggleLogTail",TOGGLE_STATS_VIEW:"toggleStatsView",OPEN_LOG_FILTER:"openLogFilter",OPEN_FILES_FILTER:"openFilesFilter",MOVE_FILE_UP:"moveFileUp",MOVE_FILE_DOWN:"moveFileDown",DOWNLOAD_SELECTED_FILE:"downloadSelectedFile",DELETE_SELECTED_FILE:"deleteSelectedFile",OPEN_SELECTED_FILE:"openSelectedFile",TOGGLE_FILE_PREVIEW_FULLSCREEN:"toggleFilePreviewFullscreen",TOGGLE_PANE_FULLSCREEN:"togglePaneFullscreen",SCROLL_UP:"scrollUp",SCROLL_DOWN:"scrollDown",PAGE_UP:"pageUp",PAGE_DOWN:"pageDown",EXPAND_HISTORY:"expandHistory",SCROLL_TOP:"scrollTop",SCROLL_BOTTOM:"scrollBottom",DONE_SESSION:"doneSession",CANCEL_SESSION:"cancelSession",STOP_TURN:"stopTurn",DELETE_SESSION:"deleteSession",REGENERATE_SESSION:"regenerateSession",PIN_SESSION:"pinSession",CYCLE_SESSION_VISIBILITY:"cycleSessionVisibility",OPEN_SHARE_SESSION:"openShareSession",TOGGLE_SELECT_MODE:"toggleSelectMode",TOGGLE_SESSION_SELECTION:"toggleSessionSelection",CLEAR_SESSION_SELECTION:"clearSessionSelection",OPEN_HISTORY_FORMAT:"openHistoryFormat",REFRESH_EXECUTION_HISTORY:"refreshExecutionHistory",EXPORT_EXECUTION_HISTORY:"exportExecutionHistory",OPEN_ADMIN_CONSOLE:"openAdminConsole",CLOSE_ADMIN_CONSOLE:"closeAdminConsole",ADMIN_REFRESH_PROFILE:"adminRefreshProfile",ADMIN_BEGIN_EDIT_GHCP_KEY:"adminBeginEditGhcpKey",ADMIN_CANCEL_EDIT_GHCP_KEY:"adminCancelEditGhcpKey",ADMIN_SAVE_GHCP_KEY:"adminSaveGhcpKey",ADMIN_CLEAR_GHCP_KEY:"adminClearGhcpKey"};function ut(t,e,s){const n=t.indexOf(e),r=((n===-1?0:n)+s+t.length)%t.length;return t[r]}function En(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 an(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 tl(t){const e=En(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function sl(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=En(t);return e==null?null:{text:`ctx ${an(t.currentTokens)}/${an(t.tokenLimit)} ${e}%`,color:tl(t)}}function nl(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 to(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function il(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function so(t,e,s={},n={}){if(!e)return null;const i=to(t)||{},r=il(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 rl(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 ${an(s.tokensRemoved)}`,color:"gray"}]:[]]}const ln=/\{(\/?)([a-z-]+)\}/g,ol={color:null,bold:!1,underline:!1},is=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,mi=/session:\/\/([A-Za-z0-9-]+)/g,al={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function ts(t){return{color:t.color,bold:t.bold,underline:t.underline}}function ll(t,e,s){const n=ts(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:al[i]||null,n}return n}function An(t){return String(t||"").replace(ln,"")}function no(t){const e=[],n=String(t||"").split(`
|
|
2
|
+
`);for(const i of n){const r=[];let o=ts(ol),a=0,l;for(;(l=ln.exec(i))!==null;){const[u,f,d]=l;l.index>a&&r.push({text:i.slice(a,l.index),...ts(o)}),o=ll(o,d,f==="/"),a=l.index+u.length}(a<i.length||r.length===0)&&r.push({text:i.slice(a),...ts(o)}),e.push(r),ln.lastIndex=0}return e}function te(t){return String(t||"").slice(0,8)}function io(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}function ro(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t);if(Number.isNaN(s.getTime()))return"";const n=s.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return s.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});const r=String(s.getDate()),o=s.toLocaleDateString("en-GB",{month:"short"}),a=s.getFullYear()===e.getFullYear()?"":String(s.getFullYear()).slice(-2);return`${r}${o}${a} ${n}`}catch{return""}}function ge(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t),n=s.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1});if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return n;const r=s.toLocaleDateString("en-GB",{month:"short",day:"numeric"}),o=s.getFullYear()===e.getFullYear()?"":` ${s.getFullYear()}`;return`${r}${o} ${n}`}catch{return""}}function gt(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 cl(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function ul(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function rs(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function gi(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!(rs(i)&&rs(n))}function dl(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!(rs(n)&&rs(i))}function yi(t,e,s){let n=s;for(;n<t.length;){const i=t.indexOf(e,n);if(i<0)return-1;if(dl(t,i,e))return i;n=i+e.length}return-1}function fl(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 pl(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function Ot(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 Ke(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 oo(t){return(t||[]).map(e=>e?.text||"").join("")}function ss(t){return Ce(oo(t))}function hl(t,e){const s=Math.max(0,Number(e)||0);if(s<=0)return[];const n=[];let i=s;for(const r of t||[]){if(i<=0)break;const o=String(r?.text||"");if(!o)continue;const a=Ut(o,i);a&&(n.push({...r,text:a}),i-=Ce(a))}return n}function ao(t,e){const s=Math.max(0,Number(e)||0),n=hl(t,s),i=ss(n),r=Math.max(0,s-i);return r>0&&n.push({text:" ".repeat(r),color:null,bold:!1,underline:!1}),n}function lo(t,e){const s=Math.max(1,Number(e)||1),n=[];let i=[],r=0;function o(){if(i.length===0){n.push([{text:"",color:null,bold:!1,underline:!1}]);return}n.push(i),i=[],r=0}for(const a of t||[]){let l=String(a?.text||"");if(l)for(;l.length>0;){const u=Math.max(1,s-r),f=Ut(l,u);if(!f)break;if(f.length===l.length||Ce(f)<u){i.push({...a,text:f}),r+=Ce(f),l=l.slice(f.length),r>=s&&o();continue}const d=f.lastIndexOf(" ");if(d>0&&(r>0||d>0)){const p=f.slice(0,d+1);i.push({...a,text:p}),r+=Ce(p),l=l.slice(p.length),o()}else i.push({...a,text:f}),r+=Ce(f),l=l.slice(f.length),r>=s&&o()}}return(i.length>0||n.length===0)&&o(),n}function Si(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function co(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 ml(t){const e=String(t||"");return is.lastIndex=0,[...e.matchAll(is)].map(s=>{const n=s[1],i=co(s[2]);return!n||!i?null:{sessionId:n,filename:i,uri:`artifact://${n}/${i}`}}).filter(Boolean)}function it(t){const e=String(t||"");if(!e)return e;is.lastIndex=0;const s=e.replace(is,(n,i,r,o,a)=>{if(a.slice(Math.max(0,o-2),o)==="](")return n;const l=co(r);return!i||!l?n:`[artifact: ${l}](artifact://${i}/${l}) (press a to download)`});return mi.lastIndex=0,s.replace(mi,(n,i)=>i?`[session: ${te(i)}](session://${i})`:n)}function Cn(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const r=pl(e,"`",n),o="`".repeat(r),a=ul(e,o,n+r);if(a>n+r-1){Ke(s,{type:"code",text:e.slice(n+r,a)}),n=a+r;continue}}if(e.startsWith("**",n)||e.startsWith("__",n)){const r=e.slice(n,n+2),o=gi(e,n,r)?yi(e,r,n+2):-1;if(o>n+2){Ke(s,{type:"strong",text:e.slice(n+2,o)}),n=o+2;continue}}if(e[n]==="["){const r=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(r){Ke(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);Ke(s,{type:"link",text:o,href:o}),n=r+1;continue}}if(e.startsWith("http://",n)||e.startsWith("https://",n)){let r=n;for(;r<e.length&&!/\s/u.test(e[r]||"");)r+=1;const{url:o,trailing:a}=fl(e.slice(n,r));if(o){Ke(s,{type:"link",text:o,href:o}),a&&Ke(s,{type:"text",text:a}),n=r;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&gi(e,n,e[n])){const r=e[n],o=yi(e,r,n+1);if(o>n+1){Ke(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)}Ke(s,{type:"text",text:e.slice(n,i)}),n=i}return s.length>0?s:[{type:"text",text:""}]}function gl(t=""){return Cn(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 Lt(t){const e=Cn(t),s=[];for(const n of e){if(n.type==="code"){Ot(s,n.text,{color:"cyan"});continue}if(n.type==="strong"){Ot(s,n.text,{bold:!0});continue}if(n.type==="em"){Ot(s,n.text,{underline:!0});continue}if(n.type==="link"){Ot(s,n.text,{color:"cyan",underline:!0,href:n.href});continue}Ot(s,n.text)}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function yt(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function St(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 os(t){return t.length>0&&t.every(e=>/^:?-+:?$/.test(String(e||"").replace(/\s+/g,"")))}function Ce(t){return Array.from(String(t||"")).length}function Ut(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 uo(t,e){const s=String(t||""),n=Math.max(0,e-Ce(s));return s+" ".repeat(n)}function fo(t){return oo(Lt(t))}function yl(t,e){const s=fo(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),i=[];let r="";const o=a=>{let l=a;for(;Ce(l)>e;){const u=Ut(l,e);if(!u)break;r&&(i.push(r),r=""),i.push(u),l=l.slice(u.length)}return l};for(const a of n){const l=o(a);if(!l)continue;if(!r){r=l;continue}const u=`${r} ${l}`;Ce(u)<=e?r=u:(i.push(r),r=l)}return r&&i.push(r),i.length>0?i:[""]}function Sl(t,e){const s=Math.max(1,...t.map(f=>f.length)),n=Math.max(s*3,e-(s*3+1)),i=Array.from({length:s},(f,d)=>Math.max(3,...t.map(p=>Ce(p[d]||"")))),r=Array.from({length:s},(f,d)=>Math.max(3,...t.map(p=>Math.max(0,...String(p[d]||"").split(/\s+/).filter(Boolean).map(h=>Ce(h)))))),o=Array.from({length:s},(f,d)=>Math.max(3,Math.min(Math.max(Ce(t[0]?.[d]||"")||3,r[d]),24)));if(i.reduce((f,d)=>f+d,0)<=n)return i;const l=o.slice();let u=n-l.reduce((f,d)=>f+d,0);if(u<0){const f=Math.max(3,Math.floor(n/s));return l.map((d,p)=>p===s-1?Math.max(3,n-f*(s-1)):f)}for(;u>0;){let f=0,d=-1/0;for(let p=0;p<s;p++){const h=i[p]-l[p];h>d&&(d=h,f=p)}if(d<=0){l[s-1]+=u;break}l[f]+=1,u-=1}return l}function bl(t,e){if(!t||t.length===0)return"";const s=Math.max(1,...t.map(p=>p.length)),i=t.map(p=>Array.from({length:s},(h,m)=>p[m]||"")).map(p=>p.map(h=>fo(h))),r=Sl(i,e),o=[],a=`┌${r.map(p=>"─".repeat(p+2)).join("┬")}┐`,l=`├${r.map(p=>"─".repeat(p+2)).join("┼")}┤`,u=`└${r.map(p=>"─".repeat(p+2)).join("┴")}┘`,f=p=>{const h=p.map((g,S)=>yl(g,r[S])),m=Math.max(...h.map(g=>g.length));for(let g=0;g<m;g++){const S=h.map((y,A)=>uo(y[g]||"",r[A]));o.push(`│ ${S.join(" │ ")} │`)}};o.push(a),f(i[0]),o.push(l);const d=i.slice(1);for(const p of d)f(p);return o.push(u),o.join(`
|
|
3
|
+
`)}function wl(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 l=s[r+1];if(!yt(o)||!yt(l)){n.push(o);continue}const u=St(o),f=St(l);if(!os(f)||u.length!==f.length){n.push(o);continue}const d=[u];for(r+=1;r+1<s.length&&yt(s[r+1]);){r+=1;const p=St(s[r]);os(p)||d.push(p)}n.push(bl(d,e))}return n.join(`
|
|
5
|
+
`)}function Il(t,e){const s=String(t||"");if(!s)return[""];const n=[];let i=s;for(;i.length>0;){const r=Ut(i,e);if(!r)break;n.push(r),i=i.slice(r.length)}return n.length>0?n:[""]}function bi(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",i=Ut(n,Math.max(1,s-4)),r=Math.max(0,s-i.length-2);return[{text:`┌${i}${"─".repeat(r)}┐`,color:"gray"}]}function wi(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function Ii(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),i=[];for(const r of t){const o=Il(r,n);for(const a of o)i.push([{text:"│",color:"gray"},{text:uo(a,n),color:"cyan"},{text:"│",color:"gray"}]);o.length===0&&i.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}])}return i.length===0&&i.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}]),i}function Et(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),i=e.tableMode==="sentinel"?"sentinel":"boxArt",o=(i==="boxArt"?wl(String(t||""),n):String(t||"")).split(`
|
|
6
|
+
`);let a=!1,l="",u=[];for(let f=0;f<o.length;f+=1){const d=o[f],p=d.trim();if(p.startsWith("```")){a?(s.push(bi(l,Math.max(8,n))),s.push(...Ii(u,Math.max(8,n))),s.push(wi(Math.max(8,n))),a=!1,l="",u=[]):(a=!0,l=p.slice(3).trim(),u=[]);continue}if(a){u.push(d);continue}if(i==="sentinel"&&d&&yt(d)){const y=o[f+1]||"";if(yt(y)){const A=St(d),x=St(y);if(os(x)&&A.length===x.length){const v=[];let I=f+2;for(;I<o.length&&yt(o[I]);){const w=St(o[I]);os(w)||v.push(w),I+=1}s.push({kind:"markdownTable",header:A,rows:v}),f=I-1;continue}}}if(!d){s.push([{text:"",color:null}]);continue}const h=/^(#{1,6})\s+(.*)$/.exec(d);if(h){s.push([{text:h[2],color:"white",bold:!0}]);continue}const m=/^>\s?(.*)$/.exec(d);if(m){s.push([{text:"> ",color:"gray"},...Lt(m[1]).map(y=>({...y,color:y.color||"gray"}))]);continue}const g=/^\s*[-*]\s+(.*)$/.exec(d);if(g){s.push([{text:"• ",color:"gray"},...Lt(g[1])]);continue}const S=/^\s*(\d+)\.\s+(.*)$/.exec(d);if(S){s.push([{text:`${S[1]}. `,color:"gray"},...Lt(S[2])]);continue}s.push(Lt(d))}return a&&(s.push(bi(l,Math.max(8,n))),s.push(...Ii(u,Math.max(8,n))),s.push(wi(Math.max(8,n)))),s}function re({title:t="SYSTEM",timestamp:e="",body:s="",width:n=80,titleColor:i="yellow",borderColor:r="gray",bodyColor:o=null,fitToContent:a=!1,tableMode:l=null}={}){const u=Math.max(a?12:20,Number(n)||(a?12:20)),f=Math.max(1,u-4),d=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:i,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]];if(l==="sentinel"){const x=Et(String(s||""),{width:f,tableMode:l}),v=o?x.map(I=>Array.isArray(I)?Si(I,o):I):x;return[{kind:"cardStart",runs:d,borderColor:r},...v,{kind:"cardEnd"},[{text:"",color:null}]]}const p=Et(String(s||""),{width:f}),h=p.length>0?p.flatMap(x=>lo(x,f)):[[{text:"",color:null}]],m=o?h.map(x=>Si(x,o)):h,g=m.reduce((x,v)=>Math.max(x,ss(v)),0),S=a?Math.min(u,Math.max(12,ss(d)+3,g+4)):u,y=Math.max(1,S-4),A=Math.max(0,S-ss(d)-3);return[[{text:"┌─",color:r},...d,{text:`${"─".repeat(A)}┐`,color:r}],...m.map(x=>[{text:"│ ",color:r},...ao(x,y),{text:" │",color:r}]),[{text:`└${"─".repeat(Math.max(1,S-2))}┘`,color:r}],[{text:"",color:null}]]}function kt(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 po(t){const e=kt(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}const ee=300,xl=[ee,1e3,3e3,1e4],vl=["user.message","assistant.message","system.message","session.epoch_committed","session.regenerate_refused","session.regenerate_failed"];function ho(t){const e=t?.data&&typeof t.data=="object"?t.data:{},s=Number.isFinite(e.toEpoch)?e.toEpoch:Number(e.epoch)||0,n=Number.isFinite(e.turnsArchived)?e.turnsArchived:null;return{id:`${t.sessionId}:${t.seq}:epoch`,kind:"epoch-divider",role:"epoch-divider",epoch:s,turnsArchived:n,time:ge(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function mo(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:ge(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function go(t){const e=t?.data&&typeof t.data=="object"?t.data:{},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:ge(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function ve(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(ee,Number(e)||ee);return s.length>n?s.slice(-n):s}function We(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 yo=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,El=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function Tn(t){return yo.test(We(t))}function ze(t){const e=String(t||"").replace(/\r\n/g,`
|
|
8
|
+
`).trim();if(!e)return"";const s=e.replace(El,"").trimStart();return s!==e?s.trim():Tn(e)?e.replace(yo,"").trim():e}function So(t){const e=String(t||"").replace(/\r\n/g,`
|
|
9
|
+
`).split(`
|
|
10
|
+
`),s=[];let n=[];function i(){n.length!==0&&(s.push({kind:"text",text:n.join(`
|
|
11
|
+
`)}),n=[])}for(let r=0;r<e.length;){const o=e[r];if(!/^\s*\[SYSTEM:/i.test(o)){n.push(o),r+=1;continue}const a=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(o);if(a){i(),s.push({kind:"system",text:a[1].trim()}),r+=1;continue}const l=[o.replace(/^\s*\[SYSTEM:\s*/i,"")];let u=-1;for(let f=r+1;f<e.length;f+=1){const d=e[f];if(d.trim()==="]"){u=f;break}if(/\]\s*$/.test(d.trim())){const p=d.replace(/\]\s*$/,"");p.trim()&&l.push(p),u=f;break}l.push(d)}if(u===-1){n.push(o),r+=1;continue}i(),s.push({kind:"system",text:l.join(`
|
|
12
|
+
`).trim()}),r=u+1}return i(),s}function bo(t,e){const s=String(t||"").replace(/\r\n/g,`
|
|
13
|
+
`);return e==="user"||e==="assistant"?So(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
|
|
14
|
+
`).trim():s.trim()}function Al(t,e){return e!=="user"&&e!=="assistant"?[]:So(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function vi(t){const e=We(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=bo(e,t.role);if(s)return s}return ze(e)}function Is(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 Cl(t){return We(An(t)).length>0}function Tl(t){const e=We(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 kl(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(We(t))}function dt(t,e){const s=String(t||""),n=`${e}=`,i=s.indexOf(n);if(i<0)return"";const r=s.slice(i+n.length),o=[" request_id="," from="," subject="," reason="," expects_response="," expires_at="," verdict="];let a=r.length;for(const l of o){const u=r.indexOf(l);u>=0&&(a=Math.min(a,u))}return r.slice(0,a).trim()}function Ml(t,e){const s=We(e);if(!s)return null;const n=/^\[SESSION_MESSAGE\s+([^\]]+)\]\n?/i.exec(s);if(n){const r=n[1],o=`
|
|
17
|
+
Request body:
|
|
18
|
+
`,a=s.indexOf(o),l=a>=0?s.slice(a+o.length).trim():s.slice(n[0].length).trim(),u=dt(r,"request_id"),f=dt(r,"from"),d=dt(r,"subject"),p=/\bexpects_response=true\b/i.test(r),h=[f?`From: session-${te(f)}`:"",u?`Request ID: ${u}`:"",d?`Subject: ${d}`:"",p?"Response: required":"Response: not required","",l].filter((m,g)=>g===4||String(m||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:h.join(`
|
|
19
|
+
`),time:ge(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:p?"Session Request":"Session Message",cardTitleColor:"cyan",cardBorderColor:"cyan"}}const i=/^\[SESSION_MESSAGE_RESPONSE\s+([^\]]+)\]\n?/i.exec(s);if(i){const r=i[1],o=/^This is the requested cross-session response\.[^\n]*\n\n?/i,a=s.slice(i[0].length).trim().replace(o,"").trim(),l=dt(r,"request_id"),u=dt(r,"from"),f=dt(r,"verdict")||"answered",d=[u?`From: session-${te(u)}`:"",l?`Request ID: ${l}`:"",`Verdict: ${f}`,"",a].filter((p,h)=>h===3||String(p||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:d.join(`
|
|
20
|
+
`),time:ge(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 Nl(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&Tl(s)?"system":e}function Pl(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 Ol(t,e){if(!t||!e||t.role!==e.role)return!1;const s=vi(t),n=vi(e);if(!s||!n||s!==n)return!1;const i=Pl(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 bt(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!Ol(n,s)){e.push(s);continue}if(n?.optimistic&&!s?.optimistic){e[e.length-1]=s;continue}if(!n?.optimistic&&s?.optimistic)continue;const i=Number(n?.createdAt||0),r=Number(s?.createdAt||0),o=r>=i?s:n;if(o.role==="user"&&!n?.optimistic&&!s?.optimistic){const a=Math.min(Number(n?.firstDeliveredAt||i||1/0),Number(s?.firstDeliveredAt||r||1/0));e[e.length-1]={...o,redelivered:!0,...Number.isFinite(a)?{firstDeliveredAt:a}:{}};continue}e[e.length-1]=o}return e}function _l(t){return typeof t=="string"?t.replace(/^\[FROM:[^\]\n]*\]\n?/,""):t}function wt(t,e){const s=Mt(t),n=Ml(t,s);if(n)return n;const i=_l(bo(s,e));if(!Cl(i))return null;const r=Array.isArray(t?.data?.clientMessageIds)?t.data.clientMessageIds.filter(l=>typeof l=="string"&&l):[],o=t?.data?.sender&&typeof t.data.sender=="object"?t.data.sender:null,a=Array.isArray(t?.data?.attachments)?t.data.attachments.filter(l=>l&&typeof l.filename=="string"&&l.filename):[];return{id:`${t.sessionId}:${t.seq}`,role:Nl(t,e,i),text:i,time:ge(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...r.length>0?{clientMessageIds:r}:{},...o?{sender:o}:{},...a.length>0?{attachments:a}:{}}}function wo(t){return t?.eventType!=="system.message"?!1:!kl(Mt(t))}function as(t,e){return Al(Mt(t),e).map((s,n)=>Gt({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function Rl(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=We(e.text),n=Is(e.text),i=n?We(n.answer):"";let r=!1;return t.filter(o=>{if(r||!o?.optimistic||o.role!==e.role)return!0;const a=We(o.text);return a!==s&&a!==i?!0:(r=!0,!1)})}function Mt(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 cl(e)}function Ll(t){return(t||[]).map(e=>e?.text||"").join("")}function $l(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function kn(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 Fl(t,e=""){return kn([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function Bl(t,e=""){return kn([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function Dl(t,e=""){const s=Mt(t),n=ze(e);return kn([ze(s),n,t?.data?.detail,t?.data?.message])}function Hl(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 Gl(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}=${Hl(r)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function Mn(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function se(t,e,s,n="",i="white"){return[...Mn(t),{text:e,color:s},...n?[{text:` ${n}`,color:i}]:[]]}function jl(t,e=96){return $l(An(Mt(t)),e)||""}function _s(t,e,s="start"){const n=typeof e?.data?.toolCallId=="string"?e.data.toolCallId:"",i=typeof e?.data?.requestId=="string"?e.data.requestId:"",r=e?.data?.toolName||e?.data?.name||(n?`tool call ${n.slice(0,8)}`:i?`tool request ${i.slice(0,8)}`:"tool"),o=e?.data?.arguments||e?.data?.args,a=e?.data?.durableSessionId,l=Gl(r,o),u=s==="start"?"▶":s==="partial"?"…":"✓",f=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...Mn(t),{text:`${u} ${r}${l}`,color:f},...a?[{text:` [sess ${te(a)}]`,color:"gray"}]:[]]}function Gt(t){const e=ge(t.createdAt),s=jl(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=_s(e,t,"start");break;case"tool.execution_complete":n=_s(e,t,"complete");break;case"tool.execution_partial_result":n=_s(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=se(e,"[tool]","cyan",`${r} ${o}`,"white");break}case"assistant.reasoning":n=se(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=se(e,"[intent]","gray",r||"…","white");break}case"assistant.turn_start":n=se(e,"[turn start]","gray",s);break;case"session.turn_completed":n=se(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=se(e,"[lossy handoff]","yellow",Bl(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=se(e,"[dehydrated]","cyan",Fl(t,s));break;case"session.hydrated":case"session.rehydrated":n=se(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=se(e,"[wait]","yellow",`${i}${o}${r}`.trim());break}case"session.input_required_started":n=se(e,"[input]","yellow",s);break;case"session.agent_spawned":n=se(e,"[spawn]","cyan",t?.data?.agentId||te(t?.data?.childSessionId),"white");break;case"session.cron_started":n=se(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=se(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=se(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=se(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=se(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=se(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=se(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=se(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.compaction_start":case"session.compaction_complete":n=rl(e,t.eventType,t.data||{});break;case"session.error":n=se(e,"[error]","red",s||"session error","white");break;case"system.message":Tn(Mt(t))?n=se(e,"[rehydrated]","green",Dl(t,s)||"conversation preserved"):n=se(e,"[system]","gray",s||"system message");break;default:n=[...Mn(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:Ll(n),line:n}}function Ul(t=ee){const e=Math.max(ee,Number(t)||ee);return xl.find(n=>n>e)||Math.min(1e5,e*2)}function zt(t=[],e={}){const s=Math.max(ee,Number(e.requestedLimit??e.eventLimit??ee)||ee),n=[],i=[],r=[];for(const o of t){if(r.push(o),o.eventType==="user.message"){i.push(...as(o,"user"));const l=wt(o,"user");l&&n.push(l);continue}if(o.eventType==="assistant.message"){i.push(...as(o,"assistant"));const l=wt(o,"assistant");l&&n.push(l);continue}if(o.eventType==="system.message"){if(wo(o)){const l=Gt(o);l&&i.push(l)}else{const l=wt(o,"system");l&&n.push(l)}continue}if(o.eventType==="session.epoch_committed"){n.push(ho(o));continue}if(o.eventType==="session.regenerate_refused"){n.push(mo(o));continue}if(o.eventType==="session.regenerate_failed"){n.push(go(o));continue}const a=Gt(o);a&&i.push(a)}return{chat:bt(n),activity:i,events:r.slice(-s),loadedEventLimit:s,loadedEventCount:r.length,hasOlderEvents:r.length>=s}}function Ei(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max(ee,Number(t?.loadedEventLimit??ee)||ee),i=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),r={chat:ve(t?.chat||[],n),activity:ve(t?.activity||[],n),events:i,lastSeq:e.seq,loadedEventLimit:n,loadedEventCount:Math.max(Number(t?.loadedEventCount||0),i.length),hasOlderEvents:!!t?.hasOlderEvents,stoppedMessageIds:Array.isArray(t?.stoppedMessageIds)?t.stoppedMessageIds:[]};if(e.eventType==="session.turn_stopped"){const a=Array.isArray(e?.data?.clientMessageIds)?e.data.clientMessageIds.filter(l=>typeof l=="string"&&l):[];if(a.length>0){const l=new Set([...r.stoppedMessageIds,...a]);r.stoppedMessageIds=Array.from(l),r.chat=r.chat.map(u=>Array.isArray(u.clientMessageIds)&&u.clientMessageIds.some(f=>l.has(f))?{...u,stopped:!0}:u)}return r}if(e.eventType==="user.message"){r.activity.push(...as(e,"user")),r.activity=ve(r.activity,n);const a=wt(e,"user");return a&&(Array.isArray(a.clientMessageIds)&&a.clientMessageIds.some(l=>r.stoppedMessageIds.includes(l))&&(a.stopped=!0),r.chat=Rl(r.chat,a),r.chat.push(a),r.chat=ve(bt(r.chat),n)),r}if(e.eventType==="assistant.message"){r.activity.push(...as(e,"assistant")),r.activity=ve(r.activity,n);const a=wt(e,"assistant");return a&&(r.chat.push(a),r.chat=ve(bt(r.chat),n)),r}if(e.eventType==="system.message"){if(wo(e)){const a=Gt(e);a&&(r.activity.push(a),r.activity=ve(r.activity,n))}else{const a=wt(e,"system");if(!a)return r;r.chat.push(a),r.chat=ve(bt(r.chat),n)}return r}if(e.eventType==="session.epoch_committed")return r.chat.push(ho(e)),r.chat=ve(r.chat,n),r;if(e.eventType==="session.regenerate_refused")return r.chat.push(mo(e)),r.chat=ve(r.chat,n),r;if(e.eventType==="session.regenerate_failed")return r.chat.push(go(e)),r.chat=ve(r.chat,n),r;const o=Gt(e);return o&&(r.activity.push(o),r.activity=ve(r.activity,n)),r}function Rs(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?kt(e,t?.title||"PilotSwarm"):e?.title||t?.title||"PilotSwarm",a="{gray-fg}Start interacting with this session to replace the splash screen.{/gray-fg}";return[{id:`splash:${o}`,role:"system",text:`${n}
|
|
21
|
+
|
|
22
|
+
${a}`,...r?{mobileText:`${r}
|
|
23
|
+
|
|
24
|
+
${a}`}:{},time:"",splash:!0}]}const Wl=.7,Kl=30,Ai=36,Ls=18,$s=18,Fs=0,Io=3,At=6,xs=10,Vl=.25,ql=.5,It=6,ls=10,xo=.336,Bs=It,Ds=ls,Hs=At,Gs=xs;function $t(t,e,s){return Math.max(e,Math.min(s,t))}function zl(t){return[T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY].includes(t)?t:null}function Yl(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function xt(t=""){const e=String(t||"").split(`
|
|
25
|
+
`).length;return $t(e,1,Io)}function vo(t){return Math.max(At,Math.floor(t*Vl))}function Eo(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*ql),n=Math.max(At,e-xs);return Math.max(At,Math.min(n,s))}function Dt(t,e=0,s=1,n=0,i=0,r=null){const o=Yl(t),a=o.width,l=o.height,u=$t(Number(s)||1,1,Io),f=zl(r),d=5+u,p=Math.max(18,l-d),m=Math.floor(a*Wl)+(Number(e)||0),g=a-m-Fs;let S=!1,y=!1;m<=Ls&&g>$s?S=!0:g<=$s&&m>Ls?y=!0:m<=Ls&&g<=$s&&(y=e>=0,S=!y);let A,x;S?(A=0,x=a):y?(A=a,x=0):(A=$t(m,Kl,a-Ai-Fs),x=Math.max(Ai,a-A-Fs));const I=vo(p)+(Number(n)||0),w=p-I;let C=!1,N=!1;w<=Gs&&I>Hs?N=!0:I<=Hs&&w>Gs?C=!0:w<=Gs&&I<=Hs&&(N=(Number(n)||0)>=0,C=!N);let R,F;if(C)R=0,F=p;else if(N)R=p,F=0;else{const Ie=Eo(l,p);R=$t(I,At,Ie),F=Math.max(xs,p-R)}const M=Math.max(It,Math.floor(p*xo))+(Number(i)||0),$=p-M;let D=!1,K=!1;$<=Ds&&M>Bs?D=!0:M<=Bs&&$>Ds?K=!0:$<=Ds&&M<=Bs&&(D=(Number(i)||0)>=0,K=!D);let z,Y;return D?(z=p,Y=0):K?(Y=p,z=0):(z=$t(M,It,Math.max(It,p-ls)),Y=Math.max(ls,p-z)),{viewport:o,totalWidth:a,totalHeight:l,reservedRows:d,bodyHeight:p,promptRows:u,fullscreenPane:f,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(i)||0,leftHidden:S,rightHidden:y,inspectorHidden:D,activityHidden:K,sessionHidden:C,chatHidden:N,leftWidth:A,rightWidth:x,sessionPaneHeight:R,chatPaneHeight:F,activityPaneHeight:z,inspectorPaneHeight:Y}}function cn(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 He(t,e){const s=cn(e);return s.includes(t)?t:s[0]||T.PROMPT}function Ql(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 Xl(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 Ci(t){return t?.isSystem?po(t):Number.MAX_SAFE_INTEGER}function Jl(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 Zl(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return Jl(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 ec(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Ti(t,e){return!!(ec(t)&&e&&e.has(t.sessionId))}function ki(t,e){return t.isSystem?0:t.isGroup&&Ti(t,e)?1:Ti(t,e)?2:t.isGroup?3:4}function Mi(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function Ni(t,e,s,n){const i=ki(t,n),r=ki(e,n);if(i!==r)return i-r;const o=Ci(t),a=Ci(e);if(o!==a)return o-a;const l=s.get(t.sessionId),u=s.get(e.sessionId);if(typeof l=="number"&&typeof u=="number"&&l!==u)return l-u;const f=Mi(t),d=Mi(e);if(f>0&&d>0&&f!==d)return d-f;const p=(e.createdAt||0)-(t.createdAt||0);if(p!==0)return p;const h=String(t.title||""),m=String(e.title||""),g=h.localeCompare(m);return g!==0?g:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function je(t=[],e=new Set,s=[],n=null){const i=new Map,r=new Map,o=Zl(s),a=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const d of t)i.set(d.sessionId,d);for(const d of t){const p=!d.isGroup&&d.groupId&&!d.parentSessionId&&i.has(`group:${d.groupId}`)?`group:${d.groupId}`:null,h=d.parentSessionId||p;!h||!i.has(h)||(r.has(h)||r.set(h,[]),r.get(h).push(d))}for(const d of r.values())d.sort((p,h)=>Ni(p,h,o,a));const l=t.filter(d=>!(d.parentSessionId&&i.has(d.parentSessionId)||!d.isGroup&&d.groupId&&!d.parentSessionId&&i.has(`group:${d.groupId}`))).sort((d,p)=>Ni(d,p,o,a)),u=[];function f(d,p){const h=r.get(d.sessionId)||[];if(u.push({sessionId:d.sessionId,depth:p,hasChildren:h.length>0,collapsed:e.has(d.sessionId)}),!e.has(d.sessionId))for(const m of h)f(m,p+1)}for(const d of l)f(d,0);return u}function tc(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function js(t){return Number.parseInt(t,16)/255}function sc(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 Us(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function nc(t){const e=sc(t);if(!e)return 0;const s=Us(js(e.slice(1,3))),n=Us(js(e.slice(3,5))),i=Us(js(e.slice(5,7)));return .2126*s+.7152*n+.0722*i}function ic(t){const e=t?.page?.background||t?.tui?.background||t?.terminal?.background;return nc(e)>=.5}function oe({id:t,label:e,description:s,page:n,terminal:i,tui:r={}}){const o={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 tc({id:t,label:e,description:s,page:n,terminal:i,tui:{...o,...r}})}const rc=oe({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"}}),oc=oe({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"}}),ac=oe({id:"daylight",label:"Daylight",description:"Crisp white workspace with near-black text and deep saturated accents — every color slot holds AA contrast.",page:{background:"#ffffff",foreground:"#111827",overlayBackground:"#ffffff",overlayForeground:"#111827",hintColor:"#4b5563",modalBackdrop:"rgba(17, 24, 39, 0.35)",modalBackground:"#ffffff",modalBorder:"#d1d5db",modalForeground:"#111827",modalMuted:"#4b5563",modalSelectedBackground:"#dbeafe",modalSelectedBorder:"#1d4ed8",modalSelectedForeground:"#1e3a8a"},terminal:{background:"#ffffff",foreground:"#111827",cursor:"#1d4ed8",cursorAccent:"#ffffff",selectionBackground:"#bfdbfe",black:"#111827",red:"#b91c1c",green:"#047857",yellow:"#92400e",blue:"#1d4ed8",magenta:"#6d28d9",cyan:"#0e7490",white:"#4b5563",brightBlack:"#374151",brightRed:"#991b1b",brightGreen:"#065f46",brightYellow:"#78350f",brightBlue:"#1e40af",brightMagenta:"#5b21b6",brightCyan:"#155e75",brightWhite:"#111827"},tui:{surface:"#ffffff",border:"#d1d5db",userChat:"#1e40af",userChatLabel:"#1e3a8a",activeHighlightBackground:"#dbeafe",activeHighlightForeground:"#1e3a8a",selectionBackground:"#1d4ed8",selectionForeground:"#ffffff",promptCursorBackground:"#1d4ed8",promptCursorForeground:"#ffffff"}}),lc=oe({id:"paper-ink",label:"Paper Ink",description:"Warm paper background with true-ink text and letterpress accents — warmth without washed-out output.",page:{background:"#faf6ef",foreground:"#1c1917",overlayBackground:"#fffdf8",overlayForeground:"#1c1917",hintColor:"#57534e",modalBackdrop:"rgba(28, 25, 23, 0.35)",modalBackground:"#fffdf8",modalBorder:"#d6cfc2",modalForeground:"#1c1917",modalMuted:"#57534e",modalSelectedBackground:"#f1e4c7",modalSelectedBorder:"#854d0e",modalSelectedForeground:"#713f12"},terminal:{background:"#faf6ef",foreground:"#1c1917",cursor:"#9f1239",cursorAccent:"#fffdf8",selectionBackground:"#f1e4c7",black:"#1c1917",red:"#9f1239",green:"#3f6212",yellow:"#854d0e",blue:"#1e40af",magenta:"#86198f",cyan:"#0f766e",white:"#57534e",brightBlack:"#44403c",brightRed:"#881337",brightGreen:"#365314",brightYellow:"#713f12",brightBlue:"#1e3a8a",brightMagenta:"#701a75",brightCyan:"#115e59",brightWhite:"#1c1917"},tui:{surface:"#fffdf8",border:"#d6cfc2",userChat:"#1e40af",userChatLabel:"#1e3a8a",activeHighlightBackground:"#f1e4c7",activeHighlightForeground:"#713f12",selectionBackground:"#854d0e",selectionForeground:"#fffdf8",promptCursorBackground:"#9f1239",promptCursorForeground:"#fffdf8"}}),cc=oe({id:"light-high-contrast",label:"Light High Contrast",description:"Pure black on white with maximum-contrast accents — nothing washes out, ever.",page:{background:"#eef0f2",foreground:"#000000",overlayBackground:"#ffffff",overlayForeground:"#000000",hintColor:"#333333",modalBackdrop:"rgba(0, 0, 0, 0.4)",modalBackground:"#ffffff",modalBorder:"#767676",modalForeground:"#000000",modalMuted:"#333333",modalSelectedBackground:"#cce5ff",modalSelectedBorder:"#0000cc",modalSelectedForeground:"#00008b"},terminal:{background:"#ffffff",foreground:"#000000",cursor:"#0000cc",cursorAccent:"#ffffff",selectionBackground:"#b3d7ff",black:"#000000",red:"#a80000",green:"#006400",yellow:"#5c4500",blue:"#0000cc",magenta:"#77008c",cyan:"#005f6b",white:"#333333",brightBlack:"#1a1a1a",brightRed:"#8b0000",brightGreen:"#004b00",brightYellow:"#4a3700",brightBlue:"#0000a0",brightMagenta:"#5f0070",brightCyan:"#004a54",brightWhite:"#000000"},tui:{surface:"#ffffff",border:"#767676",userChat:"#0000cc",userChatLabel:"#00008b",activeHighlightBackground:"#cce5ff",activeHighlightForeground:"#00008b",selectionBackground:"#0000cc",selectionForeground:"#ffffff",promptCursorBackground:"#0000cc",promptCursorForeground:"#ffffff"}}),uc=oe({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"}}),dc=oe({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"}}),fc=oe({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"}}),pc=oe({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"}}),hc=oe({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"}}),mc=oe({id:"tokyo-night",label:"Tokyo Night",description:"Deep blue-gray canvas with vivid neon accents inspired by Tokyo city lights.",page:{background:"#1a1b26",foreground:"#a9b1d6",overlayBackground:"#1a1b26",overlayForeground:"#a9b1d6",hintColor:"#737aa2",modalBackdrop:"rgba(26, 27, 38, 0.74)",modalBackground:"#24283b",modalBorder:"#414868",modalForeground:"#a9b1d6",modalMuted:"#737aa2",modalSelectedBackground:"#33467c",modalSelectedBorder:"#7aa2f7",modalSelectedForeground:"#c0caf5"},terminal:{background:"#1a1b26",foreground:"#a9b1d6",cursor:"#c0caf5",cursorAccent:"#1a1b26",selectionBackground:"rgba(122, 162, 247, 0.22)",black:"#414868",red:"#f7768e",green:"#9ece6a",yellow:"#e0af68",blue:"#7aa2f7",magenta:"#bb9af7",cyan:"#7dcfff",white:"#a9b1d6",brightBlack:"#565f89",brightRed:"#f7768e",brightGreen:"#9ece6a",brightYellow:"#e0af68",brightBlue:"#7aa2f7",brightMagenta:"#bb9af7",brightCyan:"#7dcfff",brightWhite:"#c0caf5"},tui:{surface:"#1a1b26",activeHighlightBackground:"#33467c",activeHighlightForeground:"#c0caf5",selectionBackground:"#7aa2f7",selectionForeground:"#1a1b26",promptCursorBackground:"#c0caf5",promptCursorForeground:"#1a1b26"}}),gc=oe({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"}}),yc=oe({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"}}),Ao=oe({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"}}),Sc=oe({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"}}),bc=oe({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"}}),wc=oe({id:"solarized-ops",label:"Solarized Ops",description:"Solarized-inspired operations palette with deep blue-green surfaces and balanced long-session contrast.",page:{background:"#002b36",foreground:"#d7e2d0",overlayBackground:"#073642",overlayForeground:"#e5efe4",hintColor:"#93a1a1",modalBackdrop:"rgba(0, 20, 25, 0.74)",modalBackground:"#073642",modalBorder:"#2f5d67",modalForeground:"#e5efe4",modalMuted:"#93a1a1",modalSelectedBackground:"#164b56",modalSelectedBorder:"#2aa198",modalSelectedForeground:"#fdf6e3"},terminal:{background:"#002b36",foreground:"#d7e2d0",cursor:"#2aa198",cursorAccent:"#002b36",selectionBackground:"#164b56",black:"#073642",red:"#dc322f",green:"#859900",yellow:"#b58900",blue:"#268bd2",magenta:"#6c71c4",cyan:"#2aa198",white:"#eee8d5",brightBlack:"#586e75",brightRed:"#cb4b16",brightGreen:"#93a100",brightYellow:"#c79b00",brightBlue:"#3aa0e6",brightMagenta:"#7b80d6",brightCyan:"#36b5ac",brightWhite:"#fdf6e3"},tui:{surface:"#073642",border:"#2f5d67",userChat:"#b58900",userChatLabel:"#f0d47a",activeHighlightBackground:"#164b56",activeHighlightForeground:"#fdf6e3",selectionBackground:"#268bd2",selectionForeground:"#002b36",promptCursorBackground:"#2aa198",promptCursorForeground:"#002b36"}}),Ic=oe({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"}}),xc=oe({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"}}),vc=oe({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"}}),Co=Object.freeze([dc,rc,oc,ac,lc,cc,uc,hc,pc,fc,mc,gc,yc,Ao,Sc,bc,wc,Ic,xc,vc].sort((t,e)=>t.label.localeCompare(e.label,void 0,{sensitivity:"base"}))),Ec=new Map(Co.map(t=>[t.id,t])),Ac=Ao.id;function Cc(){return Co}function Xe(t){return t?Ec.get(t)??null:null}const Tc=new Set(["agent","user","system"]);function cs(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 kc(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:Tc.has(t.source)?t.source:"agent"}}function us(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const i of e){const r=kc(i);!r||n.has(r.filename)||(n.add(r.filename),s.push(r))}return s}function Mc(t,e){const s=String(e||"").trim();return s&&us(t).find(n=>n.filename===s)||null}function Nn(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 ds(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 un(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 To(t){if(t==null)return null;const e=String(t).trim();return e||null}function Nc({mode:t="local",branding:e=null,themeId:s=null,chatViewMode:n=null,sessionOwnerFilter:i=null,layoutAdjustments:r=null,pinnedSessionIds:o=null,collapsedSessionIds:a=null,activeSessionId:l=null}={}){const u=i!=null,f=a!=null,d=Nn(r);return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},auth:{principal:null,authorization:null},ui:{focusRegion:T.SESSIONS,inspectorTab:Ne[0],sequenceExpandedTurns:[],sequenceSelectedTurn:null,chatViewMode:n==="summary"||n==="rich"?n:"transcript",statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:Xe(s)?.id||Ac,modal:null,fullscreenPane:null,layout:{...d,viewportWidth:120,viewportHeight:40},scroll:{chat:0,inspector:0,activity:0,filePreview:0},chatScrollBySession:{},followBottom:{inspector:!0,activity:!0}},connection:{mode:t,connected:!1,workersOnline:null,error:null},sessions:{byId:{},flat:[],activeSessionId:To(l),collapsedIds:un(a),collapsedIdsExplicit:f,pinnedIds:ds(o),selectedIds:[],selectMode:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:u,ownerFilter:cs(i),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}}}}function ko(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function Pc(t,e){return!(!ko(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const Mo="activeHighlightBackground",Pn="activeHighlightForeground",Ws="userChat",Oc="userChatLabel",_c="otherUserChatLabel",Pi=new WeakMap,Oi=new WeakMap;function Rc(t){return t||Pn}function No(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Rc(s?.color):Pn,backgroundColor:Mo,bold:s?.bold??!0}))}function Pe(t,{color:e=Pn,bold:s=!0}={}){return{text:t,color:e,backgroundColor:Mo,bold:s}}function Re(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Lc=72;function Po(t){const e=Number(t)||0;return e>0&&e<=Lc}function On(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function $c(t){const e=On(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function Fc(t){const e=Oo(t);return!e||e==="unknown"?"":e==="cron_waiting"?"waiting":e}function Oo(t){return t?.rowVisualStatus||On(t)}function _o(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function _n(t){const e=On(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&ko(t?.error)&&!_o(t?.orchestrationStatus)?"warning":null}function Ro(t,e="local"){const s=_n(t);if(s)return s;const n=Oo(t);if(e==="remote"&&_o(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 vt(t,e="local"){switch(Ro(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 Lo(t,e="local"){switch(Ro(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 Rn(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Bc=ue({provider:"system",subject:"system"});function _i(t){const e=String(t||"").trim();if(!e)return"";const s=e.replace(/@.*/u,"").split(/[^A-Za-z0-9]+/u).map(i=>i.trim()).filter(Boolean);return s.length>=2?`${s[0][0]}${s[1][0]}`.toLowerCase():(s[0]||e).replace(/[^A-Za-z0-9]/gu,"").slice(0,2).toLowerCase()}function Ri(t){return _i(t?.displayName)||_i(t?.email)||"?"}function Li(t){const e=t.sessions?.ownerFilter;if(Array.isArray(e?.ownerKeys)&&e.ownerKeys.length>0)return!0;const s=new Set;for(const n of Object.values(t.sessions?.byId||{})){if(!n||n.isSystem||n.isGroup)continue;const i=ue(n.owner);if(i&&(s.add(i),s.size>1))return!0}return!1}function $o(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function Ln(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of $o(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 $i(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Fi(t,e){const s=$i(t),n=$i(e?.agentId);return!!(s&&n&&s===n)}function Dc(t){if(!t?.agentId||t?.isSystem)return null;const e=String(t?.title||"").trim();if(!e)return null;const s=" · ",n=e.lastIndexOf(s);if(n>0){const o=e.slice(0,n).trim(),a=e.slice(n+s.length).trim();if(o&&Fi(a,t))return{displayTitle:o,agentTitle:a}}const i=/^(.+?)\s+[–—-]\s+(.+)$/u.exec(e);if(i){const o=i[1].trim(),a=i[2].trim();if(o&&a)return{displayTitle:a,agentTitle:o}}const r=e.indexOf(": ");if(r>0){const o=e.slice(0,r).trim(),a=e.slice(r+2).trim();if(a&&Fi(o,t))return{displayTitle:a,agentTitle:o}}return null}function Hc(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 Gc=[[/</g,"<"],[/>/g,">"],[/"/g,'"'],[/�?39;/g,"'"],[/'/g,"'"],[/ /g," "],[/&/g,"&"]];function jc(t){let e=String(t??"");if(!e.includes("&"))return e;for(const[s,n]of Gc)e=e.replace(s,n);return e}function vs(t){return jc(Uc(t))}function Uc(t){const e=String(t?.title||"").trim(),s=Dc(t);if(!s)return e;const n=Hc(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function Fo(t,e){const s=te(t?.sessionId);if(t?.isSystem)return`${kt(t,e)} (${s})`;const n=vs(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function Bi(t,e={},s={},n=void 0){if(!e||e.all===!0)return!0;if(t?.isSystem)return e.includeSystem===!0;const i=ue(n!==void 0?n:t?.owner);if(!i)return e.includeUnowned===!0;if(i===Bc)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 Bo(t,e={},s={},n=null){const i=Ln(t,n||{});if(Bi(t,e,s,i))return!0;if(!n)return!1;if(t?.isGroup)return $o(t,n).some(a=>Bo(a,e,s,n));let r=t,o=0;for(;r?.parentSessionId&&o<16;){const a=n[r.parentSessionId];if(!a)return!1;if(Bi(a,e,s))return!0;r=a,o+=1}return!1}function Wc(t){return(t||[]).map(e=>e?.text||"").join("")}function $n(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 Di(t){const{childMap:e}=$n(t),s=new Map;function n(i){if(s.has(i))return s.get(i);const o=(e.get(i)||[]).reduce((a,l)=>a+1+n(l),0);return s.set(i,o),o}for(const i of Object.keys(t||{}))n(i);return s}function Hi(t=[],e={}){const{parentMap:s}=$n(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 Fn(t={}){if(!t||typeof t!="object")return Di(t);const e=Pi.get(t);if(e)return e;const s=Di(t);return Pi.set(t,s),s}function Bn(t=[],e={}){if(!Array.isArray(t))return Hi(t,e);const s=Oi.get(t);if(s)return s;const n=Hi(t,e);return Oi.set(t,n),n}function Do(t,e,s,n){const i=s.get(t)||0,r=n.get(t)||0,o=Math.max(0,i-r),a=e?.collapsed?i:o;return a?{text:`[+${a}]`,color:"cyan"}:null}function fs(t){if(!t)return"scheduled";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"scheduled";try{return e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short"}).replace(/,\s*/g," ").replace(/\s+/g," ").trim()}catch{return e.toISOString().replace(/\.000Z$/,"Z")}}function Kc(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${fs(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${gt(t.cronInterval)}]`,color:"magenta"}:null}function Ho(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Vc(t,e){const s=[];typeof t?.regenStage=="string"&&t.regenStage&&s.push({text:`↻ regen:${t.regenStage}`,color:"magenta"});const n=Fc(t);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:vt(t,e)}));const i=Wn(t?.model,t?.reasoningEffort);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i,color:"cyan"}));const r=sl(t?.contextUsage);r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r.text,color:r.color}));const o=nl(t?.contextUsage);return o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color})),s}function qc(t,e,s,n,i){const r=[],o=s.connection?.mode||"local",a=t.depth>0?`${" ".repeat(Math.max(0,t.depth-1))}└ `:"";a&&r.push({text:a,color:"gray"});const l=new Set(Array.isArray(s.sessions?.pinnedIds)?s.sessions.pinnedIds:[]),u=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),f=!!s.sessions?.selectMode,d=u.has(t.sessionId),p=l.has(t.sessionId);if(f&&r.push({text:d?"[x] ":"[ ] ",color:d?"cyan":"gray",bold:d}),t.depth===0&&Ho(e)&&l.size>0&&(p&&!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 K=Lo(e,o);r.push({text:K?`${K} `:" ",color:vt(e,o)})}const h=e?.isGroup?"cyan":e?.isSystem?"yellow":vt(e,o),m=Ln(e,s.sessions?.byId||{}),g=te(e?.sessionId),S=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,y=S?Od(S):"",A=Wn(e?.model,e?.reasoningEffort),x=e?.isSystem?kt(e,s.branding?.title||"PilotSwarm"):vs(e),v=!!(e?.isSystem||e?.isGroup||x&&x.trim()),I=[...r];if(Li(s)&&!e?.isSystem&&!e?.isGroup){const K=m?Ri(m):"?",z=ue(s?.auth?.principal),Y=z&&ue(m)===z;I.push({text:`[${K}] `,color:Y?"green":"cyan",bold:!0})}v?I.push({text:x,color:h,bold:!!(e?.isSystem||e?.isGroup)}):(I.push({text:g,color:h}),y&&(I.push({text:" · ",color:"gray"}),I.push({text:y,color:"gray"})),A&&(I.push({text:" · ",color:"gray"}),I.push({text:A,color:"green"})));const w=Do(e?.sessionId,t,n,i);w&&I.push({text:` ${w.text}`,color:w.color,bold:w.bold});const C=Kc(e);C&&I.push({text:" ⏱",color:"magenta"});const N=[],R=e?.contextUsage?.compaction?.state,F=En(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&N.push({text:`${e.memberCount}`,color:"gray"}):R==="running"?N.push({text:"⇊",color:"magenta"}):R==="failed"?N.push({text:"!",color:"red"}):F!=null?N.push({text:`${F}%`,color:F>=85?"red":F>=70?"yellow":"green"}):N.push({text:"—",color:"gray"});const L=[];e?.isGroup&&e?.memberCount!=null&&(L.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),y&&(L.push({text:" · ",color:"gray"}),L.push({text:y,color:"gray"})));const M=[],$=()=>{M.length&&M.push({text:" · ",color:"gray"})};if(e?.isGroup)M.push(...L);else{v&&(M.push({text:g,color:"cyan"}),y&&($(),M.push({text:y,color:"gray"})),A&&($(),M.push({text:A,color:"green"})));const K=e?.contextUsage;K&&Number.isFinite(K.currentTokens)&&Number.isFinite(K.tokenLimit)&&K.tokenLimit>0&&($(),M.push({text:`ctx ${W(K.currentTokens)}/${W(K.tokenLimit)}`,color:"gray"}));const z=n?.[e?.sessionId];z&&($(),M.push({text:`${z} child${z===1?"":"ren"}`,color:"gray"})),C&&($(),M.push({text:C.text,color:C.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&($(),M.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...I,...v&&y&&!e?.isGroup?[{text:" ",color:"gray"},{text:y,color:"gray"}]:[],...N.length&&!e?.isGroup?[{text:" · ",color:"gray"},...N]:[],...e?.isGroup&&L.length?[{text:" ",color:"gray"},...L]:[]],titleRuns:I,ctxRuns:N,metaRuns:L,badgeRuns:[],selectedMetaRuns:M,detailRuns:M,childCount:n?.get?.(e?.sessionId)||0,chrome:{kind:e?.isGroup?"group":e?.isSystem?"system":e?.serviceKind?"service":"session",title:v?x:g,untitled:!v,statusColor:vt(e,o),accentColor:h,pinned:p,selectMode:f,checked:d,owner:Li(s)&&!e?.isSystem&&!e?.isGroup?{initials:m?Ri(m):"?",isMine:!!(ue(s?.auth?.principal)&&ue(m)===ue(s?.auth?.principal))}:null,childBadge:w?{text:w.text,color:w.color}:null,cron:!!C,age:y||null,model:A||null,shortId:g,ctx:N.length>0?{text:N[0].text,color:N[0].color}:null}}}function Go(t){return String(t||"").trim().toLowerCase()}function st(t,e){const s=Go(e);return s?String(t||"").toLowerCase().includes(s):!0}function zc(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 Gi=new WeakMap;function Yc(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 Ct(t){const e=Fn(t.sessions.byId),s=Bn(t.sessions.flat,t.sessions.byId),n=Go(t.sessions?.filterQuery||""),i=t.sessions?.ownerFilter||{all:!0},r=t.auth||{},o=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),a=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]),l=zc(t.sessions);let u=Gi.get(t.sessions.flat);return u||(u=new Map,Gi.set(t.sessions.flat,u)),t.sessions.flat.map(f=>{const d=t.sessions.byId[f.sessionId],p=f.sessionId===t.sessions.activeSessionId,h=o.has(f.sessionId),m=a.has(f.sessionId),g=[f,d,p,h,m,n,i,r,t.connection?.mode,t.sessions.selectMode,e,s,t.branding?.title],S=u.get(f.sessionId);if(S&&Yc(S.deps,g))return S.row;const y=qc(f,d,t,e,s),A={sessionId:f.sessionId,text:Wc(y.runs),...y,depth:f.depth,status:d?.status,statusColor:vt(d,t.connection?.mode||"local"),active:p,isSystem:!!d?.isSystem,isGroup:!!d?.isGroup,hasChildren:f.hasChildren,collapsed:f.collapsed,pinned:h,selected:m,canPin:Ho(d)};return u.set(f.sessionId,{deps:g,row:A}),A}).filter(f=>{if(l?.has(f.sessionId))return!0;const d=t.sessions.byId[f.sessionId];if(!Bo(d,i,r,t.sessions.byId))return!1;const p=Ln(d,t.sessions.byId),h=p?`${Rn(p,"")} ${p.email||""}`:"",m=`${d?.shortSummary||""} ${d?.summaryState?.intent||""} ${d?.summaryState?.summary||""}`;return st(f.text,n)||st(f.sessionId,n)||st(h,n)||st(m,n)})}function dn(t,e=8){const s=Ct(t);if(s.length===0)return[];const n=new Set(s.map(d=>d.sessionId)),i=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(d=>n.has(d.sessionId)),r=i.findIndex(d=>d.sessionId===t.sessions.activeSessionId),o=Math.max(0,r);if(i.length<=e)return s;const a=Math.floor(e/2);let l=Math.max(0,o-a),u=Math.min(i.length,l+e);u>i.length&&(u=i.length,l=Math.max(0,u-e));const f=i.slice(l,u);return Fn(t.sessions.byId),Bn(i,t.sessions.byId),s.filter(d=>f.some(p=>p.sessionId===d.sessionId))}function Te(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function Qc(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 Am(t){const e=t.sessions?.filterExceptionId||null;return!e||!t.sessions?.byId?.[e]?null:"Showing linked session outside your current filters."}function jo(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function Xc(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 Jc(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),i=String(s?.answer||"").trim();if(!n||!i||Uo(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 Zc(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 Uo(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>Is(n?.text||"")?.question?.trim()===s):!1}function eu(t){const e=String(t?.error||"").trim();if(!e)return null;const s=_n(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 ji(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 tu(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function su(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=tu(r.text);if(o)return{...r,summaryText:o}}return null}function nu(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(I=>I?.role==="user"||I?.role==="assistant"),o=r[r.length-1]||null,a=o?.role==="user",l=a&&o?.optimistic===!0,u=(n||[]).filter(I=>I?.phase==="pending").length,f=(n||[]).filter(I=>I?.phase==="queued").length,d=(n||[]).filter(I=>I?.phase==="cancelling").length,p=Array.isArray(e?.events)?e.events:[],h=ji(p,"user.message"),m=ji(p,"assistant.message"),g=h>m;if(i==="waiting"||i==="input_required"||!a&&!g&&i!=="running"&&!l)return null;const S=Math.max(h,m),y=p.filter(I=>I?.eventType==="assistant.reasoning"&&Number(I?.seq||0)>S),A=y[y.length-1]||null,x=String(A?.data?.content||A?.data?.text||A?.data?.message||"").trim();if(x)return{kind:"thinking",label:"Thinking",text:x,createdAt:A?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:A?.seq||0};const v=su(e,S);return v?.summaryText?{kind:i==="running"?"working":"sending",label:i==="running"?"Working":"Sending",text:v.summaryText,createdAt:v.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:v.seq||0}:u>0?{kind:"pending",label:u===1?"Pending":`Pending ${u}`,text:u===1?"One prompt is waiting to be sent.":`${u} prompts are waiting to be sent.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:f>0?{kind:"queued",label:f===1?"Queued":`Queued ${f}`,text:f===1?"One prompt is durably queued, waiting for the LLM to receive it.":`${f} prompts are durably queued, waiting for the LLM to receive them.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:d>0?{kind:"cancelling",label:d===1?"Cancelling":`Cancelling ${d}`,text:d===1?"One queued prompt is waiting for cancellation confirmation.":`${d} queued prompts are waiting for cancellation confirmation.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:l?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:o?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:i==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:null}function Es(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return Rs(t.branding);if(s?.isGroup){const u=Object.values(t.sessions.byId||{}).filter(h=>h&&!h.isGroup&&h.groupId===s.groupId&&!h.parentSessionId),f=h=>String(h??"").replace(/\|/g,"\\|").replace(/[\r\n]+/g," ").trim()||" ",d=u.map(h=>`| ${f(h.title||h.sessionId)} | ${f(h.status||"unknown")} | ${f(h.shortSummary||"")} |`),p=[`# ${s.title||s.groupId}`,s.shortSummary||"","","| Metric | Count |","|---|---:|",`| Members | ${s.memberCount??u.length} |`,`| Running | ${s.runningCount??0} |`,`| Waiting | ${s.waitingCount??0} |`,`| Completed | ${s.completedCount??0} |`,`| Failed | ${s.failedCount??0} |`,`| Cancelled | ${s.cancelledCount??0} |`,"","## Members",...d.length>0?["| Session | Status | Summary |","|---|---|---|",...d]:["_No top-level members._"]];return[{id:`group-details:${s.sessionId}`,role:"system",noChrome:!0,text:p.filter((h,m)=>m===1||String(h||"").length>0).join(`
|
|
30
|
+
`),createdAt:s.updatedAt||Date.now()}]}if(t.ui?.chatViewMode==="summary")return iu(s);const n=t.history.bySessionId.get(e),i=n?.chat||[],r=s?.pendingQuestion?.question&&!Uo(i,s.pendingQuestion.question)?Xc(s):null,o=Jc(s,i),a=eu(s);if((!n||i.length===0)&&!r&&!o&&!a)return Rs(t.branding,s);const l=i.length>0?[...i]:Rs(t.branding,s);return r&&l.push(r),o&&l.push(o),a&&l.push(a),l}function iu(t){const e=u=>{const f=String(u||"");return f.includes("\\n")?f.replace(/\\\\n/g,`
|
|
31
|
+
`).replace(/\\n/g,`
|
|
32
|
+
`):f},s=t?.summaryState&&typeof t.summaryState=="object"&&!Array.isArray(t.summaryState)?t.summaryState:null,n=s?.state&&typeof s.state=="object"&&!Array.isArray(s.state)?s.state:null,i=vs(t)||t?.title||t?.sessionId||"Session",r=[];r.push(`# ${i}`),r.push("");const o=[],a=$c(t);if(a&&o.push(["Status",a]),s?.intent&&o.push(["Intent",String(s.intent)]),t?.summaryUpdatedAt){const u=ge(t.summaryUpdatedAt);u&&o.push(["Updated",u])}for(const[u,f]of o)r.push(`**${u}:** ${f}`);o.length>0&&r.push("");const l=e(s?.summary||t?.shortSummary||"").trim();if(l&&(r.push(l),r.push("")),n){const u=Object.entries(n).filter(([,f])=>f!=null&&!(typeof f=="string"&&!f.trim()));if(u.length>0){r.push("## State");for(const[f,d]of u)if(Array.isArray(d))if(d.length===0)r.push(`- **${f}:** _(empty)_`);else{r.push(`- **${f}:**`);for(const p of d.slice(0,16)){const h=typeof p=="string"?e(p):JSON.stringify(p);r.push(` - ${h}`)}}else if(d&&typeof d=="object"){r.push(`- **${f}:**`);for(const[p,h]of Object.entries(d).slice(0,16)){const m=typeof h=="string"?e(h):JSON.stringify(h);r.push(` - **${p}:** ${m}`)}}else r.push(`- **${f}:** ${e(String(d))}`);r.push("")}}for(const[u,f]of[["Blockers","blockers"],["Open Questions","openQuestions"],["Next Actions","nextActions"]]){const d=Array.isArray(s?.[f])?s[f].filter(Boolean).slice(0,12):[];if(d.length!==0){r.push(`## ${u}`);for(const p of d)r.push(`- ${typeof p=="string"?e(p):JSON.stringify(p)}`);r.push("")}}for(!s&&!l&&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 ru(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>Zc(e,s)).filter(Boolean):[]:[]}function Ks(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function Wo(t,e={}){const s=ge(t?.createdAt||t?.time),n=t?.sender,i=n?.kind==="user"?ue(n):null,r=e?.viewerKey||null,o=e?.ownerKey||null,a=e?.sharedContext===!0,l=t?.role==="user",f=a&&l&&i&&!(l&&i&&r&&i===r),p=a&&l&&o&&(i&&i===o||!i&&r&&r===o)?" (owner)":"",h=l?(f?n.display||n.subject||"User":"You")+p:t?.role==="assistant"?"Agent":t?.role==="system"?"System":"PilotSwarm";let m=null,g=null;t?.pendingPhase==="pending"?(m="○",g="yellow"):t?.pendingPhase==="queued"?(m="✓",g="cyan"):t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?(m="x",g="red"):t?.role==="user"&&!t?.optimistic&&!t?.pendingPhase&&(t?.stopped?(m="⊘",g="yellow"):t?.redelivered?(m="✓✓↻",g="yellow"):(m="✓✓",g="green"));const S=t?.pendingPhase==="pending"?"yellow":t?.pendingPhase==="queued"?"cyan":t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?"red":f?_c:t?.role==="user"?Oc:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white";return{time:s,glyph:m,glyphColor:g,roleLabel:h,roleColor:S,fromOtherPerson:f}}function ou(t,e={}){const{time:s,glyph:n,glyphColor:i,roleLabel:r,roleColor:o}=Wo(t,e),a=s?`[${s}] `:"",l=[...Ks(a,"gray")];return n&&l.push(...Ks(`${n} `,i)),l.push(...Ks(`${r}: `,o,{bold:!0})),l}function Qe(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function Ko(){return[{text:"",color:null}]}function au(t){const e=(t||[]).find(n=>Qe(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=Qe(e).trimStart();return/^[┌│└]/.test(s)}function ps(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(Qe(s).trim().length>0)break;e.shift()}return e}function lu(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 cu.test(s)?{leadingText:"",systemText:s}:null}const cu=/^(?: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 Dn(t){const e=lu(t);if(e){const o=[];e.leadingText&&o.push({kind:"text",text:e.leadingText});const a=ze(e.systemText);return a&&o.push({kind:"system",text:a}),o}const s=String(t||"").replace(/\r\n/g,`
|
|
37
|
+
`).split(`
|
|
38
|
+
`),n=[];let i=[];function r(){i.length!==0&&(n.push({kind:"text",text:i.join(`
|
|
39
|
+
`)}),i=[])}for(let o=0;o<s.length;){const a=s[o];if(!/^\s*\[SYSTEM:/i.test(a)){i.push(a),o+=1;continue}const l=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(a);if(l){r();const p=ze(l[1].trim());if(!p){o+=1;continue}n.push({kind:"system",text:p}),o+=1;continue}const u=[a.replace(/^\s*\[SYSTEM:\s*/i,"")];let f=-1;for(let p=o+1;p<s.length;p+=1){const h=s[p];if(h.trim()==="]"){f=p;break}if(/\]\s*$/.test(h.trim())){const m=h.replace(/\]\s*$/,"");m.trim()&&u.push(m),f=p;break}u.push(h)}if(f===-1){i.push(a),o+=1;continue}r();const d=ze(u.join(`
|
|
40
|
+
`).trim());if(!d){o=f+1;continue}n.push({kind:"system",text:d}),o=f+1}return r(),n}function uu(t){return t?t?.role==="system"?!Tn(t?.text||"")||!!ze(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:Dn(t?.text||"").some(e=>e.kind==="system"):!1}function Ui(t){return uu(t)?"system":t?.role||"other"}function Vo(t,e){return!t||!e?!1:Ui(t)!==Ui(e)}function du(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 fu(t,e=""){const s=du(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:it(t),color:"gray"}}function Wi({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:it(s||o),color:i}}function pu(t){return t?.label?[{text:t.label,color:t.kind==="working"?"yellow":"cyan",bold:!0}]:null}function hu(t,e){return e?(t||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||e})):s):t}function mu(t){const e=(t||[]).find(s=>Qe(s).trim().length>0);return e?Qe(e).trimStart().startsWith("┌"):!1}function hs(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&mu(e)&&Qe(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function gu(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 yu(t,e,s){const n=Math.max(20,Number(s)||20),i=ge(e?.createdAt||e?.time),r=gu(t),o=a=>{const l=String(a||"").replace(/^session-/i,"");return te(l)||l||String(a||"")};if(r?.kind==="subAgentSingle"){const a=o(r.agentId),l=[r.task?`**Task:** ${r.task}`:"",r.status?`**Status:** ${r.status}`:"","",r.result||"_(no result)_"].filter((u,f)=>f===2||u).join(`
|
|
41
|
+
`);return[Wi({title:`Sub-agent Response — ${a}`,summary:r.status||"completed",timestamp:i,body:l,color:"cyan"})]}if(r?.kind==="subAgentMulti"){const a=r.agents.map(u=>{const f=o(u.agentId),d=u.task?`**Task:** ${u.task}`:"",p=u.status?`**Status:** ${u.status}`:"";return`${[`### ${f}`,d,p].filter(Boolean).join(`
|
|
42
|
+
`)}
|
|
43
|
+
|
|
44
|
+
${u.result||"_(no result)_"}`}),l=r.agents.map(u=>`${o(u.agentId)} ${u.status||"completed"}`).join(" · ");return[Wi({title:`Sub-agent Responses (${r.agents.length})`,summary:l,timestamp:i,body:a.join(`
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
`),color:"cyan"})]}return re({title:"System",timestamp:i,body:t,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function Su(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),i=ge(t?.createdAt||t?.time),r=String(t?.thinkingLabel||"Thinking…").trim()||"Thinking…",o=t?.progressKind==="working"?"yellow":(t?.progressKind==="sending","cyan"),a=J([{text:` ⠋ ${r} `,color:o,bold:!0},...i?[{text:` ${i} `,color:"gray"}]:[]],Math.max(1,s-3)),l=a.reduce((p,h)=>p+String(h?.text||"").length,0),u=Math.max(0,s-l-3),f=String(t?.text||"").trim()?ps(Et(it(t.text),{width:n})).flatMap(p=>lo(p,n)):[],d=[[{text:"┌─",color:"gray"},...a,{text:`${"─".repeat(u)}┐`,color:"gray"}]];for(const p of f)d.push([{text:"│ ",color:"gray"},...ao(p.map(h=>({...h,color:h?.color&&h.color!=="white"?h.color:"gray"})),n),{text:" │",color:"gray"}]);return d.push([{text:`└${"─".repeat(Math.max(1,s-2))}┘`,color:"gray"}]),d.push([{text:"",color:null}]),d}function bu(t){return String(t||"").split(`
|
|
49
|
+
`).reduce((e,s)=>Math.max(e,An(s).length),0)}function Tt(t,e,s={}){if(t?.splash){const u=t.mobileText&&bu(t.text)>e;return[{kind:"markup",value:u?t.mobileText:t.text,splashAlt:!u&&t.mobileText?t.mobileText:null}]}if(t?.thinking)return Su(t,e);if(t?.noChrome)return ps(Et(it(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const u=Is(t?.text||"");if(u)return[...re({title:"Question",timestamp:ge(t?.createdAt||t?.time),body:u.question,width:Math.max(20,e),titleColor:Ws,borderColor:Ws,tableMode:s.tableMode}),...Tt({...t,text:u.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const u=Dn(t?.text||"");if(u.some(f=>f.kind==="system")){const f=[];let d=!1;for(const h of u)h.kind!=="system"&&h.text.trim()&&(hs(f,Tt({...t,text:h.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:d})),d=!0);if(f.length>0)return f;const p=[];for(const h of u)h.kind!=="system"||!h.text.trim()||hs(p,yu(h.text,t,e));if(p.length>0)return p}}if(t?.role!=="user"&&t?.role!=="assistant"){const u=ze(t?.text||"");if(t?.role==="system"&&!u)return[];const f=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!f)return[fu(u||t?.text||"",ge(t?.createdAt||t?.time))];const d=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return re({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:ge(t?.createdAt||t?.time),body:it(t?.text||""),width:Math.max(20,e),titleColor:t?.cardTitleColor||(t?.role==="system"?"yellow":"cyan"),borderColor:t?.cardBorderColor||"gray",tableMode:s.tableMode,...d?{bodyColor:"gray",fitToContent:!0}:{}})}const n=ps(Et(it(t?.text||""),{width:e,tableMode:s.tableMode})),i=hu(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?Ws:null),r=s.skipPrefix?[]:ou(t,s),o=qo(t,s);if(i.length===0){const u=r.length>0?[r]:[];return o.length>0?[...u,...o]:u}if(au(i)){const u=r.length>0?[r,...i]:i;return o.length>0?[...u,...o]:u}const a=[];let l=r.length===0;for(const u of i){if(!Array.isArray(u)){l||(a.push(r),l=!0),a.push(u);continue}l?a.push(u):(a.push([...r,...u]),l=!0)}return a.push(...o),a}function qo(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 wu=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 Iu(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 xu=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),vu=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function Eu(t,e){const s=String(t||"").toLowerCase();return s==="search_skills"||s.includes("skill")?e?"loading skills…":"loaded skills":xu.has(s)?e?"reading facts…":"read facts":vu.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 Au(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=Eu(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 Hn(t,e={}){if(t?.ui?.chatViewMode==="summary")return[];const s=Te(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 A=r.length-1;A>=0;A-=1)if(r[A]?.role==="user"){o=Number(r[A]?.createdAt||0);break}const a=Array.isArray(i?.activity)?i.activity:[];let l=0,u=0;for(let A=a.length-1;A>=0;A-=1){const x=a[A],v=x?.eventType,I=Number(x?.createdAt||0);if(!l&&v==="assistant.turn_start"&&(l=I),!u&&(v==="assistant.turn_end"||v==="session.turn_completed")&&(u=I),l&&u)break}let f=0;o>u?f=o:l>u&&(f=l);let d=null;for(let A=a.length-1;A>=0;A-=1){const x=a[A];if(!(!x||wu.has(x.eventType))){if(Number(x.createdAt||0)<=u)break;d=x;break}}const p=Number.isFinite(e.now)?e.now:Date.now(),h=f>0?Iu(p-f):"",m=String(e.spinnerFrame||"").trim()||"●",g=d?Au(d):"",S=[{text:`${m} `,color:"cyan"},{text:"Working",color:"cyan"},...h?[{text:` · ${h}`,color:"gray"}]:[],...g?[{text:` — ${g}`,color:"gray"}]:[]],y=Math.max(24,Math.min(120,Math.floor(Number(e.maxWidth)||80)));return[J(S,y)]}const Ki=4;let Yt=[];function Gn(t,e=80,s={}){const n=t?.sessions?.activeSessionId??null,i={sessionId:n,session:n?t?.sessions?.byId?.[n]??null:null,byId:t?.sessions?.byId??null,chat:t?.history?.bySessionId?.get?.(n)?.chat??null,viewMode:t?.ui?.chatViewMode??null,branding:t?.branding??null,principal:t?.auth?.principal??null,maxWidth:e,tableMode:s?.tableMode??null};for(const m of Yt)if(m.sessionId===i.sessionId&&m.session===i.session&&m.byId===i.byId&&m.chat===i.chat&&m.viewMode===i.viewMode&&m.branding===i.branding&&m.principal===i.principal&&Object.is(m.maxWidth,i.maxWidth)&&m.tableMode===i.tableMode)return m.lines;const r=m=>(Yt.unshift({...i,lines:m}),Yt.length>Ki&&(Yt.length=Ki),m),o=Es(t);if(!o||o.length===0)return r([{text:"No messages yet.",color:"gray"}]);const a=ue(t?.auth?.principal),l=t?.sessions?.activeSessionId,u=l?t?.sessions?.byId?.[l]:null,f=ue(u?.owner),d=!!(u&&(u.visibility&&u.visibility!=="private"||f&&a&&f!==a)),p={...s?.tableMode?{tableMode:s.tableMode}:{},...a?{viewerKey:a}:{},...f?{ownerKey:f}:{},...d?{sharedContext:!0}:{}},h=[];for(const[m,g]of o.entries()){if(g?.kind==="epoch-divider")h.push(zo(g,e));else if(g?.kind==="regen-refused")h.push(Yo(g,e));else if(g?.kind==="regen-failed")h.push(Qo(g,e));else{const y=Tt(g,e,p);hs(h,y)}const S=o[m+1];S&&Vo(g,S)&&Qe(h[h.length-1]).trim().length>0&&h.push(Ko())}return r(h.length>0?h:[{text:"No messages yet.",color:"gray"}])}function Cu(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"&&Is(t?.text||"")||Dn(t?.text||"").some(s=>s.kind==="system"))}const Vi=new WeakMap;function Tu(t,e=80,s={}){const n=Es(t);if(!n||n.length===0)return[];const i=ue(t?.auth?.principal),r=t?.sessions?.activeSessionId,o=r?t?.sessions?.byId?.[r]:null,a=ue(o?.owner),l=!!(o&&(o.visibility&&o.visibility!=="private"||a&&i&&a!==i)),u={...s?.tableMode?{tableMode:s.tableMode}:{},...i?{viewerKey:i}:{},...a?{ownerKey:a}:{},...l?{sharedContext:!0}:{}},f=[];for(const d of n){const p=d?Vi.get(d):null;if(p&&Object.is(p.text,d.text)&&Object.is(p.kind,d.kind)&&Object.is(p.role,d.role)&&Object.is(p.id,d.id)&&Object.is(p.pendingPhase,d.pendingPhase)&&Object.is(p.stopped,d.stopped)&&Object.is(p.createdAt,d.createdAt)&&Object.is(p.time,d.time)&&Object.is(p.sender,d.sender)&&Object.is(p.attachments,d.attachments)&&Object.is(p.tableMode,u.tableMode)&&Object.is(p.viewerKey,u.viewerKey)&&Object.is(p.ownerKey,u.ownerKey)&&Object.is(p.sharedContext,u.sharedContext)){f.push(p.block);continue}if(d?.kind==="epoch-divider"){f.push({kind:"lines",variant:"divider",lines:[zo(d,e)]});continue}if(d?.kind==="regen-failed"){f.push({kind:"lines",variant:"divider",lines:[Qo(d,e)]});continue}if(d?.kind==="regen-refused"){f.push({kind:"lines",variant:"divider",lines:[Yo(d,e)]});continue}if(Cu(d)){const g=qo(d,{tableMode:"sentinel"}).find(y=>y?.kind==="imageAttachments")||null,S={kind:"message",id:d?.id??null,role:d.role,header:Wo(d,u),text:it(d?.text||""),pendingPhase:d?.pendingPhase||null,attachments:g?{sessionId:g.sessionId,attachments:g.attachments}:null};Vi.set(d,{block:S,text:d.text,kind:d.kind,createdAt:d.createdAt,time:d.time,sender:d.sender,attachments:d.attachments,role:d.role,id:d.id,pendingPhase:d.pendingPhase,stopped:d.stopped,tableMode:u.tableMode,viewerKey:u.viewerKey,ownerKey:u.ownerKey,sharedContext:u.sharedContext}),f.push(S);continue}const h=ku(d,e,u);h&&f.push(h)}return f}const qi=new WeakMap;function ku(t,e,s){if(!t||typeof t!="object"){const o=Tt(t,e,s);return o.length>0?{kind:"lines",variant:"event",lines:o}:null}const n=qi.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=Tt(t,e,s),r=i.length>0?{kind:"lines",variant:"event",lines:i}:null;return qi.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 jn(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 zo(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 jn(n,"magenta",e)}const Mu={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 Yo(t,e){const s=String(t?.reason||"unknown"),i=` ↻ regeneration refused · ${Mu[s]||s.replace(/_/g," ")} `;return jn(i,"yellow",e)}function Qo(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 jn(r,"red",e)}function Un(t,e=80,s={}){const n=ru(t);if(!n||n.length===0)return[];const i=Math.max(20,Number(e)||80),r=n.filter(m=>m.pendingPhase==="queued").length,o=n.filter(m=>m.pendingPhase==="pending").length,a=n.filter(m=>m.pendingPhase==="cancelling").length,l=n.filter(m=>m.pendingPhase==="rejected").length,u=[];o>0&&u.push(`${o} pending`),r>0&&u.push(`${r} queued`),a>0&&u.push(`${a} cancelling`),l>0&&u.push(`${l} rejected`);const p=[[{text:` queued prompts: ${u.length>0?u.join(" · "):"queued prompts"} `,color:"gray",trailingRule:!0}]],h=s?.tableMode?{tableMode:s.tableMode}:{};for(const[m,g]of n.entries()){hs(p,Tt(g,i,h));const S=n[m+1];S&&Vo(g,S)&&Qe(p[p.length-1]).trim().length>0&&p.push(Ko())}return p}function Nu(t){const e=Es(t),s=[],n=new Set;for(const i of e||[])for(const r of ml(i?.text||"")){const o=`${r.sessionId}/${r.filename}`;n.has(o)||(n.add(o),s.push(r))}return s}function Pu(t){const e=Es(t),s=[],n=new Set;for(const i of e||[])for(const r of gl(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 Wn(t,e){const s=io(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function Ou(t){return io(t)||"(unknown)"}function Xo(t,e={}){const s=Te(t),n=t.sessions?.byId||{},i=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],r=Fn(n),o=Bn(i,n),a=Po(e?.width);if(!s)return{color:"cyan",title:Re("Chat","cyan"),titleRight:null,animateTitleRight:!1};const l=te(s.sessionId),u=s.isSystem?"yellow":"cyan",f=Re(s.isSystem?`⚙ ${kt(s,t.branding?.title||"PilotSwarm")}`:vs(s)||"Chat",u),d=i.find(v=>v.sessionId===s.sessionId),p=Do(s.sessionId,d,r,o);p&&f.push({text:` ${p.text}`,color:p.color}),a||f.push({text:` [${l}]`,color:"gray"});const h=t.history?.bySessionId?.get(s.sessionId)||null,m=Array.isArray(t.outbox?.bySessionId?.[s.sessionId])?t.outbox.bySessionId[s.sessionId]:[],g=t.ui?.chatViewMode==="summary"?null:nu(s,h,h?.chat||[],m),S=t.connection?.mode||"local",y=Vc(s,S),A=pu(g),x=A?[...y,...y.length?[{text:" · ",color:"gray"}]:[],...A]:y;return{color:s.isSystem?"yellow":"cyan",title:f,titleRight:x.length?x:null,animateTitleRight:!!g}}function _u(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function Kn(t,e=12){const s=_u(t),n=Te(t),i=Re("Activity","gray");return n?.isGroup?{title:i,disabled:!0,lines:[{text:ca,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 Jo(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 Zo(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":Jo(e)}function Ru(t){return t==="raw"?"raw summary":"pretty text"}function Lu(t){return t?.sessionId?`session-${t.sessionId}`:null}function $u(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},i=Lu(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 Fu(t){const e=As(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:Zo(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${te(s)}] `,color:"gray"}]:[],{text:`${n} `,color:Jo(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function Bu(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${te(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:Zo(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function Du(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:Ru(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=$u(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"?Fu(o):Bu(o))]}function zi(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function Hu(t){return/\.(json|jsonl)$/i.test(String(t||""))}function Gu(t){return Ne.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function ju(t=""){const e=String(t||"").split(`
|
|
51
|
+
`);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function Yi(t,{selected:e=!1,width:s=24,label:n=null}={}){const i=Math.max(8,s),r=zi(t)?"# ":Hu(t)?"{ ":"• ",o=ea(`${r}${n||t}`,i).padEnd(i," ");return e?Pe(o):{text:o,color:zi(t)?"cyan":"white",bold:!1}}function Ae(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function Uu(t,e={}){if(!t)return new Set;const{childMap:s}=$n(e),n=new Set([t]),i=[t];for(;i.length>0;){const r=i.shift(),o=s.get(r)||[];for(const a of o)!a||n.has(a)||(n.add(a),i.push(a))}return n}function ms(t,e=Ae(t)){const s=Te(t)?.sessionId||null,n=Array.isArray(t.sessions?.flat)?t.sessions.flat.map(l=>l?.sessionId||l).filter(Boolean):[],i=Object.keys(t.files?.bySessionId||{}).filter(Boolean);if(e==="allSessions")return[...new Set([...n,...i])];const r=Uu(s,t.sessions?.byId||{});if(r.size===0)return[];const o=[],a=new Set;for(const l of[s,...n,...Object.keys(t.sessions?.byId||{}),...i])!l||a.has(l)||!r.has(l)||(o.push(l),a.add(l));for(const l of r)a.has(l)||o.push(l);return o}function Qi(t){const s=Te(t)?.sessionId;if(!s)return[];const i=t.history?.bySessionId?.get?.(s)?.events||[],r=new Set,o=[],a=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{})\]]+)/g;for(const l of i){const u=typeof l?.data?.content=="string"?l.data.content:"";if(!u)continue;a.lastIndex=0;let f;for(;(f=a.exec(u))!==null;){const d=`${f[1]}/${f[2]}`;r.has(d)||(r.add(d),o.push(d))}}return o}function nt(t){const e=Ae(t);Te(t)?.sessionId;const s=t.files?.filter?.query||"",n=ms(t,e),i=e==="allSessions"||n.length>1,r=[];for(const o of n){const a=us(t.files?.bySessionId?.[o]?.entries);for(const l of a){const u=l.filename;r.push({id:`${o}/${u}`,sessionId:o,filename:u,entry:l,label:i?`[${te(o)}] ${u}`:u})}}return r.filter(o=>st(o.filename,s)||st(o.sessionId,s)||st(o.label,s))}function Ve(t){const e=nt(t);if(e.length===0)return null;const s=t.files?.selectedArtifactId||null;if(s){const o=e.find(a=>a.id===s);if(o)return o}if(Ae(t)==="allSessions"){const o=Te(t)?.sessionId||null,a=o&&t.files?.bySessionId?.[o]?.selectedFilename||null;if(o&&a){const l=e.find(u=>u.sessionId===o&&u.filename===a);if(l)return l}return e[0]}const i=Te(t)?.sessionId||null,r=i&&t.files?.bySessionId?.[i]?.selectedFilename||null;return e.find(o=>o.sessionId===i&&o.filename===r)||e[0]}function Vn(t,e={}){const s=Te(t),n=Math.max(12,Number(e?.listWidth)||Number(e?.width)||24),i=Math.max(18,Number(e?.previewWidth)||Number(e?.width)||36),r=e?.showHints!==!1,o=s?.sessionId||null,a=Ae(t),l=t.files?.filter?.query||"",u=nt(t),f=Ve(t),d=f?.filename||null,p=Math.max(0,u.findIndex(M=>M.id===f?.id)),h=f?.sessionId&&d&&t.files?.bySessionId?.[f.sessionId]?.previews?.[d]||null,m=h||f?.entry||null,g=s?te(s.sessionId):"",S=ms(t,a),y=a!=="allSessions"&&S.some(M=>M&&M!==o),A=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(M=>M?.sessionId||M):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),x=a==="allSessions"&&A.some(M=>!t.files?.bySessionId?.[M]?.loaded||t.files?.bySessionId?.[M]?.loading),v=a==="allSessions"&&A.map(M=>t.files?.bySessionId?.[M]?.error).find(Boolean)||null,I=[Gu("files"),...s||a==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(a==="allSessions")x&&u.length===0?I.push({text:"Loading exported files across all sessions…",color:"gray"}):v&&u.length===0?I.push({text:v,color:"red"}):u.length===0?(I.push({text:l?`No artifacts matched "${l}" across any session.`:"No exported files across any session yet.",color:"gray"}),I.push({text:l?"Clear the query or switch back to the selected session.":"Switch the filter back to the selected session or wait for agents to export artifacts.",color:"gray"})):I.push(...u.map((M,$)=>Yi(M.filename,{selected:$===p,width:n,label:M.label})));else if(s){const M=o?t.files?.bySessionId?.[o]:null;Array.isArray(M?.entries)&&M.entries;const $=u.filter(D=>S.includes(D.sessionId));M?.loading?I.push({text:"Loading exported files…",color:"gray"}):M?.error?I.push({text:M.error,color:"red"}):$.length===0&&S.every(D=>{const K=t.files?.bySessionId?.[D]?.entries;return!Array.isArray(K)||K.length===0})?(I.push({text:l?`No artifacts matched "${l}" for this ${y?"session tree":"session"}.`:`No exported files for this ${y?"session tree":"session"} yet.`,color:"gray"}),I.push({text:l?"Clear the query or upload an artifact to this session.":y?"Artifacts exported by this session or any child session will appear here.":"Agents must write/export artifacts before they appear here.",color:"gray"})):I.push(...$.map((D,K)=>Yi(D.filename,{selected:K===p,width:n,label:D.label})))}let w,C;!s&&a!=="allSessions"?(C=[{text:"Preview",color:"cyan",bold:!0}],w=[{text:"No session selected.",color:"gray"}]):d?h?.loading?(C=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||f?.sessionId&&f.sessionId!==o)&&f?.sessionId?[{text:` · ${te(f.sessionId)}`,color:"gray"}]:[]],w=[{text:"Loading file preview…",color:"gray"}]):h?.error?(C=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||f?.sessionId&&f.sessionId!==o)&&f?.sessionId?[{text:` · ${te(f.sessionId)}`,color:"gray"}]:[]],w=[{text:h.error,color:"red"}]):(C=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(a==="allSessions"||f?.sessionId&&f.sessionId!==o)&&f?.sessionId?[{text:` · ${te(f.sessionId)}`,color:"gray"}]:[],...h?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:h?.isBinary===!0?[{text:" [file]",color:"gray"}]:h?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],w=h?.renderMode==="markdown"?ps(Et(h?.content||"",{width:i})):ju(h?.content||"")):(C=[{text:"Preview",color:"cyan",bold:!0}],w=[{text:"Select a file to preview it here.",color:"gray"}]);const N=a==="allSessions"?"Files: all sessions":s?`Files: ${g}${y?" tree":""}`:"Files",R=a==="allSessions"?"all sessions":s?`${g}${y?" tree":""}`:"Files",F=a==="allSessions"?`Artifacts${u.length>0?` [${u.length}]`:""}`:`Artifacts${y?" tree":""}${u.length>0?` [${u.length}]`:""}`,L=l?` · @${l}`:"";return{panelTitle:[{text:`${N}${L}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${R}${L}`,color:"magenta",bold:!0}],listTitle:[{text:`${F}${L}`,color:"cyan",bold:!0}],listLines:I,listBodyLines:I.slice(1),selectedIndex:p,selectedFilename:d,selectedSessionId:f?.sessionId||null,scope:a,previewTitle:C,previewLines:w,previewContent:h?.content||"",previewContentType:h?.contentType||"",previewRenderMode:h?.renderMode||null,previewIsBinary:m?.isBinary===!0,previewSizeBytes:m?.sizeBytes??null,previewUploadedAt:m?.uploadedAt||"",previewSource:m?.source||null,previewError:h?.error||null,previewLoading:!!h?.loading,previewScrollOffset:t.ui.scroll.filePreview||0,fullscreen:!!t.files?.fullscreen,fullscreenTitle:[{text:N,color:"magenta",bold:!0},...d?[{text:" · ",color:"gray"},{text:d,color:"cyan",bold:!0}]:[],...r?[{text:" [f filter] [u upload] [a download] [x delete] [o open] [v/esc close fullscreen]",color:"gray"}]:[]]}}function Wu(t){const e=t.admin||{},s=e.profile||null,n=e.ghcpKey||{editing:!1,draft:"",saving:!1,error:null},i=s?{provider:s.provider||"",subject:s.subject||"",email:s.email||null,displayName:s.displayName||null}:t.auth?.principal||null,r=e.systemGhcpKey||{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null},o=!!s?.isAdmin,a=o&&!!n.storeAsSystem,l=a?!!r.configured:!!s?.githubCopilotKeySet,u=a?"System key":"key",f=r.configured&&r.changedBy?` (set by ${r.changedBy})`:"",d=n.saving?"Saving...":n.editing?"Editing — Enter to save, Esc to cancel":a?r.configured?`System key configured — ownerless system sessions use it for GitHub Copilot models${f}`:"System key not configured — ownerless system sessions fall back to env GITHUB_TOKEN":s?.githubCopilotKeySet?"Configured (overrides env GITHUB_TOKEN for this user)":"Not configured (using env GITHUB_TOKEN fallback)",p=[];return n.editing?(p.push({id:"save",label:"Save",key:"Enter"}),p.push({id:"cancel",label:"Cancel",key:"Esc"})):(p.push({id:"edit",label:l?`Replace ${u}`:`Set ${u}`,key:"e"}),l&&p.push({id:"clear",label:`Clear ${u}`,key:"c"}),p.push({id:"refresh",label:"Refresh",key:"r"})),p.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:o,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:l,storeAsSystem:a,editing:!!n.editing,draft:n.draft||"",cursorIndex:Math.max(0,Math.min(Number(n.cursorIndex)||0,String(n.draft||"").length)),saving:!!n.saving,error:n.error||null,statusText:d},systemGhcpKey:{supported:!!r.supported,loading:!!r.loading,configured:!!r.configured,changedBy:r.changedBy||null,changedAt:r.changedAt||null,error:r.error||null},actions:p}}function Ku(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=Te(t),i=!!n?.pendingQuestion?.question,r=n?.sessionId&&Array.isArray(t.outbox?.bySessionId?.[n.sessionId])?t.outbox.bySessionId[n.sessionId]:[],o=r.length>0,a=r.some(A=>A?.phase==="pending"),l=t.ui.promptEdit?.sessionId===n?.sessionId,u=l&&t.ui.promptEdit?.phase==="queued",f=l&&t.ui.promptEdit?.phase==="cancelling",d=s===e?"v/esc close fullscreen":"v fullscreen";if(t.ui.modal?.type==="artifactUpload")return{left:"Upload a local file into this session's artifact store",right:"type path · left/right move · enter upload · esc cancel"};if(t.ui.modal?.type==="renameSession")return{left:"Rename the selected session title",right:"type title · left/right move · enter save · esc cancel"};if(t.ui.modal?.type==="shareSession")return{left:"Share the selected session",right:"name [r|w] grants · -name revokes · enter apply · esc close"};if(t.ui.modal?.type==="artifactPicker")return{left:"Select a linked artifact or URL",right:"up/down move · enter open/download · a/esc close"};if(t.ui.modal?.type==="modelPicker")return{left:"Select a model for the new session",right:"up/down move · enter next · esc cancel"};if(t.ui.modal?.type==="reasoningEffortPicker")return{left:"Select reasoning effort for the new session",right:"up/down move · enter create · esc cancel"};if(t.ui.modal?.type==="themePicker")return{left:"Select a shared portal/TUI theme",right:"up/down move · enter apply · esc close"};if(t.ui.modal?.type==="sessionAgentPicker")return{left:"Select an agent for the new session",right:"up/down move · enter create · esc cancel"};if(t.ui.modal?.type==="sessionGroupPicker")return{left:"Move selected session(s) to a group",right:"up/down move · enter choose · esc cancel"};if(t.ui.modal?.type==="sessionGroupName")return{left:"Name the new group",right:"type name · left/right move · enter create · esc cancel"};if(t.ui.modal?.type==="logFilter")return{left:"Adjust log filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="filesFilter")return{left:"Adjust files browser filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="sessionOwnerFilter")return{left:"Adjust session filters",right:"up/down choose · space toggle · esc close"};const p=!!t.sessions?.selectMode,h=Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds.length:0;if(p&&e===T.SESSIONS)return{left:`Select mode · ${h} selected`,right:"up/down move · space toggle · ctrl-g group · c cancel · d complete · D hard delete · V/esc exit"};const g=(t.ui?.chatViewMode==="summary"?"summary":"transcript")==="summary"?"s transcript":"s summary",S={[T.SESSIONS]:"up/down switch · ctrl-u/ctrl-d page · ctrl-g move group · f filter · P pin · V select · d done · D delete · r refresh · t title · v visibility · S share · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane · p prompt",[T.CHAT]:`${g} · j/k scroll · ctrl-u/ctrl-d page · e older history · g/G top/bottom · d done · ${d} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane · p prompt`,[T.INSPECTOR]:t.ui.inspectorTab==="logs"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · t tail · f filter · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane`:t.ui.inspectorTab==="stats"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f cycle session/fleet/users · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:t.ui.inspectorTab==="files"?t.files?.fullscreen?"a download · x delete · u/ctrl-a upload · o open · f filter · j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · v/esc close fullscreen · left/right tab · [/] resize pane · {/} columns · T themes · ? help · tab next pane":"j/k files · a download · x delete · u/ctrl-a upload · o open · f filter · ctrl-u/ctrl-d page preview · g/G preview top/bottom · d done · v fullscreen · left/right tab · [/] resize pane · {/} columns · T themes · ? help · tab next pane":t.ui.inspectorTab==="history"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f format · r refresh · a save artifact · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:t.ui.inspectorTab==="sequence"?`j/k turn · enter expand · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · h/l focus · a linked items · drag copy · m next tab · tab next pane`,[T.ACTIVITY]:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · h left · tab next pane`,[T.PROMPT]:i?`type answer · enter reply · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:l?u?`queued prompt selected · d delete · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:f?`cancelling prompt selected · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:`edit pending prompt · enter send batch · up/down cycle pending · esc cancel · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:a?`type message · enter queues · enter on empty sends batch · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:o?`type message · enter queues behind durable items · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:`type message · enter send · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`};let y=S[e]||S[T.SESSIONS];return jo(Te(t))&&(y=`ctrl-x stop · ${y}`),{left:t.ui.statusText,right:y}}function at(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function J(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 ye(t){return Array.from(String(t||"")).length}function ea(t,e){const s=String(t||"");return e<=0?"":ye(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function Ye(t,e){const s=ea(t,e),n=Math.max(0,e-ye(s));return s+" ".repeat(n)}function U(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function le(t){const e=Number(t);if(!Number.isFinite(e)||e<0)return"?";if(e<1024)return`${Math.round(e)} B`;if(e<1024*1024){const n=e/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=e/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function Xi(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 ta(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?ye(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function Vu(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 sa(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 qu(t,e=""){return sa([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function zu(t,e=""){return sa([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function As(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 Yu=300*1e3,Qu="last 5m";function qn(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-Yu,endMs:e,label:Qu}}function Xu(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 na(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 Ju=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done"]);function Zu(t){return Ju.has(t)}function ed(t){const e=ro(t?.createdAt),s=As(t?.workerNodeId),n=Vu(t),i=ta(n,20),r=t?.createdAt instanceof Date?t.createdAt.getTime():new Date(t?.createdAt||0).getTime(),o={time:e,createdAtMs:Number.isFinite(r)?r:0,nodeLabel:s,color:"white",detail:"",type:"other"};switch(t?.eventType){case"session.turn_started":return{...o,type:"turn_start",color:"gray",detail:`turn ${t?.data?.iteration??"?"}`};case"session.turn_completed":{const a=Number(t?.data?.turnIndex??t?.data?.iteration);return{...o,type:"turn_end",color:"gray",detail:`turn ${t?.data?.iteration??"?"} done`,...Number.isFinite(a)?{completedTurn:a}:{}}}case"user.message":return{...o,type:"user_msg",color:"white",detail:i?`>> ${i}`:">> user"};case"assistant.message":return{...o,type:"response",color:"green",detail:i?`< ${i}`:"< response"};case"system.message":return{...o,type:"system",color:"yellow",detail:i||"system"};case"session.wait_started":return{...o,type:"wait",color:"yellow",detail:`wait ${gt(t?.data?.seconds??0)}`};case"session.wait_completed":return{...o,type:"timer",color:"yellow",detail:`${gt(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const a=zu(t,i);return{...o,type:"dehydrate",color:"yellow",detail:a?`lossy ${a}`:"lossy handoff"}}case"session.dehydrated":return{...o,type:"dehydrate",color:"cyan",detail:`ZZ ${qu(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||te(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${gt(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${fs(t?.data?.nextFireAtMs??t?.data?.nextFireAt)}`};case"session.cron_fired":return{...o,type:"cron_fire",color:"magenta",detail:"cron fired"};case"session.cron_at_fired":return{...o,type:"cron_fire",color:"magenta",detail:`cron fired ${fs(t?.data?.scheduledAt)}`};case"session.cron_cancelled":case"session.cron_at_cancelled":return{...o,type:"cron_cancel",color:"magenta",detail:"cron off"};case"session.cron_at_completed":return{...o,type:"cron_cancel",color:"magenta",detail:"cron done"};case"session.command_received":return{...o,type:"cmd_recv",color:"magenta",detail:`/${t?.data?.cmd||"?"}`};case"session.command_completed":return{...o,type:"cmd_done",color:"magenta",detail:`/${t?.data?.cmd||"?"} ok`};case"session.compaction_start":return{...o,type:"compaction",color:"gray",detail:"compaction…"};case"session.compaction_complete":return{...o,type:"compaction",color:"gray",detail:"compacted"};case"session.error":return{...o,type:"error",color:"red",detail:i||"error"};default:return null}}function ia(t=[]){const e=[];for(const s of t||[]){const n=ed(s);n&&e.push({...n,nodeLabel:Zu(n.type)?"orch":n.nodeLabel||"orch"})}return e}function td(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 sd(t){const e=String(t?.error||"").trim();if(!e)return null;const s=_n(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),i=Number.isFinite(n)?n:Date.now();return{time:ro(i),createdAtMs:i,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${ta(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function nd(t,e){const s=sd(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 id(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=ia(i?.events||[]);for(const o of r){if(!o?.nodeLabel||o.nodeLabel==="orch")continue;const a=Number(o.createdAtMs||0);Number.isFinite(a)&&(a<e||a>s||n.add(o.nodeLabel))}}return Array.from(n).sort((i,r)=>i.localeCompare(r))}function rd(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const i of n?.events||[]){if(!na(i,e))continue;const r=As(i?.workerNodeId);r&&s.add(r)}return Array.from(s).sort((n,i)=>n.localeCompare(i))}function ra(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 Ji(t){return Array.isArray(t?.runs)?t.runs.reduce((e,s)=>e+ye(String(s.text??"")),0):Array.isArray(t)?t.reduce((e,s)=>e+ye(String(s.text??"")),0):ye(String(t?.text??""))}function od(t,e,s){const n=[{text:Ye("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((i,r)=>{r>0&&n.push({text:" ",color:null}),n.push({text:Ye(i,s),color:"white",bold:!0})}),ra(n)}function ad(t,e,s,n=1/0){const i=`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`;return U(Number.isFinite(n)?i.slice(0,Math.max(e,n)):i,"gray")}function ld(t,e,s){const n=t?.orchestration?.bySessionId?.[e?.sessionId]||null;let i="loading orchestration stats...";if(n)if(n.loading&&!n.stats)i="loading orchestration stats...";else if(!n.stats)i="orchestration stats unavailable";else{const r=n.stats,o=[],a=[];if(typeof r.orchestrationVersion=="string"&&r.orchestrationVersion&&(o.push(`v ${r.orchestrationVersion}`),a.push(`v${r.orchestrationVersion}`)),r.historyEventCount!=null&&(o.push(`hist ${Number(r.historyEventCount)||0} ev`),a.push(`h${Number(r.historyEventCount)||0}`)),r.historySizeBytes!=null){const l=le(r.historySizeBytes);o.push(l),a.push(l)}r.queuePendingCount!=null&&(o.push(`q ${Number(r.queuePendingCount)||0}`),a.push(`q${Number(r.queuePendingCount)||0}`)),r.kvUserKeyCount!=null&&(o.push(`kv ${Number(r.kvUserKeyCount)||0} keys`),a.push(`kv${Number(r.kvUserKeyCount)||0}`)),r.kvTotalValueBytes!=null&&o.push(le(r.kvTotalValueBytes)),i=s<=40?a.join(" · "):o.join(" | "),i||(i="orchestration stats unavailable")}return s<=52?[J([{text:"Stats ",color:"cyan",bold:!0},{text:i,color:"white"}],Math.max(18,s))]:re({title:"Stats",body:i,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function cd(t,e,s,n){const i=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],r=[{text:Ye(t.time||"",s),color:"white"},{text:" ",color:null}];return e.forEach((o,a)=>{a>0&&r.push({text:" ",color:null}),o===i?r.push({text:Ye(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):r.push({text:Ye("│",n),color:"gray"})}),ra(r)}function ud(t,e){const s=[];return t.forEach((n,i)=>{i>0&&s.push({text:" ",color:null}),s.push({text:Ye(n,e),color:"white",bold:!0})}),s}const dd=new Set(["none","minimal","low","medium","high","xhigh","max"]);function fd(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&&dd.has(n)?s.length-2:s.length-1;return s[Math.max(0,i)]||s[0]||"unknown"}function Zi(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 et(t){return Number(t||0).toLocaleString("en-US")}function pd(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 hd(t,{expanded:e,selected:s,maxWidth:n}){const i=e?"v":">",r=fd(t?.model),o=t?.durationMs!=null?`${(Number(t.durationMs)/1e3).toFixed(1)}s`:"n/a",a=`${i} Mod: ${r} tok ${Zi(t?.tokensInput)}/${Zi(t?.tokensOutput)} dur ${o}`,l=[];if(s?l.push(Pe(Ye(a,Math.max(18,n)))):l.push([{text:a,color:"magenta"}]),e){const u=[["model",t?.reasoningEffort?`${t?.model||"(unknown)"}:${t.reasoningEffort}`:t?.model||"(unknown)"],["duration",t?.durationMs!=null?`${et(t.durationMs)} ms`:null],["tokens",`${et(t?.tokensInput)} in / ${et(t?.tokensOutput)} out`],["cache",`${et(t?.tokensCacheRead)} read / ${et(t?.tokensCacheWrite)} write`],["tools",`${et(t?.toolCalls)} calls / ${et(t?.toolErrors)} errors`],["names",Array.isArray(t?.toolNames)&&t.toolNames.length?t.toolNames.join(", "):null],["worker",t?.workerNodeId||null],["result",t?.resultType||null],["error",t?.errorMessage||null]].filter(([,f])=>f!=null&&f!=="");for(const[f,d]of u)l.push([{text:` ${f}: `,color:"gray"},{text:String(d),color:"white"}])}return l}function md(t,e,s,n={}){const i=!!n?.allowWideColumns,r=ld(t,e,s),o=t.history.bySessionId.get(e.sessionId),a=nd(td(ia(o?.events||[])),e);if(a.length===0)return{stickyLines:r,lines:[U("No events yet - interact with this session to populate the sequence diagram.")]};const l=qn(t),u=a.filter(L=>Xu(L,l)),f=(u.length>0?u:a).slice(-48),d=id(t,l.startMs,l.endMs),p=Array.from(new Set(f.map(L=>L.nodeLabel).filter(L=>L&&L!=="orch"))).sort((L,M)=>L.localeCompare(M)),h=d.length>0?d:p,m=Math.min(13,Math.max(8,...f.map(L=>ye(String(L.time||""))))),g=Math.max(18,s),S=Math.max(1,Math.floor((g-m-1)/6));let y=["orch",...h];if(!i&&y.length>S){const L=Math.max(1,S-1);y=[...y.slice(0,L),"…"]}const A=Math.max(0,y.length-1),x=Math.max(4,Math.floor((g-m-1-A)/Math.max(1,y.length))),v=n?.sequenceExpansion||null,I=v?pd(o?.events||[]):null,w=v?new Set((v.expandedTurns||[]).map(Number)):null,C=v&&v.selectedTurn!=null?Number(v.selectedTurn):null,N=[];for(const L of f)if(N.push(cd(L,y,m,x)),v&&L.completedTurn!=null){const M=Number(L.completedTurn),$=I.get(M);if($)for(const D of hd($,{expanded:w.has(M),selected:C===M,maxWidth:g}))N.push(D)}const R=od(y,m,x),F=N.reduce((L,M)=>Math.max(L,Ji(M)),Ji(R));return{stickyLines:[...r,U(`Window: ${l.label}`,"gray"),R,ad(y,m,x,F)],lines:N}}function gd(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 yd(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!na(s[n],e))continue;const i=As(s[n]?.workerNodeId);if(i)return i}return null}function Sd(t,e,s,n){const i=s>=16?t?.isSystem?kt(t,e):t?.title||te(t?.sessionId):te(t?.sessionId),r=t?.isSystem?"⚙ ":t?.serviceKind?"⚗ ":`${Lo(t)||"."} `,o=Ye(`${r}${i}`,s);return n?Pe(o):{text:o,color:t?.isSystem?"yellow":vt(t),bold:!!t?.isSystem}}function bd(t,e,s={}){const n=!!s?.allowWideColumns,i=gd(t);if(i.length===0)return[U("No sessions available for the node map.","gray")];const r=qn(t),o=new Map,a=rd(t,r);let l=0,u=0;for(const y of i){const A=t.sessions.byId[y];if(!A)continue;const x=t.history.bySessionId.get(y);x?.events||(l+=1);const v=yd(x,r);!v||!a.includes(v)||(u+=1,o.has(v)||o.set(v,[]),o.get(v).push(A))}if(a.length===0)return[U(`No worker activity in the ${r.label} window.`,"gray")];const f=Math.max(18,e),d=Math.max(1,Math.floor((f+1)/10));let p=a;if(!n&&a.length>d){const y=Math.max(0,d-1),A=[],x=a.slice(0,y);for(const v of a.slice(y))A.push(...o.get(v)||[]);o.set("…",A),p=[...x,"…"]}const h=Math.max(0,p.length-1),m=Math.max(8,Math.floor((f-h)/Math.max(1,p.length))),g=p.reduce((y,A)=>Math.max(y,(o.get(A)||[]).length),0),S=[U(`Window: ${r.label}`,"gray"),ud(p,m),U(p.map(()=>"─".repeat(m)).join(" "),"gray")];for(let y=0;y<g;y+=1){const A=[];p.forEach((x,v)=>{v>0&&A.push({text:" ",color:null});const I=(o.get(x)||[])[y];if(!I){A.push({text:" ".repeat(m),color:null});return}A.push(Sd(I,t.branding?.title||"PilotSwarm",m,I.sessionId===t.sessions.activeSessionId))}),S.push(A)}return l>0&&(S.push(U("","gray")),S.push(U(`Loading worker history for ${l} session(s)…`,"gray"))),u===0&&(S.push(U("","gray")),S.push(U(`No sessions mapped onto worker nodes in the ${r.label} window.`,"gray"))),S}function wd(t,e=72){const s=t.ui.modal;if(!s||s.type!=="modelPicker")return null;const n=Array.isArray(s.groups)?s.groups:[],i=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(24,e-4),o=[],a=[];let l=0;for(const h of n){const m=J([{text:`${h.providerId}`,color:"cyan",bold:!0},{text:` (${h.providerType||"provider"})`,color:"gray"}],r);o.push(m),a.push(null);for(const g of h.models||[]){const S=Array.isArray(s.items)?s.items.findIndex(I=>I.id===g.id):-1,y=S===i,A=!!g.disabled,x=J([{text:"· ",color:"gray"},{text:g.modelName||g.qualifiedName||g.id,color:A?"gray":"white",bold:!!g.isDefault&&!A},...g.cost?[{text:` [${g.cost}]`,color:"gray"}]:[],...A?[{text:" ⊘ needs GitHub key",color:"yellow"}]:[],...g.isDefault?[{text:" ← current default",color:"gray"}]:[]],r),v=y?Pe(x.map(I=>I.text).join("").padEnd(r," ")):x;y&&(l=o.length),o.push(v),a.push(S>=0?S:null)}}const u=Array.isArray(s.items)&&s.items[i]||null,f=Array.isArray(u?.supportedReasoningEfforts)?u.supportedReasoningEfforts.filter(Boolean):[],d=typeof u?.defaultReasoningEffort=="string"?u.defaultReasoningEffort:null,p=u?[[{text:u.modelName||u.qualifiedName||u.id,color:"white",bold:!0}],[{text:`${u.providerId} (${u.providerType||"provider"})`,color:"gray"}],...u.cost?[[{text:`Cost: ${u.cost}`,color:"gray"}]]:[],...f.length>0?[[{text:`Reasoning: ${f.join(", ")}`,color:"gray"}]]:[],...d?[[{text:`Default reasoning: ${d}`,color:"gray"}]]:[],...u.disabled?[[{text:"Unavailable: requires a GitHub Copilot key. Add yours in the Admin console, then reopen this picker.",color:"yellow"}]]:[],[{text:"",color:"gray"}],[{text:u.description||"No description available for this model.",color:u.description?"white":"gray"}]]:[[{text:"No model selected.",color:"gray"}]];return{title:s.title||"Select model for new session",rows:o,rowItemIndexes:a,selectedRowIndex:l,detailsTitle:"Model Details",detailsLines:p,idealWidth:Math.min(Math.max(46,o.reduce((h,m)=>Array.isArray(m)?Math.max(h,at(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function Id(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=n.map((d,p)=>{const h=p===i,m=J([{text:d?.kind==="generic"?"○ ":"· ",color:"gray"},{text:d?.title||d?.agentName||d?.id||"Agent",color:"white",bold:!0},...d?.kind==="generic"?[{text:" [generic]",color:"gray"}]:[{text:` (${d?.agentName||d?.id||"agent"})`,color:"gray"}]],r);return h?Pe(m.map(g=>g.text).join("").padEnd(r," ")):m}),a=n[i]||null,l=s.sessionOptions?.model||null,u=s.sessionOptions?.reasoningEffort||null,f=a?[[{text:a.title||a.agentName||a.id||"Agent",color:"white",bold:!0}],...a.kind==="generic"?[[{text:"Open-ended session",color:"gray"}]]:[[{text:a.agentName||a.id||"agent",color:"gray"}]],...l?[[{text:`Model: ${l}`,color:"gray"}]]:[],...u?[[{text:`Reasoning: ${u}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:a.description||(a.kind==="generic"?"Create a general-purpose session without a specialized named agent.":"No description available for this agent."),color:a.description?"white":"gray"}],[{text:"",color:"gray"}],[{text:a.tools?.length?`Tools: ${a.tools.join(", ")}`:"Tools: system defaults only",color:"gray"}]]:[[{text:"No agent selected.",color:"gray"}]];return{title:s.title||"Select agent for new session",rows:o,selectedRowIndex:i,detailsTitle:"Agent Details",detailsLines:f,idealWidth:Math.min(Math.max(52,o.reduce((d,p)=>Array.isArray(p)?Math.max(d,at(p)):Math.max(d,String(p?.text||"").length),0)+4),e)}}function xd(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((f,d)=>{const p=d===i,h=J([{text:"· ",color:"gray"},{text:String(f?.label||f?.id||"effort"),color:"white",bold:!0},...f?.isDefault?[{text:" ← model default",color:"gray"}]:[]],r);return p?Pe(h.map(m=>m.text).join("").padEnd(r," ")):h}),a=n[i]||null,l=s.modelItem||null,u=[[{text:l?.modelName||l?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${l?.providerId||"provider"} (${l?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:a?.id?`Using reasoning effort: ${a.id}`:"Choose an effort.",color:"white"}]];return{title:s.title||"Select reasoning effort",rows:o,selectedRowIndex:i,detailsTitle:"Reasoning Details",detailsLines:u,idealWidth:Math.min(Math.max(46,o.reduce((f,d)=>Array.isArray(d)?Math.max(f,at(d)):Math.max(f,String(d?.text||"").length),0)+4),e)}}function vd(t,e=64){const s=t.ui.modal;if(!s||s.type!=="contextTierPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(24,e-4),o=n.map((d,p)=>{const h=p===i,m=J([{text:"· ",color:"gray"},{text:String(d?.label||d?.id||"tier"),color:"white",bold:!0},...d?.isDefault?[{text:" ← model default",color:"gray"}]:[]],r);return h?Pe(m.map(g=>g.text).join("").padEnd(r," ")):m}),a=n[i]||null,l=s.modelItem||null,u=a?.label||a?.id,f=[[{text:l?.modelName||l?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${l?.providerId||"provider"} (${l?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:u?`Using context window: ${u}`:"Choose a context window.",color:"white"}],[{text:"Long context costs more per token.",color:"gray"}]];return{title:s.title||"Select context window",rows:o,selectedRowIndex:i,detailsTitle:"Context Window",detailsLines:f,idealWidth:Math.min(Math.max(46,o.reduce((d,p)=>Array.isArray(p)?Math.max(d,at(p)):Math.max(d,String(p?.text||"").length),0)+4),e)}}function Ed(t,e=72){const s=t.ui.modal;if(!s||s.type!=="sessionGroupPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(24,e-4),o=Array.isArray(s.sessionIds)?s.sessionIds.length:0,a=n.map((f,d)=>{const p=d===i,h=f?.kind==="noGroup"?"○ ":f?.kind==="newGroup"?"+ ":"🗂 ",m=J([{text:h,color:f?.kind==="group"?"cyan":"gray",bold:f?.kind!=="noGroup"},{text:f?.label||f?.groupId||"Group",color:"white",bold:!0},...f?.kind==="group"?[{text:` (${f.memberCount??0})`,color:"gray"}]:[]],r);return p?Pe(m.map(g=>g.text).join("").padEnd(r," ")):m}),l=n[i]||null,u=l?[[{text:l.label||l.groupId||"Group",color:"white",bold:!0}],[{text:`${o} session${o===1?"":"s"} selected`,color:"gray"}],...l.kind==="group"?[[{text:`${l.memberCount??0} current member${l.memberCount===1?"":"s"}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:l.description||"Move selected session(s) to this group.",color:"white"}]]:[[{text:"No group selected.",color:"gray"}]];return{title:s.title||"Move to Group",rows:a,selectedRowIndex:i,detailsTitle:"Move Details",detailsLines:u,idealWidth:Math.min(Math.max(50,a.reduce((f,d)=>Array.isArray(d)?Math.max(f,at(d)):Math.max(f,String(d?.text||"").length),0)+4),e)}}function Ad(t,e=76){const s=t.ui.modal;if(!s||s.type!=="renameSession")return null;const n=String(s.value||""),i=typeof s.agentTitlePrefix=="string"&&s.agentTitlePrefix.trim()?s.agentTitlePrefix.trim():null,r=String(s.currentTitle||"").trim(),o=n.trim()?i?`${i}: ${n.trim()}`:n.trim():i?`${i}: …`:"…",a=[[{text:"Current: ",color:"gray"},{text:r||"(untitled session)",color:r?"white":"gray"}],[{text:"Saved as: ",color:"gray"},{text:o,color:"white",bold:!0}],...i?[[{text:"Named-agent prefix stays fixed.",color:"gray"}]]:[]];return{title:s.title||"Rename Session",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:i?"Type the title after the fixed agent name":"Type a session title",helpTitle:"Rename Rules",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" save ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],[{text:"Manual titles stop future automatic LLM title changes for this session.",color:"gray"}]],detailsLines:a,idealWidth:Math.min(Math.max(56,ye(r||"(untitled session)")+18,ye(o)+18),e)}}function Cd(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,ye(r)+18),e)}}function Td(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?Fo(r,t.branding?.title):te(i):"A new session will be created on upload",a=[[{text:"Target: ",color:"gray"},{text:o,color:i?"white":"gray",bold:!!i}]];return{title:s.title||"Upload Artifact",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:"~/path/to/file.md",helpTitle:"Upload Rules",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" upload ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],[{text:"The file is uploaded into this session's artifact store immediately.",color:"gray"}],[{text:"Use the files browser or @-driven browsing in the prompt to reference it after upload.",color:"gray"}]],detailsLines:a,idealWidth:Math.min(Math.max(60,ye(n||"~/path/to/file.md")+20,ye(o)+20),e)}}function zn(t,e={},s=96,n="Filters",i="Choose how this pane is filtered and rendered."){const r=Array.isArray(t.items)?t.items:[],o=Math.max(0,Number(t.selectedIndex)||0),a=r[o]||null,l=r.map((u,f)=>{const d=e?.[u.id]||u.options?.[0]?.id,p=(u.options||[]).map(h=>h.id===d?Pe(h.label):{text:h.label,color:"white"});return{id:u.id,title:u.label,focused:f===o,description:u.description||"",lines:p.length>0?p:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(u.label||"").length+4,...(u.options||[]).map(h=>String(h?.label||"").length+4))}});return{title:t.title||n,panes:l,helpTitle:a?.label||n,helpLines:[[{text:a?.description||i,color:"white"}],[{text:"",color:"gray"}],[{text:"Tab/Shift-Tab",color:"cyan",bold:!0},{text:" switch filter ",color:"gray"},{text:"Up/Down",color:"cyan",bold:!0},{text:" change value ",color:"gray"},{text:"Enter",color:"cyan",bold:!0},{text:" close ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}]],footerRuns:[{text:"Tab/Shift-Tab",color:"cyan",bold:!0},{text:" switch filter · ",color:"gray"},{text:"Up/Down",color:"cyan",bold:!0},{text:" change value · ",color:"gray"},{text:"Enter",color:"cyan",bold:!0},{text:" close · ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],idealWidth:Math.min(Math.max(72,l.reduce((u,f)=>u+f.idealWidth,0)+Math.max(0,l.length-1)*2+4),s)}}function oa(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 er(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(i=>i?.kind!=="all"&&oa(i,e,s)).map(i=>i.kind==="me"?"Me":i.label);return n.length>0?n.join(" + "):"All sessions"}function kd(t,e=88){const s=t.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return null;const n=Array.isArray(s.items)?s.items:[],i=t.sessions?.ownerFilter||{all:!0},r=t.auth||{},o=Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1))),a=n[o]||null,l=n.map((f,d)=>{const p=oa(f,i,r),h=f.kind==="system"?"yellow":f.kind==="unowned"?"gray":f.kind==="all"?"cyan":"white",m=[{text:p?"[x] ":"[ ] ",color:p?"cyan":"gray",bold:p},{text:f.label||f.id,color:h,bold:p}];return d===o?No(m,{preserveColors:!0}):m}),u=[[{text:"Active: ",color:"gray"},{text:er(n,i,r),color:"white",bold:!0}],[{text:"",color:"gray"}],[{text:a?.description||"Toggle which session owners appear in the session list.",color:"white"}],[{text:"",color:"gray"}],[{text:"Space",color:"cyan",bold:!0},{text:" toggle ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" close",color:"gray"}]];return{title:s.title||"Session Filter",rows:l.length>0?l:[{text:"No filter entries available.",color:"gray"}],selectedRowIndex:o,detailsTitle:a?.label||"Session Filter",detailsLines:u,idealWidth:Math.min(Math.max(48,l.reduce((f,d)=>Math.max(f,Array.isArray(d)?at(d):ye(d?.text||"")),0)+8,ye(er(n,i,r))+16),e)}}function Md(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:zn(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function Nd(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:zn(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function Pd(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"),a=n.filter(h=>h.kind==="url"),l=o.reduce((h,m)=>{const g=t.files?.bySessionId?.[m.sessionId]?.downloads?.[m.filename];return h+(g?.localPath?1:0)},0),u=Math.max(0,o.length-l),f=n.map((h,m)=>{let g;if(h.kind==="downloadAll")g=J([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${u} pending]`,color:"gray"}],r);else if(h.kind==="url")g=J([{text:"go ",color:"cyan",bold:!0},{text:h.text&&h.text!==h.href?h.text:h.href,color:"white",bold:!0},...h.text&&h.text!==h.href?[{text:` ${h.href}`,color:"gray"}]:[]],r);else{const S=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];g=J([{text:S?.localPath?"ok ":"dl ",color:S?.localPath?"green":"cyan",bold:!0},{text:`${te(h.sessionId)}/`,color:"gray"},{text:h.filename,color:"white"}],r)}return m!==i?g:Pe(g.map(S=>S.text).join("").padEnd(r," "))}),d=n[i]||null;let p=[[{text:"No linked item selected.",color:"gray"}]];if(d?.kind==="downloadAll")p=[[{text:`${o.length} artifacts available`,color:"white",bold:!0}],...a.length>0?[[{text:`${a.length} links available`,color:"gray"}]]:[],[{text:`${l} already downloaded`,color:"gray"}],[{text:`${u} pending download`,color:"gray"}],...s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:"Press Enter to download all pending artifacts.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(d?.kind==="url")p=[[{text:d.text||d.href,color:"white",bold:!0}],[{text:d.href,color:"gray"}],[{text:"",color:"gray"}],[{text:"Press Enter to open this link in the browser.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(d?.kind==="artifact"){const h=t.sessions?.byId?.[d.sessionId]||null,m=t.files?.bySessionId?.[d.sessionId]?.downloads?.[d.filename]||null;p=[[{text:d.filename,color:"white",bold:!0}],[{text:h?Fo(h,t.branding?.title):te(d.sessionId),color:"gray"}],...m?.localPath?[[{text:`Saved to: ${m.localPath}`,color:"white"}]]:s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:m?.localPath?"Press Enter to download this artifact again.":"Press Enter to download this artifact.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]]}return{title:s.title||"Linked Items",rows:f.length>0?f:[{text:"No linked items available.",color:"gray"}],selectedRowIndex:i,detailsTitle:"Linked Item Details",detailsLines:p,confirmLabel:a.length>0?o.length>0?"Open / Download":"Open":"Download",idealWidth:Math.min(Math.max(54,f.reduce((h,m)=>Array.isArray(m)?Math.max(h,at(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function W(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 aa(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 Od(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 Qt(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 Ft(t){return["session","fleet","users"].includes(t)?t:"session"}function Cs(t,e){const s=Ft(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"}),J(n,e)}function _d(t,e,s){if(!e)return[U("No session selected.")];const n=t.sessionStats?.bySessionId?.[e.sessionId]||null;if(!n||n.loading&&!n.summary)return[U("Loading session stats...")];const i=n.summary;if(!i)return[U("Session stats unavailable.")];const r=[],o=Math.max(24,s);r.push(Cs("session",o)),r.push(U("")),r.push(J([{text:"Session ",color:"cyan",bold:!0},{text:te(e.sessionId),color:"white"}],o));const a=e.isSystem?"system":e.owner?"user":"unowned",l=e.isSystem?"system":e.owner?Rn(e.owner):"(?) unowned",u=e.owner?.email||"—";r.push(J([{text:"Owner ",color:"cyan",bold:!0},{text:l,color:e.owner?"white":"gray"}],o)),r.push(J([{text:"Email ",color:"cyan",bold:!0},{text:u,color:e.owner?.email?"white":"gray"}],o)),r.push(J([{text:"Type ",color:"cyan",bold:!0},{text:a,color:a==="user"?"white":"gray"}],o)),i.agentId&&r.push(J([{text:"Agent ",color:"cyan",bold:!0},{text:i.agentId,color:"white"}],o));const f=Wn(i.model||e.model,i.reasoningEffort||e.reasoningEffort);f&&r.push(J([{text:"Model ",color:"cyan",bold:!0},{text:f,color:"white"}],o)),e.createdAt&&r.push(J([{text:"Created ",color:"cyan",bold:!0},{text:Qt(e.createdAt),color:"white"}],o)),e.updatedAt&&r.push(J([{text:"Updated ",color:"cyan",bold:!0},{text:Qt(e.updatedAt),color:"white"}],o)),r.push(U(""));const d=Array.isArray(n.tokensByModel)?n.tokensByModel:[];d.length>1&&(r.push(...re({title:"Models",body:d.map(L=>`${Ou(L.model)} · ${L.turnCount||0} turns · ${W(L.totalTokensInput)} in / ${W(L.totalTokensOutput)} out`).join(`
|
|
52
|
+
`),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),r.push(U("")));const p=(i.tokensInput||0)+(i.tokensOutput||0),h=i.cacheHitRatio,m=h==null?"—":`${(h*100).toFixed(1)}%`;r.push(...re({title:"Tokens",body:rt([["Input",W(i.tokensInput)],["Output",W(i.tokensOutput)],["Total",W(p)],["Cache Read",W(i.tokensCacheRead)],["Cache Write",W(i.tokensCacheWrite)],["Hit Ratio",m]]),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0})),r.push(U(""));const g=Number(i.regenCount)||0,S=i.lastRegenStats&&typeof i.lastRegenStats=="object"?i.lastRegenStats:null,y=Number.isFinite(S?.toEpoch)?S.toEpoch:g,A=S?S.distillMode==="deterministic"||!S.distillMode&&!S.distillerModel?"fast":String(S.distillerModel||"llm").replace(/^[^:]*:/,""):null,x=S?`${S.turnsArchived??0} turn${S.turnsArchived===1?"":"s"} · ${(Number(S.totalMs)/1e3).toFixed(1)}s${A?` · ${A}`:""}`:null;r.push(...re({title:"Persistence",body:rt([["Epoch",String(y)],["Regens",g>0?String(g):null],["Last Regen",x],["Snapshot",le(i.snapshotSizeBytes)],["Uncompressed",i.rawSizeBytes?le(i.rawSizeBytes):null],["Compression",Xi(i.rawSizeBytes,i.snapshotSizeBytes)],["Dehydrations",String(i.dehydrationCount)],["Hydrations",String(i.hydrationCount)],["Lossy Handoffs",String(i.lossyHandoffCount)],["Last Dehydrated",i.lastDehydratedAt?Qt(i.lastDehydratedAt):null],["Last Hydrated",i.lastHydratedAt?Qt(i.lastHydratedAt):null]]),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const v=n.treeStats?.tree;if(v&&v.sessionCount>1){const L=v.cacheHitRatio,M=L==null?"—":`${(L*100).toFixed(1)}%`,$=(v.totalTokensInput||0)+(v.totalTokensOutput||0);r.push(U("")),r.push(...re({title:`Tree (${v.sessionCount} sessions)`,body:rt([["Input",W(v.totalTokensInput)],["Output",W(v.totalTokensOutput)],["Total",W($)],["Cache Read",W(v.totalTokensCacheRead)],["Cache Write",W(v.totalTokensCacheWrite)],["Hit Ratio",M],["Snapshot",le(v.totalSnapshotSizeBytes)],["Uncompressed",v.totalRawSizeBytes?le(v.totalRawSizeBytes):null],["Compression",Xi(v.totalRawSizeBytes,v.totalSnapshotSizeBytes)],["Dehydrations",String(v.totalDehydrationCount)],["Hydrations",String(v.totalHydrationCount)]]),width:o,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const D=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];D.length>1&&(r.push(U("")),r.push(...re({title:"Tree By Model",body:Dd(D),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const I=Array.isArray(n.skillUsage)?n.skillUsage:[];I.length>0&&(r.push(U("")),r.push(...re({title:`Skills (${I.length})`,body:tr(I,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const w=n.treeSkillUsage,C=Array.isArray(w?.rolledUp)?w.rolledUp:[],N=Array.isArray(w?.perSession)?w.perSession.length:0;C.length>0&&N>1&&(r.push(U("")),r.push(...re({title:`Tree Skills (${C.length})`,body:tr(C,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const R=n.factsStats,F=n.treeFactsStats;if(R&&Array.isArray(R.rows)&&R.rows.length>0){r.push(U(""));const L=la(R.rows),M=L?L.split(`
|
|
53
|
+
`).length:0,$=`${R.totalCount} · ${le(R.totalBytes)}`;let D=L;F&&F.totalCount>R.totalCount&&(D+=`
|
|
54
|
+
Tree (${F.sessionIds.length} sessions): ${F.totalCount} · ${le(F.totalBytes)}`),M>0&&r.push(...re({title:`Facts (${$})`,body:D,width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return r}function rt(t,e={}){const s=e.gap??2,n=(t||[]).filter(a=>Array.isArray(a)&&a[1]!=null&&a[1]!=="");if(n.length===0)return"";const i=n.reduce((a,[l])=>Math.max(a,String(l).length),0),r=n.reduce((a,[,l])=>Math.max(a,String(l).length),0),o=" ".repeat(s);return n.map(([a,l])=>`${String(a).padEnd(i)}${o}${String(l).padStart(r)}`).join(`
|
|
55
|
+
`)}function Ts(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 Wt(t,e={}){const s=e.gap??2,n=(t||[]).filter(a=>Array.isArray(a)&&a.length>0);if(n.length===0)return"";const i=n.reduce((a,l)=>Math.max(a,l.length),0),r=new Array(i).fill(0);for(const a of n)for(let l=0;l<i;l+=1){const u=a[l]==null?"":String(a[l]);u.length>r[l]&&(r[l]=u.length)}const o=" ".repeat(s);return n.map(a=>a.map((l,u)=>{const f=l==null?"":String(l);return u===0?f.padEnd(r[u]):f.padStart(r[u])}).join(o)).join(`
|
|
56
|
+
`)}function tr(t,e){const s=t.slice().sort((d,p)=>(p.invocations||0)-(d.invocations||0)).slice(0,12),n=s.map(d=>`${d.invocations||0} inv`),i=n.reduce((d,p)=>Math.max(d,p.length),0),a=4+2+i,l=Number.isFinite(e)&&e>0?Math.max(8,Math.floor(e)-a):1/0,u=s.map((d,p)=>{const h=d.kind==="learned"?"L":"S",m=String(d.name||"(unknown)");return[Ts(`${h} ${m}`,l),n[p]]}),f=Wt(u);return t.length>s.length?`${f}
|
|
57
|
+
… ${t.length-s.length} more`:f}function la(t){const s=t.slice().sort((n,i)=>(i.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),le(n.totalValueBytes||0)]);return Wt(s)}function Rd(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":gt(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return Wt([["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 Ld(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 $d(t,e){const s=t.slice().sort((d,p)=>(Number(p.calls)||0)-(Number(d.calls)||0)).slice(0,12),n=s.map(d=>`${Number(d.calls)||0} calls`),i=s.map(d=>`${Number(d.totalResults)||0} res`),r=n.reduce((d,p)=>Math.max(d,p.length),0),o=i.reduce((d,p)=>Math.max(d,p.length),0),a=6+r+2+o,l=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-a):1/0,u=s.map((d,p)=>{const h=d.namespace?` ${d.namespace}`:"";return[Ts(`${Ld(d.operation)}${h}`,l),n[p],i[p]]}),f=Wt(u);return t.length>s.length?`${f}
|
|
58
|
+
… ${t.length-s.length} more`:f}function Fd(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.data)return[U("Loading fleet stats...")];const n=s.data;if(!n)return[U("Fleet stats unavailable.")];const i=[],r=Math.max(24,e);i.push(Cs("fleet",r)),i.push(U(""));const o=n.windowStart?`Since: ${aa(n.windowStart).replace(" ago","")}`:"All time",a=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";i.push(J([{text:o,color:"cyan"},{text:a?` ${a}`:"",color:"gray"}],r)),i.push(J([{text:`Sessions: ${n.totals.sessionCount}`,color:"white"},{text:` Tokens: ${W(n.totals.totalTokensInput)} in / ${W(n.totals.totalTokensOutput)} out`,color:"white"}],r)),i.push(U(""));const l=new Map;for(const g of n.byAgent||[]){const S=g.model||"(default)",y=l.get(S)||{totalTokensInput:0,totalTokensOutput:0,totalTokensCacheRead:0,totalTokensCacheWrite:0,totalSnapshotSizeBytes:0,turnCount:0};y.totalTokensInput+=Number(g.totalTokensInput)||0,y.totalTokensOutput+=Number(g.totalTokensOutput)||0,y.totalTokensCacheRead+=Number(g.totalTokensCacheRead)||0,y.totalTokensCacheWrite+=Number(g.totalTokensCacheWrite)||0,y.totalSnapshotSizeBytes+=Number(g.totalSnapshotSizeBytes)||0,y.turnCount+=Number(g.turnCount)||0,l.set(S,y)}if(l.size>0){const g=[];for(const[S,y]of l.entries()){const A=y.totalTokensInput>0?y.totalTokensCacheRead/y.totalTokensInput:null;g.push(S),g.push(Yn(y,A)),g.push("")}i.push(...re({title:"Tokens By Model",body:g.join(`
|
|
59
|
+
`).trimEnd(),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(U(""))}const u=n.totals.cacheHitRatio,f=u==null?"—":`${(u*100).toFixed(1)}%`;i.push(...re({title:"Fleet Totals",body:rt([["Sessions",String(n.totals.sessionCount)],["Tokens In",W(n.totals.totalTokensInput)],["Tokens Out",W(n.totals.totalTokensOutput)],["Total Tokens",W(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",W(n.totals.totalTokensCacheRead)],["Cache Write",W(n.totals.totalTokensCacheWrite)],["Hit Ratio",f],["Snapshots",le(n.totals.totalSnapshotSizeBytes)]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0}));const d=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(g=>!(g&&g.agentId==="facts-manager"&&String(g.name||"").startsWith("skills/")));d.length>0&&(i.push(U("")),i.push(...re({title:`Fleet Skills (${d.length})`,body:Bd(d,e),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const p=Array.isArray(s.retrievalUsage?.rows)?s.retrievalUsage.rows:[];if(p.length>0){const g=p.reduce((S,y)=>S+(Number(y.calls)||0),0);i.push(U("")),i.push(...re({title:`Fleet Retrieval (${W(g)})`,body:$d(p,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(U(""));const g=`${h.totalCount} · ${le(h.totalBytes)}`;i.push(...re({title:`Shared Facts (${g})`,body:la(h.rows),width:r,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const m=s.factsTombstoneStats;return m&&Number(m.pendingTotal)>0&&(i.push(U("")),i.push(...re({title:`Fact Tombstones (${Number(m.pendingTotal)||0})`,body:Rd(m),width:r,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),i}function Bd(t,e){const n=t.slice().sort((m,g)=>{const S=I=>I==="learned"?1:0,y=S(m.kind)-S(g.kind);if(y!==0)return y;const A=m.agentId?0:1,x=g.agentId?0:1;if(A!==x)return A-x;const v=String(m.agentId||"").localeCompare(String(g.agentId||""));return v!==0?v:String(m.name||"").localeCompare(String(g.name||""))}).slice(0,15),i=n.map(m=>`${m.invocations||0} inv`),r=n.map(m=>`${m.sessionCount||0} sess`),o=i.reduce((m,g)=>Math.max(m,g.length),0),a=r.reduce((m,g)=>Math.max(m,g.length),0),l=4,u=2,f=l+u+o+u+a,d=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-f):1/0,p=n.map((m,g)=>{const S=m.kind==="learned"?"L":"S",y=m.agentId||".",A=String(m.name||"(unknown)");return[Ts(`${S} ${y}/${A}`,d),i[g],r[g]]}),h=Wt(p);return t.length>n.length?`${h}
|
|
60
|
+
… ${t.length-n.length} more`:h}function Dd(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(Yn(n,i)),s.push("")}return s.join(`
|
|
61
|
+
`).trimEnd()}function Yn(t,e){const s=e==null?"—":`${(e*100).toFixed(1)}%`,n=(Number(t.totalTokensInput)||0)+(Number(t.totalTokensOutput)||0),i=[["Input",W(t.totalTokensInput||0)],["Output",W(t.totalTokensOutput||0)],["Total",W(n)],["Turns",W(t.turnCount||0)],["Cache Read",W(t.totalTokensCacheRead||0)],["Cache Write",W(t.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",le(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&i.push(["Orch",le(t.totalOrchestrationHistorySizeBytes||0)]),rt(i).split(`
|
|
62
|
+
`).map(o=>` ${o}`).join(`
|
|
63
|
+
`)}function fn(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":Rn(t?.owner,"Unknown User")}function Hd(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=fn(t);return e&&e!==s?e:""}function Gd(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=Ts(String(r.model||"(default)"),Math.max(12,e-10));i.push(`${o} · ${r.sessionCount||0} sess · ${r.turnCount||0} turns`),i.push(Yn(r,r.cacheHitRatio)),i.push("")}return s.length>n.length&&i.push(`… ${s.length-n.length} more models`),i.join(`
|
|
64
|
+
`).trimEnd()}function jd(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.userStats)return[U("Loading user stats...")];const n=s.userStats;if(!n)return[U("User stats unavailable.")];const i=[],r=Math.max(24,e);i.push(Cs("users",r)),i.push(U(""));const o=n.windowStart?`Since: ${aa(n.windowStart).replace(" ago","")}`:"All time",a=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";i.push(J([{text:o,color:"cyan"},{text:a?` ${a}`:"",color:"gray"}],r)),i.push(J([{text:`Users: ${Array.isArray(n.users)?n.users.length:0}`,color:"white"},{text:` Sessions: ${n.totals.sessionCount||0}`,color:"white"}],r)),i.push(U(""));const l=n.totals.cacheHitRatio,u=l==null?"—":`${(l*100).toFixed(1)}%`;i.push(...re({title:"User Totals",body:rt([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",W(n.totals.totalTokensInput||0)],["Tokens Out",W(n.totals.totalTokensOutput||0)],["Total Tokens",W((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",W(n.totals.totalTokensCacheRead||0)],["Cache Write",W(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",u],["Snapshots",le(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",le(n.totals.totalOrchestrationHistorySizeBytes||0)]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0}));const f=Array.isArray(n.users)?n.users:[],d=f.slice().sort((p,h)=>(h.totalTokensInput||0)-(p.totalTokensInput||0)||(h.totalSnapshotSizeBytes||0)-(p.totalSnapshotSizeBytes||0)).slice(0,8);for(const p of d){const h=Hd(p),m=p.cacheHitRatio,g=m==null?"—":`${(m*100).toFixed(1)}%`,S=h?`${fn(p)} <${h}>`:fn(p),y=rt([["Sessions",String(p.sessionCount||0)],["Tokens In",W(p.totalTokensInput||0)],["Tokens Out",W(p.totalTokensOutput||0)],["Total Tokens",W((p.totalTokensInput||0)+(p.totalTokensOutput||0))],["Cache Read",W(p.totalTokensCacheRead||0)],["Cache Write",W(p.totalTokensCacheWrite||0)],["Hit Ratio",g],["Snapshots",le(p.totalSnapshotSizeBytes||0)],["Orch Size",le(p.totalOrchestrationHistorySizeBytes||0)]]),A=Gd(p,r);i.push(U("")),i.push(...re({title:`${S} (${p.sessionCount||0})`,body:A?`${y}
|
|
65
|
+
|
|
66
|
+
${A}`:y,width:r,titleColor:p.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return f.length>d.length&&(i.push(U("")),i.push(U(`… ${f.length-d.length} more users`))),i}function Je(t,e={}){const s=Te(t),n=t.ui.inspectorTab,i=Math.max(18,Number(e?.width)||36),r=!!e?.allowWideColumns,o=Po(i);if(s?.isGroup)return{title:Re("Inspector","magenta"),activeTab:n,tabs:Ne,disabled:!0,stickyLines:[],lines:[U(ca,"gray")]};const a=s?te(s.sessionId):"",l=n==="sequence"||n==="nodes"?qn(t):null,u=n==="nodes"?[...Re("Node Map","magenta"),...o?[]:[{text:` [${l.label}]`,color:"gray"}]]:s?n==="sequence"?[...Re(o?"Sequence":`Sequence: ${a}`,"magenta"),...o?[]:[{text:` [${l.label}]`,color:"gray"}]]:n==="logs"?[...Re(o?"Logs":`Logs: ${a}`,"magenta")]:n==="history"?[...Re(o?"History":`History: ${a}`,"magenta")]:n==="stats"?[...Re(o?"Stats":`Stats: ${a}`,"magenta"),{text:` [${Ft(t.ui?.statsViewMode)}]`,color:"gray"}]:[...Re(o?"Files":`Files: ${a}`,"magenta")]:n==="stats"?`Stats: ${Ft(t.ui?.statsViewMode).replace(/^./u,p=>p.toUpperCase())}`:"No session selected";let f,d=[];switch(n){case"sequence":{const p=s?md(t,s,i,{allowWideColumns:r,sequenceExpansion:e?.sequenceExpansion||null}):{stickyLines:[],lines:["No session selected."]};d=p.stickyLines||[],f=p.lines;break}case"logs":f=s?Du(t,s):["No session selected."];break;case"nodes":f=bd(t,i,{allowWideColumns:r});break;case"files":f=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":f=s?Vd(t,s):["No session selected."];break;case"stats":f=Ft(t.ui?.statsViewMode)==="users"?jd(t,i):Ft(t.ui?.statsViewMode)==="fleet"?Fd(t,i):s?_d(t,s,i):[Cs("session",Math.max(24,i)),U(""),U("No session selected. Press f to cycle to fleet or users view.")];break;default:f=["Inspector view is scaffolded in the new architecture."];break}return{title:u,activeTab:n,tabs:Ne,stickyLines:d,lines:f}}const Ud={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"},ca="Select a session to see details.";function Wd(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=Ud[t.kind]||"gray",n=[],i=[{text:`#${t.eventId}`,color:"white",bold:!0},{text:` ${e}`,color:"gray"},{text:` ${t.kind}`,color:s,bold:t.kind.includes("Failed")}];if(t.sourceEventId!=null&&i.push({text:` ←#${t.sourceEventId}`,color:"cyan"}),n.push(i),t.data)try{const r=JSON.parse(t.data);if(typeof r=="object"&&r!==null)for(const[o,a]of Object.entries(r)){const l=typeof a=="string"?a:JSON.stringify(a),u=l.length>100?l.slice(0,97)+"...":l;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 Kd(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function Vd(t,e){const s=t.executionHistory?.bySessionId?.[e.sessionId];if(!s)return["No execution history loaded. Press r to refresh."];if(s.loading)return["Loading execution history..."];if(s.error)return[`Error: ${s.error}`];const n=s.events;if(!Array.isArray(n)||n.length===0)return["No history events found."];const i=t.executionHistory?.format||"pretty",r=[];if(r.push({text:`${n.length} event(s) · format: ${i}`,color:"gray"}),r.push(""),i==="raw")for(let o=0;o<n.length;o++){const a=Kd(n[o]).split(`
|
|
67
|
+
`);for(const l of a)r.push({text:l,color:"gray"});o<n.length-1&&r.push({text:"────────────────────────────────",color:"gray"})}else for(let o=0;o<n.length;o++){const a=Wd(n[o]);for(const l of a)r.push(l);o<n.length-1&&r.push({text:"────────────────────────────────",color:"gray"})}return r}function qd(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:zn(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function sr(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 zd(t,e=80){const s=t.ui.modal;if(!s||s.type!=="themePicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),r=n[i]||null,o=s.currentThemeId||t.ui.themeId||null,a=n.find(p=>p.id===o)||null,l=r&&r.id!==o,u=Math.max(24,e-4),f=n.map((p,h)=>{const m=p.id===o?" [current]":"",g=`${p.label}${m}`.slice(0,u);return h===i?Pe(g.padEnd(u," ")):[{text:g,color:p.id===o?"cyan":"white",bold:p.id===o}]}),d=r?[[{text:`theme: ${r.description||"Shared theme for the portal and native TUI."}`,color:"white"}],{text:"",color:"gray"},[{text:l?`Previewing now. Cancel reverts to ${a?.label||"the previous theme"}.`:"Currently active in this TUI session.",color:l?"yellow":"green"}],sr([{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"}]),sr([{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:f,selectedRowIndex:i,detailsTitle:"Theme Details",detailsLines:d}}function Yd(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 nr(t){return new Map(t)}function Vs(t){return new Set(t)}function Qd(t){return Array.isArray(t)?[...t]:[]}function Xd(t){return Array.isArray(t)?[...t]:[]}const Jd=5e3;function pn(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 ua(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function qs(t,e){return pn(t,e).filter(s=>ua(e[s]))}function Zd(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 da(t,e){const s=Zd(Object.values(e||{})),n=new Set;for(const i of t||[])s.has(i)&&n.add(i);return n}function ef(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 ir(t,e,s){const n=da(t,e);if(!s||!e?.[s])return n;for(const i of ef(s,e))n.delete(i);return n}function rr(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 tf(t){return{...t||{}}}function _e(t){return{...t||{}}}function or(t){return{...t||{}}}function Xt(t){return{...t||{}}}function zs(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function sf(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function nf(t){return[T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY].includes(t)?t:null}function Ys(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(ee,Number(e)||ee);return s.length>n?s.slice(-n):s}function hn(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(!hn(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)||!hn(t[i],e[i]))return!1;return!0}function ar(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 rf(t,e){const s=ar(t),n=ar(e);return s>0&&n>0&&n<=s}const of=new Set(["completed","failed","cancelled","error"]);function af(t,e){const s=String(e?.status??"").toLowerCase();if(t?.status!=="running"||s==="running"||of.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:rf(t,e)}function lr(t={},e={}){let s=t||{};const n=af(t,e);for(const[i,r]of Object.entries(e||{}))if(r!==void 0&&!(i==="status"&&n)){if(i==="pendingQuestion"&&lf(t,r)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}hn(t?.[i],r)||(s===t&&(s={...t||{}}),s[i]=r)}return s}function cr(t){if(!t)return"unknown";const e=t.status||"unknown";return t.cronActive===!0&&(e==="waiting"||e==="idle"||e==="unknown")?"cron_waiting":e}function ur(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=cr(e),i=t?.rowVisualStatus||cr(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>=Jd?{...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 dr(t){return String(t?.question||"").trim()}function lf(t,e){const s=dr(t?.answeredPendingQuestion),n=dr(e);return!!(s&&n&&s===n)}function cf(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&po(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function fr(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 pr(t={}){const e=String(t?.filterQuery||"").trim(),s=cs(t?.ownerFilter);return!!e||s.all!==!0}function uf(t,e=[]){const s=Ct(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(r=>r.sessionId===n)||t.sessions?.navigationIntent||n&&t.sessions?.byId?.[n]&&!pr(t.sessions))return n;if(pr(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 cf(i)}function df(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 ft(t,e){let s=e;const n=s.navigationIntent||null,i=n&&n.status!=="failed"&&s.byId?.[n.sessionId]?n.sessionId:null;i&&(s={...s,activeSessionId:i,navigationIntent:n.status==="resolved"?n:{sessionId:n.sessionId,status:"resolved"}});const r=s.activeSessionId||null;if(r&&s.byId?.[r]){const d=ir(s.collapsedIds,s.byId,r);rr(d,s.collapsedIds)||(s={...s,collapsedIds:d,flat:je(Object.values(s.byId||{}),d,s.orderById,s.pinnedIds)})}i&&s.filterExceptionId!==i&&(Ct({...t,sessions:s}).some(p=>p.sessionId===i)||(s={...s,filterExceptionId:i}));const o={...t,sessions:s},a=uf(o,Object.values(s.byId||{})),l=ir(s.collapsedIds,s.byId,a);return{sessions:{...!rr(l,s.collapsedIds)?{...s,collapsedIds:l,flat:je(Object.values(s.byId||{}),l,s.orderById,s.pinnedIds)}:s,activeSessionId:a},ui:df(t,a)}}function hr(t={},e=0,s=[]){const n=tf(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 ff(t=[],e=[]){const s=je(t,new Set,{},e),n={};let i=0;for(const r of s){const o=r?.sessionId;!o||typeof n[o]=="number"||(n[o]=i,i+=1)}for(const r of t||[]){const o=r?.sessionId;!o||typeof n[o]=="number"||(n[o]=i,i+=1)}return{orderById:n,nextOrderOrdinal:i}}function pf(t,e,s=null){const n=String(t||""),i=Number.isFinite(e)?e:Number.isFinite(s)?s:n.length;return Math.max(0,Math.min(i,n.length))}function mr(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 hf(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"||s.chatViewMode==="rich"),a=Object.prototype.hasOwnProperty.call(s,"pinnedSessionIds"),l=Object.prototype.hasOwnProperty.call(s,"collapsedSessionIds"),u=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.status!=="failed"),f=Object.prototype.hasOwnProperty.call(s,"activeSessionId")&&!u,d=Object.keys(t.sessions.byId||{}).length>0,p=r?{...t.ui.layout||{},...Nn(s.layoutAdjustments)}:t.ui.layout,h=a?d?qs(ds(s.pinnedSessionIds),t.sessions.byId):ds(s.pinnedSessionIds):t.sessions.pinnedIds,m=l?d?da(un(s.collapsedSessionIds),t.sessions.byId):un(s.collapsedSessionIds):t.sessions.collapsedIds,g=f?To(s.activeSessionId):t.sessions.activeSessionId,S={...t.sessions,...i?{ownerFilter:cs(s.sessionOwnerFilter),ownerFilterExplicit:!0}:{},pinnedIds:h,collapsedIds:m,collapsedIdsExplicit:l?!0:t.sessions.collapsedIdsExplicit,activeSessionId:g,flat:a||l?je(Object.values(t.sessions.byId),m,t.sessions.orderById,h):t.sessions.flat},y=d&&(i||a||l||f)?ft(t,S):{sessions:S,ui:t.ui};return{...t,sessions:y.sessions,ui:{...y.ui,themeId:n?s.themeId.trim():y.ui.themeId,chatViewMode:o?s.chatViewMode:y.ui.chatViewMode,layout:p}}}case"ui/chatViewMode":return e.mode!=="summary"&&e.mode!=="transcript"&&e.mode!=="rich"?t:{...t,ui:{...t.ui,chatViewMode:e.mode,scroll:{...t.ui.scroll,chat:0}}};case"ui/modal":return{...t,ui:{...t.ui,modal:e.modal??null}};case"ui/viewport":{const s=t.ui.layout?.viewportWidth??120,n=t.ui.layout?.viewportHeight??40,i=Math.max(40,e.width??s),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=ft(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:cs(e.filter),navigationIntent:null,filterExceptionId:null},n=ft(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=ft(t,n);return{...t,sessions:i.sessions,ui:i.ui}}case"sessions/navigationIntentFailed":{const s=t.sessions.navigationIntent,n=String(e.sessionId||"").trim();return!s||n&&s.sessionId!==n?t:{...t,sessions:{...t.sessions,navigationIntent:{sessionId:s.sessionId,status:"failed",errorKind:e.errorKind==="not_found"?"not_found":"network"}}}}case"ui/modalSelection":{const s=t.ui.modal;if(!s)return t;if(s.type==="help")return{...t,ui:{...t.ui,modal:{...s,selectedIndex:Math.max(0,Number(e.index)||0)}}};if(!Array.isArray(s.items)||s.items.length===0)return t;const n=Math.max(0,Math.min(e.index??0,s.items.length-1)),i=s.type==="themePicker"?s.items[n]?.id:null;return{...t,ui:{...t.ui,...i?{themeId:i}:{},modal:{...s,selectedIndex:n}}}}case"ui/scroll":return{...t,ui:{...t.ui,scroll:{...t.ui.scroll,[e.pane]:Math.max(0,e.offset??0)}}};case"ui/followBottom":{if(e.pane!=="inspector"&&e.pane!=="activity")return t;const s=!!e.followBottom;return t.ui.followBottom?.[e.pane]===s?t:{...t,ui:{...t.ui,followBottom:{...t.ui.followBottom||{},[e.pane]:s}}}}case"ui/inspectorTab":return{...t,ui:{...t.ui,inspectorTab:e.inspectorTab,fullscreenPane:e.inspectorTab==="files"&&t.ui.fullscreenPane===T.INSPECTOR?null:t.ui.fullscreenPane,scroll:{...t.ui.scroll,inspector:0},followBottom:{...t.ui.followBottom||{},inspector:!0}},files:e.inspectorTab==="files"?t.files:{...t.files,fullscreen:!1}};case"ui/statsViewMode":return{...t,ui:{...t.ui,statsViewMode:["session","fleet","users"].includes(e.statsViewMode)?e.statsViewMode:"session",scroll:{...t.ui.scroll,inspector:0}}};case"ui/prompt":return{...t,ui:{...t.ui,prompt:e.prompt,promptCursor:pf(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:xt(e.prompt),promptAttachments:mr(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:mr(t.ui.prompt,e.attachments)}};case"sessions/gone":{const s=e.sessionId;if(!s)return t;const n=!!t.sessions.byId[s],i=t.sessions.activeSessionId===s;if(!n&&!i)return t;const r={...t.sessions.byId};delete r[s];const o=Array.isArray(t.sessions.selectedIds)?t.sessions.selectedIds.filter(a=>a!==s):t.sessions.selectedIds;return{...t,sessions:{...t.sessions,byId:r,selectedIds:o,activeSessionId:i?null:t.sessions.activeSessionId}}}case"sessions/loaded":{const s={};let n=!1;const i=Date.now();for(const x of e.sessions){const v=t.sessions.byId[x.sessionId],I=ur(v,lr(v,x),i);s[x.sessionId]=I,!n&&I!==v&&(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 x of o)if(!t.sessions.byId[x]){n=!0;break}}if(!n)return t;const a=Object.values(s),l=Object.keys(t.sessions.orderById||{}).length>0,u=fr(a),f=!!t.sessions.collapsedIdsExplicit,{orderById:d,nextOrderOrdinal:p}=l?hr(t.sessions.orderById,t.sessions.nextOrderOrdinal,a):ff(a,t.sessions.pinnedIds),h=f?Vs(t.sessions.collapsedIds):u;if(f){const x=fr(Object.values(t.sessions.byId));for(const v of u)x.has(v)||h.add(v)}const m=qs(t.sessions.pinnedIds,s),g=pn(t.sessions.selectedIds,s),S=je(a,h,d,m),y={...t.sessions,byId:s,collapsedIds:h,collapsedIdsExplicit:f,pinnedIds:m,selectedIds:g,selectMode:t.sessions.selectMode&&g.length>0,flat:S,activeSessionId:t.sessions.activeSessionId,orderById:d,nextOrderOrdinal:p},A=ft(t,y);return{...t,sessions:A.sessions,ui:A.ui}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=ur(s,lr(s,e.session),Date.now());if(n===s)return t;const i={...t.sessions.byId,[e.session.sessionId]:n},r=qs(t.sessions.pinnedIds,i),{orderById:o,nextOrderOrdinal:a}=hr(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(i)),l={...t.sessions,byId:i,pinnedIds:r,flat:je(Object.values(i),t.sessions.collapsedIds,o,r),activeSessionId:t.sessions.activeSessionId,orderById:o,nextOrderOrdinal:a},u=ft(t,l);return{...t,sessions:u.sessions,ui:u.ui}}case"sessions/selected":{const s=t.sessions.activeSessionId,n={...t.ui.chatScrollBySession||{}};s&&s!==e.sessionId&&(n[s]=Number(t.ui.scroll?.chat)||0);const i=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.sessionId!==e.sessionId);return{...t,sessions:{...t.sessions,activeSessionId:e.sessionId,...i?{navigationIntent:null,filterExceptionId:null}:{}},ui:{...t.ui,chatScrollBySession:n,statusText:s!==e.sessionId?"":t.ui.statusText,scroll:{...t.ui.scroll,chat:Number(n[e.sessionId])||0,inspector:0,activity:0},followBottom:{...t.ui.followBottom||{},inspector:!0,activity:!0}}}}case"ui/fullscreenPane":{const s=nf(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=Vs(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:je(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds)}}}case"sessions/expand":{const s=Vs(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:je(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds)}}}case"sessions/pinToggle":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=t.sessions.byId[s];if(!ua(n))return t;const i=Qd(t.sessions.pinnedIds),o=i.indexOf(s)>=0?i.filter(a=>a!==s):[...i,s];return{...t,sessions:{...t.sessions,pinnedIds:o,flat:je(Object.values(t.sessions.byId),t.sessions.collapsedIds,t.sessions.orderById,o)}}}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=Xd(t.sessions.selectedIds),o=i.indexOf(s)>=0?i.filter(a=>a!==s):[...i,s];return{...t,sessions:{...t.sessions,selectedIds:o,selectMode:o.length>0?!0:t.sessions.selectMode}}}case"sessions/selectSet":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[],n=pn(s,t.sessions.byId).filter(i=>!t.sessions.byId[i]?.isSystem&&!t.sessions.byId[i]?.isGroup);return{...t,sessions:{...t.sessions,selectedIds:n,selectMode:n.length>0?!0:t.sessions.selectMode}}}case"sessions/selectClear":return t.sessions.selectedIds.length===0&&!t.sessions.selectMode?t:{...t,sessions:{...t.sessions,selectedIds:[],selectMode:!1}};case"history/set":{const s=t.history.bySessionId.get(e.sessionId)||null,n=s?.chat||[],i=Math.max(ee,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??ee)||ee),r=Ys(bt(e.history?.chat||[]),i),o=n[n.length-1]?.id||null,a=r[r.length-1]?.id||null,l=e.sessionId===t.sessions.activeSessionId&&a!==o,u=nr(t.history.bySessionId);return u.set(e.sessionId,{...e.history||{},chat:r,activity:Ys(e.history?.activity||[],i),events:Ys(e.history?.events||[],i),loadedEventLimit:i}),{...t,history:{...t.history,bySessionId:u},ui:l?{...t.ui,scroll:{...t.ui.scroll,chat:0}}:t.ui}}case"history/evict":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=nr(t.history.bySessionId);for(const o of s)n.delete(o);const i=or(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=or(t.outbox?.bySessionId);return n.length===0?delete i[s]:i[s]=n,{...t,outbox:{...t.outbox,bySessionId:i}}}case"orchestration/statsLoading":{const s=Xt(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=Xt(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=Xt(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=Xt(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/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=_e(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=_e(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=_e(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},i=us(e.entries),r=Number(e.fetchedAt)||0,o=l=>i.some(u=>u.filename===l),a=n.selectedFilename&&o(n.selectedFilename)?n.selectedFilename:e.selectedFilename&&o(e.selectedFilename)?e.selectedFilename:i[0]?.filename||null;return s[e.sessionId]={...n,entries:i,selectedFilename:a,loading:!1,loaded:!0,fetchedAt:r,error:null},{...t,files:{...t.files,bySessionId:s}}}case"files/sessionError":{const s=_e(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=_e(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=_e(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=_e(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=_e(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=_e(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.downloads||{},[e.filename]:{localPath:e.localPath||null,downloadedAt:e.downloadedAt||Date.now()}};return s[e.sessionId]={...n,downloads:i},{...t,files:{...t.files,bySessionId:s}}}case"files/deleted":{t={...t,files:{...t.files,markedIds:(t.files.markedIds||[]).filter(d=>d!==`${e.sessionId}/${e.filename}`)}};const s=_e(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},i=us(n.entries).filter(d=>d.filename!==e.filename),r=n.selectedFilename===e.filename?i[0]?.filename||null:n.selectedFilename,{[e.filename]:o,...a}=n.previews||{},{[e.filename]:l,...u}=n.downloads||{},f=e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:null;return s[e.sessionId]={...n,entries:i,previews:a,downloads:u,selectedFilename:r},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:t.files.selectedArtifactId===f?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:{...zs(t.files.filter),...zs(e.filter)},...zs(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:sf(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 mf(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 gf=2e4,yf=2e4,Sf=3e4,bf=30,gr="Session refresh failed",wf=3,If=200,xf=5,vf=new Set([T.SESSIONS,T.CHAT,T.INSPECTOR,T.ACTIVITY]);function Ef(t){if(!t?.groupId)return null;const e=t.latestSummaryUpdatedAt?new Date(t.latestSummaryUpdatedAt).getTime():null,s=t.memberCount??0;return{sessionId:`group:${t.groupId}`,groupId:t.groupId,isGroup:!0,title:t.title||t.groupId,status:"group",description:t.description??null,owner:t.owner??null,shortSummary:`${s} grouped session${s===1?"":"s"}`,summaryUpdatedAt:Number.isFinite(e)?e:null,latestSummaryUpdatedAt:Number.isFinite(e)?e:null,memberCount:s,runningCount:t.runningCount??0,waitingCount:t.waitingCount??0,completedCount:t.completedCount??0,failedCount:t.failedCount??0,cancelledCount:t.cancelledCount??0,createdAt:t.createdAt?new Date(t.createdAt).getTime():0,updatedAt:t.updatedAt?new Date(t.updatedAt).getTime():Date.now()}}function Qs(t){return!t?.sessionId||t.isGroup?t:{...t,groupId:t.viewerGroupId??null,parentSessionId:t.parentSessionId??null}}function Xs(t){return String(t||"").startsWith("group:")?String(t).slice(6):null}function Af(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 Js(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 _t(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||s==="NOT_FOUND"}async function Cf(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<xf;n+=1){const i=await t.listSessionsPage({limit:If,cursor:s}),r=Array.isArray(i?.sessions)?i.sessions:[];if(e.push(...r),!i?.hasMore||!i?.nextCursor)break;s=i.nextCursor}return e}function Tf(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 mn(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 yr(t){const e=mn(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 gn(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 kf(t){const e=gn(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 fa={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function Mf(t){const e=Number(t);return!Number.isSafeInteger(e)||e<=0?null:e%1e6===0?`${e/1e6}M`:e%1e3===0?`${e/1e3}K`:e.toLocaleString("en-US")}function Nf(t,e){const s=Mf(e);return s?t==="long_context"?`Long context (${s} tokens, higher cost)`:`Default (${s} tokens)`:fa[t]||t}function yn(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 Pf(t){return yn([t])}function Sr(t,e=[]){let s=to(t);for(const n of e){const i=so(s,n?.eventType,n?.data,{timestamp:n?.createdAt});i&&(s=i)}return s}function gs(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(!gs(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)||!gs(t[i],e[i]))return!1;return!0}function br(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 Qn(t,e){const s=br(t?.updatedAt),n=br(e?.updatedAt);return s>0&&n>0&&n<=s}function Of(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function _f(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&Of(e?.status)&&Qn(t,e)}function Rf(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!ha(e?.status)&&!pa(e?.orchestrationStatus)&&Qn(t,e)}function Lf(t,e){if(!e?.sessionId)return null;const s={sessionId:e.sessionId};let n=!1;for(const[a,l]of Object.entries(e))a==="sessionId"||l===void 0||gs(t?.[a],l)||(s[a]=l,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&!Qn(t,e)&&(s.pendingQuestion=null,n=!0),_f(t,e)?(s.status!==t.status&&(s.status=t.status,n=!0),s.waitReason!==t.waitReason&&(s.waitReason=t.waitReason,n=!0)):e.waitReason===void 0&&t?.waitReason&&e.status!=="waiting"&&e.status!=="input_required"&&(s.waitReason=null,n=!0),Pc(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),Rf(t,e))for(const a of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[a]!=null&&(gs(s[a],t[a])||(s[a]=t[a],n=!0));else if(e.cronActive!==!0){t?.cronReason&&(s.cronReason=null,n=!0);for(const a of["cronKind","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[a]!=null&&e[a]===void 0&&(s[a]=null,n=!0);t?.cronInterval!=null&&e.cronInterval===void 0&&(s.cronInterval=null,n=!0)}if((ha(e.status)||pa(e.orchestrationStatus))&&t?.contextUsage?.compaction?.state==="running"&&e.contextUsage===void 0){const a={...t.contextUsage};delete a.compaction,s.contextUsage=Object.keys(a).length>0?a:null,n=!0}return n?s:null}function wr(t){return String(t||"").replace(/\r\n/g,`
|
|
68
|
+
`).trim()}function pa(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function ha(t){return t==="completed"||t==="failed"||t==="cancelled"}function de(t){return String(t||"").slice(0,8)}function ys(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function Jt(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const $f=ys({provider:"system",subject:"system"});function Ir(t){const e=t.auth?.principal||null,s=ys(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=Jt(e,"current user");n.push({id:"me",kind:"me",label:`Me (${r})`,ownerKey:s,description:"Show sessions owned by the authenticated user currently signed in."}),n.push({id:"shared",kind:"shared",label:"Shared with me",description:"Show sessions other users have shared with you."})}const i=new Map;for(const r of Object.values(t.sessions?.byId||{})){const o=r?.owner,a=ys(o);!a||a===s||a===$f||i.has(a)||i.set(a,o)}for(const[r,o]of[...i.entries()].sort((a,l)=>Jt(a[1]).localeCompare(Jt(l[1])))){const a=Jt(o),l=String(o?.email||"").trim();n.push({id:`owner:${r}`,kind:"owner",ownerKey:r,label:l&&l!==a?`${a} <${l}>`:a,description:"Show sessions owned by this user."})}return n}function Ss(t){return ys(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,includeShared:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function Ff(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||t?.includeShared||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function Bf(t,e,s){const n=t||Ss(s);if(!e)return n;if(e.kind==="all")return n.all?Ss(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 Ff(i)?i:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function Xn(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 Df(t){const e=Xn(t);return e?Math.max(1,60-`${e}: `.length):60}function Hf(t){const e=String(t?.title||"").trim();if(!e)return"";const s=Xn(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===de(t?.sessionId)?"":n}return e===de(t?.sessionId)?"":e}function xr(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 vr(t){return`📎 ${String(t||"").trim()}`}function Er(t,e){const s=String(t||""),n=ne(s,e,s.length),r=s.slice(0,n).match(/(^|\s)(@@?)([^\s]*)$/u);if(!r)return null;const o=r[2],a=String(r[3]||"");return{kind:o==="@@"?"sessions":"artifacts",query:a,signature:`${o}${a}`,tokenStart:(r.index||0)+String(r[1]||"").length,tokenEnd:n}}function Gf(t,e,s,n){const i=String(t||""),r=ne(i,e),o=ne(i,s),a=String(n||"");return{prompt:`${i.slice(0,r)}${a}${i.slice(o)}`,cursor:r+a.length}}function jf(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function Uf(t){const e=String(t?.sessionId||"").trim(),s=de(e)||"session";return`Referenced session: ${jf(t?.title,s)} — session://${e}`}function Ar(t,e,s){if(!e)return qe(t,String(t||"").length,s);const n=String(t||""),i=n.slice(e.tokenEnd,e.tokenEnd+1),r=!i||/\s/u.test(i);return Gf(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${r?" ":""}`)}function Wf(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 Cr=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Tr=4*1024*1024,Zs=4;function Kf(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=Wf(t,s);return n.join(`
|
|
71
|
+
`)+(i?`
|
|
72
|
+
|
|
73
|
+
${i}`:"")}function pt(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function ma(t){return Array.from(String(t||"")).length}function Vf(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=no(s.value||"");for(const i of n)e.push(i);continue}if(Array.isArray(s)){e.push(s);continue}e.push(s)}return e}function qf(t,e){const s=Math.max(1,Number(e)||1),n=ma(t);return Math.max(1,Math.ceil(n/s))}function ht(t,e){const s=Math.max(1,Number(e)||1);return Vf(t).reduce((n,i)=>{if(!i)return n+1;if(Array.isArray(i)){const r=i.reduce((o,a)=>o+ma(a?.text||""),0);return n+Math.max(1,Math.ceil(r/s))}return n+qf(i.text||"",s)},0)}function ne(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function ga(t){return String(t||"").split(`
|
|
74
|
+
`)}function zf(t,e){const n=String(t||"").slice(0,ne(t,e)).split(`
|
|
75
|
+
`),i=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:i.length}}function Yf(t,e,s){const n=ga(t),i=Math.max(0,Math.min(Number(e)||0,Math.max(0,n.length-1))),r=Math.max(0,Math.min(Number(s)||0,n[i]?.length||0));let o=0;for(let a=0;a<i;a+=1)o+=(n[a]?.length||0)+1;return ne(t,o+r)}function qe(t,e,s){const n=String(t||""),i=ne(n,e),r=String(s||"");return{prompt:`${n.slice(0,i)}${r}${n.slice(i)}`,cursor:i+r.length}}function mt(t,e){const s=String(t||""),n=ne(s,e);return n<=0?{prompt:s,cursor:n}:{prompt:`${s.slice(0,n-1)}${s.slice(n)}`,cursor:n-1}}function Zt(t){return/\s/u.test(t||"")}function ya(t,e,s){const n=String(t||"");let i=ne(n,e);if(s<0){for(;i>0&&Zt(n[i-1]);)i-=1;for(;i>0&&!Zt(n[i-1]);)i-=1;return i}for(;i<n.length&&Zt(n[i]);)i+=1;for(;i<n.length&&!Zt(n[i]);)i+=1;return i}function Qf(t,e){const s=String(t||""),n=ne(s,e),i=ya(s,n,-1);return i===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,i)}${s.slice(n)}`,cursor:i}}function Xf(t,e,s){const n=ga(t);if(n.length<=1)return ne(t,e);const i=zf(t,e),r=Math.max(0,Math.min(i.line+s,n.length-1));return r===i.line?ne(t,e):Yf(t,r,i.column)}const Sn=3e3,Jf=new Set(["logs","sequence"]),Zf=2e5,ep=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),tp=new Set([".json",".jsonl"]),sp=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function Sa(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function np(t,e=""){const s=Sa(t),n=String(e||"").toLowerCase();return sp.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}function kr(t,e=Zf){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 ip(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 rp(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${ip(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
|
|
78
|
+
`)}function Mr(t,e,s="",n=null){const i=String(s||"").toLowerCase(),r=Sa(t);if(n?.isBinary===!0||np(t,s))return{content:rp(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=kr(e);if(ep.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(tp.has(r)||i.includes("json"))try{return{content:kr(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 op=1e4,ap=140,lp=1500;class cp{constructor({store:e,transport:s}){this.store=e,this.transport=s,this.catalogTimer=null,this.activeSessionUnsub=null,this.activeSessionSubscriptionId=null,this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.sessionRefreshTimer=null,this.sessionHistoryLoads=new Map,this.sessionHistoryExpansionLoads=new Map,this.sessionOrchestrationStatsLoads=new Map,this.outboxFlushPromises=new Map,this.logUnsubscribe=null,this.promptReferenceSignature=null,this.promptReferenceSyncVersion=0,this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}getState(){return this.store.getState()}subscribe(e){return this.store.subscribe(e)}dispatch(e){return this.store.dispatch(e)}setStatus(e){this.dispatch({type:"ui/status",text:e})}getPromptAttachments(){const e=this.getState().ui.promptAttachments;return Array.isArray(e)?e.filter(Boolean):[]}setPromptAttachments(e){this.dispatch({type:"ui/promptAttachments",attachments:Array.isArray(e)?e:[]})}getSessionOutbox(e){if(!e)return[];const s=this.getState().outbox?.bySessionId?.[e];return Array.isArray(s)?s.filter(Boolean):[]}setSessionOutboxItems(e,s){e&&this.dispatch({type:"outbox/setSessionItems",sessionId:e,items:Array.isArray(s)?s:[]})}buildOutboxItem(e,s="pending"){const n=`msg:${Date.now()}:${Math.random().toString(36).slice(2,10)}`,i=s==="queued"||s==="cancelling"?s:"pending";return{id:n,text:String(e||""),createdAt:Date.now(),phase:i,attempted:!1,clientMessageIds:[n]}}getPendingOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="pending")}getQueuedOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="queued")}getNavigableOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="pending"||s?.phase==="queued"||s?.phase==="cancelling")}getEditableOutboxItems(e){return this.getPendingOutboxItems(e).filter(s=>s?.attempted!==!0)}getPromptEditSessionMatch(e=this.getState().sessions.activeSessionId){const s=this.getState().ui.promptEdit;return s?.sessionId===e?s:null}enterPendingPromptEdit(e,s){if(!e||!s)return!1;const i=this.getNavigableOutboxItems(e).find(l=>l.id===s);if(!i)return!1;const r=this.getState().ui,o=this.getPromptEditSessionMatch(e),a=o?{...o,itemId:s,phase:i.phase}:{sessionId:e,itemId:s,phase:i.phase,draftPrompt:r.prompt,draftCursor:r.promptCursor};return this.dispatch({type:"ui/promptEdit",promptEdit:a}),this.setPrompt(i.text,i.text.length),this.setFocus(T.PROMPT),!0}exitPendingPromptEdit({restoreDraft:e=!0}={}){const s=this.getState().ui.promptEdit;return s?(this.dispatch({type:"ui/promptEdit",promptEdit:null}),e&&this.setPrompt(s.draftPrompt||"",Number.isFinite(s.draftCursor)?s.draftCursor:String(s.draftPrompt||"").length),!0):!1}selectPreviousPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e);if(s.length===0)return!1;const n=this.getPromptEditSessionMatch(e);if(!n)return this.enterPendingPromptEdit(e,s[s.length-1].id);const i=s.findIndex(r=>r.id===n.itemId);return i<=0?!1:this.enterPendingPromptEdit(e,s[i-1].id)}selectNextPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e),n=this.getPromptEditSessionMatch(e);if(!n)return!1;const i=s.findIndex(r=>r.id===n.itemId);return i===-1||i>=s.length-1?this.exitPendingPromptEdit({restoreDraft:!0}):this.enterPendingPromptEdit(e,s[i+1].id)}async cancelSelectedOutboxPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const n=this.getSessionOutbox(e.sessionId).find(r=>r.id===e.itemId);return n?n.phase==="cancelling"?(this.exitPendingPromptEdit({restoreDraft:!0}),!1):await this.cancelOutboxItem(e.sessionId,e.itemId)?(this.exitPendingPromptEdit({restoreDraft:!0}),!0):!1:!1}cancelSelectedPendingPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const s=this.getSessionOutbox(e.sessionId);if(!s.find(r=>r.id===e.itemId&&r.phase==="pending"))return!1;const i=s.filter(r=>r.id!==e.itemId);return this.setSessionOutboxItems(e.sessionId,i),this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"ui/status",text:"Cancelled pending prompt"}),!0}async cancelOutboxItem(e,s){if(!e||!s)return!1;const n=this.getSessionOutbox(e),i=n.find(o=>o.id===s);if(!i||i.phase==="cancelling")return!1;this.getPromptEditSessionMatch(e)?.itemId===s&&this.exitPendingPromptEdit({restoreDraft:!0});const r=Array.isArray(i.clientMessageIds)&&i.clientMessageIds.length>0?i.clientMessageIds:[i.id];if(i.phase==="queued")if(this.setSessionOutboxItems(e,n.map(o=>o.id===s?{...o,phase:"cancelling"}:o)),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,r),this.dispatch({type:"ui/status",text:"Cancelling queued prompt"})}catch(o){return this.setSessionOutboxItems(e,n),this.dispatch({type:"ui/status",text:o?.message||String(o)}),!1}else this.dispatch({type:"ui/status",text:"Queued prompt marked cancelling (local only — transport has no cancel)"});else{const o=n.filter(a=>a.id!==s);if(this.setSessionOutboxItems(e,o),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,r)}catch{}this.dispatch({type:"ui/status",text:"Cancelled pending prompt"})}return!0}async cancelLatestQueuedOutbox(e=this.getState().sessions.activeSessionId){if(!e)return!1;const s=this.getQueuedOutboxItems(e);if(s.length===0)return!1;const n=s[s.length-1];return await this.cancelOutboxItem(e,n.id)}queuePromptInOutbox(e,s,n=null){const i=this.buildOutboxItem(s,"pending");return Array.isArray(n?.attachments)&&n.attachments.length>0&&(i.attachments=n.attachments),this.setSessionOutboxItems(e,[...this.getSessionOutbox(e),i]),i}addPendingImageFiles(e){const s=Array.from(e||[]).filter(Boolean),n=this.getPromptAttachments(),i=n.filter(a=>a?.kind==="image"),r=[],o=[];for(const a of s){const l=String(a.type||"").toLowerCase();if(!Cr.has(l)){o.push({name:a.name||"image",reason:"unsupported type"});continue}if((Number(a.size)||0)>Tr){o.push({name:a.name||"image",reason:"over 4 MB"});continue}if(i.length+r.length>=Zs){o.push({name:a.name||"image",reason:`max ${Zs} images`});continue}r.push({kind:"image",file:a,filename:String(a.name||"image"),contentType:l,sizeBytes:Number(a.size)||0})}return r.length>0&&this.setPromptAttachments([...n,...r]),o.length>0&&this.dispatch({type:"ui/status",text:`Skipped ${o.map(a=>`${a.name} (${a.reason})`).join(", ")}`}),{accepted:r.length,rejected:o}}stageUploadedImageAttachment(e,s){const n=String(e?.contentType||"").toLowerCase();return!Cr.has(n)||(Number(e?.sizeBytes)||0)>Tr||this.getPromptAttachments().filter(r=>r?.kind==="image").length>=Zs?!1:(this.setPromptAttachments([...this.getPromptAttachments(),{kind:"image",uploaded:!0,sessionId:s,filename:e.filename,contentType:n,sizeBytes:Number(e?.sizeBytes)||0}]),!0)}async pasteImageFromClipboard(){if(typeof this.transport.captureClipboardImage!="function"||typeof this.transport.uploadArtifactFromPath!="function")return this.dispatch({type:"ui/status",text:"Clipboard image paste is not supported by this transport"}),!1;let e=null;try{e=await this.transport.captureClipboardImage()}catch(s){return this.dispatch({type:"ui/status",text:`Clipboard read failed: ${s?.message||s}`}),!1}if(!e?.path)return this.dispatch({type:"ui/status",text:"No image on the clipboard"}),!1;this.dispatch({type:"ui/status",text:"Attaching clipboard image..."});try{const s=this.getPromptDraftSessionId()||await this.ensurePromptAttachmentSessionId(),n=await this.transport.uploadArtifactFromPath(s,e.path),i=await this.finalizeArtifactUpload(n,{sessionId:s,suppressStatus:!0});return this.stageUploadedImageAttachment(i,s)?(this.dispatch({type:"ui/status",text:`Clipboard image attached to your next message (${i.filename})`}),!0):(this.dispatch({type:"ui/status",text:`Uploaded ${i.filename} (not attachable: type/size/count limit)`}),!1)}catch(s){return this.dispatch({type:"ui/status",text:`Clipboard image attach failed: ${s?.message||s}`}),!1}}removePendingImageAttachment(e){const s=this.getPromptAttachments(),i=s.filter(r=>r?.kind==="image")[e];i&&this.setPromptAttachments(s.filter(r=>r!==i))}async uploadPendingImageAttachments(e,s,n){const i=[],r=String(n||Date.now()).replace(/[^a-zA-Z0-9_-]/g,"").slice(-24)||"img";let o=0;for(const a of s){if(!a.file){a.uploaded&&a.filename&&i.push({filename:a.filename});continue}o+=1;const l={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[a.contentType]||"png",u=`attach-${r}-${o}.${l}`;await this.transport.uploadArtifactFromFile(e,a.file,u),i.push({filename:u})}return i}acknowledgeOutboxPrompt(e,s,n=null){if(!e)return!1;const i=this.getSessionOutbox(e);if(n){const l=i.findIndex(u=>(u?.phase==="pending"||u?.phase==="queued"||u?.phase==="cancelling")&&Array.isArray(u.clientMessageIds)&&u.clientMessageIds.includes(n));if(l!==-1){const u=i[l];return this.setSessionOutboxItems(e,i.filter((f,d)=>d!==l)),this.getPromptEditSessionMatch(e)?.itemId===u?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const r=wr(s);if(!r)return!1;const o=i.findIndex(l=>(l?.phase==="pending"||l?.phase==="queued"||l?.phase==="cancelling")&&wr(l.text)===r);if(o===-1)return!1;const a=i[o];return this.setSessionOutboxItems(e,i.filter((l,u)=>u!==o)),this.getPromptEditSessionMatch(e)?.itemId===a?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}acknowledgeCancelledOutboxPrompt(e,s=[]){if(!e)return!1;const n=new Set((s||[]).filter(l=>typeof l=="string"&&l));if(n.size===0)return!1;const i=this.getSessionOutbox(e),r=i.filter(l=>l?.phase!=="cancelling"?!0:!(Array.isArray(l.clientMessageIds)?l.clientMessageIds:[l.id]).some(f=>n.has(f)));if(r.length===i.length)return!1;const o=new Set(i.filter(l=>!r.some(u=>u.id===l.id)).map(l=>l.id));this.setSessionOutboxItems(e,r);const a=this.getPromptEditSessionMatch(e);return a&&o.has(a.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}scheduleOutboxDispatch(e){if(!e||(this._outboxDispatchTimers||(this._outboxDispatchTimers=new Map),this._outboxDispatchTimers.has(e)))return;const s=setTimeout(()=>{this._outboxDispatchTimers.delete(e),this.dispatchPendingOutbox(e).catch(()=>{})},10);this._outboxDispatchTimers.set(e,s)}async dispatchPendingOutbox(e){if(!e)return!1;await Promise.resolve();const s=this.outboxFlushPromises.get(e);if(s)return await s.catch(()=>{}),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e),!1;const n=this.getPendingOutboxItems(e),i=n.find(m=>m?.attempted===!0),r=i?[i]:n.filter(m=>m?.attempted!==!0);if(r.length===0)return!1;const o=r.flatMap(m=>Array.isArray(m.clientMessageIds)&&m.clientMessageIds.length>0?m.clientMessageIds:[m.id]),a=r.map(m=>String(m.text||"")).join(`
|
|
79
|
+
|
|
80
|
+
`),l=r.flatMap(m=>Array.isArray(m.attachments)?m.attachments:[]),u={id:r[0].id,text:a,createdAt:r[0].createdAt||Date.now(),phase:"pending",attempted:!0,clientMessageIds:o,...l.length>0?{attachments:l}:{}},f=new Set(r.map(m=>m.id)),d=this.getSessionOutbox(e).filter(m=>!f.has(m.id));this.setSessionOutboxItems(e,[...d,u]);const p=this.getPromptEditSessionMatch(e);p&&f.has(p.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const h=(async()=>{await this.transport.sendMessage(e,u.text,{enqueueOnly:!0,clientMessageIds:u.clientMessageIds,...Array.isArray(u.attachments)&&u.attachments.length>0?{attachments:u.attachments}:{}});const g=this.getSessionOutbox(e).map(S=>S.id===u.id?{...S,phase:"queued"}:S);return this.setSessionOutboxItems(e,g),this.syncSessionEvents(e).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(m=>{const g=m?.code==="FORBIDDEN"||m?.code==="UNAUTHORIZED"||m?.status===403||m?.status===401,S=this.getSessionOutbox(e);if(g){const y=S.map(A=>A.id===u.id?{...A,phase:"rejected"}:A);this.setSessionOutboxItems(e,y),setTimeout(()=>{const A=this.getSessionOutbox(e),x=A.filter(v=>!(v.id===u.id&&v.phase==="rejected"));x.length!==A.length&&this.setSessionOutboxItems(e,x)},6e3)}else{const y=S.map(A=>A.id===u.id?{...u,phase:"pending",attempted:!0}:A);this.setSessionOutboxItems(e,y)}throw this.dispatch({type:"ui/status",text:m?.message||String(m)}),m}).finally(()=>{this.outboxFlushPromises.delete(e),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e)});return this.outboxFlushPromises.set(e,h),await h}async flushQueuedOutbox(e){return await this.dispatchPendingOutbox(e)}maybeFlushQueuedOutbox(e){return!e||this.getPendingOutboxItems(e).length===0?!1:(this.scheduleOutboxDispatch(e),!0)}getPromptReferenceContext(){const e=this.getState();return Er(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=Ve(s),i=n?.sessionId||s.sessions.activeSessionId||null,r=n?.filename||null;if(!i||!r)return!1;const o=vr(r),a=Ar(s.ui.prompt,e,o),l=this.getPromptAttachments(),u=l.findIndex(p=>p?.sessionId===i&&p?.filename===r),f={...u>=0?l[u]:{},id:`${i}/${r}`,sessionId:i,filename:r,resolvedPath:r,token:o},d=u>=0?l.map((p,h)=>h===u?f:p):[...l,f];return this.setPrompt(a.prompt,a.cursor),this.setPromptAttachments(d),this.setFocus(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=Ct(s)[0]||null,r=i?.sessionId&&s.sessions.byId[i.sessionId]||null;if(!r?.sessionId)return!1;const o=Uf(r),a=Ar(s.ui.prompt,e,o);return this.setPrompt(a.prompt,a.cursor),this.setFocus(T.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${de(r.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}openSessionOwnerFilter(){const e=this.getState(),s=Ir(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=Bf(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=Ir(e),i=Array.isArray(s.items)?s.items:[];if(i.length===n.length&&i.every((u,f)=>u?.id===n[f]?.id))return;const o=i[Math.max(0,Number(s.selectedIndex)||0)]?.id,a=o!=null?n.findIndex(u=>u.id===o):-1,l=a>=0?a:Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1)));this.dispatch({type:"ui/modal",modal:{...s,items:n,selectedIndex:l}})}setFilesFilter(e={}){this.dispatch({type:"files/filter",filter:e})}clearPromptReferenceBrowser(){this.promptReferenceSignature=null,this.promptReferenceSyncVersion+=1,this.getState().sessions.filterQuery&&this.setSessionFilterQuery(""),this.getState().files.filter?.query&&this.setFilesFilter({query:""})}syncPromptReferenceBrowser(){const e=this.getState(),s=Er(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(ms(this.getState(),"selectedSession")),a=nt(this.getState()).filter(l=>r.has(l.sessionId))[0]||null;a?.filename&&(this.dispatch({type:"files/select",sessionId:a.sessionId,filename:a.filename}),await this.ensureFilePreview(a.sessionId,a.filename).catch(()=>{}))}).catch(()=>{})}async start({initialSessionId:e=null}={}){await this.transport.start();const s=typeof this.transport.getAuthContext=="function"?this.transport.getAuthContext():null;this.dispatch({type:"auth/context",principal:s?.principal??null,authorization:s?.authorization??null}),this.getState().sessions.ownerFilterExplicit||this.dispatch({type:"sessions/ownerFilter",filter:Ss(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:gr})})},4e3)}async stop(){this.catalogTimer&&clearInterval(this.catalogTimer),this.catalogTimer=null,this.activeSessionDetailTimer&&clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.sessionRefreshTimer&&clearTimeout(this.sessionRefreshTimer),this.sessionRefreshTimer=null,this.sessionHistoryExpansionLoads.clear(),this.sessionOrchestrationStatsLoads.clear(),this.detachActiveSession(),this.detachLogStream(),await this.transport.stop()}detachActiveSession(){this.activeSessionUnsub&&(this.activeSessionUnsub(),this.activeSessionUnsub=null),this.activeSessionSubscriptionId=null}handleSessionGone(e){e&&(this.activeSessionSubscriptionId===e&&this.detachActiveSession(),this.activeSessionDetailSessionId===e&&this.activeSessionDetailTimer&&(clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null),this.dispatch({type:"sessions/gone",sessionId:e}))}detachLogStream(){this.logUnsubscribe&&(this.logUnsubscribe(),this.logUnsubscribe=null)}async refreshSessions(){const e=this.getState(),s=!e.connection.connected||!!e.connection.error,n=e.ui.statusText===gr,i=this.getState().sessions.activeSessionId;let r=(await Cf(this.transport)).map(Qs);if(typeof this.transport.listSessionGroups=="function"){const f=await this.transport.listSessionGroups().catch(()=>[]),d=(Array.isArray(f)?f:[]).map(Ef).filter(Boolean);d.length>0&&(r=[...d,...r])}const o=e.sessions.navigationIntent;if(o?.status==="pending"&&!r.some(f=>f?.sessionId===o.sessionId)&&typeof this.transport.getSession=="function")try{const f=await this.transport.getSession(o.sessionId);f?.sessionId?r=[...r,Qs(f)]:this.dispatch({type:"sessions/navigationIntentFailed",sessionId:o.sessionId,errorKind:"not_found"})}catch(f){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:o.sessionId,errorKind:Js(f)})}const a=i;if(a&&!r.some(f=>f?.sessionId===a)&&typeof this.transport.getSession=="function"){const f=await this.transport.getSession(a).catch(()=>null);f?.sessionId&&(r=[...r,Qs(f)])}s&&this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,...n?{statusText:"Connected"}:{}}),this.dispatch({type:"sessions/loaded",sessions:r}),this.refreshOpenSessionOwnerFilterModal();const l=this.getState().sessions.activeSessionId,u=new Set;if(l){if(l!==i){if(!this.getState().sessions.byId[l]?.isGroup){const h=this.getState().sessions.navigationIntent;if(h&&h.sessionId===l&&h.status!=="failed")try{await this.loadSession(l)}catch(m){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:l,errorKind:Js(m)})}else await this.loadSession(l)}return}if(this.getState().sessions.byId[l]?.isGroup)return;this.getState().history.bySessionId.get(l)?.events?.length||await this.ensureSessionHistory(l,{force:!0}).catch(()=>{}),this.activeSessionSubscriptionId!==l&&this.attachActiveSession(l),await this.syncSessionDetail(l).catch(()=>{}),await this.syncSessionEvents(l).catch(()=>{}),u.add(l);const d=this.getState(),p=d.sessions.byId[l]||null;if(p?.parentSessionId&&typeof this.transport.getSession=="function"){const h=Object.values(d.sessions.byId).filter(m=>m?.parentSessionId===p.parentSessionId).map(m=>m.sessionId).filter(m=>m&&m!==l).slice(0,6);await Promise.all(h.map(m=>this.syncSessionDetail(m).catch(()=>{})));for(const m of h)u.add(m)}}await this.syncVisibleSessionDetails(u).catch(()=>{}),this.ensureInspectorData().catch(()=>{}),this.evictStaleSessionState()}evictStaleSessionState(){const e=this.getState(),s=e.sessions.activeSessionId,n=Date.now(),i=6e4,r=20,o=Object.entries(e.orchestration.bySessionId||{});if(o.length>r){const f=o.filter(([d,p])=>d!==s&&!p?.loading).sort((d,p)=>(d[1]?.fetchedAt||0)-(p[1]?.fetchedAt||0)).slice(0,o.length-r).filter(([,d])=>n-(d?.fetchedAt||0)>i);f.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:f.map(([d])=>d)})}const a=Object.entries(e.executionHistory?.bySessionId||{});if(a.length>r){const f=a.filter(([d,p])=>d!==s&&!p?.loading).sort((d,p)=>(d[1]?.fetchedAt||0)-(p[1]?.fetchedAt||0)).slice(0,a.length-r).filter(([,d])=>n-(d?.fetchedAt||0)>i);f.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:f.map(([d])=>d)})}const l=Object.entries(e.files.bySessionId||{});if(l.length>r){const f=l.filter(([d])=>d!==s).slice(0,l.length-r);f.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:f.map(([d])=>d)})}const u=[...e.history.bySessionId.entries()];if(u.length>r*2){const f=u.filter(([d])=>d!==s).slice(0,u.length-r*2).map(([d])=>d);f.length>0&&this.dispatch({type:"history/evict",sessionIds:f})}}async syncVisibleSessionDetails(e=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=Dt({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??xt(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(a=>a.sessionId).filter(a=>a&&!e.has(a)))];o.length!==0&&await Promise.all(o.map(a=>this.syncSessionDetail(a).catch(()=>{})))}async catchUpSessionHistory(e,s,n){let r;try{r=await this.transport.getSessionEvents(e,n,1e3)}catch(f){return _t(f)&&this.handleSessionGone(e),null}if(!Array.isArray(r)||r.length>=1e3)return null;if(r.length===0)return s;let o=s;for(const f of r)o=Ei(o,f);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 f of r)this.reconcileOutboxAgainstEvent(e,f);const a=yn(r),l=this.getState().sessions.byId[e]||{},u=Sr(l.contextUsage,r);return(a||u)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...a||{},...u?{contextUsage:u}:{}}}),o}async ensureSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),i=Math.min(lp,Math.max(ee,Number(n?.loadedEventLimit??ee)||ee));if(!s&&n?.events)return n;if(!s&&this.sessionHistoryLoads.has(e))return this.sessionHistoryLoads.get(e);const r=Number(n?.lastSeq)||0;if(s&&r>0&&Array.isArray(n?.events)&&n.events.length>0){const a=await this.catchUpSessionHistory(e,n,r);if(a)return a}const o=(async()=>{let a;try{a=await this.transport.getSessionEvents(e,void 0,i)}catch(p){if(_t(p))return this.handleSessionGone(e),null;throw p}const l={...zt(a,{requestedLimit:i}),lastSeq:a[a.length-1]?.seq||0};this.dispatch({type:"history/set",sessionId:e,history:l});for(const p of a||[])this.reconcileOutboxAgainstEvent(e,p);const u=yn(a),f=this.getState().sessions.byId[e]||{},d=Sr(f.contextUsage,a);return(u||d)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...u||{},...d?{contextUsage:d}:{}}}),l})().finally(()=>{this.sessionHistoryLoads.delete(e)});return this.sessionHistoryLoads.set(e,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"){const s=this.getState(),n=Dt({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??xt(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(a=>a.sessionId).filter(Boolean))];if(o.length===0)return;await Promise.allSettled(o.map(a=>this.ensureSessionHistory(a)));return}if(e==="files"&&await this.ensureFilesForScope(Ae(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<gf)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 _t(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<yf)){this.dispatch({type:"sessionStats/loading",sessionId:s});try{const[r,o,a,l,u,f,d]=await Promise.all([this.transport.getSessionMetricSummary(s),typeof this.transport.getSessionTokensByModel=="function"?this.transport.getSessionTokensByModel(s).catch(()=>[]):[],typeof this.transport.getSessionTreeStats=="function"?this.transport.getSessionTreeStats(s):null,typeof this.transport.getSessionSkillUsage=="function"?this.transport.getSessionSkillUsage(s).catch(()=>null):null,typeof this.transport.getSessionTreeSkillUsage=="function"?this.transport.getSessionTreeSkillUsage(s).catch(()=>null):null,typeof this.transport.getSessionFactsStats=="function"?this.transport.getSessionFactsStats(s).catch(()=>null):null,typeof this.transport.getSessionTreeFactsStats=="function"?this.transport.getSessionTreeFactsStats(s).catch(()=>null):null]);this.dispatch({type:"sessionStats/loaded",sessionId:s,summary:r,tokensByModel:o,treeStats:a,skillUsage:l,treeSkillUsage:u,factsStats:f,treeFactsStats:d})}catch{this.dispatch({type:"sessionStats/loaded",sessionId:s,summary:null,tokensByModel:[],treeStats:null,skillUsage:null,treeSkillUsage:null,factsStats:null,treeFactsStats:null})}}}async ensureFleetStats({force:e=!1}={}){if(typeof this.transport.getFleetStats!="function")return;const s=this.getState().fleetStats,n=Date.now();if(!(!e&&s?.loading)&&!(!e&&s?.data&&Number.isFinite(s.fetchedAt)&&n-s.fetchedAt<Sf)){this.dispatch({type:"fleetStats/loading"});try{const r={since:new Date(Date.now()-bf*864e5),includeDeleted:!0},[o,a,l,u,f,d]=await Promise.all([this.transport.getFleetStats(r),typeof this.transport.getUserStats=="function"?this.transport.getUserStats(r).catch(()=>null):null,typeof this.transport.getFleetSkillUsage=="function"?this.transport.getFleetSkillUsage(r).catch(()=>null):null,typeof this.transport.getFleetRetrievalUsage=="function"?this.transport.getFleetRetrievalUsage(r).catch(()=>null):null,typeof this.transport.getSharedFactsStats=="function"?this.transport.getSharedFactsStats().catch(()=>null):null,typeof this.transport.getFactsTombstoneStats=="function"?this.transport.getFactsTombstoneStats().catch(()=>null):null]);this.dispatch({type:"fleetStats/loaded",data:o,userStats:a,skillUsage:l,retrievalUsage:u,sharedFactsStats:f,factsTombstoneStats:d})}catch{this.dispatch({type:"fleetStats/loaded",data:null,userStats:null,skillUsage:null,retrievalUsage:null,sharedFactsStats:null,factsTombstoneStats:null})}}}async openAdminConsole(){this.dispatch({type:"admin/visibility",visible:!0}),await this.refreshAdminProfile().catch(()=>{})}closeAdminConsole(){this.dispatch({type:"admin/visibility",visible:!1})}async refreshAdminProfile(){if(typeof this.transport.getCurrentUserProfile!="function")return this.dispatch({type:"admin/profile/loadFailed",error:"Admin Console is not available on this transport."}),null;this.dispatch({type:"admin/profile/loading"});try{const e=await this.transport.getCurrentUserProfile();return this.dispatch({type:"admin/profile/loaded",profile:e}),await this.refreshSystemGhcpKeyStatus(e),e||null}catch(e){return this.dispatch({type:"admin/profile/loadFailed",error:e?.message||String(e)}),null}}async refreshSystemGhcpKeyStatus(e=null){if(!(e||this.getState().admin?.profile||null)?.isAdmin||typeof this.transport.getSystemGitHubCopilotKeyStatus!="function")return null;this.dispatch({type:"admin/systemGhcpKey/loading"});try{const n=await this.transport.getSystemGitHubCopilotKeyStatus();return this.dispatch({type:"admin/systemGhcpKey/loaded",status:n}),n||null}catch(n){return this.dispatch({type:"admin/systemGhcpKey/loadFailed",error:n?.message||String(n)}),null}}setAdminGhcpKeyStoreAsSystem(e){e&&!this.getState().admin?.profile?.isAdmin||this.dispatch({type:"admin/ghcpKey/setSystemTarget",value:!!e})}beginAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/beginEdit",draft:""})}setAdminGhcpKeyDraft(e,s=String(e||"").length){this.dispatch({type:"admin/ghcpKey/setDraft",draft:e,cursorIndex:s})}insertAdminGhcpKeyText(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=String(e||"").replace(/\r?\n/g,""),i=qe(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=mt(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,ne(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=Ae(this.getState()),{force:s=!1}={}){const n=ms(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=Ve(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<op)return n.selectedFilename&&await this.ensureFilePreview(e,n.selectedFilename).catch(()=>{}),n;this.dispatch({type:"files/sessionLoading",sessionId:e});try{const r=await this.transport.listArtifacts(e),o=Date.now();this.dispatch({type:"files/sessionLoaded",sessionId:e,entries:r,fetchedAt:o});const a=this.getState().files.bySessionId[e];return a?.selectedFilename&&await this.ensureFilePreview(e,a.selectedFilename).catch(()=>{}),a}catch(r){return this.dispatch({type:"files/sessionError",sessionId:e,error:r?.message||String(r)}),null}}async ensureFilePreview(e,s,{force:n=!1}={}){if(!e||!s||typeof this.transport.downloadArtifact!="function")return null;const i=this.getState().files.bySessionId[e],r=i?.previews?.[s];let o=Mc(i?.entries,s);if(!n&&r?.loading||!n&&r&&(r.content!==void 0||r.error))return r;if(!o&&typeof this.transport.getArtifactMetadata=="function")try{o=await this.transport.getArtifactMetadata(e,s)}catch{o=null}this.dispatch({type:"files/previewLoading",sessionId:e,filename:s});try{const a=o?.isBinary===!0?Mr(s,"",o.contentType||"",o):Mr(s,await this.transport.downloadArtifact(e,s),o?.contentType||"",o);return this.dispatch({type:"files/previewLoaded",sessionId:e,filename:s,...a}),a}catch(a){return this.dispatch({type:"files/previewError",sessionId:e,filename:s,error:a?.message||String(a)}),null}}buildArtifactPickerItems(e=[],s=[]){const n=(e||[]).map(i=>({id:`${i.sessionId}/${i.filename}`,kind:"artifact",sessionId:i.sessionId,filename:i.filename}));for(const i of s||[]){const r=String(i?.href||"").trim();r&&n.push({id:`url:${r}`,kind:"url",href:r,text:String(i?.text||r).trim()||r})}return(e||[]).length>1&&n.push({id:"__downloadAll__",kind:"downloadAll"}),n}buildArtifactPickerModal({artifactLinks:e,httpLinks:s,previousFocus:n,selectedId:i}={}){const r=this.buildArtifactPickerItems(e,s);if(r.length===0)return null;const o=r.findIndex(a=>a.id===i);return{type:"artifactPicker",title:"Linked Items",previousFocus:n,artifactLinks:e,httpLinks:s,items:r,selectedIndex:o>=0?o:0,exportDirectory:typeof this.transport.getArtifactExportDirectory=="function"?this.transport.getArtifactExportDirectory():null}}getArtifactPickerSelectionId(){const e=this.getState().ui.modal;return!e||e.type!=="artifactPicker"?null:e.items?.[e.selectedIndex||0]?.id||null}replaceArtifactPickerModal(e=null){const s=this.getState().ui.modal;if(!s||s.type!=="artifactPicker")return;const n=this.buildArtifactPickerModal({artifactLinks:s.artifactLinks||[],httpLinks:s.httpLinks||[],previousFocus:s.previousFocus,selectedId:e||this.getArtifactPickerSelectionId()});if(!n){this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:n})}async saveArtifactDownload(e,s){if(typeof this.transport.saveArtifactDownload!="function")return this.dispatch({type:"ui/status",text:"Artifact download is not supported by this transport"}),null;try{const n=await this.transport.saveArtifactDownload(e,s);this.dispatch({type:"files/downloaded",sessionId:e,filename:s,localPath:n?.localPath||"",downloadedAt:Date.now()});const i=this.getState().sessions.activeSessionId;return(e===i||this.getState().ui.inspectorTab==="files")&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),e===i&&(this.dispatch({type:"files/select",sessionId:e,filename:s}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(e,s,{force:!0}).catch(()=>null))),n}catch(n){return this.dispatch({type:"ui/status",text:`Download failed: ${n?.message||String(n)}`}),null}}async openSelectedFileInDefaultApp(){const e=this.getState(),s=Ve(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||Ae(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:i}=s,r=Ae(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 ${de(n)} ${i} in the default app`:`Opened ${i} in the default app`})}catch(a){this.dispatch({type:"ui/status",text:`Open failed: ${a?.message||String(a)}`})}}async downloadSelectedArtifact(){const e=Ve(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=nt(this.getState()),n=this.getState().files.markedIds||[],i=n.length>0?n[n.length-1]:this.getState().files.selectedArtifactId,r=s.findIndex(f=>f.id===i),o=s.findIndex(f=>f.id===e.id);if(o<0)return;if(r<0){this.dispatch({type:"files/toggleMark",artifactId:e.id});return}const[a,l]=r<=o?[r,o]:[o,r],u=s.slice(a,l+1).map(f=>f.id);this.dispatch({type:"files/setMarks",artifactIds:[...new Set([...n,...u])]})}clearArtifactMarks(){this.dispatch({type:"files/clearMarks"})}async deleteMarkedArtifacts({confirmed:e=!1}={}){const s=this.getState(),n=s.files.markedIds||[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No artifacts marked"}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifacts",message:`Delete ${n.length} artifact${n.length===1?"":"s"}? This action cannot be undone.`,confirmLabel:`Delete ${n.length}`,action:"deleteMarkedArtifacts",previousFocus:s.ui.focusRegion}}),!1;const i=new Set;let r=0;const o=[];for(const a of n){const l=String(a).indexOf("/");if(l<=0)continue;const u=a.slice(0,l),f=a.slice(l+1);try{await this.transport.deleteArtifact(u,f),this.dispatch({type:"files/deleted",sessionId:u,filename:f}),i.add(u),r+=1}catch(d){o.push(`${f}: ${d?.message||String(d)}`)}}for(const a of i)await this.ensureFilesForSession(a,{force:!0}).catch(()=>null);return this.dispatch({type:"files/clearMarks"}),this.dispatch({type:"ui/status",text:o.length>0?`Deleted ${r}, ${o.length} failed — ${o[0]}`:`Deleted ${r} artifact${r===1?"":"s"}`}),o.length===0}async deleteSelectedArtifact({confirmed:e=!1}={}){const s=this.getState(),n=Ve(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const i=Ae(s),r=i==="allSessions"?`${de(n.sessionId)} ${n.filename}`:n.filename;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifact",message:`Delete artifact "${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=Ve(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 ${de(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=Nu(e),i=Pu(e);if(n.length===0&&i.length===0){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}const r=this.getState().files.bySessionId[s]?.selectedFilename||null,o=r?`${s}/${r}`:null,a=this.buildArtifactPickerModal({artifactLinks:n,httpLinks:i,previousFocus:e.ui.focusRegion,selectedId:o});if(!a){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:a}),this.dispatch({type:"ui/status",text:"Select a linked item and press Enter to open or download it"})}async downloadArtifactModalSelection(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="url"){if(typeof this.transport.openUrlInDefaultBrowser!="function"){this.dispatch({type:"ui/status",text:"Opening URLs is not supported by this transport"});return}this.dispatch({type:"ui/status",text:`Opening ${s.href}...`}),await this.transport.openUrlInDefaultBrowser(s.href),this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Opened ${s.href}`});return}if(s.kind==="downloadAll"){const i=(e.items||[]).filter(o=>o.kind!=="artifact"?!1:!this.getState().files.bySessionId[o.sessionId]?.downloads?.[o.filename]?.localPath);if(i.length===0){this.dispatch({type:"ui/status",text:"All artifacts already downloaded"});return}this.dispatch({type:"ui/status",text:`Downloading ${i.length} artifacts...`});let r=0;for(const o of i)(await this.saveArtifactDownload(o.sessionId,o.filename))?.localPath&&(r+=1);this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${r}/${i.length} artifacts`});return}this.dispatch({type:"ui/status",text:`Downloading ${s.filename}...`}),(await this.saveArtifactDownload(s.sessionId,s.filename))?.localPath&&(this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${s.filename}`}))}async moveFileSelection(e){const s=Ae(this.getState());await this.ensureFilesForScope(s);const n=nt(this.getState());if(n.length===0)return;const i=Ve(this.getState())||n[0],r=Math.max(0,n.findIndex(l=>l.id===i?.id)),o=Math.max(0,Math.min(n.length-1,r+e)),a=n[o];!a?.sessionId||!a?.filename||(s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:a.id}):this.dispatch({type:"files/select",sessionId:a.sessionId,filename:a.filename}),await this.ensureFilePreview(a.sessionId,a.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${de(a.sessionId)} ${a.filename}`:`Previewing ${a.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;this.dispatch({type:"files/previewOrigin",origin:"list"});const s=Ae(this.getState());s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:e.id}):this.dispatch({type:"files/select",sessionId:e.sessionId,filename:e.filename}),await this.ensureFilePreview(e.sessionId,e.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${de(e.sessionId)} ${e.filename}`:`Previewing ${e.filename}`})}toggleFilePreviewFullscreen(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.files.bySessionId[s],i=!!e.files.fullscreen;if(!i&&!n?.selectedFilename){this.dispatch({type:"ui/status",text:"Select a file before entering fullscreen"});return}const 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(!vf.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=Ae(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:Js(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:Ei(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=Pf(s),o=this.getState().sessions.byId[e]||{sessionId:e},a=so(o.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(r||a)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...r||{},...a?{contextUsage:a}:{}}}),this.maybeFlushQueuedOutbox(e,this.getState().sessions.byId[e]||o),this.scheduleSessionDetailSync(e),!0}async syncSessionEvents(e){if(!e||typeof this.transport.getSessionEvents!="function")return;const s=this.getState().history.bySessionId.get(e);if(!s?.events){await this.ensureSessionHistory(e,{force:!0});return}const n=Number(s.lastSeq||0);let i=null;try{i=await this.transport.getSessionEvents(e,n,200)}catch(r){if(_t(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||(this.activeSessionDetailTimer&&clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailSessionId=e,this.activeSessionDetailTimer=setTimeout(()=>{const n=this.activeSessionDetailSessionId;this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.syncSessionDetail(n).catch(()=>{})},s))}scheduleSessionsRefresh(e=0){this.sessionRefreshTimer&&clearTimeout(this.sessionRefreshTimer),this.sessionRefreshTimer=setTimeout(()=>{this.sessionRefreshTimer=null,this.refreshSessions().catch(()=>{})},Math.max(0,e))}async syncSessionDetail(e){if(typeof this.transport.getSession!="function"||!e)return;let s=null;try{s=await this.transport.getSession(e)}catch(r){if(_t(r)){this.handleSessionGone(e);return}throw r}if(!s)return;const n=this.getState().sessions.byId[e]||null,i=Lf(n,s);(i||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:i||{sessionId:e}}),this.maybeFlushQueuedOutbox(e,s)}async createSession(e={}){try{const s=this.applyActiveGroupDefault(e),n=await this.transport.createSession(s);return await this.placeCreatedSessionInGroup(n,s.groupId??null),await this.refreshSessions(),await this.loadSession(n.sessionId),this.setFocus(T.PROMPT),this.dispatch({type:"ui/status",text:`Created session ${n.sessionId.slice(0,8)}`}),n}catch(s){return this.dispatch({type:"ui/status",text:s?.message||String(s)||"Failed to create session"}),null}}async createSessionForAgent(e,s={}){if(typeof this.transport.createSessionForAgent!="function")throw new Error("Named-agent session creation is not supported by this transport");try{const n=this.applyActiveGroupDefault(s),i=await this.transport.createSessionForAgent(e,n);return await this.placeCreatedSessionInGroup(i,n.groupId??null),await this.refreshSessions(),await this.loadSession(i.sessionId),this.setFocus(T.PROMPT),this.dispatch({type:"ui/status",text:`Created ${xr(e,s.title)} session ${i.sessionId.slice(0,8)}`}),i}catch(n){return this.dispatch({type:"ui/status",text:n?.message||String(n)||"Failed to create session"}),null}}async placeCreatedSessionInGroup(e,s){!s||!e?.sessionId||typeof this.transport.placeSessionsInGroup=="function"&&(e.viewerGroupId??null)!==s&&await this.transport.placeSessionsInGroup([e.sessionId],s).catch(()=>{})}getMovableGroupSessionSelection(){const e=this.getState();return(Array.isArray(e.sessions.selectedIds)&&e.sessions.selectedIds.length>0?e.sessions.selectedIds:e.sessions.activeSessionId?[e.sessions.activeSessionId]:[]).map(n=>e.sessions.byId[n]).filter(n=>n&&!n.isSystem&&!n.isGroup&&!n.parentSessionId)}async openMoveToGroupModal(){const e=this.getState(),s=this.getMovableGroupSessionSelection();if(s.length===0)return this.dispatch({type:"ui/status",text:"Select a top-level non-system session to move"}),null;if(typeof this.transport.listSessionGroups!="function")return this.dispatch({type:"ui/status",text:"Session groups are not supported by this transport"}),null;const n=await this.transport.listSessionGroups().catch(()=>[]),i=s.map(l=>l.sessionId),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(l=>({id:l.groupId,kind:"group",label:l.title||l.groupId,description:l.description||"Move selected session(s) into this group.",groupId:l.groupId,memberCount:l.memberCount??0}))],a=r?Math.max(0,o.findIndex(l=>l.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(l=>l.title||l.sessionId.slice(0,8)),selectedIndex:a>=0?a:0,items:o}}),this.dispatch({type:"ui/status",text:"Choose a group, [New Group], or [No Group]"}),o}async createSessionGroupFromSelection(){return this.openMoveToGroupModal()}async moveSessionsToGroup(e,s,{statusTitle:n=null}={}){const i=Array.from(new Set((Array.isArray(s)?s:[]).map(d=>String(d||"").trim()).filter(Boolean)));if(i.length===0)return this.dispatch({type:"ui/status",text:"No sessions selected to move"}),null;let r=null;if(typeof this.transport.placeSessionsInGroup=="function")r=await this.transport.placeSessionsInGroup(i,e??null);else if(typeof this.transport.moveSessionsToGroup=="function")await this.transport.moveSessionsToGroup(e??null,i);else if(e&&typeof this.transport.assignSessionsToGroup=="function")await this.transport.assignSessionsToGroup(e,i);else return this.dispatch({type:"ui/status",text:"Moving sessions between groups is not supported by this transport"}),null;const o=Array.isArray(r)?r.filter(Boolean):null,a=o?o.filter(d=>d.placed!==!0):[],l=o?o.filter(d=>d.placed===!0).length:i.length;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&l>0&&await this.loadSession(`group:${e}`).catch(()=>{});const u=e?`group ${n||e}`:"No Group",f=a.length>0?` · skipped ${a.length} (${Af(a)})`:"";return this.dispatch({type:"ui/status",text:l>0?`Moved ${l} session${l===1?"":"s"} to ${u}${f}`:`No sessions moved to ${u}${f}`}),l>0}async confirmSessionGroupPickerModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="newGroup"){const i=(e.sessionLabels||[]).length===1?`${e.sessionLabels[0]} Group`:`${(e.sessionIds||[]).length} Session Group`;this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.previousFocus,sessionIds:e.sessionIds||[],value:i,cursorIndex:i.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{await this.moveSessionsToGroup(s.kind==="noGroup"?null:s.groupId,e.sessionIds||[],{statusTitle:s.label})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}updateSessionGroupNameModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setSessionGroupNameValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="sessionGroupName")return;const i=pt(e,n.maxLength||80),r=ne(i,s);this.updateSessionGroupNameModal({value:i,cursorIndex:r})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=qe(s.value||"",s.cursorIndex||0,pt(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=mt(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||"",ne(s.value||"",(s.cursorIndex||0)+e))}moveSessionGroupNameCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmSessionGroupNameModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"Group name cannot be empty"});return}if(typeof this.transport.createSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{const i=await this.transport.createSessionGroup({title:s,description:`${(e.sessionIds||[]).length} grouped session${(e.sessionIds||[]).length===1?"":"s"}`,sessionIds:e.sessionIds||[]});await this.moveSessionsToGroup(i.groupId,e.sessionIds||[],{statusTitle:i.title||s})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}applyActiveGroupDefault(e={}){if(e&&Object.prototype.hasOwnProperty.call(e,"groupId"))return e;const s=this.getState(),n=s.sessions?.activeSessionId?s.sessions.byId[s.sessions.activeSessionId]:null,i=n?.isGroup?n.groupId||Xs(n.sessionId):n?.groupId;return i?{...e,groupId:i}:e}getActiveSession(e=this.getState()){const s=e.sessions?.activeSessionId;return s&&e.sessions.byId[s]||null}toggleChatViewMode(){if(this.getActiveSession()?.isGroup){this.dispatch({type:"ui/status",text:"Session groups show group details"});return}const s=this.getState().ui?.chatViewMode==="summary"?"transcript":"summary";this.dispatch({type:"ui/chatViewMode",mode:s}),this.dispatch({type:"ui/status",text:s==="summary"?"Showing session summary":"Showing chat transcript"})}setChatViewMode(e){e!=="summary"&&e!=="transcript"&&e!=="rich"||this.getActiveSession()?.isGroup||this.dispatch({type:"ui/chatViewMode",mode:e})}async openSessionAgentPicker(e={}){const s=typeof this.transport.listCreatableAgents=="function"?await this.transport.listCreatableAgents():[],i=(typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0;if(!Array.isArray(s)||s.length===0){if(!i){this.dispatch({type:"ui/status",text:"No user-creatable agents are available for this app"});return}await this.createSession(e);return}const r=[];i&&r.push({id:"__generic__",kind:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,splashMobile:null,initialPrompt:null});for(const o of s){const a=String(o?.name||"").trim();a&&r.push({id:a,kind:"agent",agentName:a,title:xr(a,o?.title),description:String(o?.description||"").trim(),tools:Array.isArray(o?.tools)?o.tools.filter(Boolean):[],splash:typeof o?.splash=="string"&&o.splash.trim()?o.splash:null,splashMobile:typeof o?.splashMobile=="string"&&o.splashMobile.trim()?o.splashMobile:null,initialPrompt:typeof o?.initialPrompt=="string"&&o.initialPrompt.trim()?o.initialPrompt:null})}this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",items:r,selectedIndex:0,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select an agent and press Enter"})}async openNewSessionFlow(e={}){if((typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0){await this.createSession(e);return}if(typeof this.transport.listModels=="function"){await this.openModelPicker(e);return}await this.openSessionAgentPicker(e)}async openReasoningEffortPicker(e,s={}){const n=mn(e?.supportedReasoningEfforts),i=s?.reasoningEffort||yr(e);if(!n.length||!i){await this.openContextTierPicker(e,s);return}const r=n.map(a=>({id:a,effort:a,label:a,isDefault:i===a})),o=Math.max(0,r.findIndex(a=>a.id===i));this.dispatch({type:"ui/modal",modal:{type:"reasoningEffortPicker",title:s?.mode==="switchModel"?`Switch reasoning for ${e?.modelName||e?.qualifiedName||"model"}`:`Reasoning effort for ${e?.modelName||e?.qualifiedName||"model"}`,items:r,selectedIndex:o,previousFocus:this.getState().ui.focusRegion,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a reasoning effort and press Enter"})}async openContextTierPicker(e,s={}){const n=gn(e?.supportedContextTiers),i=s?.contextTier||kf(e);if(!n.length||!i){if(s?.mode==="switchModel"){await this.switchSessionModel({...s,model:e?.id});return}await this.openSessionAgentPicker(s);return}const r=n.map(a=>({id:a,tier:a,tokenLimit:e?.contextWindowSizes?.[a]||null,label:Nf(a,e?.contextWindowSizes?.[a]),isDefault:i===a})),o=Math.max(0,r.findIndex(a=>a.id===i));this.dispatch({type:"ui/modal",modal:{type:"contextTierPicker",title:`Context window for ${e?.modelName||e?.qualifiedName||"model"}`,items:r,selectedIndex:o,previousFocus:this.getState().ui.focusRegion,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a context window and press Enter"})}async openModelPicker(e={}){if(typeof this.transport.listModels!="function"){await this.openSessionAgentPicker(e);return}const s=await this.transport.listModels();if(!Array.isArray(s)||s.length===0){this.dispatch({type:"ui/status",text:"No models available"});return}const n=typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0,i=typeof this.transport.getModelsByProvider=="function"?this.transport.getModelsByProvider():Tf(s),r=await this._resolveGhcpUserKeySet(),o=[],a=i.map(f=>({providerId:f.providerId,providerType:f.type||f.providerType,models:(f.models||[]).map(d=>{const p=d.providerType||f.type||f.providerType,h=p==="github"&&d.credentialAvailable===!1&&r===!1,m={id:d.qualifiedName,qualifiedName:d.qualifiedName,modelName:d.modelName||d.qualifiedName,providerId:d.providerId||f.providerId,providerType:p,description:d.description||"",cost:d.cost||null,supportedReasoningEfforts:mn(d.supportedReasoningEfforts),defaultReasoningEffort:d.defaultReasoningEffort||null,supportedContextTiers:gn(d.supportedContextTiers),defaultContextTier:d.defaultContextTier||null,contextWindowSizes:d.contextWindowSizes||null,isDefault:n===d.qualifiedName,ghcpKeyMissing:h,disabled:h};return o.push(m),m})})).filter(f=>f.models.length>0),l=e?.model||n;let u=o.findIndex(f=>f.qualifiedName===l&&!f.disabled);u<0&&(u=o.findIndex(f=>!f.disabled)),u<0&&(u=0),this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:e?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:o,groups:a,selectedIndex:u,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async _resolveGhcpUserKeySet(){const e=this.getState().admin?.profile;if(typeof e?.githubCopilotKeySet=="boolean")return e.githubCopilotKeySet;if(typeof this.transport.getCurrentUserProfile!="function")return null;try{const s=await this.transport.getCurrentUserProfile();return s&&typeof s.githubCopilotKeySet=="boolean"?s.githubCopilotKeySet:!1}catch{return null}}async openSwitchModelPicker(e=null){this._onSwitchModelApplied=typeof e=="function"?e:null;const s=this.getState(),n=s.sessions.activeSessionId,i=n&&s.sessions.byId[n]||null;if(!i||i.isGroup){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Select a session before switching model"});return}if(typeof this.transport.setSessionModel!="function"){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.openModelPicker({mode:"switchModel",sessionId:n,model:i.model||void 0,reasoningEffort:i.reasoningEffort||void 0})}async switchSessionModel(e={}){const s=e.sessionId||this.getState().sessions.activeSessionId,n=String(e.model||"").trim();if(!s||!n){this.dispatch({type:"ui/status",text:"Select a model before switching"});return}if(typeof this.transport.setSessionModel!="function"){this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.transport.setSessionModel(s,{model:n,..."reasoningEffort"in e?{reasoningEffort:e.reasoningEffort??null}:{},..."contextTier"in e?{contextTier:e.contextTier??null}:{},source:"ui"});const i=e.reasoningEffort?`${n}:${e.reasoningEffort}`:n,r=e.contextTier?` · ${fa[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=Cc().map(i=>({id:i.id,label:i.label,description:i.description,page:i.page,terminal:i.terminal,tui:i.tui}));if(e.length===0){this.dispatch({type:"ui/status",text:"No themes available"});return}const s=this.getState().ui.themeId,n=Math.max(0,e.findIndex(i=>i.id===s));this.dispatch({type:"ui/modal",modal:{type:"themePicker",title:"Theme Picker",items:e,selectedIndex:n,previousFocus:this.getState().ui.focusRegion,currentThemeId:s}}),this.dispatch({type:"ui/status",text:"Select a theme and press Enter"})}getPromptDraftSessionId(){return this.getPromptAttachments()[0]?.sessionId||null||this.getState().sessions.activeSessionId||null}openArtifactUploadModal(){if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}const e=this.getState(),s=this.getPromptDraftSessionId();this.dispatch({type:"ui/modal",modal:{type:"artifactUpload",title:s?`Upload Artifact (${de(s)})`:"Upload Artifact",sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0}}),this.dispatch({type:"ui/status",text:s?"Paste a local file path and press Enter to upload it into this session's artifacts":"Paste a local file path and press Enter to upload it; a new session will be created if needed"})}updateArtifactUploadModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setArtifactUploadValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="artifactUpload")return;const i=String(e||"").replace(/\r?\n/g,""),r=ne(i,s);this.updateArtifactUploadModal({value:i,cursorIndex:r})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=qe(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=mt(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||"",ne(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=Qi(s);if(n.length===0){await this.moveFileSelection(e);return}const i=n.indexOf(s.files.selectedArtifactId),o=(i>=0?i:e>0?-1:n.length)+(e>0?1:-1);if(o<0||o>=n.length)return;const a=n[o],l=a.indexOf("/");if(l<=0)return;const u=a.slice(0,l),f=a.slice(l+1);this.dispatch({type:"files/select",sessionId:u,filename:f}),await this.ensureFilePreview(u,f).catch(()=>{})}canStepArtifactPreview(e){const s=this.getState(),n=s.files.previewOrigin==="chat"?Qi(s):nt(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=vr(e.filename),o=this.getState().ui.prompt,a=this.getState().ui.promptCursor,l=this.getPromptAttachments(),u=l.findIndex(d=>d?.sessionId===i&&d?.filename===e.filename);if(this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),u===-1||!o.includes(l[u]?.token||r)){const d=qe(o,a,`${r} `);this.setPrompt(d.prompt,d.cursor)}const f=u>=0?l.map((d,p)=>p===u?{...d,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:r}:d):[...l,{id:`${i}/${e.filename}`,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:r}];return this.setPromptAttachments(f),await this.ensureFilesForSession(i,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:i,filename:e.filename}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(i,e.filename,{force:!0}).catch(()=>null),this.setFocus(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(l=>l&&typeof l.name=="string"):[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No files selected"}),[];if(typeof this.transport.uploadArtifactFromFile!="function")return this.dispatch({type:"ui/status",text:"Browser file uploads are not supported by this transport"}),[];this.dispatch({type:"ui/status",text:n.length===1?`Uploading ${n[0].name}...`:`Uploading ${n.length} artifact files...`});const i=s||await this.ensurePromptAttachmentSessionId(),r=[];let o=0,a=null;for(const l of n)try{const u=await this.transport.uploadArtifactFromFile(i,l);r.push(u),await this.finalizeArtifactUpload(u,{sessionId:i,suppressStatus:!0})}catch(u){o+=1,a=u}return r.length>0?this.dispatch({type:"ui/status",text:o>0?`Uploaded ${r.length}/${n.length} file(s); last error: ${a?.message||String(a)}`:r.length===1?`Uploaded ${r[0].filename}`:`Uploaded ${r.length} files`}):a&&this.dispatch({type:"ui/status",text:`Upload failed: ${a?.message||String(a)}`}),r}async uploadPromptAttachmentFiles(e=[]){return this.uploadArtifactFiles(e)}async confirmArtifactUploadModal(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"File path cannot be empty"});return}if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}this.dispatch({type:"ui/status",text:"Uploading artifact..."});try{const n=e.sessionId||await this.ensurePromptAttachmentSessionId(),i=await this.transport.uploadArtifactFromPath(n,s),r=await this.finalizeArtifactUpload(i,{sessionId:n,suppressStatus:!0});if(this.dispatch({type:"ui/modal",modal:null}),this.stageUploadedImageAttachment(r,n)){this.dispatch({type:"ui/status",text:`Uploaded ${r.filename} — attached to your next message`});return}this.dispatch({type:"ui/status",text:`Uploaded ${r.filename}`})}catch(n){this.dispatch({type:"ui/status",text:`Upload failed: ${n?.message||String(n)}`})}}openRenameSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.sessions.byId[s];if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System session titles are fixed"});return}const i=Hf(n),r=Xn(n),o=Df(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:`Rename (${de(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:i,cursorIndex:i.length,agentTitlePrefix: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:`Lifecycle (${de(n)})`,sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:String(i.title||"").trim(),state:String(i.state||"").trim(),canRegenerate:typeof this.transport.regenerateSession=="function"&&!i.serviceKind}})}async pickTerminateAction(e){const s=this.getState().ui.modal;if(!s||s.type!=="terminatePicker")return;const n=s.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),e==="complete"?await this.completeActiveSession():e==="cancel"?await this.cancelActiveSession():e==="delete"?await this.deleteActiveSession():e==="regenerate"&&await this.regenerateActiveSession()}getBulkSelectedSessionActions(e=this.getState()){const s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[],i=[...new Set(s.map(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=pt(e,n.maxLength),r=ne(i,s);this.updateRenameSessionModal({value:i,cursorIndex:r})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=qe(s.value||"",s.cursorIndex||0,pt(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=mt(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||"",ne(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||Xs(s):null;if(r){if(typeof this.transport.updateSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group renaming is not supported by this transport"});return}const a=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),a&&this.setFocus(a),this.dispatch({type:"ui/status",text:`Renaming group ${r.slice(0,8)}...`});try{await this.transport.updateSessionGroup(r,{title:n}),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Renamed group ${n}`})}catch(l){this.dispatch({type:"ui/status",text:`Rename failed: ${l?.message||String(l)}`})}return}if(typeof this.transport.renameSession!="function"){this.dispatch({type:"ui/status",text:"Session renaming is not supported by this transport"});return}const o=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),o&&this.setFocus(o),this.dispatch({type:"ui/status",text:`Renaming ${de(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${de(s)}`})}catch(a){this.dispatch({type:"ui/status",text:`Rename failed: ${a?.message||String(a)}`})}}async cycleSessionVisibility(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups don't have visibility"});return}if(typeof this.transport.setSessionVisibility!="function"){this.dispatch({type:"ui/status",text:"Not supported by this transport"});return}const i=ut(["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 (${de(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0,shares:Array.isArray(i)?i:[],visibility:n.visibility||"private"}}),this.dispatch({type:"ui/status",text:"name [r|w] grants · -name revokes · Enter apply"})}updateShareSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setShareSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="shareSession")return;const i=pt(e,120),r=ne(i,s);this.updateShareSessionModal({value:i,cursorIndex:r})}insertShareSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=qe(s.value||"",s.cursorIndex||0,pt(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=mt(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||"",ne(s.value||"",(s.cursorIndex||0)+e))}moveShareSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmShareSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim(),i=e.previousFocus;if(!n){this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);return}const r=n.startsWith("-")?n.slice(1).trim():n.toLowerCase().startsWith("revoke ")?n.slice(7).trim():null;if(r!==null){const h=r.toLowerCase(),m=(e.shares||[]).find(g=>g.subject&&String(g.subject).toLowerCase()===h||g.email&&String(g.email).toLowerCase()===h||g.displayName&&String(g.displayName).toLowerCase()===h);if(!m){this.dispatch({type:"ui/status",text:`No grant matching "${r}"`});return}this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.revokeSessionShare(s,{provider:m.provider,subject:m.subject}),this.dispatch({type:"ui/status",text:`Revoked ${r}`})}catch(g){this.dispatch({type:"ui/status",text:g?.message||String(g)})}return}const o=n.split(/\s+/),a={r:"read",read:"read",w:"write",write:"write"},l=o.length>1?o[o.length-1].toLowerCase():null,u=l&&a[l]?a[l]:"read",f=l&&a[l]?o.slice(0,-1).join(" "):n,d=f.toLowerCase();let p=null;if(typeof this.transport.listKnownUsers=="function"){let h=[];try{h=await this.transport.listKnownUsers({limit:500})}catch{h=[]}const m=Array.isArray(h)?h:[];if(p=m.find(g=>g.displayName&&g.displayName.toLowerCase()===d||g.email&&g.email.toLowerCase()===d||g.subject&&g.subject.toLowerCase()===d)||null,!p){const g=m.filter(S=>S.displayName&&S.displayName.toLowerCase().includes(d)||S.email&&S.email.toLowerCase().includes(d)||S.subject&&S.subject.toLowerCase().includes(d));if(g.length===1)p=g[0];else if(g.length>1){this.dispatch({type:"ui/status",text:`"${f}" is ambiguous (${g.length} matches)`});return}}}p||(p={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:f,email:null,displayName:null}),this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.grantSessionShare(s,{provider:p.provider,subject:p.subject,email:p.email??null,displayName:p.displayName??null},u),this.dispatch({type:"ui/status",text:`Granted ${u} to ${f}`})}catch(h){this.dispatch({type:"ui/status",text:h?.message||String(h)})}}closeModal(){const e=this.getState().ui.modal;e&&(this.dispatch({type:"ui/modal",modal:null}),e.type==="themePicker"&&e.currentThemeId&&this.dispatch({type:"ui/theme",themeId:e.currentThemeId}),e.previousFocus&&this.setFocus(e.previousFocus),this.dispatch({type:"ui/status",text:"Connected"}))}moveModalSelection(e){const s=this.getState().ui.modal;if(!s)return;if(s.type==="help"){const r=Math.max(0,Number(s.selectedIndex)||0);this.dispatch({type:"ui/modalSelection",index:Math.max(0,r+e)});return}if(!Array.isArray(s.items)||s.items.length===0)return;if(s.type==="logFilter"||s.type==="filesFilter"||s.type==="historyFormat"){const r=Math.max(0,Math.min(Number(s.selectedIndex)||0,s.items.length-1)),o=s.items[r];if(!o||!Array.isArray(o.options)||o.options.length===0)return;const a=o.options.map(d=>d.id).filter(Boolean);if(a.length===0)return;const l=s.type==="filesFilter"?this.getState().files.filter?.[o.id]||a[0]:s.type==="historyFormat"?this.getState().executionHistory?.format||a[0]:this.getState().logs.filter?.[o.id]||a[0],u=ut(a,l,e),f=o.options.find(d=>d.id===u)||o.options[0];this.dispatch({type:s.type==="filesFilter"?"files/filter":s.type==="historyFormat"?"executionHistory/format":"logs/filter",filter:s.type==="historyFormat"?void 0:{[o.id]:u},...s.type==="historyFormat"?{format:u}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(u).catch(()=>{}),this.ensureSelectedFilePreview().catch(()=>{})),this.dispatch({type:"ui/status",text:`${s.type==="filesFilter"?"Files":s.type==="historyFormat"?"History":"Log"} filter updated: ${o.label} = ${f?.label||u}`});return}const n=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(0,Math.min(n+e,s.items.length-1));this.dispatch({type:"ui/modalSelection",index:i})}moveModalPane(e){const s=this.getState().ui.modal;if(!s||s.type!=="logFilter"&&s.type!=="filesFilter"&&s.type!=="historyFormat"||!Array.isArray(s.items)||s.items.length===0)return;const i=(Math.max(0,Number(s.selectedIndex)||0)+e+s.items.length)%s.items.length,r=s.items[i],o=s.type==="filesFilter"?this.getState().files.filter?.[r.id]||r.options?.[0]?.id:s.type==="historyFormat"?this.getState().executionHistory?.format||r.options?.[0]?.id:this.getState().logs.filter?.[r.id]||r.options?.[0]?.id,a=r.options?.find(l=>l.id===o)||r.options?.[0];this.dispatch({type:"ui/modalSelection",index:i}),this.dispatch({type:"ui/status",text:`Editing ${r.label}: ${a?.label||o||""}`})}async confirmModal(){const e=this.getState().ui.modal;if(e){if(e.type==="help"){this.closeModal();return}if(e.type==="confirm"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s),e.action==="cancelSession"?await this.cancelActiveSession({confirmed:!0}):e.action==="completeSession"?await this.completeActiveSession("Completed by user",{confirmed:!0}):e.action==="deleteSession"?await this.deleteActiveSession({confirmed:!0}):e.action==="regenerateSession"?await this.regenerateActiveSession({confirmed:!0,...e.extras||{}}):e.action==="deleteArtifact"?await this.deleteSelectedArtifact({confirmed:!0}):e.action==="deleteMarkedArtifacts"&&await this.deleteMarkedArtifacts({confirmed:!0});return}if(e.type==="artifactUpload"){await this.confirmArtifactUploadModal();return}if(e.type==="renameSession"){await this.confirmRenameSessionModal();return}if(e.type==="shareSession"){await this.confirmShareSessionModal();return}if(e.type==="sessionGroupPicker"){await this.confirmSessionGroupPickerModal();return}if(e.type==="sessionGroupName"){await this.confirmSessionGroupNameModal();return}if(e.type==="sessionOwnerFilter"){this.toggleSessionOwnerFilter();return}if(e.type==="filesFilter"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s);return}if(e.type==="themePicker"){const s=e.items?.[e.selectedIndex||0],n=Xe(s?.id);if(!n){this.dispatch({type:"ui/status",text:"Unable to apply that theme"});return}const i=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i),this.dispatch({type:"ui/status",text:`Applied theme: ${n.label}`});return}if(e.type==="modelPicker"){const s=e.items?.[e.selectedIndex||0];if(s?.disabled){this.dispatch({type:"ui/status",text:s.ghcpKeyMissing?"This model needs a GitHub Copilot key — add yours in the Admin console first":"This model is not available"});return}const n=e.previousFocus;if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s){if(e.sessionOptions?.mode==="switchModel"){this.dispatch({type:"ui/status",text:"No model selected"});return}await this.openSessionAgentPicker({});return}const i=yr(s);if(e.sessionOptions?.mode==="switchModel"){await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,reasoningEffort:i??null});return}await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,...i?{reasoningEffort:i}:{}});return}if(e.type==="reasoningEffortPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),await this.openContextTierPicker(e.modelItem,{...i,...s?.id?{reasoningEffort:s.id}:{}});return}if(e.type==="contextTierPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);const r={...i,...s?.id?{contextTier:s.id}:{}};if(i?.mode==="switchModel"){await this.switchSessionModel({...r,model:e.modelItem?.id||i.model});return}await this.openSessionAgentPicker(r);return}if(e.type==="sessionAgentPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s||s.kind==="generic"){await this.createSession(i);return}await this.createSessionForAgent(s.agentName,{...i,...s.title?{title:s.title}:{},...s.splash?{splash:s.splash}:{},...s.splashMobile?{splashMobile:s.splashMobile}:{},...s.initialPrompt?{initialPrompt:s.initialPrompt}:{}});return}if(e.type==="logFilter"){this.closeModal();return}if(e.type==="historyFormat"){this.closeModal();return}e.type==="artifactPicker"&&await this.downloadArtifactModalSelection()}}openLogFilter(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"logFilter",title:"Log Filters",previousFocus:e,selectedIndex:0,items:[{id:"source",label:"Source nodes",description:"Choose whether the log pane shows logs from all nodes or only the current orchestration.",options:[{id:"allNodes",label:"All nodes"},{id:"currentOrchestration",label:"Current orchestration"}]},{id:"level",label:"Levels",description:"Filter logs by severity/verbosity level.",options:[{id:"all",label:"All"},{id:"info",label:"Info"},{id:"warn",label:"Warn"},{id:"error",label:"Error"},{id:"debug",label:"Debug"},{id:"trace",label:"Trace"}]},{id:"format",label:"Format",description:"Raw shows the structured time/node/level summary. Pretty shows the cleaned message text, colored by orchestration vs activity.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw summary"}]}]}}),this.dispatch({type:"ui/status",text:"Tab/Shift-Tab switch filters · Up/Down change values · Enter close · Esc cancel"})}openHistoryFormat(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"historyFormat",title:"Execution History Format",previousFocus:e,selectedIndex:0,items:[{id:"format",label:"Format",description:"Pretty prints a human-readable view with colored event kinds. Raw JSON shows the full event objects.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw JSON"}]}]}}),this.dispatch({type:"ui/status",text:"Up/Down change format · Enter close · Esc cancel"})}toggleLogTail(){const e=this.getState().logs;if(!e.available){this.dispatch({type:"ui/status",text:e.availabilityReason||"Log tailing is not available in this environment"});return}if(e.tailing){this.detachLogStream(),typeof this.transport.stopLogTail=="function"&&this.transport.stopLogTail().catch(()=>{}),this.dispatch({type:"logs/tailing",tailing:!1}),this.dispatch({type:"ui/status",text:"Log tailing stopped"});return}if(typeof this.transport.startLogTail!="function"){this.dispatch({type:"ui/status",text:"Log tailing is not supported by this transport"});return}this.logUnsubscribe=this.transport.startLogTail(s=>{const n=Array.isArray(s)?s:[s];n.length>0&&this.dispatch({type:"logs/append",entries:n})}),this.dispatch({type:"logs/tailing",tailing:!0}),this.dispatch({type:"ui/status",text:"Log tailing started"})}async sendPrompt(){const e=this.getState(),s=e.ui.prompt,n=this.getPromptAttachments(),i=n[0]?.sessionId||null,r=Kf(s,n);let o=e.sessions.activeSessionId;i&&(o=i,e.sessions.activeSessionId!==i&&await this.loadSession(i));let a=o&&e.sessions.byId[o]||null;if(o&&!a&&(a=this.getState().sessions.byId[o]||null),!o){const g=await this.createSession({});if(!g?.sessionId)return;o=g.sessionId,a=this.getState().sessions.byId[o]||null}const l=n.some(g=>g?.kind==="image");if(!r.trim()&&!l){o&&this.getPendingOutboxItems(o).length>0&&await this.dispatchPendingOutbox(o).catch(()=>{});return}const u=a?.pendingQuestion||null,f=!!u?.question,d=this.getPromptEditSessionMatch(o);if(d){const g=this.getSessionOutbox(o).find(S=>S.id===d.itemId);if(g?.phase==="queued"||g?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(o).catch(()=>{});return}if(f&&typeof this.transport.sendAnswer=="function"){const g=Date.now(),S={...u,answer:r,answeredAt:g,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:null,answeredPendingQuestion:S}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(o,r),this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:{...S,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(o,100),this.syncSessionEvents(o).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(y){this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:u}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(r,String(r||"").length),this.dispatch({type:"ui/status",text:y?.message||String(y)})}return}const p=n.filter(g=>g?.kind==="image");let h=null;if(p.length>0){if(p.some(y=>y.file)&&typeof this.transport.uploadArtifactFromFile!="function"){this.dispatch({type:"ui/status",text:"This transport does not support image attachments."});return}const S=this.buildOutboxItem("","pending");this.dispatch({type:"ui/status",text:`Uploading ${p.length} image${p.length>1?"s":""}...`});try{h=await this.uploadPendingImageAttachments(o,p,S.id),this.dispatch({type:"ui/status",text:""})}catch(y){this.dispatch({type:"ui/status",text:`Image upload failed: ${y?.message||y}`});return}}const m=r.trim()?r:h&&h.length>0?"See the attached image(s).":r;this.queuePromptInOutbox(o,m,h?{attachments:h}:null),this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(o).catch(()=>{})}setPrompt(e,s=String(e||"").length){const n=String(e||""),i=Math.max(0,Math.min(Number.isFinite(s)?s:n.length,n.length)),r=this.getState().ui;if(!(r.prompt===n&&r.promptCursor===i)){if(r.promptEdit?.sessionId&&r.promptEdit?.itemId){const a=this.getSessionOutbox(r.promptEdit.sessionId).map(l=>l.id===r.promptEdit.itemId&&l.phase==="pending"&&l.attempted!==!0?{...l,text:n}:l);this.setSessionOutboxItems(r.promptEdit.sessionId,a)}this.dispatch({type:"ui/prompt",prompt:n,promptCursor:i}),this.syncPromptReferenceBrowser()}}setPromptCursor(e){const s=this.getState().ui.prompt||"";this.setPrompt(s,e)}insertPromptText(e){const s=this.getState().ui,n=qe(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=mt(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=Qf(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,ne(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,ya(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=Xf(s.prompt,s.promptCursor,e);if(n!==s.promptCursor){this.setPrompt(s.prompt,n);return}e<0&&this.selectPreviousPendingPrompt()||e>0&&this.selectNextPendingPrompt()||this.setPrompt(s.prompt,n)}getCurrentLayout(e={}){const s=this.getState().ui.layout||{},n=this.getState().ui,i=e.prompt??n.prompt;return Dt({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??xt(i),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===T.SESSIONS?e.bodyHeight:e.sessionPaneHeight;return Math.max(3,s-2)}setViewport(e={}){const s=Math.max(40,Number(e.width)||120),n=Math.max(18,Number(e.height)||40),i=this.getState().ui.layout||{};(i.viewportWidth!==s||i.viewportHeight!==n)&&this.dispatch({type:"ui/viewport",width:s,height:n});const r=this.getCurrentLayout({width:s,height:n}),o=this.getState().ui.focusRegion,a=He(o,r);a!==o&&this.setFocus(a)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:He(e,this.getCurrentLayout())})}focusNext(){const e=this.getCurrentLayout(),s=He(this.getState().ui.focusRegion,e),n=cn(e);this.setFocus(ut(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=He(this.getState().ui.focusRegion,e),n=cn(e);this.setFocus(ut(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=He(this.getState().ui.focusRegion,e);this.setFocus(Ql(s,e))}focusRight(){const e=this.getCurrentLayout(),s=He(this.getState().ui.focusRegion,e);this.setFocus(Xl(s,e))}adjustPaneSplit(e){const s=this.getState().ui.layout||{},n=s.viewportWidth??120,i=Math.max(-n,Math.min(n,(s.paneAdjust||0)+e));this.dispatch({type:"ui/paneAdjust",paneAdjust:i});const r=this.getCurrentLayout({paneAdjust:i}),o=this.getState().ui.focusRegion,a=He(o,r);a!==o&&this.setFocus(a)}adjustSessionPaneSplit(e){const s=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,r=Math.max(-i,Math.min(i,(s.sessionPaneAdjust||0)+e));this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:r});const o=this.getCurrentLayout({sessionPaneAdjust:r}),a=this.getState().ui.focusRegion,l=He(a,o);l!==a&&this.setFocus(l)}adjustActivityPaneSplit(e){const s=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,r=Math.max(-i,Math.min(i,(s.activityPaneAdjust||0)+e));this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:r});const o=this.getCurrentLayout({activityPaneAdjust:r}),a=this.getState().ui.focusRegion,l=He(a,o);l!==a&&this.setFocus(l)}resizeFocusedPane(e){const s=this.getState().ui.focusRegion,n=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??n.viewportHeight??40,r=n.viewportHeight??40,o=(a,l,u,f)=>{const d=Math.max(u,f);return Math.max(u,Math.min(d,(a||0)+l))};if(s===T.SESSIONS||s===T.CHAT){const a=vo(i),l=At+1,u=Math.min(Eo(r,i),i-xs-1),f=s===T.CHAT?-e:e,d=o(n.sessionPaneAdjust,f,l-a,u-a);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:d})}else if(s===T.INSPECTOR||s===T.ACTIVITY){const a=Math.max(It,Math.floor(i*xo)),l=It+1,u=i-ls-1,f=s===T.INSPECTOR?-e:e,d=o(n.activityPaneAdjust,f,l-a,u-a);this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:d})}}getActiveSequenceCompletedTurns(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return[];const n=e.history.bySessionId?.get?.(s),i=[],r=new Set;for(const o of n?.events||[]){if(o?.eventType!=="session.turn_completed")continue;const a=Number(o?.data?.turnIndex??o?.data?.iteration);!Number.isFinite(a)||r.has(a)||(r.add(a),i.push(a))}return i.sort((o,a)=>o-a),i}moveSequenceSelection(e){const s=this.getActiveSequenceCompletedTurns();if(s.length===0)return;const n=s.indexOf(Number(this.getState().ui.sequenceSelectedTurn)),i=n===-1?s.length-1:Math.max(0,Math.min(s.length-1,n+e));this.dispatch({type:"ui/sequenceSelectedTurn",turn:s[i]})}toggleSequenceTurnExpanded(){const e=this.getActiveSequenceCompletedTurns();if(e.length===0)return;let s=Number(this.getState().ui.sequenceSelectedTurn);e.includes(s)||(s=e[e.length-1],this.dispatch({type:"ui/sequenceSelectedTurn",turn:s}));const n=Array.isArray(this.getState().ui.sequenceExpandedTurns)?this.getState().ui.sequenceExpandedTurns.map(Number):[],i=n.includes(s)?n.filter(r=>r!==s):[...n,s];this.dispatch({type:"ui/sequenceExpandedTurns",turns:i})}nextInspectorTab(){const e=this.getState().ui.inspectorTab,s=ut(Ne,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=ut(Ne,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){Ne.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=Ct(s);if(n.length===0)return;const i=s.sessions.activeSessionId||n[0].sessionId,r=Math.max(0,n.findIndex(l=>l.sessionId===i)),o=Math.max(0,Math.min(n.length-1,r+e)),a=n[o].sessionId;this.navigateToSession(a)}navigateToSession(e){e&&(this.getState().sessions.activeSessionId!==e&&(this.dispatch({type:"sessions/selected",sessionId:e}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.sessionNavSettleTimer&&clearTimeout(this.sessionNavSettleTimer),this.sessionNavSettleTimer=setTimeout(()=>{this.sessionNavSettleTimer=null,this.loadSession(e).catch(()=>{})},ap))}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 Jf.has(this.getState().ui.inspectorTab)}paneUsesStickyBottomFollow(e,s=this.getState()){return e==="activity"?!0:e==="inspector"?s.ui.inspectorTab==="logs":!1}isPaneFollowingBottom(e,s=this.getState()){return this.paneUsesStickyBottomFollow(e,s)?s.ui.followBottom?.[e]!==!1:!1}getPaneVisualScrollOffset(e,s=this.getState()){const n=this.getPaneMaxScrollOffset(e,s),i=Math.max(0,Math.min(Number(s.ui.scroll?.[e])||0,n));return this.isPaneFollowingBottom(e,s)?Math.max(0,n-i):i}applyPaneVisualScrollOffset(e,s,n={},i=this.getState()){const r=this.getPaneMaxScrollOffset(e,i),o=Math.max(0,Math.min(Number(s)||0,r));if(this.paneUsesStickyBottomFollow(e,i)){const a=n.followBottom!==void 0?!!n.followBottom:n.atBottom!==void 0?!!n.atBottom:o>=r;return this.dispatch({type:"ui/followBottom",pane:e,followBottom:a}),this.dispatch({type:"ui/scroll",pane:e,offset:a?0:o}),o}return this.dispatch({type:"ui/scroll",pane:e,offset:o}),o}updatePaneScrollFromViewport(e,s,n={}){const i=this.getState();if(this.paneUsesStickyBottomFollow(e,i)){this.applyPaneVisualScrollOffset(e,s,n,i);return}this.scrollPaneTo(e,s)}expandActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/expand",sessionId:e})}collapseActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/collapse",sessionId:e})}scrollPane(e,s){const n=this.getState(),i=this.getPaneMaxScrollOffset(e,n);if(this.paneUsesStickyBottomFollow(e,n)){const a=this.getPaneVisualScrollOffset(e,n),l=Math.max(0,Math.min(a-s,i));this.applyPaneVisualScrollOffset(e,l,{followBottom:l>=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:wf,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=Gn(e,n),o=[...Un(e,n),...Hn(e)],a=Math.min(Math.max(0,Math.floor(i*.34)),ht(o,n)),l=ht(r,n);return{contentWidth:n,contentHeight:Math.max(1,i-a),totalLines:l}}getActivityRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.activityHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.rightWidth-4),i=Math.max(1,s.activityPaneHeight-2),r=e.sessions.activeSessionId,o={sessions:{activeSessionId:r,byId:r?{[r]:e.sessions.byId[r]||null}:{}},history:{bySessionId:r?new Map([[r,e.history.bySessionId.get(r)||null]]):new Map}},a=Kn(o);return{contentWidth:n,contentHeight:i,totalLines:ht(a.lines,n)}}getInspectorRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.inspectorHidden)return{contentWidth:20,contentHeight:1,stickyLineCount:0,totalLines:0};const n=Math.max(20,s.rightWidth-4),i=e.sessions.activeSessionId,r=i&&e.orchestration.bySessionId?.[i]||null,o={branding:e.branding,sessions:{activeSessionId:i,byId:e.sessions.byId,flat:e.sessions.flat},history:{bySessionId:e.history.bySessionId},orchestration:{bySessionId:i&&r?{[i]:r}:{}},logs:e.logs,sessionStats:e.sessionStats,fleetStats:e.fleetStats,ui:{inspectorTab:e.ui.inspectorTab,statsViewMode:e.ui.statsViewMode},executionHistory:e.executionHistory},a=Je(o,{width:n}),l=a.tabs.map(p=>({text:p===a.activeTab?`[${p}] `:`${p} `,color:p===a.activeTab?"magenta":"gray",bold:p===a.activeTab})),u=(a.lines||[]).map(p=>typeof p=="string"?{text:p,color:"white"}:p),f=a.activeTab==="sequence"?[l,...(a.stickyLines||[]).map(p=>typeof p=="string"?{text:p,color:"white"}:p)]:[],d=a.activeTab==="sequence"?u:[l,...u];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:ht(f,n),totalLines:ht(d,n)}}getFilePreviewRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if((s.rightHidden||s.inspectorHidden)&&!e.files?.fullscreen)return{contentWidth:20,contentHeight:1,totalLines:0};const n=e.ui.inspectorTab==="files"&&!!e.files?.fullscreen,i=n?s.totalWidth:s.rightWidth,r=n?Math.max(10,s.bodyHeight):s.inspectorPaneHeight,o=Math.max(20,i-4),a=Math.max(8,o-4),l=e.sessions.activeSessionId,u=l&&e.sessions.byId[l]||null,f={sessions:{activeSessionId:l,byId:l&&u?{[l]:u}:{},flat:e.sessions.flat},files:{bySessionId:e.files.bySessionId,fullscreen:!!e.files.fullscreen,selectedArtifactId:e.files.selectedArtifactId,filter:e.files.filter},ui:{scroll:{filePreview:e.ui.scroll.filePreview}}},d=Vn(f,{listWidth:a,previewWidth:a}),p=Math.max(9,r-4),h=Math.max(5,Math.min(10,Math.floor(p*.35)));let m=Math.max(5,Math.min(h,(d.listBodyLines||[]).length+2)),g=Math.max(5,p-m-1);const S=8;if(g<S){const y=S-g;m=Math.max(5,m-y),g=Math.max(5,p-m-1)}return{contentWidth:a,contentHeight:Math.max(1,g-2),totalLines:ht(d.previewLines,a)}}getPaneMaxScrollOffset(e,s=this.getState()){if(!e)return 0;if(e==="chat"){const n=this.getActiveChatRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="activity"){const n=this.getActivityRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="inspector"){const n=this.getInspectorRenderMetrics(s),i=Math.min(n.contentHeight,n.stickyLineCount||0),r=Math.max(0,n.contentHeight-i);return Math.max(0,n.totalLines-r)}if(e==="filePreview"){const n=this.getFilePreviewRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}return 0}async maybeAutoExpandActiveHistory(e,s={}){const n=this.getState(),i=n.sessions.activeSessionId;if(!i)return;const r=n.history.bySessionId.get(i);if(!r?.hasOlderEvents||this.sessionHistoryExpansionLoads.has(i))return;if(Number(r.loadedEventCount||0)>=Sn){this.dispatch({type:"ui/status",text:"Reached automatic history limit. Press e to load more older CMS events."});return}const o=Array.isArray(r?.chat)&&r.chat.length>0;if(!s.force&&o){const{contentHeight:a,totalLines:l}=this.getActiveChatRenderMetrics(n),u=Math.max(0,l-a);if(e<u)return}await this.expandSessionHistory(i,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages,eventTypes:vl})}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(ee,Number(i?.loadedEventLimit??ee)||ee),o=ee,a=Array.isArray(i?.events)&&i.events.length>0?Number(i.events[0]?.seq||0):0;if(!i?.hasOlderEvents||a<=1){this.dispatch({type:"ui/status",text:"Already showing the oldest loaded history"});return}const l=e===n.sessions.activeSessionId,u=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),f=l?this.getActiveChatRenderMetrics(n).totalLines:0,d=(async()=>{let p;const h=Math.max(1,Math.floor(Number(s.pages)||1)),m=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&a>0){p=i||zt([],{requestedLimit:r});for(let y=0;y<h;y+=1){const A=Array.isArray(p?.events)&&p.events.length>0?Number(p.events[0]?.seq||0):0;if(!p?.hasOlderEvents||A<=1){p={...p,hasOlderEvents:!1};break}if(Number(p.loadedEventCount||0)>=Sn)break;const x=await this.transport.getSessionEventsBefore(e,A,o,m);if(!Array.isArray(x)||x.length===0){p={...p,hasOlderEvents:!1};break}const v=zt(x,{requestedLimit:o}),I=[...v.events||[],...p?.events||[]];if(p={chat:bt([...v.chat||[],...p?.chat||[]]),activity:[...v.activity||[],...p?.activity||[]],events:I,lastSeq:p?.lastSeq||p?.events?.[p?.events?.length-1]?.seq||x[x.length-1]?.seq||0,loadedEventLimit:I.length,loadedEventCount:I.length,hasOlderEvents:x.length>=o&&Number(x[0]?.seq||0)>1},!p.hasOlderEvents)break}}else{const y=Ul(r);if(y<=r){this.dispatch({type:"ui/status",text:i?.hasOlderEvents?`Already showing a large recent history window (${r} events)`:"Already showing the oldest loaded history"});return}const A=await this.transport.getSessionEvents(e,void 0,y);p={...zt(A,{requestedLimit:y}),lastSeq:A[A.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:p});for(const y of p?.events||[])this.reconcileOutboxAgainstEvent(e,y);const g=Array.isArray(i?.chat)&&i.chat.length>0;if(l&&!g)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(l&&u>0){const y=this.getState(),A=this.getActiveChatRenderMetrics(y).totalLines,x=Math.max(0,A-f);x>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:u+x})}const S=p.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${p.loadedEventCount} events loaded)`:`Loaded older history page (${p.loadedEventCount} events loaded)`:`Loaded full available history (${p.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:S}),p.hasOlderEvents?s.autoTriggered&&l&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,d),d}async cancelActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:o,skippedCount:a}=this.getBulkSelectedSessionActions(s);if(o.length===0){this.dispatch({type:"ui/status",text:"No cancellable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Sessions",message:`Cancel ${o.length} selected session${o.length===1?"":"s"}?${a>0?` (${a} selected row${a===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Cancel Sessions",action:"cancelSession",previousFocus:s.ui.focusRegion}});return}let l=0;const u=[];for(const d of o)try{await this.transport.cancelSession(d.sessionId),l+=1}catch(p){u.push(`${d.sessionId.slice(0,8)}: ${p?.message||String(p)}`)}this.dispatch({type:"sessions/selectClear"});const f=u.length===0?`Cancelled ${l} session${l===1?"":"s"}`:`Cancelled ${l}/${o.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:f}),await this.refreshSessions();return}const i=s.sessions.activeSessionId;if(!i)return;const r=s.sessions.byId[i];if(r?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; cancel sessions individually."});return}if(r?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const o=r.title||r.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Terminate & Restart System Session",message:`Terminate system session "${o}" and start a fresh one?`,confirmLabel:"Terminate & Restart",action:"cancelSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(r.agentId||i,{disposition:"terminate",reason:"Terminated by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${r.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const a=r?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Session",message:`Cancel session "${a}"? The session will stop processing.`,confirmLabel:"Cancel Session",action:"cancelSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.cancelSession(i),this.dispatch({type:"ui/status",text:`Cancelled ${i.slice(0,8)}`}),await this.refreshSessions()}updateConfirmExtras(e){const s=this.getState().ui.modal;!s||s.type!=="confirm"||this.dispatch({type:"ui/modal",modal:{...s,extras:{...s.extras||{},...e||{}}}})}async regenerateActiveSession({confirmed:e=!1,instructions:s="",distillMode:n="llm",distillerModel:i="",distillerEffort:r="",distillerContextTier:o=""}={}){const a=this.getState(),l=a.sessions.activeSessionId;if(!l)return;if(typeof this.transport.regenerateSession!="function"){this.dispatch({type:"ui/status",text:"Session regeneration is not supported by this deployment"});return}const u=a.sessions.byId[l];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 f=u?.title||l.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Regenerate Session",message:`Regenerate context for "${f}"? 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:l,previousFocus:a.ui.focusRegion,extras:{instructions:"",distillMode:"llm",distillerModel:"",distillerEffort:"",distillerContextTier:"",distillerModelOptions:await this._loadDistillerModelOptions()}}});return}try{const f=String(s||"").trim();await this.transport.regenerateSession(l,{force:!0,...f?{instructions:f.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 ${l.slice(0,8)} — rebuilding at the next boundary`})}catch(f){this.dispatch({type:"ui/status",text:`Regenerate failed: ${f?.message||String(f)}`});return}await this.refreshSessions()}async _loadDistillerModelOptions(){if(typeof this.transport.listModels!="function")return[];try{const e=await this.transport.listModels({groupByProvider:!0});return(Array.isArray(e)?e:Array.isArray(e?.providers)?e.providers:Array.isArray(e?.models)?e.models:[]).flatMap(i=>Array.isArray(i?.models)?i.models.map(r=>({...r,providerId:r.providerId||i.providerId})):[i]).filter(i=>i&&(i.qualifiedName||i.modelName)).map(i=>({qualifiedName:i.qualifiedName||i.modelName,modelName:i.modelName||i.qualifiedName,providerId:i.providerId||"",supportedReasoningEfforts:Array.isArray(i.supportedReasoningEfforts)?i.supportedReasoningEfforts:[],supportedContextTiers:Array.isArray(i.supportedContextTiers)?i.supportedContextTiers:[]}))}catch(e){return this.dispatch({type:"ui/status",text:`Could not load distiller models: ${e?.message||String(e)}`}),[]}}async stopActiveSessionTurn(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n||n.isGroup){this.dispatch({type:"ui/status",text:"Select a session to stop its turn."});return}if(typeof this.transport.stopSessionTurn!="function"){this.dispatch({type:"ui/status",text:"Stop turn is not supported by this transport"});return}if(this._stopTurnInFlight||(this._stopTurnInFlight=new Set),!this._stopTurnInFlight.has(s)){this._stopTurnInFlight.add(s),this.dispatch({type:"ui/status",text:`Stopping turn for ${s.slice(0,8)}…`});try{const r=(await this.transport.stopSessionTurn(s,{reason:"Stopped by user"}))?.outcome||"stopped";r==="no_active_turn"?this.dispatch({type:"ui/status",text:"No active turn to stop"}):r==="timeout"?this.dispatch({type:"ui/status",text:"Stop requested — waiting for the turn to unwind"}):this.dispatch({type:"ui/status",text:`Stopped turn for ${s.slice(0,8)}`})}catch(i){this.dispatch({type:"ui/status",text:`Stop turn failed: ${i?.message||i}`})}finally{this._stopTurnInFlight.delete(s)}await this.refreshSessions(),await this.refreshActiveSessionDetail?.().catch?.(()=>{})}}togglePinActiveSession(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n)return;if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be pinned."});return}if(!n.isGroup&&(n.parentSessionId||n.groupId)){this.dispatch({type:"ui/status",text:"Sessions inside groups or parents cannot be pinned."});return}const i=Array.isArray(e.sessions.pinnedIds)&&e.sessions.pinnedIds.includes(s);this.dispatch({type:"sessions/pinToggle",sessionId:s}),this.dispatch({type:"ui/status",text:i?`Unpinned ${s.slice(0,8)}`:`Pinned ${s.slice(0,8)}`})}toggleSessionSelectMode(){const e=this.getState(),s=!e.sessions.selectMode;if(this.dispatch({type:"sessions/selectMode",enabled:s}),s){const n=e.sessions.activeSessionId;n&&e.sessions.byId[n]&&this.dispatch({type:"sessions/selectToggle",sessionId:n}),this.dispatch({type:"ui/status",text:"Select mode: space toggles, Ctrl+G moves, c cancels, V/esc exits"})}else this.dispatch({type:"ui/status",text:"Select mode off"})}toggleActiveSessionSelection(){const e=this.getState(),s=e.sessions.activeSessionId;s&&(e.sessions.selectMode||this.dispatch({type:"sessions/selectMode",enabled:!0}),this.dispatch({type:"sessions/selectToggle",sessionId:s}))}setSessionSelection(e){const s=Array.isArray(e)?e:[];this.dispatch({type:"sessions/selectSet",sessionIds:s})}clearSessionSelection(){this.dispatch({type:"sessions/selectClear"})}async completeActiveSession(e="Completed by user",{confirmed:s=!1}={}){const n=this.getState(),i=Array.isArray(n.sessions.selectedIds)?n.sessions.selectedIds:[];if(n.sessions.selectMode&&i.length>=1){const{eligible:a,skippedCount:l}=this.getBulkSelectedSessionActions(n);if(a.length===0){this.dispatch({type:"ui/status",text:"No completable sessions in selection (system sessions and groups are skipped)."});return}if(!s){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Sessions",message:`Complete ${a.length} selected session${a.length===1?"":"s"}? This will cascade to their sub-agents.${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Complete Sessions",action:"completeSession",previousFocus:n.ui.focusRegion}});return}let u=0;const f=[];for(const p of a)try{await this.transport.completeSession(p.sessionId,e),u+=1}catch(h){f.push(`${p.sessionId.slice(0,8)}: ${h?.message||String(h)}`)}this.dispatch({type:"sessions/selectClear"});const d=f.length===0?`Completed ${u} session${u===1?"":"s"}`:`Completed ${u}/${a.length}; ${f.length} failed: ${f.slice(0,2).join(", ")}${f.length>2?"…":""}`;this.dispatch({type:"ui/status",text:d}),await this.refreshSessions();return}const r=this.getState().sessions.activeSessionId;if(!r)return;const o=this.getState().sessions.byId[r];if(o?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; complete sessions individually."});return}if(o?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!s){const a=o.title||o.agentId||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete & Restart System Session",message:`Mark system session "${a}" complete and start a fresh one?`,confirmLabel:"Complete & Restart",action:"completeSession",sessionId:r,previousFocus:this.getState().ui.focusRegion}});return}await this.transport.restartSystemSession(o.agentId||r,{disposition:"complete",reason:e}),this.dispatch({type:"ui/status",text:`Restarted system session ${o.agentId||r.slice(0,8)}`}),await this.refreshSessions();return}if(typeof this.transport.completeSession!="function"){this.dispatch({type:"ui/status",text:"Session completion is not supported by this transport"});return}if(o?.status==="completed"&&!o?.cronActive&&!o?.cronInterval){this.dispatch({type:"ui/status",text:`${r.slice(0,8)} is already completed`});return}if(!s){const a=o?.title||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Session",message:`Complete session "${a}"? This will cascade to all sub-agents.`,confirmLabel:"Complete",action:"completeSession",sessionId:r,previousFocus:this.getState().ui.focusRegion}});return}this.dispatch({type:"ui/status",text:`Completing ${r.slice(0,8)} (cascading to sub-agents)...`});try{await this.transport.completeSession(r,e),await this.refreshSessions(),this.scheduleSessionDetailSync(r,100),this.scheduleSessionsRefresh(900)}catch(a){await this.loadSession(r).catch(()=>{}),this.dispatch({type:"ui/status",text:`Failed to send /done: ${a?.message||String(a)}`})}}async deleteActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:o,skippedCount:a}=this.getBulkSelectedSessionActions(s);if(o.length===0){this.dispatch({type:"ui/status",text:"No deletable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete Sessions",message:`Hard delete ${o.length} selected session${o.length===1?"":"s"}? This action cannot be undone.${a>0?` (${a} selected row${a===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Hard Delete Sessions",action:"deleteSession",previousFocus:s.ui.focusRegion}});return}let l=0;const u=[];for(const d of o)try{await this.transport.deleteSession(d.sessionId),this.handleSessionGone(d.sessionId),l+=1}catch(p){u.push(`${d.sessionId.slice(0,8)}: ${p?.message||String(p)}`)}this.dispatch({type:"sessions/selectClear"});const f=u.length===0?`Deleted ${l} session${l===1?"":"s"}`:`Deleted ${l}/${o.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:f}),await this.refreshSessions();return}const i=s.sessions.activeSessionId;if(!i)return;const r=s.sessions.byId[i];if(r?.isGroup){const o=r.groupId||Xs(i);if(!o||typeof this.transport.deleteSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group deletion is not supported by this transport"});return}if(Number(r.memberCount||0)>0){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Group Not Empty",message:`Group "${r.title||o}" is not empty. Move all sessions out of the group before deleting it.`,confirmLabel:"OK",action:"alert",alert:!0,previousFocus:s.ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Move all sessions out of the group before deleting it."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Group",message:`Delete empty group "${r.title||o}"? This action cannot be undone.`,confirmLabel:"Delete Group",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSessionGroup(o),this.dispatch({type:"ui/status",text:`Deleted group ${r.title||o}`}),await this.refreshSessions();return}if(r?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const o=r.title||r.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete & Restart System Session",message:`Hard delete system session "${o}" and start a fresh one? This removes the current orchestration immediately.`,confirmLabel:"Hard Delete & Restart",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(r.agentId||i,{disposition:"hard_delete",reason:"Hard-deleted by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${r.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const a=r?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Session",message:`Delete session "${a}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSession(i),this.handleSessionGone(i),this.dispatch({type:"ui/status",text:`Deleted ${i.slice(0,8)}`}),await this.refreshSessions()}async handleCommand(e){switch(e){case E.REFRESH:await this.refreshSessions();return;case E.NEW_SESSION:await this.openNewSessionFlow();return;case E.OPEN_MODEL_PICKER:await this.openModelPicker();return;case E.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case E.OPEN_THEME_PICKER:this.openThemePicker();return;case E.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case E.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case E.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case E.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case E.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case E.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case E.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case E.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case E.TOGGLE_CHAT_VIEW:this.toggleChatViewMode();return;case E.CLOSE_MODAL:this.closeModal();return;case E.MODAL_PREV:this.moveModalSelection(-1);return;case E.MODAL_NEXT:this.moveModalSelection(1);return;case E.MODAL_PANE_PREV:this.moveModalPane(-1);return;case E.MODAL_PANE_NEXT:this.moveModalPane(1);return;case E.MODAL_CONFIRM:await this.confirmModal();return;case E.SEND_PROMPT:await this.sendPrompt();return;case E.FOCUS_NEXT:this.focusNext();return;case E.FOCUS_PREV:this.focusPrev();return;case E.FOCUS_LEFT:this.focusLeft();return;case E.FOCUS_RIGHT:this.focusRight();return;case E.FOCUS_PROMPT:this.setFocus(T.PROMPT);return;case E.FOCUS_SESSIONS:this.setFocus(T.SESSIONS);return;case E.MOVE_SESSION_UP:await this.moveSession(-1);return;case E.MOVE_SESSION_DOWN:await this.moveSession(1);return;case E.EXPAND_SESSION:this.expandActiveSession();return;case E.COLLAPSE_SESSION:this.collapseActiveSession();return;case E.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case E.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case E.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case E.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case E.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case E.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case E.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case E.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case E.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case E.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case E.OPEN_HELP:this.openHelpModal();return;case E.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case E.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case E.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case E.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case E.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case E.OPEN_LOG_FILTER:this.openLogFilter();return;case E.OPEN_FILES_FILTER:this.openFilesFilter();return;case E.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case E.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case E.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case E.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case E.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case E.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case E.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case E.SCROLL_UP:this.scrollCurrentPane(1);return;case E.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case E.PAGE_UP:if(this.getState().ui.focusRegion===T.SESSIONS){await this.moveSessionPage(-1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(-10);return}this.scrollCurrentPane(10);return;case E.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 E.EXPAND_HISTORY:await this.expandActiveHistory();return;case E.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case E.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case E.CANCEL_SESSION:await this.cancelActiveSession();return;case E.STOP_TURN:await this.stopActiveSessionTurn();return;case E.DONE_SESSION:await this.completeActiveSession();return;case E.DELETE_SESSION:await this.deleteActiveSession();return;case E.REGENERATE_SESSION:await this.regenerateActiveSession();return;case E.PIN_SESSION:this.togglePinActiveSession();return;case E.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case E.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case E.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case E.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case E.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case E.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case E.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case E.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case E.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case E.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case E.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case E.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case E.ADMIN_CLEAR_GHCP_KEY:await this.clearAdminGhcpKey();return;default:return}}async exportExecutionHistory(){const e=this.getState().sessions.activeSessionId;if(!e){this.dispatch({type:"ui/status",text:"No session selected."});return}if(typeof this.transport.exportExecutionHistory!="function"){this.dispatch({type:"ui/status",text:"History export is not supported by this transport."});return}this.dispatch({type:"ui/status",text:"Exporting execution history..."});try{const s=await this.transport.exportExecutionHistory(e);s?.filename&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:e,filename:s.filename}),this.dispatch({type:"files/selectGlobal",artifactId:`${e}/${s.filename}`}),await this.ensureFilePreview(e,s.filename,{force:!0}).catch(()=>null)),this.dispatch({type:"ui/status",text:s?.filename?`History saved as artifact ${s.filename}`:`History exported → ${s?.artifactLink||"artifact created"}`})}catch(s){this.dispatch({type:"ui/status",text:`Export failed: ${s?.message||String(s)}`})}}}const ks=0;function we(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 en(){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 up(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 dp(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 fp(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 pp(t=2e3){const[e,s]=c.useState(()=>en());return c.useEffect(()=>{if(en()==null)return;const n=()=>{const r=en();r!=null&&s(o=>o===r?o:r)};n();const i=setInterval(n,t);return()=>clearInterval(i)},[t]),c.useMemo(()=>up(e),[e])}function Nt(t,e){return t&&e?{[t]:e}:{}}function Nr(t){return typeof t=="string"?{text:t,color:"white"}:t}function Kt(t,e,s,n,i,r){const o=(e.tabs||Ne).map(d=>({text:d===e.activeTab?`[${d}] `:`${d} `,color:d===e.activeTab?"magenta":"gray",bold:d===e.activeTab})),a=(e.lines||[]).map(Nr),l=(e.stickyLines||[]).map(Nr),u=e.activeTab==="sequence"?[o,...l]:[],f=e.activeTab==="sequence"?a:[o,...a];return c.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:i,stickyLines:u,marginBottom:ks,lines:f,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="sequence"||e.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:r})}function Pr(t,e){const s=String(t||"");return e<=0?"":s.length<=e?s:e===1?s.slice(0,1):`${s.slice(0,e-1)}...`}c.memo(function({controller:e,maxRows:s,width:n,height:i,frame:r,versionLabel:o=null}){const a=Me(),l=pp(),u=q(e,m=>({sessions:m.sessions,mode:m.connection?.mode||"local",brandingTitle:m.branding?.title||"PilotSwarm",focused:m.ui.focusRegion==="sessions",identityLabel:dp(m.auth)}),we),f=c.useMemo(()=>fp(l,o,u.identityLabel),[l,o,u.identityLabel]),d=c.useMemo(()=>({sessions:u.sessions,connection:{mode:u.mode},branding:{title:u.brandingTitle}}),[u.brandingTitle,u.mode,u.sessions]),p=c.useMemo(()=>dn(d,s),[d,s]),h=c.useMemo(()=>p.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:p.map(m=>m.active?No(m.runs,{preserveColors:!0}):m.runs),[p]);return c.createElement(a.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:f,color:"yellow",focused:u.focused,width:n,height:i,marginBottom:ks,lines:h,paneId:"sessions",paneLabel:"Sessions",frame:r})});c.memo(function({controller:e,width:s,height:n,frame:i}){const r=Me(),o=q(e,x=>{const v=x.sessions.activeSessionId;return{activeSessionId:v,activeSession:v&&x.sessions.byId[v]||null,activeHistory:v&&x.history.bySessionId.get(v)||null,activeOutbox:v&&x.outbox?.bySessionId?.[v]||null,authPrincipal:x.auth?.principal||null,branding:x.branding,connectionError:x.connection.error,connectionMode:x.connection.mode,chatViewMode:x.ui.chatViewMode||"transcript",chatScroll:x.ui.scroll.chat,focused:x.ui.focusRegion==="chat"}},we),a=Math.max(20,s-4),l=c.useMemo(()=>{const x=new Map;return o.activeSessionId&&o.activeHistory&&x.set(o.activeSessionId,o.activeHistory),{branding:o.branding,auth:{principal:o.authPrincipal},connection:{error:o.connectionError,mode:o.connectionMode},ui:{chatViewMode:o.chatViewMode},sessions:{activeSessionId:o.activeSessionId,byId:Nt(o.activeSessionId,o.activeSession)},history:{bySessionId:x},outbox:{bySessionId:o.activeSessionId&&o.activeOutbox?{[o.activeSessionId]:o.activeOutbox}:{}}}},[o.activeHistory,o.activeSessionId,o.activeSession,o.activeOutbox,o.authPrincipal,o.branding,o.chatViewMode,o.connectionError,o.connectionMode]),u=c.useMemo(()=>Xo(l,{width:a}),[a,l]),f=Zr(!!u?.animateTitleRight),d=c.useMemo(()=>eo(u?.titleRight,f),[f,u?.titleRight]),p=!o.activeSessionId&&o.connectionError,h=c.useMemo(()=>p?[{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"}]:Gn(l,a),[o.branding.splash,o.connectionError,a,l,p]),m=String(o.activeSession?.status||"").toLowerCase()==="running",g=Jr(m),S=c.useMemo(()=>p?[]:Hn(l,{spinnerFrame:g,maxWidth:a}),[l,p,g,a]),y=c.useMemo(()=>p?[]:Un(l,a),[l,p,a]),A=c.useMemo(()=>y.length>0||S.length>0?[...y,...S]:[],[y,S]);return c.createElement(r.Panel,{title:u.title,titleRight:d,color:u.color,focused:o.focused,width:s,height:n,lines:h,bottomStickyLines:A,scrollOffset:o.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:i})});const hp=c.memo(function({controller:e,width:s,height:n,shellTitle:i,focused:r=!1,frame:o,showFullscreenTitle:a=!1,embedded:l=!1}){const u=Me(),f=q(e,F=>({activeSessionId:F.sessions.activeSessionId,activeSession:F.sessions.activeSessionId&&F.sessions.byId[F.sessions.activeSessionId]||null,sessionsFlat:F.sessions.flat,filesBySessionId:F.files.bySessionId,filesFullscreen:!!F.files.fullscreen,selectedArtifactId:F.files.selectedArtifactId,filesFilter:F.files.filter,filePreviewScroll:F.ui.scroll.filePreview}),we),d=Math.max(20,s-4),p=c.useMemo(()=>({sessions:{activeSessionId:f.activeSessionId,byId:f.activeSessionId&&f.activeSession?{[f.activeSessionId]:f.activeSession}:{},flat:f.sessionsFlat},files:{bySessionId:f.filesBySessionId,fullscreen:f.filesFullscreen,selectedArtifactId:f.selectedArtifactId,filter:f.filesFilter},ui:{scroll:{filePreview:f.filePreviewScroll}}}),[f]),h=c.useMemo(()=>Vn(p,{listWidth:Math.max(8,d-4),previewWidth:Math.max(8,d-4)}),[d,p]),m=i||(a?h.fullscreenTitle:h.panelTitle||h.listTitle)||[{text:"Files",color:"magenta",bold:!0}],g=Math.max(9,n-4),S=Math.max(5,Math.min(10,Math.floor(g*.35)));let y=Math.max(5,Math.min(S,(h.listBodyLines||[]).length+2)),A=Math.max(5,g-y-1);const x=8;if(A<x){const F=x-A;y=Math.max(5,y-F),A=Math.max(5,g-y-1)}const v=Math.max(1,y-2),I=Math.max(0,h.selectedIndex-Math.floor(v/2)),w=!l&&o?{x:o.x+2,y:o.y+2,width:d,height:y}:null,C=!l&&o?{x:o.x+2,y:o.y+2+y+1,width:d,height:A}:null,N=Ne.map(F=>({text:F==="files"?`[${F}] `:`${F} `,color:F==="files"?"magenta":"gray",bold:F==="files"})),R=c.createElement(u.Column,{width:d},c.createElement(u.Lines,{lines:[N]}),c.createElement(u.Panel,{title:h.listTitle,color:"gray",focused:!1,width:d,height:y,lines:h.listBodyLines||h.listLines.slice(1),scrollOffset:I,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:w}),c.createElement(u.Panel,{title:h.previewTitle,color:"gray",focused:!1,width:d,height:A,lines:h.previewLines,scrollOffset:h.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:C}));return l?R:c.createElement(u.Panel,{title:m,color:"magenta",focused:r,width:s,height:n,marginBottom:ks,paneId:"inspector",paneLabel:"Inspector",frame:o},R)}),mp=c.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Me(),a=Math.max(20,s-4),l=q(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null}),we),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:Nt(l.activeSessionId,l.activeSession)},ui:{inspectorTab:"files"}}),[l.activeSession,l.activeSessionId]),f=c.useMemo(()=>Je(u,{width:a}),[a,u]);return c.createElement(o.Panel,{title:f.title,color:"magenta",focused:r.focused,width:s,height:n,marginBottom:ks,paneId:"inspector",paneLabel:"Inspector",frame:i},c.createElement(hp,{controller:e,width:s,height:n,frame:i,focused:r.focused,embedded:!0}))}),gp=c.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Me(),a=Math.max(20,s-4),l=q(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,activeOrchestration:d.sessions.activeSessionId&&d.orchestration.bySessionId?.[d.sessions.activeSessionId]||null,histories:d.history.bySessionId,expandedTurns:d.ui.sequenceExpandedTurns,selectedTurn:d.ui.sequenceSelectedTurn}),we),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:Nt(l.activeSessionId,l.activeSession)},history:{bySessionId:l.histories},orchestration:{bySessionId:l.activeSessionId&&l.activeOrchestration?{[l.activeSessionId]:l.activeOrchestration}:{}},ui:{inspectorTab:"sequence"}}),[l.activeOrchestration,l.activeSession,l.activeSessionId,l.histories]),f=c.useMemo(()=>Je(u,{width:a,sequenceExpansion:{expandedTurns:l.expandedTurns||[],selectedTurn:l.selectedTurn??null}}),[a,u,l.expandedTurns,l.selectedTurn]);return Kt(o,f,r,s,n,i)}),yp=c.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Me(),a=Math.max(20,s-4),l=q(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,logs:d.logs}),we),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:Nt(l.activeSessionId,l.activeSession)},logs:l.logs,ui:{inspectorTab:"logs"}}),[l.activeSession,l.activeSessionId,l.logs]),f=c.useMemo(()=>Je(u,{width:a}),[a,u]);return Kt(o,f,r,s,n,i)}),Sp=c.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Me(),a=Math.max(20,s-4),l=q(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,executionHistory:d.executionHistory}),we),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:Nt(l.activeSessionId,l.activeSession)},executionHistory:l.executionHistory,ui:{inspectorTab:"history"}}),[l.activeSession,l.activeSessionId,l.executionHistory]),f=c.useMemo(()=>Je(u,{width:a}),[a,u]);return Kt(o,f,r,s,n,i)}),bp=c.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Me(),a=Math.max(20,s-4),l=q(e,d=>({activeSessionId:d.sessions.activeSessionId,sessionsById:d.sessions.byId,sessionsFlat:d.sessions.flat,histories:d.history.bySessionId}),we),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:l.sessionsById,flat:l.sessionsFlat},history:{bySessionId:l.histories},ui:{inspectorTab:"nodes"}}),[l.activeSessionId,l.histories,l.sessionsById,l.sessionsFlat]),f=c.useMemo(()=>Je(u,{width:a}),[a,u]);return Kt(o,f,r,s,n,i)}),wp=c.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Me(),a=Math.max(20,s-4),l=q(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,sessionStats:d.sessionStats,fleetStats:d.fleetStats,statsViewMode:d.ui.statsViewMode}),we),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:Nt(l.activeSessionId,l.activeSession)},sessionStats:l.sessionStats,fleetStats:l.fleetStats,ui:{inspectorTab:"stats",statsViewMode:l.statsViewMode}}),[l.activeSession,l.activeSessionId,l.fleetStats,l.sessionStats,l.statsViewMode]),f=c.useMemo(()=>Je(u,{width:a}),[a,u]);return Kt(o,f,r,s,n,i)});c.memo(function({controller:e,width:s,height:n,frame:i}){const r=q(e,o=>({inspectorTab:o.ui.inspectorTab,inspectorScroll:o.ui.scroll.inspector,inspectorFollowBottom:o.ui.followBottom?.inspector!==!1,focused:o.ui.focusRegion==="inspector"}),we);return r.inspectorTab==="files"?c.createElement(mp,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="sequence"?c.createElement(gp,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="logs"?c.createElement(yp,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="history"?c.createElement(Sp,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="stats"?c.createElement(wp,{controller:e,width:s,height:n,frame:i,meta:r}):c.createElement(bp,{controller:e,width:s,height:n,frame:i,meta:r})});c.memo(function({controller:e,width:s,height:n,maxLines:i,frame:r}){const o=Me(),a=q(e,f=>{const d=f.sessions.activeSessionId;return{sessionsById:f.sessions.byId,activeSessionId:d,activeSession:d&&f.sessions.byId[d]||null,activeHistory:d&&f.history.bySessionId.get(d)||null,scroll:f.ui.scroll.activity,followBottom:f.ui.followBottom?.activity!==!1,focused:f.ui.focusRegion==="activity"}},we),l=c.useMemo(()=>{const f=new Map;return a.activeSessionId&&a.activeHistory&&f.set(a.activeSessionId,a.activeHistory),{sessions:{activeSessionId:a.activeSessionId,byId:a.sessionsById},history:{bySessionId:f}}},[a.activeHistory,a.activeSessionId,a.sessionsById]),u=c.useMemo(()=>Kn(l,i),[i,l]);return c.createElement(o.Panel,{title:u.title,color:"gray",focused:a.focused,width:s,height:n,lines:u.lines,scrollOffset:a.scroll,scrollMode:a.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:r})});c.memo(function({controller:e,rows:s}){const n=Me(),i=q(e,r=>{const o=r.sessions.activeSessionId,a=o&&r.sessions.byId[o]||null,l=o&&r.outbox?.bySessionId?.[o]?r.outbox.bySessionId[o]:[];return{prompt:r.ui.prompt,promptCursor:r.ui.promptCursor,focused:r.ui.focusRegion==="prompt",answeringQuestion:!!a?.pendingQuestion?.question,editingPending:r.ui.promptEdit?.sessionId===o,hasOutbox:l.length>0,hasPendingOutbox:l.some(u=>u?.phase==="pending")}},we);return c.createElement(n.Input,{label:i.answeringQuestion?"answer":i.editingPending?"pending":"you",value:i.prompt,cursorIndex:i.promptCursor,focused:i.focused,placeholder:i.answeringQuestion?"Type an answer and press Enter":i.editingPending?"Edit pending prompt, Enter sends batch, Esc cancels":i.hasOutbox?"Type a message and press Enter to queue it":"Type a message and press Enter",rows:s})});c.memo(function({controller:e}){const s=Me(),n=q(e,f=>({connected:f.connection.connected,workersOnline:f.connection.workersOnline,focusRegion:f.ui.focusRegion,inspectorTab:f.ui.inspectorTab,chatViewMode:f.ui.chatViewMode||"transcript",fullscreenPane:f.ui.fullscreenPane||null,logsAvailable:f.logs.available,logsTailing:f.logs.tailing,filesFullscreen:!!f.files.fullscreen,mode:f.connection.mode,statusText:f.ui.statusText,modal:f.ui.modal,activeSessionId:f.sessions.activeSessionId,activeSession:f.sessions.activeSessionId&&f.sessions.byId[f.sessions.activeSessionId]||null,selectedIds:f.sessions.selectedIds,selectMode:f.sessions.selectMode}),we),i=c.useMemo(()=>({connection:{connected:n.connected,workersOnline:n.workersOnline,mode:n.mode},ui:{focusRegion:n.focusRegion,inspectorTab:n.inspectorTab,chatViewMode:n.chatViewMode,fullscreenPane:n.fullscreenPane,statusText:n.statusText,modal:n.modal},logs:{available:n.logsAvailable,tailing:n.logsTailing},files:{fullscreen:n.filesFullscreen},sessions:{activeSessionId:n.activeSessionId,selectedIds:n.selectedIds,selectMode:n.selectMode,byId:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{}}}),[n]),r=c.useMemo(()=>Ku(i),[i]),o=typeof s.getViewport=="function"?s.getViewport():{width:120},a=Math.max(20,(o.width||120)-4),l=Math.min(Math.max(18,Math.floor(a*.45)),a-8),u=Math.max(8,a-l-3);return c.createElement(s.StatusLine,{left:Pr(r.left,u),right:Pr(r.right,l)})});const Ip="modulepreload",xp=function(t){return"/"+t},Or={},ba=function(e,s,n){let i=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(f=>Promise.resolve(f).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");i=l(s.map(u=>{if(u=xp(u),u in Or)return;Or[u]=!0;const f=u.endsWith(".css"),d=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const p=document.createElement("link");if(p.rel=f?"stylesheet":Ip,f||(p.as="script"),p.crossOrigin="",p.href=u,a&&p.setAttribute("nonce",a),document.head.appendChild(p),f)return new Promise((h,m)=>{p.addEventListener("load",h),p.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${u}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})};var wa=Za();const vp=920,Ia=7,xa=19,Jn=.24,va=16,Ea=8,Ep=224,Ap=190,Cp=48,Ue=16,Aa=.5,Rt=Aa,Tp=24,kp=700,Mp=5e3,Np=new Set(["low","medium","high","xhigh"]),Pp=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],Op=["pilotswarm_theme","pilotswarm_session_owner_filter"],_p={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"History",files:"Files",stats:"Stats"},Rp={sequence:"⇶",logs:"≣",nodes:"⬡",history:"⟲",files:"⧉",stats:"▁▄▇"};function Lp(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 $p(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function Fp(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function Bp(t){return typeof t?.transport?.listArtifacts=="function"}function Dp(t){return typeof t?.transport?.deleteArtifact=="function"}function Hp(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const Gp="Session link copied to clipboard",jp=140,Up="Only people with access can open this link.";function Wp(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function _r(t){navigator?.clipboard?.writeText&&navigator.clipboard.writeText(t).catch(()=>{})}async function Kp(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 Vp(){if(!(typeof window>"u")){try{for(const t of Pp)window.localStorage.removeItem(t)}catch{}try{for(const t of Op)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function ot(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()),be(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=be(n,"includeShared")?n:{...n,includeShared:!0}}if(be(e,"layoutAdjustments")&&(s.layoutAdjustments=Nn(e.layoutAdjustments)),be(e,"pinnedSessionIds")&&(s.pinnedSessionIds=ds(e.pinnedSessionIds)),be(e,"collapsedSessionIds")&&(s.collapsedSessionIds=qp(e.collapsedSessionIds)),be(e,"activeSessionId")){const n=e.activeSessionId==null?null:String(e.activeSessionId).trim();s.activeSessionId=n||null}return jt(e.chatViewMode)&&(s.chatViewMode=e.chatViewMode),jt(e.chatViewModeMobile)&&(s.chatViewModeMobile=e.chatViewModeMobile),s}function jt(t){return t==="summary"||t==="transcript"||t==="rich"}function Ca(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches}function bs(){return Ca()?"chatViewModeMobile":"chatViewMode"}function ws(){return Ca()?"chatViewMode":"chatViewModeMobile"}function qp(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 be(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function tn(t,e=null){return ot({themeId:t.themeId,sessionOwnerFilter:t.ownerFilter,layoutAdjustments:{paneAdjust:t.paneAdjust,sessionPaneAdjust:t.sessionPaneAdjust,portalSessionColumnAdjust:t.portalSessionColumnAdjust,activityPaneAdjust:t.activityPaneAdjust},pinnedSessionIds:t.pinnedIds,collapsedSessionIds:t.collapsedSessionIds,activeSessionId:t.activeSessionId,[bs()]:t.chatViewMode,...jt(e)?{[ws()]:e}:{}})}function Rr(t,e=null){return ot({themeId:t?.ui?.themeId,sessionOwnerFilter:Ss(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,[bs()]:t?.ui?.chatViewMode,...jt(e)?{[ws()]:e}:{}})}function zp(t,e){const s=ot(t),n=ot(e);return ot({themeId:be(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:be(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:be(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:be(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,...be(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...be(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...be(s,bs())?{chatViewMode:s[bs()]}:{}})}async function Yp(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:ot(e)})}function Zn(t){return Bp(t)?Ne:Ne.filter(e=>e!=="files")}function ke(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Object.is(t[i],e[i]))return!1;return!0}function bn(t,e,s){return Math.max(e,Math.min(s,t))}function wn(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-va-Ea*2),n=s*Jn,i=Math.max(0,s-Ep);return{minAdjust:-n,maxAdjust:i-n}}function Qp(t,e){const s=wn(t),n=Math.max(0,Number(t)||0),r=Math.max(0,n-va-Ea*2)*Jn;return bn(r+(Number(e)||0),0,r+s.maxAdjust)}function Xp(t){return t<=Cp?"hidden":t<=Ap?"compact":"wrap"}function Ta(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:xt(t?.ui?.prompt||"")}function Ms(t){return Dt({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,Ta(t),t.ui.layout?.sessionPaneAdjust??0)}function Jp(t,e){return Math.max(20,t-4)}function pe(t){const e=[],s=n=>{const i=String(n||"");return!i.includes("\\n")||i.includes(`
|
|
81
|
+
`)?i:i.replace(/\\n/g,`
|
|
82
|
+
`)};for(const n of t||[]){if(n?.kind==="markup"){const i=n.splashAlt?[{text:n.value,variant:"desktop"},{text:n.splashAlt,variant:"mobile"}]:[{text:n.value,variant:null}];for(const r of i)for(const o of no(r.text||""))e.push({kind:"runs",runs:o,preserve:!0,splashVariant:r.variant});continue}if(n?.kind==="markdownTable"||n?.kind==="cardStart"||n?.kind==="cardEnd"||n?.kind==="imageAttachments"){e.push(n);continue}if(n?.kind==="runs"){const i=Array.isArray(n.runs)?n.runs:[];if(i.length===1){const r=i[0]||{},o=s(r.text||"");if(o.includes(`
|
|
83
|
+
`)){const a=o.split(`
|
|
84
|
+
`);for(const l of a)e.push({kind:"runs",runs:[{...r,text:l}]});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(`
|
|
85
|
+
`)){const r=i.split(`
|
|
86
|
+
`);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 ae(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function ka(t=[]){return t.map(e=>String(e?.text||"")).join("")}function Lr(t){return Array.isArray(t)?ka(t):String(t||"")}function $r(t,e=40){if(!Array.isArray(t)){const r=String(t||"");return[{text:r.length>e?`${r.slice(0,e-1)}…`:r,color:"white",bold:!0}]}const s=[],n=r=>/^[\s·—-]+$/.test(String(r?.text||""));let i=Math.max(8,e);for(const r of t){if(i<=0)break;if(r?.color==="gray"&&s.length>0&&!n(r))continue;const a=String(r?.text||"");if(!a)continue;if(n(r)&&i<a.length+2)break;const l=a.length>i&&i>1?`${a.slice(0,i-1)}…`:a.slice(0,i);l&&(s.push({...r,text:l}),i-=l.length)}for(;s.length>0&&n(s[s.length-1]);)s.pop();return s.length>0?s:t}function Zp(t){const e=Xe(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.dataset.psTheme=e.id}function Fr(t){const[e,s]=c.useState({width:0,height:0});return c.useLayoutEffect(()=>{const n=t.current;if(!n)return;const i=()=>{s({width:n.clientWidth,height:n.clientHeight})};i();const r=new ResizeObserver(i);return r.observe(n),window.addEventListener("resize",i),()=>{r.disconnect(),window.removeEventListener("resize",i)}},[t]),e}function eh(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/Ia)),height:Math.max(18,Math.floor(s/xa))}}function th(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function sh(t){return th(t)<=Aa}function nh(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)*Ue;return s==="bottom"?Math.max(0,i-r):Math.min(i,r)}function ih(t,e,s,n,i,r,{stickyBottom:o=!1}={}){const a=c.useMemo(()=>pe(e),[e]),l=c.useRef(null),u=c.useRef({scrollMode:n,scrollOffset:s}),f=c.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),d=c.useRef({width:null,height:null}),[p,h]=c.useState(0);c.useLayoutEffect(()=>{const I=t.current;if(!I||typeof ResizeObserver>"u")return;d.current={width:I.clientWidth,height:I.clientHeight};const w=new ResizeObserver(()=>{const C={width:I.clientWidth,height:I.clientHeight},N=d.current;C.width===N.width&&C.height===N.height||(d.current=C,h(R=>R+1))});return w.observe(I),()=>w.disconnect()},[t]),c.useLayoutEffect(()=>{const I=t.current;if(!I)return;const w=u.current,C=f.current,N=typeof performance<"u"?performance.now():Date.now(),R=C.touching||N-(C.lastUserScrollAt||0)<kp,F=C.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-C.lastDispatchedOffset)<2;if(R&&n===w?.scrollMode&&(s===w?.scrollOffset||F)){u.current={scrollMode:n,scrollOffset:s};return}const L=o&&n==="top"&&w?.scrollMode==="top"&&w?.scrollOffset===s,M=nh(I,s,n,L);if(Math.abs(I.scrollTop-M)>Rt){const $={target:M};l.current=$,I.scrollTop=M,window.requestAnimationFrame(()=>{l.current===$&&(l.current=null)})}u.current={scrollMode:n,scrollOffset:s}},[a,t,n,s,o,p]);const m=oh(I=>{r.dispatch({type:"ui/scroll",pane:i,offset:I})}),g=c.useCallback(()=>{const I=t.current;if(!I||!i)return;const w=l.current;if(w){if(Math.abs(I.scrollTop-w.target)<=Rt)return;l.current=null}f.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const C=Math.max(0,I.scrollHeight-I.clientHeight);if(C<=0)return;if(o&&typeof r.updatePaneScrollFromViewport=="function"){const R=Math.max(0,I.scrollTop)/Ue;f.current.lastDispatchedOffset=R,r.updatePaneScrollFromViewport(i,R,{atBottom:sh(I)});return}const N=n==="bottom"?Math.max(0,C-I.scrollTop):Math.max(0,I.scrollTop);f.current.lastDispatchedOffset=N/Ue,m(N/Ue),i==="chat"&&n==="bottom"&&I.scrollTop<=Rt&&r.armChatTopHistoryLoad?.()},[r,m,i,t,n,o]),S=c.useCallback(I=>{const w=t.current;if(!w||i!=="chat"||n!=="bottom"||I.deltaY>=0||w.scrollTop>Rt)return;const C=Math.max(0,w.scrollHeight-w.clientHeight);r.handleChatTopHistoryScrollIntent?.(C/Ue)},[r,i,t,n]),y=c.useRef({startY:null,fired:!1}),A=c.useCallback(I=>{f.current.touching=!0,!(i!=="chat"||n!=="bottom")&&(y.current={startY:I.touches?.[0]?.clientY??null,fired:!1})},[i,n]),x=c.useCallback(()=>{f.current.touching=!1,f.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),v=c.useCallback(I=>{const w=t.current,C=y.current;if(!w||i!=="chat"||n!=="bottom"||C.fired||C.startY==null||w.scrollTop>Rt)return;const N=I.touches?.[0]?.clientY;if(N==null||N-C.startY<Tp)return;C.fired=!0;const R=Math.max(0,w.scrollHeight-w.clientHeight);r.handleChatTopHistoryScrollIntent?.(R/Ue+1,{force:!0})},[r,i,t,n]);return{normalizedLines:a,onScroll:g,onWheel:S,onTouchStart:A,onTouchMove:v,onTouchEnd:x}}function me({runs:t,theme:e}){return c.createElement(c.Fragment,null,(t||[]).map((s,n)=>{const i={color:ae(e,s.color),backgroundColor:ae(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"};if(s?.trailingRule)return c.createElement("span",{key:`${n}:rule`,className:"ps-line-trailing-rule",style:i},s.text||"");const r=String(s?.href||"").trim(),o=/^https?:\/\//i.test(r),a=_a(r);return a?c.createElement(La,{key:`${n}:${s.text||""}`,label:s.text||"",artifactRef:a,style:i}):o?c.createElement("a",{key:`${n}:${s.text||""}`,className:"ps-md-link",href:r,target:"_blank",rel:"noreferrer",style:i},s.text||""):c.createElement("span",{key:`${n}:${s.text||""}`,style:i},s.text||"")}))}function rh({line:t,theme:e}){const s=String(t?.body||"").trim();return c.createElement("details",{className:"ps-system-notice"},c.createElement("summary",{className:"ps-system-notice-summary",style:{color:ae(e,t?.color)||"var(--ps-muted)"}},c.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),s?c.createElement("div",{className:"ps-system-notice-body"},c.createElement(ni,{content:s,theme:e})):null)}function oh(t){const e=c.useRef(0),s=c.useRef(null),n=c.useRef(t);return n.current=t,c.useEffect(()=>()=>{e.current&&cancelAnimationFrame(e.current)},[]),c.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 he=c.memo(function({line:e,theme:s,className:n=""}){const i=n?`ps-line ${n}`:"ps-line";return e?e.kind==="systemNotice"?c.createElement(rh,{line:e,theme:s}):e.kind==="runs"?c.createElement("div",{className:i},c.createElement(me,{runs:e.runs,theme:s})):c.createElement("div",{className:i,style:{color:ae(s,e.color),backgroundColor:ae(s,e.backgroundColor),fontWeight:e.bold?700:400,textDecoration:e.underline?"underline":"none"}},e.text||" "):c.createElement("div",{className:i}," ")});function Ee(t){return t?t.kind==="runs"?ka(t.runs):String(t.text||""):""}function Ma(t,e,s,n){const i=c.useRef(!1);return c.useLayoutEffect(()=>{const r=t.current;if(!r||!s)return;const o=Math.max(0,r.scrollHeight-r.clientHeight),a=Math.min(o,Math.max(0,Number(e)||0)*Ue);Math.abs(r.scrollTop-a)>2&&(i.current=!0,r.scrollTop=a,window.requestAnimationFrame(()=>{i.current=!1}))},[t,e,s]),c.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)/Ue})},[n,s,t])}const ah={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"},lh=new Set(["diff","patch","udiff"]),ch=/\.(patch|diff)$/i,Na=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,Pa=/\.(png|jpe?g|gif|webp|avif|bmp|svg|ico)$/i,uh={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 dh(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 fh=/\.(csv|tsv)$/i;function ph(t,e){return fh.test(String(t||""))?!0:/^text\/(csv|tab-separated-values)$/i.test(String(e||"").trim())}const sn=2e3;function hh(t){const e=String(t??"");return/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function mh({content:t,filename:e}){const[s,n]=c.useState(null),i=c.useRef(null),r=c.useRef(null),o=c.useRef(null);c.useEffect(()=>{let v=!1;return n(null),ba(()=>import("./papaparse.min-BU0o7jXn.js").then(I=>I.p),[]).then(I=>{if(v)return;const w=I.default||I,C=/\.tsv$/i.test(String(e||""))?" ":"",N=w.parse(String(t||"").trim(),{delimiter:C,skipEmptyLines:"greedy"});n({rows:N.data||[],errors:N.errors||[]})}).catch(()=>{v||n({rows:null,errors:[{message:"parser unavailable"}]})}),()=>{v=!0}},[t,e]),c.useEffect(()=>{const v=()=>{o.current=null};return window.addEventListener("mouseup",v),()=>window.removeEventListener("mouseup",v)},[]);const a=c.useCallback((v,I)=>{if(!v||!I)return;const w=window.getSelection();if(!w)return;const C=!!(v.compareDocumentPosition(I)&Node.DOCUMENT_POSITION_PRECEDING),N=document.createRange();N.setStartBefore(C?I:v),N.setEndAfter(C?v:I),w.removeAllRanges(),w.addRange(N)},[]),l=v=>v.target?.closest?v.target.closest("td,th"):null,u=c.useCallback(v=>{if(v.button!==0)return;const I=l(v);I&&(v.preventDefault(),i.current?.focus(),o.current=I,a(I,I))},[a]),f=c.useCallback(v=>{if(!o.current||!(v.buttons&1))return;const I=l(v);I&&a(o.current,I)},[a]),d=c.useCallback(v=>{if(!(v.metaKey||v.ctrlKey)||v.altKey||v.key!=="a"&&v.key!=="A")return;const I=r.current,w=window.getSelection();if(!I||!w)return;v.preventDefault(),v.stopPropagation();const C=document.createRange();C.selectNodeContents(I),w.removeAllRanges(),w.addRange(C)},[]),p=c.useCallback(v=>{const I=r.current,w=window.getSelection();if(!I||!w||w.rangeCount===0)return;const C=w.getRangeAt(0),N=new Map;for(const R of I.querySelectorAll("th,td")){if(!C.intersectsNode(R))continue;const F=R.parentElement;N.has(F)||N.set(F,[]),N.get(F).push(hh(R.textContent))}N.size!==0&&(v.clipboardData.setData("text/plain",Array.from(N.values(),R=>R.join(" ")).join(`
|
|
87
|
+
`)),v.preventDefault())},[]);if(!s)return c.createElement("div",{className:"ps-csv-status"},"Parsing…");if(!s.rows||s.rows.length===0)return c.createElement("pre",{className:"ps-md-code-pre"},c.createElement("code",null,String(t||"")));const[h,...m]=s.rows,g=m.reduce((v,I)=>Math.max(v,I.length),h.length),S=Array.from({length:g},(v,I)=>h[I]??""),y=m.length>sn,A=y?m.slice(0,sn):m,x=[];return y&&x.push(`showing first ${sn} of ${m.length} rows`),s.errors.length&&x.push(`${s.errors.length} parse warning${s.errors.length===1?"":"s"}`),c.createElement("div",{className:"ps-csv-wrap",ref:i,tabIndex:0,onMouseDown:u,onMouseMove:f,onKeyDown:d,onCopy:p},c.createElement("table",{className:"ps-csv-table",ref:r},c.createElement("thead",null,c.createElement("tr",null,S.map((v,I)=>c.createElement("th",{key:`h${I}`},String(v??""))))),c.createElement("tbody",null,A.map((v,I)=>c.createElement("tr",{key:`r${I}`},S.map((w,C)=>c.createElement("td",{key:`c${C}`},String(v[C]??""))))))),x.length?c.createElement("div",{className:"ps-csv-status"},x.join(" · ")):null)}function Oa(t){const e=/\.([A-Za-z0-9]+)$/.exec(String(t||""));return e&&uh[e[1].toLowerCase()]||null}function ei(t,e){return ch.test(String(t||""))?!0:/^text\/x-(patch|diff)$/i.test(String(e||"").trim())}function _a(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 Ra=c.createContext(null);function La({label:t,artifactRef:e,style:s}){const n=c.useContext(Ra),i=ei(e.filename),r=c.useCallback(o=>{if(o.preventDefault(),o.stopPropagation(),!n?.revealArtifact)return;const a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;Promise.resolve(n.revealArtifact(e.sessionId,e.filename,{fullscreen:a})).catch(()=>{})},[n,e.sessionId,e.filename]);return c.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?c.createElement("span",{className:"ps-artifact-link-glyph","aria-hidden":"true"},"±"):null,c.createElement("span",{className:"ps-artifact-link-label"},t||e.filename))}function $a(t){return lh.has(String(t||"").trim().toLowerCase())}const gh=/^(?: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 yh(t){return gh.test(t)?"meta":t.startsWith("@@")?"hunk":t.startsWith("+")?"add":t.startsWith("-")?"del":"context"}const Sh={add:"green",del:"red",hunk:"cyan",meta:"gray"};function ti(t,e){return String(t||"").replace(/\n$/,"").split(`
|
|
88
|
+
`).map((n,i)=>{const r=yh(n),o=Sh[r],a=r==="add"||r==="del"||r==="context"&&n.startsWith(" "),l=a?n.slice(0,1):"",u=a?n.slice(1):n;return c.createElement("span",{key:`d:${i}`,className:`ps-diff-line is-${r}`,style:o?{color:ae(e,o)||void 0}:void 0},c.createElement("span",{className:"ps-diff-marker","aria-hidden":"true"},l.trim()),c.createElement("span",{className:"ps-diff-text"},u))})}function Fa(t){return String(t||"").trim().toLowerCase()==="mermaid"}const Br={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 bh(t){const e={type:"comment",re:/#[^\n]*/y},s={type:"comment",re:/\/\/[^\n]*|\/\*[\s\S]*?\*\//y},n={type:"comment",re:/--[^\n]*|\/\*[\s\S]*?\*\//y},i={type:"number",re:/\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b0[xX][0-9a-fA-F]+\b/y},r={type:"identifier",re:/[A-Za-z_$][\w$]*/y},o={type:"string",re:/"(?:\\.|[^"\\])*"?/y},a={type:"string",re:/'(?:\\.|[^'\\])*'?/y},l={type:"string",re:/`(?:\\.|[^`\\])*`?/y},u={type:"string",re:/"""[\s\S]*?"""|'''[\s\S]*?'''/y};switch(t){case"python":return[e,u,o,a,i,r];case"shell":return[e,o,a,i,r];case"sql":return[n,a,o,i,r];case"yaml":return[e,o,a,i,r];case"json":return[o,i,r];case"css":return[{type:"comment",re:/\/\*[\s\S]*?\*\//y},o,a,i,r];default:return[s,o,a,l,i,r]}}const wh={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},Ih=2e4,tt=new Map,xh=120;function vh(t,e){const s=`${e||""}\0${t}`,n=tt.get(s);if(n)return tt.delete(s),tt.set(s,n),n;const i=Eh(t,e);return tt.set(s,i),tt.size>xh&&tt.delete(tt.keys().next().value),i}function Eh(t,e){const s=ah[String(e||"").trim().toLowerCase()]||"default",n=Br[s]||Br.js,i=bh(s),r=[];let o=0,a=0;const l=u=>{u>a&&r.push({type:"plain",text:t.slice(a,u)})};for(;o<t.length;){let u=null;for(const d of i){d.re.lastIndex=o;const p=d.re.exec(t);if(p&&p.index===o&&p[0].length>0){u={type:d.type,text:p[0]};break}}if(!u){o+=1;continue}let f=u.type;if(f==="identifier")if(n.has(u.text))f="keyword";else{const d=t.slice(o+u.text.length);f=/^\s*\(/.test(d)?"fn":"plain"}if(f==="plain"){o+=u.text.length;continue}l(o),r.push({type:f,text:u.text}),o+=u.text.length,a=o}return l(t.length),r}function si(t,e,s){const n=String(t||"");if(!n||n.length>Ih)return n;let i;try{i=vh(n,e)}catch{return n}return i.map((r,o)=>{const a=wh[r.type];return a?c.createElement("span",{key:`t:${o}`,className:`ps-code-token is-${r.type}`,style:{color:ae(s,a)||void 0}},r.text):c.createElement(c.Fragment,{key:`t:${o}`},r.text)})}let es=null;function Ah(){return es||(es=ba(()=>import("./mermaid.core--xGRoQTa.js").then(t=>t.bp),[]).then(t=>t.default||t).catch(t=>{throw es=null,t})),es}function Ch(t,e){return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"default":"dark",fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"}),t}let Dr=0,Hr=Promise.resolve();function Th(t){const e=Hr.then(t,t);return Hr=e.then(()=>{},()=>{}),e}function Ba({code:t,theme:e,fallback:s}){const[n,i]=c.useState(null),[r,o]=c.useState(!1),[a,l]=c.useState(""),u=c.useMemo(()=>ic(e),[e]);return c.useEffect(()=>{let f=!0;const d=String(t||"").trim();if(d)return o(!1),Ah().then(p=>Th(async()=>{if(!f)return;Ch(p,u),Dr+=1;const h=`ps-mermaid-${Dr}`;await p.parse(d);const{svg:m}=await p.render(h,d);f&&i(m)})).catch(p=>{f&&(i(null),o(!0),l(String(p?.message||p)))}),()=>{f=!1}},[t,u]),n&&!r?c.createElement("div",{className:"ps-mermaid",dangerouslySetInnerHTML:{__html:n}}):r&&a?c.createElement("div",{className:"ps-mermaid-failed"},c.createElement("div",{className:"ps-mermaid-error"},`Diagram could not be rendered — ${String(a).split(`
|
|
89
|
+
`)[0]}`),s):s}function Le(t,e,s="md"){return Cn(t).map((n,i)=>{const r=`${s}:${i}`;if(n.type==="code")return c.createElement("code",{key:r,className:"ps-md-inline-code"},n.text);if(n.type==="strong")return c.createElement("strong",{key:r,className:"ps-md-strong"},Le(n.text,e,`${r}:strong`));if(n.type==="em")return c.createElement("em",{key:r,className:"ps-md-em"},Le(n.text,e,`${r}:em`));if(n.type==="link"){const o=_a(n.href);return o?c.createElement(La,{key:r,label:n.text,artifactRef:o,style:{color:ae(e,"cyan")}}):/^https?:\/\//i.test(String(n.href||"").trim())?c.createElement("a",{key:r,className:"ps-md-link",href:n.href,target:"_blank",rel:"noreferrer",style:{color:ae(e,"cyan")}},n.text):c.createElement("span",{key:r,style:{color:ae(e,"cyan")}},n.text)}return c.createElement(c.Fragment,{key:r},n.text)})}function In(t=""){return String(t||"").replace(/\s+/g," ").trim()}const kh=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],Mh=24,Nh=32,Ph=6,Gr=30,Oh=56,nn=.4,_h=1.4,Rh=2;function Da(t=[]){const e=Math.max(0,...t.map(m=>m.length));if(e<=0)return null;const s=t[0]||[],n=Math.max(1,t.length-1),i=Array.from({length:e},()=>({max:0,spaceCells:0}));for(let m=0;m<t.length;m+=1){const g=t[m];for(let S=0;S<e;S+=1){const y=In(g[S]||"");y.length>i[S].max&&(i[S].max=y.length),m>0&&/\s/.test(y)&&(i[S].spaceCells+=1)}}let r=-1,o=0;for(let m=0;m<e;m+=1){const g=i[m];if(g.max<Mh||g.spaceCells/n<.4)continue;const y=In(s[m]||"").toLowerCase(),A=kh.some(v=>y.includes(v))?60:0,x=g.max+A;x>o&&(o=x,r=m)}if(r<0)return null;const a=i.map((m,g)=>g===r?0:Math.max(Ph,Math.min(m.max+2,Nh))),l=a.reduce((m,g)=>m+g,0),u=i[r],f=Math.max(Gr,Math.min(u.max*.45,Oh,Math.max(Gr,l*_h))),d=a.map((m,g)=>g===r?f:m),p=d.reduce((m,g)=>m+g,0);if(p>0&&d[r]/p<nn){const m=p-d[r];d[r]=m*(nn/(1-nn))}const h=d.reduce((m,g)=>m+g,0);return h>0?{widths:d.map(m=>`${(m/h*100).toFixed(2)}%`),flexIndex:r,minWidth:`${Math.ceil(h+Rh)}ch`}:null}function Ha(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(r=>In(r?.[n]||"")).filter(Boolean).join(" / ")||null)}function jr(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 Ur(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Lh(t=""){const s=String(t||"").replace(/\r\n?/g,`
|
|
90
|
+
`).split(`
|
|
91
|
+
`),n=[];for(let i=0;i<s.length;){const r=s[i],o=r.trim();if(!o){i+=1;continue}const a=/^```(\S*)\s*$/.exec(o);if(a){const d=a[1]||"",p=[];for(i+=1;i<s.length&&!/^```/.test(s[i].trim());)p.push(s[i]),i+=1;i<s.length&&(i+=1),n.push({type:"code",language:d,content:p.join(`
|
|
92
|
+
`)});continue}const l=/^(#{1,6})\s+(.*)$/.exec(r);if(l){n.push({type:"heading",level:l[1].length,text:l[2].trim()}),i+=1;continue}if(r.includes("|")&&i+1<s.length&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(s[i+1].trim())){const d=Ur(r);i+=2;const p=[];for(;i<s.length&&s[i].includes("|")&&s[i].trim();)p.push(Ur(s[i])),i+=1;n.push({type:"table",header:d,rows:p});continue}if(/^\s*>/.test(r)){const d=[];for(;i<s.length&&/^\s*>/.test(s[i]);)d.push(s[i].replace(/^\s*>\s?/,"")),i+=1;n.push({type:"blockquote",text:d.join(`
|
|
93
|
+
`).trim()});continue}const u=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(r);if(u){const d=/\d+\./.test(u[2]),p=[];for(;i<s.length;){const h=s[i],m=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(h);if(!m||/\d+\./.test(m[2])!==d)break;const g=[m[3].trim()];for(i+=1;i<s.length&&s[i].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[i])&&!jr(s[i],s[i+1]||"");)g.push(s[i].trim()),i+=1;if(p.push(g.join(" ")),!s[i]?.trim())break}n.push({type:"list",ordered:d,items:p});continue}const f=[r.trim()];for(i+=1;i<s.length&&s[i].trim()&&!jr(s[i],s[i+1]||"");)f.push(s[i].trim()),i+=1;n.push({type:"paragraph",text:f.join(" ")})}return n}function ni({content:t,theme:e}){const s=c.useMemo(()=>Lh(t),[t]);return s.length===0?c.createElement("div",{className:"ps-empty-state"},"No preview content."):c.createElement("div",{className:"ps-markdown-preview"},s.map((n,i)=>{if(n.type==="heading")return c.createElement("div",{key:`block:${i}`,className:`ps-md-heading is-h${n.level}`},Le(n.text,e,`heading:${i}`));if(n.type==="code"){const r=$a(n.language),o=c.createElement("section",{key:`block:${i}`,className:`ps-md-code-block${r?" is-diff":""}`},c.createElement("div",{className:"ps-md-code-header"},n.language||"text"),c.createElement("pre",{className:"ps-md-code-pre"},c.createElement("code",null,r?ti(n.content,e):si(n.content,n.language,e))));return Fa(n.language)?c.createElement(Ba,{key:`block:${i}`,code:n.content,theme:e,fallback:o}):o}if(n.type==="blockquote")return c.createElement("blockquote",{key:`block:${i}`,className:"ps-md-quote"},Le(n.text,e,`quote:${i}`));if(n.type==="list"){const r=n.ordered?"ol":"ul";return c.createElement(r,{key:`block:${i}`,className:`ps-md-list${n.ordered?" is-ordered":""}`},n.items.map((o,a)=>c.createElement("li",{key:`item:${a}`,className:"ps-md-list-item"},Le(o,e,`list:${i}:${a}`))))}if(n.type==="table"){const r=Math.max(n.header.length||0,...n.rows.map(m=>m.length)),o=r>0&&r<=6,a=o?Da([n.header,...n.rows]):null,l=!!a,u=a?a.flexIndex:-1,f=m=>m===u?"is-flex-column":null,d=Ha([n.header],r),p=`ps-md-table${o?" is-fit-width":""}${l?" has-flex-column":""}`,h=`ps-md-table-wrap${o?" is-fit-width":""}${l?" has-flex-column":""}`;return c.createElement("div",{key:`block:${i}`,className:h},c.createElement("table",{className:p,style:a?.minWidth?{"--ps-table-min-width":a.minWidth}:void 0},a?c.createElement("colgroup",null,a.widths.map((m,g)=>c.createElement("col",{key:`col:${g}`,className:f(g)||void 0,style:{width:m}}))):null,c.createElement("thead",null,c.createElement("tr",null,n.header.map((m,g)=>c.createElement("th",{key:`head:${g}`,className:f(g)||void 0},Le(m,e,`table:${i}:head:${g}`))))),c.createElement("tbody",null,n.rows.map((m,g)=>c.createElement("tr",{key:`row:${g}`},m.map((S,y)=>c.createElement("td",{key:`cell:${g}:${y}`,className:f(y)||void 0,"data-label":d[y]||void 0},c.createElement("span",{className:"ps-table-cell-value"},Le(S,e,`table:${i}:${g}:${y}`)))))))))}return c.createElement("p",{key:`block:${i}`,className:"ps-md-paragraph"},Le(n.text,e,`para:${i}`))}))}function rn({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:r,theme:o,className:a="",focusRegion:l=null,children:u}){const f=c.useRef(null),d=Ma(f,i,r,t),p=c.useCallback(()=>{const h=ii(r,l);h&&t?.setFocus&&t.setFocus(h)},[t,r,l]);return c.createElement(lt,{title:e,color:s,focused:n,theme:o},c.createElement("div",{ref:f,className:`ps-scroll-panel is-preview ${a}`.trim(),onScroll:d,onMouseDown:p},u))}function $h({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:r,theme:o,content:a,focusRegion:l=null}){const u=c.useCallback(()=>{const p=ii(r,l);p&&t?.setFocus&&t.setFocus(p)},[t,r,l]),f=c.useRef(null),d=Ma(f,i,r,t);return c.createElement(lt,{title:e,color:s,focused:n,theme:o},c.createElement("div",{ref:f,className:"ps-scroll-panel ps-markdown-scroll",onScroll:d,onMouseDown:u},c.createElement(ni,{content:a,theme:o})))}function Fh(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 Wr({title:t,color:e,focused:s,theme:n,filename:i,contentType:r,sizeBytes:o,source:a,uploadedAt:l,controller:u=null,sessionId:f=null}){const d=[];r&&d.push(r),o!=null&&d.push(Fh(o)),a&&d.push(a);const p=l?new Date(l).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"",h=Na.test(String(r||""))||Pa.test(String(i||"")),[m,g]=c.useState(null);return c.useEffect(()=>{if(g(null),!h||!u||!f||!i)return;let S=!1;return Ua(u,f,i).then(y=>{S||g(y)}).catch(()=>{S||g("error")}),()=>{S=!0}},[h,u,f,i]),c.createElement(lt,{title:t,color:e,focused:s,theme:n},c.createElement("div",{className:"ps-binary-preview-card"},c.createElement("div",{className:"ps-binary-preview-kicker"},h?"Image artifact":"Binary artifact"),c.createElement("h3",{className:"ps-binary-preview-title"},i||"Artifact"),d.length>0?c.createElement("div",{className:"ps-binary-preview-meta"},d.join(" • ")):null,p?c.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${p}`):null,h&&m&&m!=="error"?c.createElement("img",{className:"ps-binary-preview-image",src:m,alt:i||"artifact image",onClick:()=>{try{window.open(m,"_blank","noopener")}catch{}}}):c.createElement("p",{className:"ps-binary-preview-copy"},h?m==="error"?"Could not load the image preview. Use Download to save the file.":"Loading image preview…":"Preview is intentionally disabled for non-text artifacts in the browser workspace. Use Download to save the file and open it in the default app.")))}function ns(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function on(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function Bh(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function Ht(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function Dh(t){const e=String(Ee(t)||"").trim();return ns(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function Hh(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=Ee(t);return Ht(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function Gh(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 Kr(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?Gh(t.runs.slice(1,-1)):[{text:Ee(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function jh(t){const e=String(t||"").trim();return Ht(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function Uh(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 Wh(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)=>Uh(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function Vr(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>Wh(t.map(i=>String(i[n]||"").trim()).filter(Boolean)))}function Ga(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&&Ee(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:Ga(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=Ee(n);if(ns(i)&&i.includes("┬")){const r=[],o=[];let a=[],l=!0;for(s+=1;s<t.length;){const u=t[s],f=Ee(u);if(on(f)){if(a.length>0){const d=Vr(a);d.length>0&&(l?r.push(d):o.push(d))}s+=1;break}if(Bh(f)){if(a.length>0){const d=Vr(a);d.length>0&&(l?r.push(d):o.push(d))}a=[],l=!1,s+=1;continue}if(Ht(f)){const d=jh(f);d.length>0&&a.push(d)}s+=1}e.push({type:"table",headerRows:r,bodyRows:o});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&ns(i)){const r=Dh(n),o=[];for(s+=1;s<t.length;){const a=t[s],l=Ee(a);if(on(l)){s+=1;break}Ht(l)?o.push(Hh(a)):o.push(Ee(a)),s+=1}s<t.length&&Ee(t[s]).trim().length===0&&(s+=1),e.push({type:"code",language:r||"text",content:o.join(`
|
|
94
|
+
`)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&ns(i)){const r=Kr(n),o=n.runs[0]?.color||"gray",a=[];for(s+=1;s<t.length;){const l=t[s],u=Ee(l);if(on(u)){s+=1;break}Ht(u)?a.push(Kr(l)):a.push(l?.kind==="runs"?l.runs:[{text:Ee(l),color:l?.color||null}]),s+=1}s<t.length&&Ee(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:r,bodyLines:a,borderColor:o});continue}e.push({type:"line",line:n}),s+=1}return e}function ja({lines:t,theme:e,controller:s=null}){const n=c.useMemo(()=>Ga(t),[t]);return c.createElement(Ka,{blocks:n,theme:e,controller:s})}const Kh=c.memo(function({block:e,theme:s,controller:n,continued:i}){const r=e.header||{},o=e.role==="user"?" is-user":" is-assistant",a=e.pendingPhase?` is-${e.pendingPhase}`:"",l=String(e.text||""),u=e.role==="user"&&r.fromOtherPerson;return c.createElement("article",{className:`ps-rich-msg${o}${a}${i?" is-continued":""}`},c.createElement("header",{className:"ps-rich-msg-head"},u?c.createElement("span",{className:"ps-rich-msg-label",style:{color:ae(s,r.roleColor)||void 0}},r.roleLabel):null,c.createElement("span",{className:"ps-rich-msg-meta"},r.glyph?c.createElement("span",{className:"ps-rich-msg-glyph",title:e.pendingPhase||void 0,style:{color:ae(s,r.glyphColor)||void 0}},r.glyph):null,r.time?c.createElement("span",{className:"ps-rich-msg-time"},r.time):null)),l.trim()?c.createElement("div",{className:"ps-rich-msg-body"},c.createElement(ni,{content:l,theme:s})):null,e.attachments?c.createElement(Wa,{controller:n,sessionId:e.attachments.sessionId,attachments:e.attachments.attachments}):null)}),Vh=c.memo(function({block:e,theme:s,controller:n}){const i=c.useMemo(()=>pe(e.lines||[]),[e.lines]);return c.createElement("div",{className:`ps-rich-lineblock is-${e.variant||"event"}`},c.createElement(ja,{lines:i,theme:s,controller:n}))});function qh({blocks:t,theme:e,controller:s=null}){return c.createElement("div",{className:"ps-rich-chat"},(t||[]).map((n,i)=>{if(n.kind==="message"){const r=t[i-1],o=n.header||{},a=n.role==="user"&&o.fromOtherPerson,l=!!(r&&r.kind==="message"&&r.role===n.role&&!(r.header&&r.header.fromOtherPerson)&&!a);return c.createElement(Kh,{key:n.id!=null?`msg:${n.id}`:`msg:${i}`,block:n,theme:e,controller:s,continued:l})}return c.createElement(Vh,{key:`lines:${i}`,block:n,theme:e,controller:s})}))}const Ge=new Map,zh=60;function Ua(t,e,s){const n=`${e}/${s}`,i=Ge.get(n);if(i)return Ge.delete(n),Ge.set(n,i),i;const r=t?.transport?.api?.downloadArtifactResponse;if(typeof r!="function")return Promise.reject(new Error("artifact download unavailable"));const o=r.call(t.transport.api,e,s).then(async a=>{if(!a?.ok)throw new Error(`download failed (${a?.status})`);const l=await a.blob();return URL.createObjectURL(l)}).catch(a=>{throw Ge.get(n)===o&&Ge.delete(n),a});for(Ge.set(n,o);Ge.size>zh;){const[a,l]=Ge.entries().next().value;Ge.delete(a),Promise.resolve(l).then(u=>URL.revokeObjectURL(u)).catch(()=>{})}return o}function Wa({controller:t,sessionId:e,attachments:s}){const[n,i]=c.useState({});return c.useEffect(()=>{if(!t||!e)return;let r=!1;for(const o of s){const a=o?.filename;a&&Ua(t,e,a).then(l=>{r||i(u=>u[a]===l?u:{...u,[a]:l})}).catch(()=>{r||i(l=>l[a]==="error"?l:{...l,[a]:"error"})})}return()=>{r=!0}},[t,e,s]),c.createElement("div",{className:"ps-chat-image-strip"},s.map((r,o)=>{const a=r?.filename||`image-${o}`,l=n[a];return l&&l!=="error"?c.createElement("img",{key:`thumb:${o}:${a}`,className:"ps-chat-image-thumb",src:l,alt:a,title:`${a} — click to view full size`,onClick:()=>{try{window.open(l,"_blank","noopener")}catch{}}}):c.createElement("div",{key:`thumb:${o}:${a}`,className:`ps-chat-image-thumb is-pending${l==="error"?" is-error":""}`,title:a},l==="error"?"⚠":"🖼")}))}function Ka({blocks:t,theme:e,controller:s=null}){return c.createElement(c.Fragment,null,(t||[]).map((n,i)=>{if(n.type==="imageAttachments")return c.createElement(Wa,{key:`imageAttachments:${i}`,controller:s,sessionId:n.sessionId,attachments:n.attachments});if(n.type==="preserve"){const r=n.splashVariant?` is-splash-${n.splashVariant}`:"";return c.createElement("div",{key:`preserve:${i}`,className:`ps-chat-preserve-block${r}`},n.lines.map((o,a)=>c.createElement(he,{key:`preserve:${i}:${a}`,line:o,theme:e,className:"ps-line-preserve"})))}if(n.type==="code"){const r=$a(n.language),o=c.createElement("section",{key:`code:${i}`,className:`ps-md-code-block ps-chat-code-block${r?" is-diff":""}`},c.createElement("div",{className:"ps-md-code-header"},n.language||"text"),c.createElement("pre",{className:"ps-md-code-pre"},c.createElement("code",null,r?ti(n.content||"",e):si(n.content||"",n.language,e))));return Fa(n.language)?c.createElement(Ba,{key:`code:${i}`,code:n.content||"",theme:e,fallback:o}):o}if(n.type==="card")return c.createElement("section",{key:`card:${i}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":ae(e,n.borderColor)||"var(--ps-border)"}},c.createElement("header",{className:"ps-chat-card-header"},c.createElement(me,{runs:n.headerRuns,theme:e})),c.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?c.createElement(Ka,{blocks:n.blocks,theme:e,controller:s}):(n.bodyLines||[]).map((r,o)=>c.createElement("div",{key:`card:${i}:line:${o}`,className:"ps-chat-card-line"},c.createElement(me,{runs:r,theme:e})))));if(n.type==="table"){const r=n.headerRows||[],o=n.bodyRows||[],a=Math.max(1,...r.map(S=>S.length),...o.map(S=>S.length)),l=a<=6,u=l?Da([...r,...o]):null,f=!!u,d=u?u.flexIndex:-1,p=S=>S===d?"is-flex-column":null,h=Ha(r,a),m=`ps-chat-table${l?" is-fit-width":""}${f?" has-flex-column":""}`,g=`ps-chat-table-wrap${l?" is-fit-width":""}${f?" has-flex-column":""}`;return c.createElement("div",{key:`table:${i}`,className:g},c.createElement("table",{className:m,style:u?.minWidth?{"--ps-table-min-width":u.minWidth}:void 0},u?c.createElement("colgroup",null,u.widths.map((S,y)=>c.createElement("col",{key:`col:${y}`,className:p(y)||void 0,style:{width:S}}))):null,r.length>0?c.createElement("thead",null,r.map((S,y)=>c.createElement("tr",{key:`thead:${y}`},Array.from({length:a},(A,x)=>c.createElement("th",{key:`th:${y}:${x}`,className:p(x)||void 0},Le(S[x]||"",e,`chat-table:${i}:head:${y}:${x}`)))))):null,c.createElement("tbody",null,o.map((S,y)=>c.createElement("tr",{key:`tbody:${y}`},Array.from({length:a},(A,x)=>c.createElement("td",{key:`td:${y}:${x}`,className:p(x)||void 0,"data-label":h[x]||void 0},c.createElement("span",{className:"ps-table-cell-value"},Le(S[x]||"",e,`chat-table:${i}:${y}:${x}`)))))))))}return c.createElement(he,{key:`line:${i}`,line:n.line,theme:e})}))}function Yh(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 lt({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:i=null,children:r,theme:o,className:a=""}){const l=ae(o,s),u=!!((Array.isArray(t)?t.length>0:String(t??"").trim())||e||i);return c.createElement("section",{className:`ps-panel${n?" is-focused":""}${u?"":" is-chromeless"}${a?` ${a}`:""}`,style:{"--ps-panel-accent":l||"var(--ps-border)"}},u?c.createElement("header",{className:"ps-panel-header"},c.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?c.createElement(me,{runs:t,theme:o}):Lr(t)),e||i?c.createElement("div",{className:"ps-panel-header-right"},e?c.createElement("div",{className:"ps-panel-title-right"},Array.isArray(e)?c.createElement(me,{runs:e,theme:o}):Lr(e)):null,i?c.createElement("div",{className:"ps-panel-actions"},i):null):null):null,c.createElement("div",{className:"ps-panel-body"},r))}function Qh({lines:t,theme:e,completionByTurn:s}){const[n,i]=c.useState(()=>new Set),r=c.useCallback(f=>{i(d=>{const p=new Set(d);return p.has(f)?p.delete(f):p.add(f),p})},[]),o=f=>Number(f||0).toLocaleString("en-US"),a=f=>{const d=Number(f||0);if(!Number.isFinite(d))return"?K";const p=d/1e3,h=Math.abs(p)>=10?1:2;return`${p.toFixed(h)}K`},l=f=>{const d=Number(f||0);return Number.isFinite(d)?`${(d/1e3).toFixed(1)}s`:"?s"},u=f=>{const d=String(f||"").trim();if(!d)return"unknown";const p=d.split(":").filter(Boolean),h=p[p.length-1]||"",m=p.length>1&&Np.has(h.toLowerCase())?p.length-2:p.length-1;return p[Math.max(0,m)]||p[0]||"unknown"};return c.createElement(c.Fragment,null,t.map((f,d)=>{const p=f?.kind==="runs"&&Array.isArray(f.runs)?f.runs.find(C=>C?.completedTurn!=null)?.completedTurn:null,h=p!=null?s.get(Number(p)):null;if(!h)return c.createElement(he,{key:`line:${d}`,line:f,theme:e});const m=h.data||{},g=String(h.seq??`${m.turnIndex??p}:${h.createdAt??d}`),S=n.has(g),y=m.reasoningEffort?`${m.model||"(unknown)"}:${m.reasoningEffort}`:m.model||"(unknown)",A=u(m.model),x=m.durationMs!=null?l(m.durationMs):"duration n/a",v=m.durationMs!=null?`${o(m.durationMs)} ms`:"duration n/a",I=`${a(m.tokensInput)} / ${a(m.tokensOutput)}`,w=[["model",y],["started",m.startedAt?new Date(m.startedAt).toLocaleString():null],["ended",m.endedAt?new Date(m.endedAt).toLocaleString():null],["duration",v],["tokens",`${o(m.tokensInput)} in / ${o(m.tokensOutput)} out`],["cache",`${o(m.tokensCacheRead)} read / ${o(m.tokensCacheWrite)} write`],["tools",`${o(m.toolCalls)} calls / ${o(m.toolErrors)} errors`],["names",Array.isArray(m.toolNames)&&m.toolNames.length?m.toolNames.join(", "):null],["worker",m.workerNodeId||null],["result",m.resultType||null],["error",m.errorMessage||null]].filter(([,C])=>C!=null&&C!=="");return c.createElement(c.Fragment,{key:`seq:${d}`},c.createElement(he,{line:f,theme:e}),c.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>r(g)},c.createElement("span",{className:"ps-sequence-turn-caret"},S?"v":">"),c.createElement("span",{className:"ps-sequence-turn-rule"},"--- "),c.createElement("span",{className:"ps-sequence-turn-key"},"Mod: "),c.createElement("span",{className:"ps-sequence-turn-model"},A),c.createElement("span",{className:"ps-sequence-turn-rule"}," ("),c.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),c.createElement("span",{className:"ps-sequence-turn-tokens"},I),c.createElement("span",{className:"ps-sequence-turn-rule"},", "),c.createElement("span",{className:"ps-sequence-turn-key"},"dur: "),c.createElement("span",{className:"ps-sequence-turn-duration"},x),c.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),S?c.createElement("div",{className:"ps-sequence-turn-details"},w.map(([C,N])=>c.createElement("div",{key:C},c.createElement("span",{className:"ps-sequence-turn-detail-label"},`${C}: `),c.createElement("span",null,String(N))))):null)}))}const Xh={chat:"chat",activity:"activity",inspector:"inspector",filePreview:"inspector"};function ii(t,e=null){return e||Xh[String(t||"")]||null}function Ns({title:t,titleRight:e=null,color:s,focused:n,actions:i,lines:r,stickyLines:o=[],bottomStickyLines:a=[],scrollOffset:l=0,scrollMode:u="top",paneKey:f,controller:d,className:p="",panelClassName:h="",topContent:m=null,bottomContent:g=null,structuredBlocks:S=!1,stickyBottom:y=!1,renderBody:A=null,focusRegion:x=null}){const v=q(d,k=>k.ui.themeId),I=Xe(v),w=c.useRef(null),C=c.useRef(null),N=c.useRef(!1),{normalizedLines:R,onScroll:F,onWheel:L,onTouchStart:M,onTouchMove:$,onTouchEnd:D}=ih(w,r,l,u,f,d,{stickyBottom:y}),K=c.useMemo(()=>pe(o),[o]),z=c.useMemo(()=>pe(a),[a]),Y=p.includes("is-preserve")&&h.includes("has-preserved-sticky"),Ie=c.useCallback(()=>{const k=ii(f,x);k&&d?.setFocus&&d.setFocus(k)},[d,f,x]),Z=c.useCallback((k,B)=>{!k||!B||Math.abs((B.scrollLeft||0)-(k.scrollLeft||0))<=1||(N.current=!0,B.scrollLeft=k.scrollLeft,window.requestAnimationFrame(()=>{N.current=!1}))},[]),[xe,b]=c.useState({up:!1,down:!1}),O=c.useCallback(k=>{if(!k)return;const B=k.scrollHeight-k.scrollTop-k.clientHeight>4,H=k.scrollTop>4;b(V=>V.up===B&&V.down===H?V:{up:B,down:H})},[]),G=c.useCallback(k=>{F(),O(k.currentTarget),!(!Y||N.current)&&Z(k.currentTarget,C.current)},[F,Y,Z,O]);c.useEffect(()=>{O(w.current)});const P=c.useCallback(k=>{!Y||N.current||Z(k.currentTarget,w.current)},[Y,Z]);return c.createElement(lt,{title:t,titleRight:e,color:s,focused:n,actions:i,theme:I,className:h},m,K.length>0?c.createElement("div",{ref:C,className:`ps-panel-sticky${Y?" is-scroll-sync":""}`,onScroll:P},K.map((k,B)=>c.createElement(he,{key:`sticky:${B}`,line:k,theme:I}))):null,c.createElement("div",{ref:w,className:`ps-scroll-panel ${p}${xe.down?" is-scrolled-down":""}${xe.up?" is-scrolled-up":""}`.trim(),onScroll:G,onMouseDown:Ie,onTouchStart:M,onWheel:L,onTouchMove:$,onTouchEnd:D,onTouchCancel:D},typeof A=="function"?A(R,I):S?c.createElement(ja,{lines:R,theme:I,controller:d}):R.map((k,B)=>c.createElement(he,{key:`line:${B}`,line:k,theme:I}))),z.length>0?c.createElement("div",{className:"ps-panel-bottom-sticky"},z.map((k,B)=>c.createElement(he,{key:`bottom-sticky:${B}`,line:k,theme:I}))):null,g)}const Jh={group:"🗂",system:"⚙",service:"⚗"},qr="—";function Zh({session:t,childCount:e=0}){const s=(d,p,h="")=>{const m=p==null||p===""?qr:String(p),g=m===qr;return c.createElement("div",{className:`ps-session-detail-field${h?` ${h}`:""}${g?" is-none":""}`,key:d},c.createElement("span",{className:"ps-session-detail-label"},d),c.createElement("span",{className:"ps-session-detail-value",title:m},m))},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?`${W(n.currentTokens)} / ${W(n.tokenLimit)} · ${r}%`:null;let a=null;t&&!t.isGroup&&(a="off",t.cronActive===!0&&(a=t.cronKind==="wall-clock"?`next ${fs(t.cronNextFireAt)}`:typeof t.cronInterval=="number"?`every ${gt(t.cronInterval)}`:"on"));const l=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,f=t?.isGroup?t.memberCount==null?null:String(t.memberCount):e>0?String(e):null;return c.createElement("div",{className:"ps-session-detail-box"},s("Title",t?.title,"is-title"),s("ID",t?.sessionId,"is-id"),s("Model",l),s("Context",o,r!=null&&r>=85?"is-hot":r!=null&&r>=70?"is-warm":""),s("Cron",a,t?.cronActive===!0?"is-armed":""),s("Agent",t?.agentId),s("Status",t?.status),s("Children",f),s("Access",u))}const em=c.memo(function({row:e,theme:s,rich:n,structuredRows:i,mobile:r,onRowClick:o,setRef:a}){const l=c.useCallback(f=>a(e.sessionId,f),[a,e.sessionId]),u=c.useCallback(f=>o(f,e),[o,e]);return c.createElement("button",{type:"button",ref:l,className:`ps-list-button ps-session-list-button${e.active?" is-selected":""}${e.selected?" is-multiselected":""}${e.pinned?" is-pinned":""}`,tabIndex:e.active?0:-1,"aria-selected":e.active?"true":"false",onClick:u},c.createElement("div",{className:n?"ps-session-row-content is-rich":"ps-line ps-session-row-content",style:{paddingInlineStart:n?`${Math.max(0,e.depth)*14}px`:`${Math.max(0,e.depth)*4}px`}},n?c.createElement(tm,{row:e,theme:s,showDetail:r}):c.createElement(Va,{row:e,theme:s,structured:i,showInlineDetail:r})))});function tm({row:t,theme:e,showDetail:s=!1}){const n=t.chrome;if(!n)return c.createElement(Va,{row:t,theme:e,structured:!0,showInlineDetail:s});const i=Jh[n.kind]||null,r=ae(e,n.accentColor)||void 0,o=s&&Array.isArray(t.detailRuns)?t.detailRuns:[];return c.createElement("div",{className:"ps-rich-session-row"},c.createElement("div",{className:"ps-rich-session-main"},n.selectMode?c.createElement("span",{className:`ps-rich-session-check${n.checked?" is-checked":""}`},n.checked?"✓":""):null,i?c.createElement("span",{className:"ps-rich-session-kind"},i):c.createElement("span",{className:"ps-rich-session-dot",style:{background:ae(e,n.statusColor)||void 0},title:t.status||void 0}),n.owner?c.createElement("span",{className:`ps-rich-session-owner${n.owner.isMine?" is-mine":""}`,title:n.owner.initials},n.owner.initials):null,c.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?c.createElement("span",{className:"ps-rich-session-pin",title:"Pinned"},"📌"):null,n.cron?c.createElement("span",{className:"ps-rich-session-cron",title:"Scheduled"},"⏱"):null,n.childBadge?c.createElement("span",{className:"ps-rich-session-count",style:{color:ae(e,n.childBadge.color)||void 0}},n.childBadge.text):null,n.ctx?c.createElement("span",{className:"ps-rich-session-ctx",style:{color:ae(e,n.ctx.color)||void 0}},n.ctx.text):null),o.length>0?c.createElement("div",{className:"ps-rich-session-detail"},c.createElement(me,{runs:o,theme:e})):null)}function Va({row:t,theme:e,structured:s=!1,showInlineDetail:n=!1}){if(!(s&&Array.isArray(t.titleRuns)))return Array.isArray(t.runs)?c.createElement(me,{runs:t.runs,theme:e}):t.text;const r=Array.isArray(t.ctxRuns)?t.ctxRuns:[],o=r.length>0,a=Array.isArray(t.detailRuns)?t.detailRuns:Array.isArray(t.selectedMetaRuns)?t.selectedMetaRuns:[],l=n&&t.active&&a.length>0;return c.createElement(c.Fragment,null,c.createElement("div",{className:"ps-session-row-line"},c.createElement("div",{className:"ps-session-row-title"},c.createElement(me,{runs:t.titleRuns,theme:e})),o?c.createElement("div",{className:"ps-session-row-ctx"},c.createElement(me,{runs:r,theme:e})):null),l?c.createElement("div",{className:"ps-session-row-detail"},c.createElement(me,{runs:a,theme:e})):null)}function sm(t){const e=c.useRef(t),s=c.useRef(null),n=c.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]);return(n===null||s.current!==n)&&(s.current=n,e.current=t),e.current}function ri({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1}){const i=String(s).includes("ps-mobile-session-pane"),r=q(t,P=>P.ui.themeId),o=Xe(r),a=c.useRef(new Map),l=q(t,P=>({branding:P.branding,activeSessionId:P.sessions.activeSessionId,sessionsById:P.sessions.byId,sessionsFlat:P.sessions.flat,filterQuery:P.sessions.filterQuery||"",ownerFilter:P.sessions.ownerFilter,pinnedIds:P.sessions.pinnedIds,selectedIds:P.sessions.selectedIds,selectMode:P.sessions.selectMode,auth:P.auth,connectionMode:P.connection?.mode||"local",modalOpen:!!P.ui.modal,focused:P.ui.focusRegion==="sessions",rich:P.ui.chatViewMode==="rich"}),ke),u=c.useMemo(()=>Ct({sessions:{activeSessionId:l.activeSessionId,byId:l.sessionsById,flat:l.sessionsFlat,filterQuery:l.filterQuery,ownerFilter:l.ownerFilter,pinnedIds:l.pinnedIds,selectedIds:l.selectedIds,selectMode:l.selectMode},auth:l.auth,connection:{mode:l.connectionMode},branding:l.branding}),[l.activeSessionId,l.auth,l.branding,l.connectionMode,l.filterQuery,l.ownerFilter,l.pinnedIds,l.selectedIds,l.selectMode,l.sessionsById,l.sessionsFlat]),f=sm(u),d=l.activeSessionId&&l.sessionsById[l.activeSessionId]||null,p=l.activeSessionId&&f.find(P=>P.sessionId===l.activeSessionId)||null,[h,m]=c.useState(!1),[g,S]=c.useState(null),y=c.useRef(!1),A=["modelPicker","reasoningEffortPicker","contextTierPicker"],x=q(t,P=>A.includes(P.ui.modal?.type));c.useEffect(()=>{!x&&y.current&&(y.current=!1,m(!0))},[x]);const v=()=>{y.current=!0,m(!1),t.openSwitchModelPicker(()=>{y.current=!1}).then(()=>{!A.includes(t.getState().ui.modal?.type)&&y.current&&(y.current=!1,m(!0))}).catch(P=>{y.current=!1,m(!0),t.dispatch({type:"ui/status",text:P?.message||String(P)||"Failed to switch model"})})},I=l.auth?.principal||null,w=l.auth?.authorization?.role,C=w==="admin"||w==="anonymous",N=!!(d?.owner&&I&&String(d.owner.provider)===String(I.provider)&&String(d.owner.subject)===String(I.subject)),R=!!(d&&!d.isSystem&&!d.isGroup&&(C||N)),F=Array.isArray(l.selectedIds)?l.selectedIds.length:0,L=F>1,M=!!(d&&!d.isSystem&&(d.isGroup||!d.parentSessionId&&!d.groupId)),$=!!(d&&Array.isArray(l.pinnedIds)&&l.pinnedIds.includes(d.sessionId)),D=!!(d?.isGroup&&Number(d.memberCount||0)===0),K=L?Array.isArray(l.selectedIds)&&l.selectedIds.some(P=>{const k=l.sessionsById[P];return k&&!k.isSystem&&!k.isGroup}):d?.isGroup?!0:!!d,Y=F>0?l.selectedIds.filter(P=>{const k=l.sessionsById[P];return k&&!k.isSystem&&!k.isGroup&&!k.parentSessionId}):d&&!d.isSystem&&!d.isGroup&&!d.parentSessionId?[d.sessionId]:[],Ie=Y.length>0,Z=`ps-session-pane${l.rich?" is-rich":""}${s?` ${s}`:""}`,xe=c.useRef(null);xe.current={rows:f,viewState:l,controller:t};const b=c.useCallback((P,k)=>{const{rows:B,viewState:H,controller:V}=xe.current;if(P.metaKey||P.ctrlKey){P.preventDefault(),H.selectMode||V.dispatch({type:"sessions/selectMode",enabled:!0}),V.dispatch({type:"sessions/selectToggle",sessionId:k.sessionId}),V.setFocus("sessions");return}if(P.shiftKey&&H.activeSessionId){P.preventDefault();const Se=B.map(Ze=>Ze.sessionId),$e=Se.indexOf(H.activeSessionId),Fe=Se.indexOf(k.sessionId);if($e>=0&&Fe>=0){const[Ze,Pt]=$e<=Fe?[$e,Fe]:[Fe,$e],Vt=Se.slice(Ze,Pt+1),ct=Array.from(new Set([...H.selectedIds||[],...Vt]));V.setSessionSelection(ct),V.setFocus("sessions");return}}if(k.hasChildren&&k.active){V.dispatch({type:k.collapsed?"sessions/expand":"sessions/collapse",sessionId:k.sessionId}),V.setFocus("sessions");return}H.selectMode&&V.dispatch({type:"sessions/selectClear"}),V.setFocus("sessions"),k.active||V.loadSession(k.sessionId).catch(()=>{})},[]),O=c.useCallback((P,k)=>{P&&(k?a.current.set(P,k):a.current.delete(P))},[]);c.useEffect(()=>{if(l.modalOpen||!l.focused||!l.activeSessionId)return;const P=a.current.get(l.activeSessionId);P&&(document.activeElement!==P&&P.focus({preventScroll:!0}),P.scrollIntoView({block:"nearest"}))},[l.activeSessionId,l.focused,l.modalOpen]);const G=c.createElement(c.Fragment,null,L?c.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",fontSize:"12px",opacity:.85},title:"Multiple sessions selected. Move to group or cancel selected sessions; click Clear to exit."},`${F} selected`):null,L?c.createElement(ie,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(E.CLEAR_SESSION_SELECTION).catch(()=>{})}):c.createElement(ie,{className:"ps-mini-button",icon:"📌",onClick:()=>t.handleCommand(E.PIN_SESSION).catch(()=>{}),disabled:!M,active:$,label:M?$?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"}),c.createElement(ie,{className:"ps-mini-button",icon:Y.length>1?`⊞${Y.length}`:"⊞",onClick:()=>t.handleCommand(E.OPEN_MOVE_TO_GROUP).catch(()=>{}),disabled:!Ie,label:Ie?Y.length>1?`Move ${Y.length} selected sessions to a group`:"Move this session to a group":"Select a top-level non-system session to move to a group"}),c.createElement(ie,{className:"ps-mini-button",icon:c.createElement(im),onClick:()=>m(!0),disabled:!R||L,label:L?"Disabled while multiple sessions are selected":"Manage session — rename, switch model, and sharing"}),c.createElement(ie,{className:"ps-mini-button",icon:c.createElement(rm),onClick:()=>{const P=d?.sessionId;if(!P)return;const k=Wp(P);k&&(_r(k),S({url:k,warn:!1}),Kp(t,P).then(B=>{S(H=>H&&H.url===k?{...H,warn:B}:H)}).catch(()=>{}))},disabled:!d||d.isGroup||L,label:"Copy link — copy a direct link to this session"}),c.createElement(ie,{className:"ps-mini-button",icon:d?.isSystem?"↻":d?.isGroup?"⊗":c.createElement(om),onClick:()=>t.handleCommand(d?.isGroup?E.DELETE_SESSION:E.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!K,label:L?`Terminate ${F} selected sessions (Mark Completed, Cancel, or Delete)`:d?.isGroup?D?"Delete this empty group":"This group cannot be deleted yet":d?.isSystem?"Restart this system session (complete, terminate, or hard delete)":"Lifecycle — regenerate context, mark completed, cancel, or delete"}),e);return c.createElement(c.Fragment,null,c.createElement(lt,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:l.focused,theme:o,actions:G,className:Z},c.createElement("div",{className:"ps-action-list ps-session-list"},f.length===0?c.createElement("div",{className:"ps-empty-state"},l.filterQuery?`No sessions matched "@@${l.filterQuery}".`:"No sessions yet."):f.map(P=>c.createElement(em,{key:P.sessionId,row:P,theme:o,rich:l.rich,structuredRows:n,mobile:i,onRowClick:b,setRef:O}))),i?null:c.createElement(Zh,{session:d,childCount:p?.childCount||0})),h&&d&&!d.isGroup?c.createElement(lm,{controller:t,sessionId:d.sessionId,initialTitle:d.title||"",currentModel:d.model||"",currentReasoningEffort:d.reasoningEffort||"",principal:l.auth?.principal||null,onClose:()=>m(!1),onSwitchModel:v,onChanged:()=>{}}):null,g?c.createElement(nm,{url:g.url,warn:g.warn,onCopyAgain:()=>{_r(g.url),t.dispatch({type:"ui/status",text:Gp})},onClose:()=>S(null)}):null)}function nm({url:t,warn:e,onCopyAgain:s,onClose:n}){const i=c.useRef(null);c.useEffect(()=>{const o=i.current;o&&(o.focus(),o.select())},[]);const r=o=>o.stopPropagation();return c.createElement("div",{className:"ps-share-overlay",onClick:n},c.createElement("div",{className:"ps-link-modal",onClick:r},c.createElement("div",{className:"ps-share-modal-head"},c.createElement("span",null,"Link copied"),c.createElement("button",{className:"ps-modal-close",onClick:n,"aria-label":"Close",title:"Close"},"✕")),c.createElement("div",{className:"ps-share-section-sub"},"Copied to your clipboard — anyone with access can open the session from this link."),c.createElement("div",{className:"ps-link-row"},c.createElement("input",{ref:i,className:"ps-link-input",readOnly:!0,value:t,onFocus:()=>i.current?.select()}),c.createElement("button",{className:"ps-mini-button",onClick:s},"Copy")),e?c.createElement("div",{className:"ps-link-warn"},Up):null))}const zr={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function im(){return c.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},c.createElement("line",{x1:"4",y1:"6",x2:"20",y2:"6"}),c.createElement("line",{x1:"4",y1:"12",x2:"20",y2:"12"}),c.createElement("line",{x1:"4",y1:"18",x2:"20",y2:"18"}),c.createElement("circle",{cx:"9",cy:"6",r:"2",fill:"currentColor"}),c.createElement("circle",{cx:"15",cy:"12",r:"2",fill:"currentColor"}),c.createElement("circle",{cx:"8",cy:"18",r:"2",fill:"currentColor"}))}function rm(){return c.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},c.createElement("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),c.createElement("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}))}function om(){return c.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},c.createElement("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),c.createElement("path",{d:"M3 3v5h5"}),c.createElement("path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"}),c.createElement("path",{d:"M21 21v-5h-5"}))}function am(t,e,s){const[n,i]=c.useState({access:null,loading:!1}),r=c.useCallback(()=>{if(!e||s||typeof t.transport.getSessionAccess!="function"){i({access:null,loading:!1});return}let o=!1;return i(a=>({...a,loading:!0})),t.transport.getSessionAccess(e).then(a=>{o||i({access:a,loading:!1})}).catch(()=>{o||i({access:null,loading:!1})}),()=>{o=!0}},[t,e,s]);return c.useEffect(()=>{let o;const a=setTimeout(()=>{o=r()},jp);return()=>{clearTimeout(a),typeof o=="function"&&o()}},[r]),{access:n.access,loading:n.loading,reload:r}}function lm({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:i,principal:r,onClose:o,onSwitchModel:a,onChanged:l}){const[u,f]=c.useState("general"),[d,p]=c.useState(null),[h,m]=c.useState(s||""),[g,S]=c.useState([]),[y,A]=c.useState([]),[x,v]=c.useState("private"),[I,w]=c.useState(""),[C,N]=c.useState("write"),[R,F]=c.useState([]),[L,M]=c.useState(!1),[$,D]=c.useState(null);c.useEffect(()=>{let _=!1;return t.transport.getSessionAccess(e).then(Q=>{!_&&Q&&(p(Q),v(Q.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(Q=>{_||F(Array.isArray(Q)?Q:[])}).catch(()=>{}),()=>{_=!0}},[t,e]);const K=c.useCallback(()=>{t.transport.listSessionShares(e).then(_=>{const Q=Array.isArray(_)?_:[];S(Q),A(Q)}).catch(()=>{S([]),A([])})},[t,e]);c.useEffect(()=>{K()},[K]);const z=async _=>{M(!0),D(null);try{await _(),l?.()}catch(Q){D(Q?.message||String(Q))}finally{M(!1)}},Y=()=>z(async()=>{await t.transport.renameSession(e,h.trim())}),Ie=_=>{const Q=_.trim().toLowerCase();if(!Q)return null;const Oe=R.find(fe=>fe.displayName&&fe.displayName.toLowerCase()===Q||fe.email&&fe.email.toLowerCase()===Q||fe.subject&&fe.subject.toLowerCase()===Q);return Oe||{provider:r?.provider||"dev",subject:_.trim(),email:null,displayName:null}},Z=_=>`${_.provider}${_.subject}`,xe=_=>{const Q=Z(_);A(Oe=>[...Oe.filter(fe=>Z(fe)!==Q),{provider:_.provider,subject:_.subject,email:_.email??null,displayName:_.displayName??null,access:C}]),w("")},b=()=>{const _=Ie(I);_&&xe(_)},O=_=>{const Q=Z(_);A(Oe=>Oe.filter(fe=>Z(fe)!==Q))},G=new Set(y.map(Z)),P=d?.owner?`${d.owner.provider}${d.owner.subject}`:null,k=I.trim().toLowerCase(),B=k?R.filter(_=>{const Q=Z(_);return Q===P||G.has(Q)?!1:_.displayName&&_.displayName.toLowerCase().includes(k)||_.email&&_.email.toLowerCase().includes(k)||_.subject&&_.subject.toLowerCase().includes(k)}).slice(0,25):[],H=!!d?.canManage,V=d?.visibility||"private",X=new Set(y.map(_=>`${Z(_)}:${_.access}`)),Se=new Set(g.map(_=>`${Z(_)}:${_.access}`)),$e=X.size!==Se.size||[...X].some(_=>!Se.has(_)),Fe=H&&(x!==V||$e),Ze=()=>z(async()=>{x!==V&&await t.transport.setSessionVisibility(e,x);const _=new Map(g.map(Be=>[Z(Be),Be])),Q=new Map(y.map(Be=>[Z(Be),Be]));for(const[Be,De]of Q){const li=_.get(Be);(!li||li.access!==De.access)&&await t.transport.grantSessionShare(e,{provider:De.provider,subject:De.subject,email:De.email??null,displayName:De.displayName??null},De.access)}for(const[Be,De]of _)Q.has(Be)||await t.transport.revokeSessionShare(e,{provider:De.provider,subject:De.subject});const Oe=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(Oe)&&(S(Oe),A(Oe));const fe=await t.transport.getSessionAccess(e).catch(()=>null);fe&&(p(fe),v(fe.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),Pt=a||(()=>{o(),t.openSwitchModelPicker().catch(_=>{t.dispatch({type:"ui/status",text:_?.message||String(_)||"Failed to switch model"})})}),Vt=n?i?`${n}:${i}`:n:"—",ct=[{id:"general",label:"General"},...H?[{id:"access",label:"Access"}]:[]],qt=ct.some(_=>_.id===u)?u:"general",za=_=>_.stopPropagation();return c.createElement("div",{className:"ps-share-overlay",onClick:o},c.createElement("div",{className:"ps-share-modal",onClick:za},c.createElement("div",{className:"ps-share-modal-head"},c.createElement("span",null,"Manage session"),c.createElement("button",{className:"ps-modal-close",onClick:o,"aria-label":"Close",title:"Close"},"✕")),c.createElement("div",{className:"ps-manage-tabs",role:"tablist"},ct.map(_=>c.createElement("button",{key:_.id,type:"button",role:"tab","aria-selected":qt===_.id?"true":"false",className:`ps-manage-tab${qt===_.id?" is-active":""}`,onClick:()=>f(_.id)},_.label))),qt==="general"?c.createElement(c.Fragment,null,c.createElement("div",{className:"ps-share-section-label"},"Name"),c.createElement("div",{className:"ps-share-add-row"},c.createElement("input",{className:"ps-share-add-input",placeholder:"Session title",value:h,disabled:L,onChange:_=>m(_.target.value),onKeyDown:_=>{_.key==="Enter"&&Y()}}),c.createElement("button",{className:"ps-mini-button",disabled:L||!h.trim(),onClick:Y},"Save")),c.createElement("div",{className:"ps-share-section-label"},"Model"),c.createElement("div",{className:"ps-share-section-sub"},"The model this session uses on its next turn."),c.createElement("div",{className:"ps-share-add-row"},c.createElement("span",{className:"ps-manage-model-current"},Vt),c.createElement("button",{className:"ps-mini-button",disabled:L,onClick:Pt},"Switch model…"))):null,qt==="access"&&H?c.createElement(c.Fragment,null,c.createElement("div",{className:"ps-share-section-label"},"General access"),c.createElement("div",{className:"ps-share-section-sub"},"The baseline level for everyone signed in to this workspace."),["private","shared_read","shared_write"].map(_=>c.createElement("label",{key:_,className:`ps-share-radio${x===_?" is-active":""}`},c.createElement("input",{type:"radio",name:"visibility",checked:x===_,disabled:L,onChange:()=>v(_)}),c.createElement("span",{className:"ps-share-radio-glyph"},zr[_].glyph),c.createElement("span",null,zr[_].label),c.createElement("span",{className:"ps-share-radio-hint"},_==="private"?"only you and admins":_==="shared_read"?"everyone here can view":"everyone here can view and send"))),c.createElement("div",{className:"ps-share-section-label"},"Special access"),c.createElement("div",{className:"ps-share-section-sub"},"Give specific people more than the general level. A person's grant wins over general access."),y.length===0?c.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):y.map(_=>c.createElement("div",{key:`${_.provider}/${_.subject}`,className:"ps-share-grant-row"},c.createElement("span",{className:"ps-share-grant-name"},_.displayName||_.subject),c.createElement("span",{className:"ps-share-grant-access"},`can ${_.access}`),c.createElement("button",{className:"ps-mini-button",disabled:L,onClick:()=>O(_)},"Remove"))),c.createElement("div",{className:"ps-share-add-wrap"},c.createElement("div",{className:"ps-share-add-row"},c.createElement("input",{className:"ps-share-add-input",placeholder:"Name, email, or id",value:I,disabled:L,autoComplete:"off",onChange:_=>w(_.target.value),onKeyDown:_=>{_.key==="Enter"&&b()}}),c.createElement("select",{className:"ps-share-add-select",value:C,disabled:L,onChange:_=>N(_.target.value)},c.createElement("option",{value:"read"},"can read"),c.createElement("option",{value:"write"},"can write")),c.createElement("button",{className:"ps-mini-button",disabled:L||!I.trim(),onClick:b},"Add")),B.length>0?c.createElement("div",{className:"ps-share-suggestions"},B.map(_=>c.createElement("button",{key:`${_.provider}/${_.subject}`,type:"button",className:"ps-share-suggestion",disabled:L,onClick:()=>xe(_)},c.createElement("span",{className:"ps-share-suggestion-name"},_.displayName||_.subject),_.email?c.createElement("span",{className:"ps-share-suggestion-email"},_.email):null))):null),c.createElement("div",{className:"ps-share-foot-hint"},"Sharing applies to this session and its sub-agents. Suggestions are people who have signed in before — you can also grant by email to someone who hasn't; it takes effect when they first sign in."),c.createElement("div",{className:"ps-manage-apply-bar"},c.createElement("span",{className:"ps-share-section-sub"},Fe?"Unsaved access changes.":"No changes to apply."),c.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:L||!Fe,onClick:Ze},"Apply"))):null,$?c.createElement("div",{className:"ps-share-error"},$):null))}function oi({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const i=q(t,$=>$.ui.themeId),r=Xe(i),o=q(t,$=>{const D=$.sessions.activeSessionId,K=Ms($),z=s||e?K.totalWidth:K.leftWidth,Y=Math.max(20,z-4);return{activeSessionId:D,activeHistory:D&&$.history.bySessionId.get(D)||null,activeOutbox:D&&$.outbox?.bySessionId?.[D]?$.outbox.bySessionId[D]:[],branding:$.branding,connection:$.connection,sessionsById:$.sessions.byId,sessionsFlat:$.sessions.flat,inspectorTab:$.ui.inspectorTab,chatViewMode:$.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(D&&$.sessions.byId[D]?.isGroup),activeSessionStatus:D?String($.sessions.byId[D]?.status||"").toLowerCase():"",focused:$.ui.focusRegion==="chat",scroll:$.ui.scroll.chat,authPrincipal:$.auth?.principal||null,contentWidth:Y}},ke),a=c.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]),l=c.useMemo(()=>Xo(a,{width:o.contentWidth}),[a,o.contentWidth]),u=Zr(!!l.animateTitleRight),f=c.useMemo(()=>eo(l.titleRight,l.animateTitleRight?u:""),[u,l.animateTitleRight,l.titleRight]),d=o.chatViewMode==="rich"&&!o.activeSessionIsGroup,[p,h]=c.useState(!1),m=!!(o.activeHistory?.hasOlderEvents&&Number(o.activeHistory?.loadedEventCount||0)>=Sn),g=c.useMemo(()=>d?Tu(a,o.contentWidth,{tableMode:"sentinel"}):null,[d,a,o.contentWidth]),S=c.useMemo(()=>g?g.map(($,D)=>({text:$.kind==="message"?`m:${$.id??D}:${($.text||"").length}:${$.pendingPhase||""}`:`l:${D}:${($.lines||[]).length}`})):Gn(a,o.contentWidth,{tableMode:"sentinel"}),[g,a,o.contentWidth]),y=Jr(o.activeSessionStatus==="running"),x=c.useMemo(()=>Hn(a,{spinnerFrame:y,maxWidth:o.contentWidth}),[a,y,o.contentWidth]),v=c.useMemo(()=>Un(a,o.contentWidth,{tableMode:"sentinel"}),[a,o.contentWidth]),I=c.useMemo(()=>x.length>0?[...v,...x]:v,[v,x]),{access:w}=am(t,o.activeSessionId,o.activeSessionIsGroup),C=q(t,Qc,ke),N=n&&!o.activeSessionIsGroup&&o.chatViewMode!=="summary",R=!!o.sessionsById?.[o.activeSessionId]?.serviceKind,F=R||!!w&&w.canWrite===!1,L=N?c.createElement("div",{className:"ps-chat-composer"},F?c.createElement("div",{className:"ps-composer-readonly"},R?"⚗ Service session — runtime machinery. Its transcript is a read-only trace; it does not accept messages.":`You have view access to this session. Ask ${w.owner?.displayName||w.owner?.email||"the owner"} for write access to participate.`):c.createElement(pm,{controller:t,mobile:e,active:!0})):null,M=!!(o.activeSessionId&&o.sessionsById[o.activeSessionId]);return C&&!M?c.createElement(lt,{title:l.title,color:l.color,focused:o.focused,theme:r,className:"ps-chat-panel"},c.createElement("div",{className:"ps-empty-state ps-nav-error-state"},c.createElement("div",{className:"ps-nav-error-message"},C.message),C.retryable?c.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(C.sessionId)},"Retry"):null)):c.createElement(Ns,{controller:t,title:(()=>{const $=e?$r(l.title,28):l.title;return d?Yh($):$})(),titleRight:e&&f?$r(f,18):f,actions:null,color:l.color,focused:o.focused,lines:S,bottomStickyLines:I,scrollOffset:o.scroll,scrollMode:"bottom",paneKey:"chat",className:d?"is-wrapped is-rich":"is-wrapped",panelClassName:d?"ps-chat-panel is-rich":"ps-chat-panel",bottomContent:L,topContent:m?c.createElement("div",{className:"ps-load-older-bar"},c.createElement("button",{type:"button",className:"ps-load-older-button",disabled:p,onClick:()=>{h(!0),t.handleCommand(E.EXPAND_HISTORY).catch(()=>{}).finally(()=>h(!1))}},p?"Loading older messages…":"↑ Load older messages")):null,structuredBlocks:!0,renderBody:g?($,D)=>c.createElement(qh,{blocks:g,theme:D,controller:t}):null})}function cm({controller:t}){const e=q(t,o=>{const a=o.files.selectedArtifactId||"";return{filename:a?a.slice(a.indexOf("/")+1):"",origin:o.files.previewOrigin||null,canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},ke),s=!!Oa(e.filename)||ei(e.filename),[n,i]=c.useState(!1);c.useEffect(()=>{i(!1)},[e.filename]);const r=c.useCallback(o=>{t.stepArtifactPreview(o).catch(()=>{})},[t]);return c.createElement("div",{className:"ps-artifact-overlay"},c.createElement("header",{className:"ps-artifact-overlay-bar"},c.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"},"✕"),c.createElement("span",{className:"ps-artifact-overlay-title"},e.filename||"Artifact"),s?c.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,c.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canPrev,onClick:()=>r(-1),"aria-label":"Previous artifact"},"‹"),c.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canNext,onClick:()=>r(1),"aria-label":"Next artifact"},"›")),c.createElement("div",{className:`ps-artifact-overlay-body${n?" is-content-width":""}`},c.createElement(ai,{controller:t,focused:!0,mobile:!0,previewOnly:!0,nativeScroll:!0})))}function um({controller:t}){return c.createElement("div",{className:"ps-mobile-workspace"},c.createElement(ri,{controller:t,panelClassName:"ps-mobile-session-pane"}),c.createElement("div",{className:"ps-mobile-chat-pane"},c.createElement(oi,{controller:t,mobile:!0,fullWidth:!0})))}function qa({activeTab:t,controller:e}){const s=c.useMemo(()=>Zn(e),[e]);return c.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>c.createElement(ie,{key:n,icon:Rp[n]||"•",label:_p[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function ai({controller:t,focused:e,mobile:s=!1,previewOnly:n=!1,nativeScroll:i=!1}){const r=q(t,M=>M.ui.themeId),o=Xe(r),a=c.useRef(null),l=q(t,M=>{const $=M.sessions.activeSessionId,D=Ms(M),K=s||M.files.fullscreen?M.ui.layout?.viewportWidth??120:D.rightWidth;return{activeSessionId:$,sessionsById:M.sessions.byId,sessionsFlat:M.sessions.flat,filesBySessionId:M.files.bySessionId,filesFilter:M.files.filter,selectedArtifactId:M.files.selectedArtifactId,markedIds:M.files.markedIds||[],previewOrigin:M.files.previewOrigin||null,focused:e,previewScroll:M.ui.scroll.filePreview,fullscreen:!!M.files.fullscreen,contentWidth:Math.max(20,K-4),canBrowserUpload:$p(t),canPathUpload:Fp(t),canDeleteArtifacts:Dp(t),canOpenLocally:Hp(t)}},ke),u=c.useMemo(()=>({sessions:{activeSessionId:l.activeSessionId,byId:l.sessionsById,flat:l.sessionsFlat},files:{bySessionId:l.filesBySessionId,selectedArtifactId:l.selectedArtifactId,filter:l.filesFilter,fullscreen:l.fullscreen},ui:{scroll:{filePreview:l.previewScroll}}}),[l.activeSessionId,l.filesBySessionId,l.filesFilter,l.fullscreen,l.previewScroll,l.selectedArtifactId,l.sessionsById,l.sessionsFlat]),f=c.useMemo(()=>Vn(u,{listWidth:Math.max(18,l.contentWidth-4),previewWidth:Math.max(18,l.contentWidth-4),showHints:!1}),[u,l.contentWidth]),d=c.useMemo(()=>nt(u),[u]),p=d.length>0,h=c.useCallback(M=>{const $=Array.isArray(M)?M.filter(Boolean):[];$.length!==0&&t.uploadArtifactFiles($).catch(()=>{})},[t]),m=c.useCallback(()=>{if(l.canBrowserUpload&&a.current){a.current.click();return}l.canPathUpload&&t.handleCommand(E.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,l.canBrowserUpload,l.canPathUpload]),g=c.useMemo(()=>new Set(l.markedIds||[]),[l.markedIds]),S=c.createElement(c.Fragment,null,g.size>0?c.createElement(c.Fragment,null,c.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",opacity:.85},title:"Cmd/Ctrl-click to mark, Shift-click for a range"},`${g.size} marked`),l.canDeleteArtifacts?c.createElement(ie,{icon:"🗑",label:`Delete ${g.size} marked`,onClick:()=>t.deleteMarkedArtifacts().catch(()=>{})}):null,c.createElement(ie,{icon:"✕",label:"Clear marks",onClick:()=>t.clearArtifactMarks()})):null,c.createElement("input",{ref:a,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:M=>{h(Array.from(M.currentTarget.files||[])),M.currentTarget.value=""}}),c.createElement(ie,{icon:"↥",label:"Upload",onClick:m,disabled:!l.canBrowserUpload&&!l.canPathUpload}),c.createElement(ie,{icon:"↧",label:"Download",onClick:()=>t.handleCommand(E.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!p}),l.canDeleteArtifacts?c.createElement(ie,{icon:"✕",label:"Delete",onClick:()=>t.handleCommand(E.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!p}):null,l.canOpenLocally?c.createElement(ie,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(E.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!p}):null,c.createElement(ie,{icon:"▾",label:"Filter",onClick:()=>t.handleCommand(E.OPEN_FILES_FILTER).catch(()=>{})}),c.createElement(ie,{icon:l.fullscreen?"⇱":"⛶",label:l.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(E.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),y=c.useRef(null);c.useEffect(()=>{const M=y.current;M&&typeof M.scrollIntoView=="function"&&M.scrollIntoView({block:"nearest"})},[f.selectedIndex,l.selectedArtifactId]);const A=d.length===0?pe(f.listBodyLines||[]).map((M,$)=>c.createElement(he,{key:`empty:${$}`,line:M,theme:o})):d.map((M,$)=>c.createElement("button",{key:M.id,type:"button",ref:$===f.selectedIndex?y:null,className:`ps-list-button${$===f.selectedIndex?" is-selected":""}`+(g.has(M.id)?" is-marked":""),onClick:D=>{if(t.setFocus("inspector"),D.metaKey||D.ctrlKey){t.toggleArtifactMark(M);return}if(D.shiftKey){t.markArtifactRange(M);return}t.clearArtifactMarks(),t.selectFileBrowserItem(M).then(()=>{s&&t.handleCommand(E.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})}).catch(()=>{})}},c.createElement(he,{line:pe([f.listBodyLines?.[$]])[0],theme:o}))),x=!f.previewLoading&&!f.previewError,v=x&&ei(f.selectedFilename,f.previewContentType)&&!f.previewIsBinary&&!!f.previewContent,I=x&&(Na.test(String(f.previewContentType||""))||Pa.test(String(f.selectedFilename||""))),w=x&&!f.previewIsBinary&&!v&&f.previewRenderMode!=="markdown"&&f.previewContent?Oa(f.selectedFilename):null,C=n?"activity":null,N=i?null:"filePreview",F=x&&!f.previewIsBinary&&ph(f.selectedFilename,f.previewContentType)&&!!f.previewContent?c.createElement(rn,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:N,scrollOffset:l.previewScroll,className:"ps-csv-preview",focusRegion:C},c.createElement(mh,{content:f.previewContent,filename:f.selectedFilename})):I?c.createElement(Wr,{title:null,color:"cyan",focused:!1,theme:o,filename:f.selectedFilename,contentType:f.previewContentType,sizeBytes:f.previewSizeBytes,source:f.previewSource,uploadedAt:f.previewUploadedAt,controller:t,sessionId:f.selectedSessionId}):w?c.createElement(rn,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:N,scrollOffset:l.previewScroll,className:"ps-diff-preview",focusRegion:C},c.createElement("pre",{className:"ps-md-code-pre"},c.createElement("code",null,si(f.previewContent,w,o)))):v?c.createElement(rn,{controller:t,title:null,color:"cyan",focused:!1,theme:o,paneKey:N,scrollOffset:l.previewScroll,className:"ps-diff-preview",focusRegion:C},c.createElement("pre",{className:"ps-md-code-pre is-diff"},c.createElement("code",null,ti(f.previewContent,o)))):f.previewRenderMode==="markdown"&&!f.previewLoading&&!f.previewError?c.createElement($h,{controller:t,title:null,color:"cyan",focused:!1,scrollOffset:l.previewScroll,paneKey:N,theme:o,focusRegion:C,content:dh(f.previewContent||"")}):f.previewIsBinary&&!f.previewLoading&&!f.previewError?c.createElement(Wr,{title:null,color:"cyan",focused:!1,theme:o,filename:f.selectedFilename,contentType:f.previewContentType,sizeBytes:f.previewSizeBytes,source:f.previewSource,uploadedAt:f.previewUploadedAt,controller:t,sessionId:f.selectedSessionId}):c.createElement(Ns,{controller:t,title:null,color:"cyan",focused:!1,lines:f.previewLines,scrollOffset:l.previewScroll,scrollMode:"top",paneKey:N,focusRegion:C,className:"is-preview is-wrapped"}),L=l;return n?F:c.createElement(lt,{title:L.fullscreen?f.fullscreenTitle:s&&f.panelTitleMobile?f.panelTitleMobile:f.panelTitle,color:"magenta",focused:L.focused,actions:S,theme:o},c.createElement(qa,{activeTab:"files",controller:t}),L.fullscreen?F:c.createElement("div",{className:"ps-files-grid is-list-only"},c.createElement("div",{className:"ps-action-list ps-files-list"},A)))}function Bt({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const i=q(t,d=>{const p=Ms(d),h=d.ui.inspectorTab,m=e?d.ui.layout?.viewportWidth??120:p.rightWidth;return{inspectorTab:h,statsViewMode:d.ui.statsViewMode,activeSessionId:d.sessions.activeSessionId,sessionsById:d.sessions.byId,sessionsFlat:d.sessions.flat,historyBySessionId:d.history.bySessionId,sessionStats:d.sessionStats,fleetStats:d.fleetStats,connection:d.connection,orchestrationBySessionId:d.orchestration.bySessionId,executionHistoryBySessionId:d.executionHistory?.bySessionId||{},executionHistoryFormat:d.executionHistory?.format||"pretty",logs:d.logs,files:d.files,focused:d.ui.focusRegion==="inspector",scroll:d.ui.scroll.inspector,followBottom:d.ui.followBottom?.inspector!==!1,logsTailing:d.logs.tailing,filesFullscreen:!!d.files.fullscreen,contentWidth:Jp(m)}},ke),r=c.useMemo(()=>({sessions:{activeSessionId:i.activeSessionId,byId:i.sessionsById,flat:i.sessionsFlat},history:{bySessionId:i.historyBySessionId},sessionStats:i.sessionStats,fleetStats:i.fleetStats,connection:i.connection,ui:{inspectorTab:i.inspectorTab,statsViewMode:i.statsViewMode,scroll:{inspector:i.scroll}},logs:i.logs,files:i.files,orchestration:{bySessionId:i.orchestrationBySessionId},executionHistory:{bySessionId:i.executionHistoryBySessionId,format:i.executionHistoryFormat}}),[i.activeSessionId,i.connection,i.executionHistoryBySessionId,i.executionHistoryFormat,i.fleetStats,i.files,i.historyBySessionId,i.inspectorTab,i.sessionStats,i.statsViewMode,i.logs,i.orchestrationBySessionId,i.scroll,i.sessionsById,i.sessionsFlat]),o=c.useMemo(()=>Je(r,{width:i.contentWidth,allowWideColumns:e}),[e,r,i.contentWidth]),a=c.useMemo(()=>{const d=i.activeSessionId&&i.historyBySessionId?.get(i.activeSessionId)||null,p=new Map;for(const h of d?.events||[]){if(h?.eventType!=="session.turn_completed")continue;const m=Number(h?.data?.turnIndex??h?.data?.iteration);Number.isFinite(m)&&p.set(m,h)}return p},[i.activeSessionId,i.historyBySessionId]),l=c.useCallback((d,p)=>c.createElement(Qh,{lines:d,theme:p,completionByTurn:a}),[a]);if(i.inspectorTab==="files"&&!o.disabled)return c.createElement(ai,{controller:t,focused:i.focused,mobile:e});const u=[];if(i.inspectorTab==="logs")u.push(c.createElement(ie,{key:"tail",icon:i.logsTailing?"■":"⇣",label:i.logsTailing?"Stop tailing":"Tail (follow)",active:i.logsTailing,onClick:()=>t.handleCommand(E.TOGGLE_LOG_TAIL).catch(()=>{})})),u.push(c.createElement(ie,{key:"filter",icon:"▾",label:"Filter",onClick:()=>t.handleCommand(E.OPEN_LOG_FILTER).catch(()=>{})}));else if(i.inspectorTab==="history")u.push(c.createElement(ie,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(E.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),u.push(c.createElement(ie,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(E.EXPORT_EXECUTION_HISTORY).catch(()=>{})}));else if(i.inspectorTab==="stats"){const d={session:"◉",fleet:"⬢",users:"⚇"};for(const p of["session","fleet","users"])u.push(c.createElement(ie,{key:`stats-view:${p}`,icon:d[p],label:`${p.replace(/^./u,h=>h.toUpperCase())} stats`,active:i.statsViewMode===p,onClick:()=>t.setStatsViewMode(p)}))}const f=n?u.concat(n):u;return c.createElement(Ns,{controller:t,title:o.title,color:"magenta",focused:i.focused,actions:f,topContent:c.createElement(qa,{activeTab:o.activeTab,controller:t}),stickyLines:o.stickyLines||[],lines:o.lines,renderBody:o.activeTab==="sequence"?l: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 xn({controller:t,panelClassName:e="",extraActions:s=null}){const n=q(t,o=>{const a=o.sessions.activeSessionId,l=Ms(o),u=Math.max(3,l.activityPaneHeight-2);return{activeSessionId:a,activeSession:a&&o.sessions.byId[a]||null,activeHistory:a&&o.history.bySessionId.get(a)||null,focused:o.ui.focusRegion==="activity",scroll:o.ui.scroll.activity,followBottom:o.ui.followBottom?.activity!==!1,maxLines:u}},ke),i=c.useMemo(()=>({sessions:{activeSessionId:n.activeSessionId,byId:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{}},history:{bySessionId:n.activeSessionId&&n.activeHistory?new Map([[n.activeSessionId,n.activeHistory]]):new Map}}),[n.activeHistory,n.activeSession,n.activeSessionId]),r=c.useMemo(()=>Kn(i,n.maxLines),[i,n.maxLines]);return c.createElement(Ns,{controller:t,title:r.title,color:"gray",focused:n.focused,actions:s,lines:r.lines,scrollOffset:n.scroll,scrollMode:n.followBottom?"bottom":"top",stickyBottom:!0,paneKey:"activity",className:"is-wrapped",panelClassName:`ps-activity-pane${e?` ${e}`:""}`})}const vn=[{id:"sessions",label:"Sessions",side:"left"},{id:"inspector",label:"Inspector",side:"right"},{id:"activity",label:"Activity",side:"right"}];function dm({controller:t,pane:e,onClose:s,mobile:n=!1}){if(!e)return null;let i=null;e==="sessions"?i=c.createElement(ri,{controller:t,panelClassName:"ps-chat-focus-pane",structuredRows:n,actions:c.createElement("button",{type:"button",className:"ps-mini-button ps-overlay-close",onClick:s,"aria-label":"Close",title:"Close"},"✕")}):e==="inspector"?i=c.createElement(Bt,{controller:t,mobile:!1,panelClassName:"ps-chat-focus-pane",extraActions:c.createElement("button",{type:"button",className:"ps-mini-button ps-overlay-close",onClick:s,"aria-label":"Close",title:"Close"},"✕")}):e==="activity"&&(i=c.createElement(xn,{controller:t,panelClassName:"ps-chat-focus-pane",extraActions:c.createElement("button",{type:"button",className:"ps-mini-button ps-overlay-close",onClick:s,"aria-label":"Close",title:"Close"},"✕")}));const r=vn.find(o=>o.id===e);return c.createElement("div",{className:`ps-chat-focus-overlay${r?.side==="left"?" is-left":" is-right"}`},i)}function fm({controller:t,openPane:e,onTogglePane:s,onExitFocus:n,mobile:i=!1}){const r=q(t,a=>a.ui.focusRegion),o=i?c.createElement("div",{className:"ps-chat-focus-rail"},c.createElement("button",{type:"button",className:"ps-mini-button ps-chat-focus-button",onClick:n},"Exit Focus"),c.createElement("button",{type:"button",className:`ps-mini-button ps-chat-focus-button${e==="sessions"?" is-active":""}`,onClick:()=>s("sessions")},"Sessions")):c.createElement("div",{className:"ps-chat-focus-rail"},vn.map(a=>c.createElement("button",{key:a.id,type:"button",className:`ps-mini-button ps-chat-focus-button${e===a.id?" is-active":""}`,"aria-pressed":e===a.id?"true":"false",onClick:()=>s(a.id)},a.label)),c.createElement("div",{className:"ps-chat-focus-status"},e?`Focused: ${vn.find(a=>a.id===e)?.label||e}`:`Focused: ${r==="prompt"?"Prompt":"Chat"}`));return c.createElement("div",{className:"ps-chat-focus-shell"},o,c.createElement("div",{className:"ps-chat-focus-body"},c.createElement(oi,{controller:t,mobile:i,fullWidth:!0}),c.createElement(dm,{controller:t,pane:e,onClose:()=>s(e),mobile:i})))}const Yr=Object.freeze([]);function Qr(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 pm({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const i=q(t,w=>{const C=w.sessions.activeSessionId,N=C&&w.sessions.byId[C]||null,R=C&&w.outbox?.bySessionId?.[C]?w.outbox.bySessionId[C]:[];return{value:w.ui.prompt,cursor:w.ui.promptCursor,focused:w.ui.focusRegion==="prompt",modalOpen:!!w.ui.modal,answerMode:!!N?.pendingQuestion?.question,canStopTurn:jo(N),hasOutbox:R.length>0,hasPendingOutbox:R.some(F=>F?.phase==="pending"),pendingCount:R.filter(F=>F?.phase==="pending").length,editingPending:w.ui.promptEdit?.sessionId===C,selectedOutboxPhase:w.ui.promptEdit?.sessionId===C&&w.ui.promptEdit?.phase||null,promptAttachments:w.ui.promptAttachments||Yr}},ke),r=c.useRef(null),o=c.useRef(null),[a,l]=c.useState(!1),u=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",f=u?i.promptAttachments.filter(w=>w?.kind==="image"):Yr,d=c.useRef(new Map);c.useEffect(()=>{const w=d.current,C=new Set(f.map(N=>N.file));for(const[N,R]of w)C.has(N)||(URL.revokeObjectURL(R),w.delete(N));for(const N of f)if(N.file&&!w.has(N.file))try{w.set(N.file,URL.createObjectURL(N.file))}catch{}},[f]),c.useEffect(()=>()=>{for(const w of d.current.values())URL.revokeObjectURL(w);d.current.clear()},[]);const p=c.useCallback(w=>{if(!u)return 0;const C=Array.from(w||[]).filter(R=>R&&typeof R.type=="string"&&R.type.startsWith("image/"));return C.length===0?0:t.addPendingImageFiles(C)?.accepted||0},[t,u]);c.useEffect(()=>{const w=r.current;if(!(!s||i.modalOpen||!i.focused||!w)){if(document.activeElement!==w)try{w.focus({preventScroll:!0})}catch{w.focus()}w.setSelectionRange(i.cursor,i.cursor)}},[s,i.cursor,i.focused,i.modalOpen]);const h=c.useCallback(()=>{t.handleCommand(E.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[m,g]=c.useState(!1),S=c.useCallback(()=>{g(!0),t.handleCommand(E.STOP_TURN).catch(()=>{}).finally(()=>g(!1))},[t]),y=c.useCallback(()=>{if(t.getState().ui.promptEdit){typeof t.cancelSelectedOutboxPrompt=="function"?t.cancelSelectedOutboxPrompt().catch(()=>{}):t.cancelSelectedPendingPrompt();return}typeof t.cancelLatestQueuedOutbox=="function"&&t.cancelLatestQueuedOutbox().catch(()=>{})},[t]),A=i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"⇪":i.hasOutbox?"+":"❯",x=i.selectedOutboxPhase==="queued",v=i.selectedOutboxPhase==="cancelling",I=x||v;return c.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}${a?" is-drag-over":""}`,...u?{onDragOver:w=>{w.dataTransfer?.types?.includes?.("Files")&&(w.preventDefault(),l(!0))},onDragLeave:w=>{w.currentTarget.contains(w.relatedTarget)||l(!1)},onDrop:w=>{l(!1),w.dataTransfer?.files?.length&&(w.preventDefault(),p(w.dataTransfer.files))}}:{}},f.length>0?c.createElement("div",{className:"ps-prompt-attachments"},f.map((w,C)=>{const N=w.file?d.current.get(w.file):null;return c.createElement("div",{key:`attach:${C}:${w.filename}`,className:"ps-attach-chip",title:`${w.filename} · ${Qr(w.sizeBytes)}`},N?c.createElement("img",{className:"ps-attach-thumb",src:N,alt:w.filename}):c.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),c.createElement("div",{className:"ps-attach-size"},Qr(w.sizeBytes)),c.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${w.filename}`,"aria-label":`Remove attachment ${w.filename}`,onClick:()=>t.removePendingImageAttachment(C)},"✕"))})):null,(()=>{const w=i.answerMode?"answer":v?"cancelling":x?"queued":i.editingPending?"pending":"you";return c.createElement("label",{className:`ps-prompt-label${w==="you"?" is-default":""}`},w)})(),c.createElement("textarea",{ref:r,className:"ps-prompt-input",rows:e?2:Math.max(2,xt(i.value)),value:i.value,readOnly:I,placeholder:i.answerMode?"Type an answer and press Enter":i.editingPending?v?"Cancellation requested":x?"Queued message selected":"Edit the pending message, then send or cancel it":i.hasOutbox?"Type a message and press Enter to queue it behind the pending batch":"Type a message and press Enter",enterKeyHint:"send",onFocus:()=>t.setFocus("prompt"),onSelect:w=>t.setPromptCursor(w.currentTarget.selectionStart||0),onChange:w=>t.setPrompt(w.currentTarget.value,w.currentTarget.selectionStart||w.currentTarget.value.length),onPaste:u?w=>{const N=Array.from(w.clipboardData?.items||[]).filter(R=>R.kind==="file"&&R.type.startsWith("image/")).map(R=>R.getAsFile()).filter(Boolean);N.length>0&&p(N)>0&&w.preventDefault()}:void 0,onKeyDown:w=>{if(w.key==="Tab"&&!w.shiftKey&&t.acceptPromptReferenceAutocomplete()){w.preventDefault();return}if(w.key==="ArrowUp"&&!w.shiftKey&&!w.metaKey&&!w.altKey){w.preventDefault(),t.movePromptCursorVertical(-1);return}if(w.key==="ArrowDown"&&!w.shiftKey&&!w.metaKey&&!w.altKey){w.preventDefault(),t.movePromptCursorVertical(1);return}if(w.key==="Escape"&&i.editingPending){if(w.preventDefault(),I){t.exitPendingPromptEdit({restoreDraft:!0});return}y();return}w.key==="Enter"&&!w.shiftKey&&!w.metaKey&&!e&&(w.preventDefault(),h())}}),c.createElement("div",{className:"ps-prompt-actions"},u?c.createElement(c.Fragment,null,c.createElement("input",{ref:o,type:"file",accept:"image/*",multiple:!0,className:"ps-hidden-file-input","aria-hidden":!0,tabIndex:-1,onChange:w=>{p(w.currentTarget.files),w.currentTarget.value=""}}),c.createElement("button",{type:"button",className:"ps-mini-button ps-attach-button",title:"Attach images (or paste / drop them into the composer)","aria-label":"Attach images",onClick:()=>o.current?.click()},"📎")):null,i.editingPending&&!v?c.createElement("button",{type:"button",className:"ps-mini-button",title:x?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":x?"Delete selected queued prompt":"Cancel selected pending prompt",onClick:y},x?"Delete":"Cancel"):null,i.canStopTurn||m?c.createElement("button",{type:"button",className:`ps-stop-button${m?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:m,onClick:S},"■"):null,c.createElement("button",{type:"button",className:`ps-send-button${e?" is-inline":""}`,title:i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"Send all queued prompts":i.hasOutbox?"Queue prompt behind the pending batch":"Send prompt","aria-label":i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"Send queued prompts":i.hasOutbox?"Queue prompt":"Send prompt",onClick:h},A)))}const hm=1e3;function ie({icon:t,label:e,onClick:s,disabled:n=!1,active:i=!1,className:r="ps-toolbar-button"}){const[o,a]=c.useState(null),l=c.useRef(null),u=c.useRef(null),f=c.useRef(null),d=c.useRef(!1);c.useLayoutEffect(()=>{if(!o||!u.current||typeof window>"u")return;const C=u.current.offsetWidth/2,N=6,R=Math.max(C+N,Math.min(o.x,window.innerWidth-C-N));u.current.style.left=`${R}px`},[o]);const p=(C=!1)=>{const N=l.current;if(!N||typeof window>"u")return;const R=N.getBoundingClientRect(),F=C?R.top-44<0:R.bottom+44<window.innerHeight;a({x:R.left+R.width/2,y:F?R.bottom+6:R.top-6,placement:F?"below":"above"})},h=c.useRef(null),m=c.useRef(null),g=C=>{C.pointerType==="mouse"&&(clearTimeout(f.current),clearTimeout(h.current),f.current=setTimeout(p,hm))},S=C=>{C.pointerType==="mouse"&&(clearTimeout(f.current),clearTimeout(h.current),a(null))},y=C=>{C.pointerType!=="mouse"&&(d.current=!1,m.current={x:C.clientX,y:C.clientY},clearTimeout(f.current),clearTimeout(h.current),f.current=setTimeout(()=>{d.current=!0,p(!0)},450))},A=C=>{if(C.pointerType==="mouse"||!m.current)return;const N=C.clientX-m.current.x,R=C.clientY-m.current.y;N*N+R*R>100&&(m.current=null,clearTimeout(f.current),a(null))},x=C=>{C.pointerType!=="mouse"&&(m.current=null,clearTimeout(f.current),d.current?(clearTimeout(h.current),h.current=setTimeout(()=>a(null),3e3),setTimeout(()=>{d.current=!1},250)):a(null))};c.useEffect(()=>()=>{clearTimeout(f.current),clearTimeout(h.current)},[]);const v=C=>{if(d.current){d.current=!1,C.preventDefault?.();return}n||s?.(C)},I=C=>{C.preventDefault?.()},w=o&&typeof document<"u"&&document.body?wa.createPortal(c.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 c.createElement("button",{ref:l,type:"button",className:`${r} ps-icon-button${i?" is-active":""}`,onClick:v,disabled:n,"aria-label":e,onPointerEnter:g,onPointerLeave:S,onPointerDown:y,onPointerMove:A,onPointerUp:x,onPointerCancel:x,onContextMenu:I},c.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),w)}function mm({controller:t,mobile:e,chatFocusMode:s=!1,onToggleChatFocus:n=null,chatFocusDisabled:i=!1}){const r=q(t,h=>h.ui.chatViewMode==="rich"),[o,a]=c.useState(null);c.useEffect(()=>{typeof document>"u"||a(e?null:document.getElementById("ps-header-toolbar-slot"))},[r,e]);const l=q(t,h=>!!h.admin?.visible),u=q(t,h=>({mode:h.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(h.sessions.activeSessionId&&h.sessions.byId[h.sessions.activeSessionId]?.isGroup)}),ke),f=[{key:"new",icon:"+",label:"New session",onClick:()=>t.handleCommand(E.NEW_SESSION).catch(()=>{})},{key:"model",icon:"+⚙",label:"New session + choose model",onClick:()=>t.handleCommand(E.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:"▾",label:"Filter sessions",onClick:()=>t.handleCommand(E.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:"◑",label:"Theme",onClick:()=>t.handleCommand(E.OPEN_THEME_PICKER).catch(()=>{})},{key:"rich",icon:"Aa",label:u.activeSessionIsGroup?"Groups show group details":u.mode==="rich"?"Show terminal transcript":"Rich chat view (experimental)",onClick:()=>t.setChatViewMode(u.mode==="rich"?"transcript":"rich"),disabled:u.activeSessionIsGroup,active:u.mode==="rich"},{key:"summary",icon:u.mode==="summary"?"💬":"≣",label:u.activeSessionIsGroup?"Groups show group details":u.mode==="summary"?"Show chat transcript":"Show summary",onClick:()=>t.setChatViewMode(u.mode==="summary"?"transcript":"summary"),disabled:u.activeSessionIsGroup,active:u.mode==="summary"},...n?[{key:"focus",icon:s?"⇱":"⛶",label:s?"Exit focus mode":"Focus the chat pane",onClick:n,disabled:i,active:s}]:[],{key:"admin",icon:"⚙",label:l?"Close admin console":"Admin console",onClick:()=>t.handleCommand(l?E.CLOSE_ADMIN_CONSOLE:E.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:l}],d=h=>c.createElement(ie,{key:h.key,icon:h.icon,label:h.label,onClick:h.onClick,disabled:!!h.disabled,active:!!h.active});if(e)return c.createElement("div",{className:"ps-toolbar is-mobile"},c.createElement("div",{className:"ps-toolbar-row ps-toolbar-row-primary"},c.createElement("div",{className:"ps-toolbar-row-actions"},f.map(d))));const p=c.createElement("div",{className:"ps-toolbar"},c.createElement("div",{className:"ps-toolbar-actions"},f.map(d)));return o?wa.createPortal(p,o):p}function gm({controller:t,paneAdjust:e=0}){const s=c.useRef(null),[n,i]=c.useState(!1);return c.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")};let o=0,a=0;const l=()=>{o=0;const f=s.current;if(!f)return;const d=Math.round((a-f.startX)/Ia),p=d-f.appliedCells;p&&(t.adjustPaneSplit(p),f.appliedCells=d)},u=f=>{s.current&&(a=f.clientX,!o&&(o=requestAnimationFrame(l)))};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]),c.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector column. Double-click to reset.","aria-label":"Resize inspector column",onPointerDown: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(E.GROW_RIGHT_PANE).catch(()=>{});return}r.key==="ArrowRight"&&(r.preventDefault(),t.handleCommand(E.GROW_LEFT_PANE).catch(()=>{}))}},c.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"})))}function ym({controller:t,portalSessionColumnAdjust:e=0}){const s=c.useRef(null),[n,i]=c.useState(!1);return c.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")},o=a=>{const l=s.current;if(!l)return;const u=bn(l.startAdjust+(a.clientX-l.startX),l.minAdjust,l.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]),c.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the sessions and chat columns. Double-click to reset.","aria-label":"Resize sessions and chat columns",onPointerDown:r=>{if(r.button!==0)return;r.preventDefault();const o=r.currentTarget.closest(".ps-workspace-main-grid"),a=wn(o?.getBoundingClientRect?.().width);s.current={startX:r.clientX,startAdjust:Number(e)||0,minAdjust:a.minAdjust,maxAdjust:a.maxAdjust},i(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>{t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:0})},onKeyDown:r=>{const o=r.currentTarget.closest(".ps-workspace-main-grid"),a=wn(o?.getBoundingClientRect?.().width),l=u=>{const f=bn((Number(e)||0)+u,a.minAdjust,a.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:f})};if(r.key==="ArrowLeft"){r.preventDefault(),l(-24);return}r.key==="ArrowRight"&&(r.preventDefault(),l(24))}},c.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"}),c.createElement("span",{className:"ps-column-resizer-dot"})))}function Sm({controller:t,activityPaneAdjust:e=0}){const s=c.useRef(null),[n,i]=c.useState(!1);return c.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-y")},o=a=>{const l=s.current;if(!l)return;const u=Math.round((a.clientY-l.startY)/xa),f=u-l.appliedCells;f&&(t.adjustActivityPaneSplit(-f),l.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]),c.createElement("button",{type:"button",className:`ps-row-resizer${n?" is-dragging":""}`,title:"Drag to resize the activity pane. Double-click to reset.","aria-label":"Resize activity pane",onPointerDown: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))}},c.createElement("span",{className:"ps-row-resizer-handle","aria-hidden":"true"},c.createElement("span",{className:"ps-row-resizer-dot"}),c.createElement("span",{className:"ps-row-resizer-dot"}),c.createElement("span",{className:"ps-row-resizer-dot"})))}function bm({activePane:t,setActivePane:e,controller:s}){const n=[{id:"workspace",label:"Main",focus:"chat"},{id:"inspector",label:"Inspector",focus:"inspector"},{id:"activity",label:"Activity",focus:"activity"}];return c.createElement("div",{className:"ps-mobile-nav"},n.map(i=>c.createElement("button",{key:i.id,type:"button",className:`ps-mobile-nav-button${t===i.id?" is-active":""}`,onClick:()=>{e(i.id),s.setFocus(i.focus)}},i.label)))}function wm({controller:t}){const e=q(t,p=>p.ui.themeId),s=Xe(e),n=q(t,p=>({rawModal:p.ui.modal,themePicker:zd(p),modelPicker:wd(p),reasoningEffortPicker:xd(p),contextTierPicker:vd(p),sessionAgentPicker:Id(p),sessionGroupPicker:Ed(p),sessionGroupName:Cd(p),artifactPicker:Pd(p),logFilter:Md(p),filesFilter:Nd(p),historyFormat:qd(p),renameSession:Ad(p),sessionOwnerFilter:kd(p),artifactUpload:Td(p),confirm:Yd(p),logsFilter:p.logs.filter,filesFilterState:p.files.filter,historyFormatState:p.executionHistory?.format||"pretty"}),ke),i=n.rawModal,r=c.useRef(null),o=c.useRef(null),a=c.useRef(null);if(c.useEffect(()=>{if(i?.type!=="renameSession"||!n.renameSession)return;const p=r.current;if(p){if(document.activeElement!==p)try{p.focus({preventScroll:!0})}catch{p.focus()}p.setSelectionRange(n.renameSession.cursorIndex,n.renameSession.cursorIndex)}},[i?.type,n.renameSession?.cursorIndex,n.renameSession?.value]),c.useEffect(()=>{if(i?.type!=="sessionGroupName"||!n.sessionGroupName)return;const p=o.current;if(p){if(document.activeElement!==p)try{p.focus({preventScroll:!0})}catch{p.focus()}p.setSelectionRange(n.sessionGroupName.cursorIndex,n.sessionGroupName.cursorIndex)}},[i?.type,n.sessionGroupName?.cursorIndex,n.sessionGroupName?.value]),c.useEffect(()=>{if(!i||!["themePicker","modelPicker","reasoningEffortPicker","contextTierPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(i.type))return;const p=a.current;if(!p)return;const h=p.querySelector(".ps-list-button.is-selected");h&&typeof h.scrollIntoView=="function"&&h.scrollIntoView({block:"nearest"})},[i?.type,i?.selectedIndex,n.themePicker?.selectedRowIndex,n.modelPicker?.selectedRowIndex,n.reasoningEffortPicker?.selectedRowIndex,n.contextTierPicker?.selectedRowIndex,n.sessionAgentPicker?.selectedRowIndex,n.sessionGroupPicker?.selectedRowIndex,n.artifactPicker?.selectedRowIndex,n.sessionOwnerFilter?.selectedRowIndex,n.logFilter?.selectedRowIndex,n.filesFilter?.selectedRowIndex,n.historyFormat?.selectedRowIndex]),!i)return null;const l=()=>t.handleCommand(E.CLOSE_MODAL).catch(()=>{}),u=(p,h="Apply")=>{const m=Array.isArray(p.rows)?p.rows:[],g=Array.isArray(p.rowItemIndexes)?p.rowItemIndexes:null,S=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",y=g&&g.length===m.length?m.map((A,x)=>{const v=g[x],I=Array.isArray(A)?A:pe([A])[0]?.runs||[{text:A?.text||"",color:A?.color}];if(v==null||v<0)return c.createElement("div",{key:`row:${x}`,className:"ps-line ps-modal-list-heading-line"},c.createElement(me,{runs:I,theme:s}));const w=i.items?.[v];return c.createElement("button",{key:w?.id||`row:${x}`,type:"button",className:`ps-list-button ps-modal-list-button${v===i.selectedIndex?" is-selected":""}${S?" is-hanging":""}${w?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:v})},c.createElement("div",{className:"ps-line ps-modal-list-line"},c.createElement(me,{runs:I,theme:s})))}):(i.items||[]).map((A,x)=>c.createElement("button",{key:A.id||x,type:"button",className:`ps-list-button ps-modal-list-button${x===i.selectedIndex?" is-selected":""}${S?" is-hanging":""}${A?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:x})},c.createElement("div",{className:"ps-line ps-modal-list-line"},c.createElement(me,{runs:Array.isArray(m?.[x])?m[x]:pe([m?.[x]])[0]?.runs||[{text:m?.[x]?.text||"",color:m?.[x]?.color}],theme:s}))));return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:`ps-modal${i.type==="themePicker"?" is-theme-picker":""}`,onClick:A=>A.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},p.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l,"aria-label":"Close",title:"Close"},"✕")),c.createElement("div",{className:"ps-modal-grid"},c.createElement("div",{ref:a,className:"ps-modal-list"},y),c.createElement("div",{className:"ps-modal-details"},c.createElement("div",{className:"ps-modal-details-title"},p.detailsTitle||"Details"),pe(p.detailsLines||[]).map((A,x)=>c.createElement(he,{key:`detail:${x}`,line:A,theme:s,className:"ps-modal-detail-line"})))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(E.MODAL_CONFIRM).catch(()=>{})},h))))};if(i.type==="confirm"&&n.confirm){const p=!!i.alert,h=!p&&i.action==="deleteSession",m=i.action==="regenerateSession",g=i.extras||{};return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:S=>S.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.confirm.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l,"aria-label":"Close",title:"Close"},"✕")),c.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},c.createElement("p",{style:{color:"#94a3b8",margin:0}},n.confirm.message)),m?c.createElement("div",{className:"ps-modal-body",style:{padding:"0 20px 12px",display:"flex",flexDirection:"column",gap:10}},c.createElement("label",{style:{color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8}},"Distillation",c.createElement("select",{className:"ps-modal-input",style:{flex:"1",padding:"4px 8px"},value:g.distillMode||"llm",onChange:S=>t.updateConfirmExtras({distillMode:S.currentTarget.value})},c.createElement("option",{value:"llm"},"Intelligent (LLM reads the whole transcript)"),c.createElement("option",{value:"deterministic"},"Fast (no LLM — tail + pointers)"))),(g.distillMode||"llm")==="llm"?c.createElement(Im,{controller:t,extras:g}):null,(g.distillMode||"llm")==="llm"?c.createElement("textarea",{className:"ps-modal-input",style:{width:"100%",minHeight:"64px",resize:"vertical",fontFamily:"inherit",fontSize:"13px"},placeholder:'Distilling instructions (optional) — e.g. "preserve every SQL snippet verbatim"',value:g.instructions||"",maxLength:4e3,onChange:S=>t.updateConfirmExtras({instructions:S.currentTarget.value})}):null):null,c.createElement("div",{className:"ps-modal-footer"},p?null:c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:`ps-modal-button ${h?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(E.MODAL_CONFIRM).catch(()=>{})},n.confirm.confirmLabel))))}if(i.type==="themePicker"&&n.themePicker)return u(n.themePicker,"Apply Theme");const f=i.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(i.type==="modelPicker"&&n.modelPicker)return u(n.modelPicker,f);if(i.type==="reasoningEffortPicker"&&n.reasoningEffortPicker)return u(n.reasoningEffortPicker,f);if(i.type==="contextTierPicker"&&n.contextTierPicker)return u(n.contextTierPicker,f);if(i.type==="sessionAgentPicker"&&n.sessionAgentPicker)return u(n.sessionAgentPicker,"Create Session");if(i.type==="sessionGroupPicker"&&n.sessionGroupPicker)return u(n.sessionGroupPicker,"Move");if(i.type==="artifactPicker"&&n.artifactPicker)return u(n.artifactPicker,n.artifactPicker.confirmLabel||"Open / Download");if(i.type==="sessionOwnerFilter"&&n.sessionOwnerFilter){const p=n.sessionOwnerFilter,h=Array.isArray(p.rows)?p.rows:[];return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal",onClick:m=>m.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},p.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l,"aria-label":"Close",title:"Close"},"✕")),c.createElement("div",{className:"ps-modal-grid"},c.createElement("div",{ref:a,className:"ps-modal-list"},(i.items||[]).map((m,g)=>c.createElement("button",{key:m.id||g,type:"button",className:`ps-list-button ps-modal-list-button${g===i.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(g)},c.createElement("div",{className:"ps-line ps-modal-list-line"},c.createElement(me,{runs:Array.isArray(h?.[g])?h[g]:pe([h?.[g]])[0]?.runs||[{text:h?.[g]?.text||"",color:h?.[g]?.color}],theme:s}))))),c.createElement("div",{className:"ps-modal-details"},c.createElement("div",{className:"ps-modal-details-title"},p.detailsTitle||"Details"),pe(p.detailsLines||[]).map((m,g)=>c.createElement(he,{key:`detail:${g}`,line:m,theme:s,className:"ps-modal-detail-line"})))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:l},"Done"))))}if(i.type==="renameSession"&&n.renameSession)return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:p=>p.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.renameSession.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l,"aria-label":"Close",title:"Close"},"✕")),c.createElement("input",{ref:r,className:"ps-modal-input",value:n.renameSession.value,placeholder:n.renameSession.placeholder,onChange:p=>t.setRenameSessionValue(p.currentTarget.value,p.currentTarget.selectionStart??p.currentTarget.value.length),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),t.handleCommand(E.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),c.createElement("div",{className:"ps-modal-details"},pe(n.renameSession.helpLines||[]).map((p,h)=>c.createElement(he,{key:`help:${h}`,line:p,theme:s,className:"ps-modal-detail-line"}))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(E.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(i.type==="sessionGroupName"&&n.sessionGroupName)return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:p=>p.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.sessionGroupName.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l,"aria-label":"Close",title:"Close"},"✕")),c.createElement("input",{ref:o,className:"ps-modal-input",value:n.sessionGroupName.value,placeholder:n.sessionGroupName.placeholder,onChange:p=>t.setSessionGroupNameValue(p.currentTarget.value,p.currentTarget.selectionStart??p.currentTarget.value.length),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),t.handleCommand(E.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),c.createElement("div",{className:"ps-modal-details"},pe(n.sessionGroupName.helpLines||[]).map((p,h)=>c.createElement(he,{key:`help:${h}`,line:p,theme:s,className:"ps-modal-detail-line"}))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(E.MODAL_CONFIRM).catch(()=>{})},"Create and Move"))));if(i.type==="terminatePicker"){const p=Number(i.bulkCount)>1,h=!!i.systemRestart,m=String(i.sessionTitle||"").trim()||"this session",g=Number(i.bulkCount)||0,S=p?`What should happen to the ${g} selected sessions? Choose an action; you'll be asked to confirm.`:h?`How should "${m}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${m}"? Choose an action; you'll be asked to confirm.`,y=A=>()=>{t.pickTerminateAction(A).catch(()=>{})};return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:A=>A.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},i.title||"Session Lifecycle"),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l,"aria-label":"Close",title:"Close"},"✕")),c.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},c.createElement("p",{style:{color:"#94a3b8",margin:0}},S)),c.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},i.canRegenerate?c.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},title:"Archive and distill the transcript, then rebuild context fresh at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved.",onClick:y("regenerate")},"Regenerate Context"):null,c.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:y("complete")},p?`Mark ${g} Completed`:h?"Complete & Restart":"Mark Completed"),c.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:y("cancel")},p?`Cancel ${g} Sessions`:h?"Terminate & Restart":"Cancel Session"),c.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:y("delete")},p?`Hard Delete ${g} Sessions`:h?"Hard Delete & Restart":"Delete Session")),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Close"))))}if(i.type==="artifactUpload"&&n.artifactUpload)return c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-narrow",onClick:p=>p.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},n.artifactUpload.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l,"aria-label":"Close",title:"Close"},"✕")),c.createElement("input",{className:"ps-modal-input",value:n.artifactUpload.value,placeholder:n.artifactUpload.placeholder,onChange:p=>t.setArtifactUploadValue(p.currentTarget.value,p.currentTarget.selectionStart||p.currentTarget.value.length),autoFocus:!0}),c.createElement("div",{className:"ps-modal-details"},pe(n.artifactUpload.helpLines||[]).map((p,h)=>c.createElement(he,{key:`help:${h}`,line:p,theme:s,className:"ps-modal-detail-line"}))),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button",onClick:l},"Cancel"),c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(E.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const d=i.type==="logFilter"?n.logFilter:i.type==="filesFilter"?n.filesFilter:i.type==="historyFormat"?n.historyFormat:null;return d?c.createElement("div",{className:"ps-modal-backdrop",onClick:l},c.createElement("div",{className:"ps-modal is-wide",onClick:p=>p.stopPropagation()},c.createElement("div",{className:"ps-modal-header"},c.createElement("div",{className:"ps-modal-title"},d.title),c.createElement("button",{type:"button",className:"ps-modal-close",onClick:l,"aria-label":"Close",title:"Close"},"✕")),c.createElement("div",{className:"ps-filter-grid"},(i.items||[]).map((p,h)=>{const m=i.type==="filesFilter"?n.filesFilterState?.[p.id]||p.options?.[0]?.id:i.type==="historyFormat"?n.historyFormatState:n.logsFilter?.[p.id]||p.options?.[0]?.id;return c.createElement("div",{key:p.id||h,className:"ps-filter-column"},c.createElement("div",{className:"ps-filter-title"},p.label),(p.options||[]).map(g=>c.createElement("button",{key:g.id,type:"button",className:`ps-filter-option${g.id===m?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:h}),i.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:g.id}):i.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[p.id]:g.id}}),t.ensureFilesForScope(g.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[p.id]:g.id}})}},g.label)))})),c.createElement("div",{className:"ps-modal-footer"},c.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:l},"Done")))):null}function Im({controller:t,extras:e}){const s=Array.isArray(e.distillerModelOptions)?e.distillerModelOptions:[],n=s.find(u=>u.qualifiedName===e.distillerModel)||null,i=n?.supportedReasoningEfforts||[],r=n?.supportedContextTiers||[],o={color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8},a={flex:"1",padding:"4px 8px"},l=u=>t.updateConfirmExtras(u);return c.createElement(c.Fragment,null,c.createElement("label",{style:o},"Distiller model",c.createElement("select",{className:"ps-modal-input",style:a,value:e.distillerModel||"",onChange:u=>l({distillerModel:u.currentTarget.value,distillerEffort:"",distillerContextTier:""})},c.createElement("option",{value:""},"Deployment default"),s.map(u=>c.createElement("option",{key:u.qualifiedName,value:u.qualifiedName},u.qualifiedName)))),i.length>0?c.createElement("label",{style:o},"Reasoning",c.createElement("select",{className:"ps-modal-input",style:a,value:e.distillerEffort||"",onChange:u=>l({distillerEffort:u.currentTarget.value})},c.createElement("option",{value:""},"Model default"),i.map(u=>c.createElement("option",{key:u,value:u},u)))):null,r.length>0?c.createElement("label",{style:o},"Context",c.createElement("select",{className:"ps-modal-input",style:a,value:e.distillerContextTier||"",onChange:u=>l({distillerContextTier:u.currentTarget.value})},c.createElement("option",{value:""},"Model default"),r.map(u=>c.createElement("option",{key:u,value:u},u==="long_context"?"long context (fits a larger transcript)":u)))):null)}function xm(t,e){c.useEffect(()=>{const s=n=>{const i=n.target,r=i instanceof HTMLElement&&(i.tagName==="TEXTAREA"||i.tagName==="INPUT"||i.tagName==="SELECT"||i.isContentEditable),o=t.getState().ui.modal,a=Zn(t),l=t.getState().ui.inspectorTab,u=t.getState().ui.focusRegion,f=!n.metaKey&&!n.ctrlKey&&!n.altKey,d=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="T"&&n.shiftKey,p=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="N"&&n.shiftKey,h=m=>{const g=Lp(a,l,m);t.selectInspectorTab(g).catch(()=>{})};if(!r&&d){n.preventDefault(),t.handleCommand(E.OPEN_THEME_PICKER).catch(()=>{});return}if(!r&&p){n.preventDefault(),t.handleCommand(E.OPEN_MODEL_PICKER).catch(()=>{});return}if(o&&!r){if(n.key==="Escape"||o.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(E.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||o.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(E.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(E.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(E.MODAL_PANE_NEXT).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(E.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(E.MODAL_NEXT).catch(()=>{}));return}if(!r){if(n.key==="r"&&f&&u!=="prompt"){n.preventDefault(),t.handleCommand(E.REFRESH).catch(()=>{});return}if(u==="chat"&&n.key==="s"&&f){n.preventDefault(),t.handleCommand(E.TOGGLE_CHAT_VIEW).catch(()=>{});return}if(n.key==="n"&&f){n.preventDefault(),t.handleCommand(E.NEW_SESSION).catch(()=>{});return}if(u==="inspector"&&l==="files"&&(n.key==="u"&&f||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(E.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(u==="inspector"&&l==="files"&&n.key==="a"&&f){n.preventDefault(),t.handleCommand(E.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&l==="files"&&n.key==="x"&&f){n.preventDefault(),t.handleCommand(E.DELETE_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&l==="files"&&n.key==="o"&&f){n.preventDefault(),t.handleCommand(E.OPEN_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&l==="files"&&n.key==="f"&&f){n.preventDefault(),t.handleCommand(E.OPEN_FILES_FILTER).catch(()=>{});return}if(u==="inspector"&&l==="stats"&&n.key==="f"&&f){n.preventDefault(),t.handleCommand(E.TOGGLE_STATS_VIEW).catch(()=>{});return}if(u==="inspector"&&l==="files"&&n.key==="v"&&f){n.preventDefault(),t.handleCommand(E.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(u==="inspector"&&l==="logs"&&n.key==="t"&&f){n.preventDefault(),t.handleCommand(E.TOGGLE_LOG_TAIL).catch(()=>{});return}if(u==="inspector"&&l==="logs"&&n.key==="f"&&f){n.preventDefault(),t.handleCommand(E.OPEN_LOG_FILTER).catch(()=>{});return}if(u==="inspector"&&l==="history"&&n.key==="f"&&f){n.preventDefault(),t.handleCommand(E.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(u==="inspector"&&l==="history"&&n.key==="r"&&f){n.preventDefault(),t.handleCommand(E.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(u==="inspector"&&l==="history"&&n.key==="a"&&f){n.preventDefault(),t.handleCommand(E.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&f){n.preventDefault(),t.handleCommand(E.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&f){n.preventDefault(),t.handleCommand(E.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&f){n.preventDefault(),t.handleCommand(E.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&f){n.preventDefault(),t.handleCommand(E.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(E.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&f&&u==="inspector"){n.preventDefault(),h(1);return}if(n.key==="["&&f){n.preventDefault(),t.handleCommand(E.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&f){n.preventDefault(),t.handleCommand(E.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&f){n.preventDefault(),t.handleCommand(E.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&f){n.preventDefault(),t.handleCommand(E.GROW_SESSION_PANE).catch(()=>{});return}if(u==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),h(-1);return}if(u==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),h(1);return}if(u==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(E.MOVE_SESSION_UP).catch(()=>{});return}if(u==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(E.MOVE_SESSION_DOWN).catch(()=>{});return}if(u==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(E.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(u==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(E.PAGE_UP).catch(()=>{});return}if(u==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(E.PAGE_DOWN).catch(()=>{});return}if(u==="sessions"&&n.key==="t"&&f){n.preventDefault(),t.handleCommand(E.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(E.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(E.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&f){n.preventDefault(),t.handleCommand(E.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(E.SCROLL_BOTTOM).catch(()=>{});return}if(u!=="prompt"&&n.key==="h"&&f){n.preventDefault(),t.handleCommand(E.FOCUS_LEFT).catch(()=>{});return}if(u!=="prompt"&&n.key==="l"&&f){n.preventDefault(),t.handleCommand(E.FOCUS_RIGHT).catch(()=>{});return}if(!e&&u==="inspector"&&l==="files"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(E.MOVE_FILE_UP).catch(()=>{});return}if(!e&&u==="inspector"&&l==="files"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(E.MOVE_FILE_DOWN).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(E.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(E.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(E.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function vm(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 Em({controller:t}){const e=q(t,Wu,ke),s=c.useRef(null);c.useEffect(()=>{if(e.ghcpKey.editing){const d=window.requestAnimationFrame(()=>{s.current&&s.current.focus()});return()=>window.cancelAnimationFrame(d)}},[e.ghcpKey.editing]);const n=c.useCallback(()=>{t.closeAdminConsole()},[t]),i=c.useCallback(()=>{t.refreshAdminProfile().catch(()=>{})},[t]),r=c.useCallback(()=>{t.beginAdminEditGhcpKey()},[t]),o=c.useCallback(()=>{t.cancelAdminEditGhcpKey()},[t]),a=c.useCallback(()=>{t.clearAdminGhcpKey().catch(()=>{})},[t]),l=c.useCallback(d=>{d.preventDefault(),t.saveAdminGhcpKey().catch(()=>{})},[t]),u=c.useCallback(d=>{t.setAdminGhcpKeyDraft(d.target.value)},[t]),f=vm(e.principal);return c.createElement("div",{className:"ps-admin-console"},c.createElement("header",{className:"ps-admin-console__header"},c.createElement("h2",null,"Admin Console"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:n},"Close")),c.createElement("section",{className:"ps-admin-console__identity"},c.createElement("dl",null,c.createElement("dt",null,"Signed in as"),c.createElement("dd",null,f))),e.loadError?c.createElement("div",{className:"ps-admin-console__error",role:"alert"},e.loadError):null,c.createElement("section",{className:"ps-admin-console__section"},c.createElement("h3",null,"GitHub Copilot key"),e.ghcpKey.storeAsSystem?c.createElement("p",{className:"ps-admin-console__hint"},"System-wide key for platform-managed (ownerless) system ","sessions — agent tuners, repo cache managers, and other ","sessions with no owner resolve this key for GitHub Copilot ","models. Clearing it reverts them to the worker default."):c.createElement("p",{className:"ps-admin-console__hint"},"Per-user override for the GitHub Copilot model provider token. ","When set, this key is used instead of the worker's env-supplied ","GITHUB_TOKEN for sessions you own. Clearing the key reverts to ","the worker default."),e.isAdmin&&e.systemGhcpKey.supported?c.createElement("label",{className:"ps-admin-console__system-toggle"},c.createElement("input",{type:"checkbox",checked:e.ghcpKey.storeAsSystem,disabled:e.ghcpKey.saving,onChange:d=>t.setAdminGhcpKeyStoreAsSystem(d.target.checked)}),"Store as System key"):null,c.createElement("p",{className:`ps-admin-console__status${e.ghcpKey.error?" is-error":""}`},e.ghcpKey.error||e.ghcpKey.statusText),e.ghcpKey.editing?c.createElement("form",{className:"ps-admin-console__form",onSubmit:l},c.createElement("input",{ref:s,type:"password",autoComplete:"off",spellCheck:!1,value:e.ghcpKey.draft,disabled:e.ghcpKey.saving,placeholder:"Paste GitHub Copilot key",onChange:u}),c.createElement("div",{className:"ps-admin-console__actions"},c.createElement("button",{type:"submit",className:"ps-primary-button",disabled:e.ghcpKey.saving},e.ghcpKey.saving?"Saving...":"Save"),c.createElement("button",{type:"button",className:"ps-mini-button",onClick:o,disabled:e.ghcpKey.saving},"Cancel"))):c.createElement("div",{className:"ps-admin-console__actions"},c.createElement("button",{type:"button",className:"ps-primary-button",onClick:r},e.ghcpKey.targetConfigured?e.ghcpKey.storeAsSystem?"Replace System key":"Replace key":e.ghcpKey.storeAsSystem?"Set System key":"Set key"),e.ghcpKey.targetConfigured?c.createElement("button",{type:"button",className:"ps-mini-button",onClick:a},e.ghcpKey.storeAsSystem?"Clear System key":"Clear key"):null,c.createElement("button",{type:"button",className:"ps-mini-button",onClick:i},e.loading?"Refreshing...":"Refresh"))))}function Cm({transport:t,mode:e="remote",branding:s=null}={}){Vp();const n=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches,i=mf(hf,Nc({mode:e,branding:s,chatViewMode:n?"transcript":"rich"}));return new cp({store:i,transport:t})}function Tm({controller:t}){const e=q(t,k=>k.ui.chatViewMode==="rich");c.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-rich-ui",e),()=>document.body.classList.remove("ps-rich-ui")},[e]);const s=c.useRef(null),n=c.useRef(null),i=Fr(s),r=Fr(n),o=eh(i);c.useEffect(()=>{const k=()=>{const V=document.createElement("span");V.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const X=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");X&&(V.style.font=window.getComputedStyle(X).font),V.textContent="0".repeat(100),(X?.parentElement||document.body).appendChild(V);const Se=V.getBoundingClientRect().width/100||8;V.remove(),t.dispatch({type:"ui/viewport",width:Math.floor(window.innerWidth/Se),height:Math.floor(window.innerHeight/Ue)})};k();let B;const H=()=>{clearTimeout(B),B=setTimeout(k,150)};return window.addEventListener("resize",H),window.addEventListener("orientationchange",H),()=>{clearTimeout(B),window.removeEventListener("resize",H),window.removeEventListener("orientationchange",H)}},[t]);const[a,l]=c.useState(!1),[u,f]=c.useState(null),d=q(t,k=>({themeId:k.ui.themeId,ownerFilter:k.sessions.ownerFilter,pinnedIds:k.sessions.pinnedIds,collapsedSessionIds:k.sessions.collapsedIds,activeSessionId:k.sessions.activeSessionId||null,promptRows:Ta(k),chatViewMode:k.ui.chatViewMode||"transcript",activeSessionIsGroup:!!(k.sessions.activeSessionId&&k.sessions.byId[k.sessions.activeSessionId]?.isGroup),paneAdjust:k.ui.layout?.paneAdjust??0,sessionPaneAdjust:k.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:k.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:k.ui.layout?.activityPaneAdjust??0,focusRegion:k.ui.focusRegion,inspectorTab:k.ui.inspectorTab,filesFullscreen:!!k.files.fullscreen,selectedArtifactId:k.files.selectedArtifactId||null,adminVisible:!!k.admin?.visible}),ke),p=c.useRef(!1),h=c.useRef(null),m=c.useRef(null),g=c.useRef(null),S=c.useRef(null),y=c.useRef(!1),A=c.useRef(!1),x=c.useRef(null),v=c.useRef(null),[I,w]=c.useState("workspace"),C=(i.width||window.innerWidth||0)<vp,R=d.activeSessionIsGroup||d.chatViewMode==="summary"?0:d.promptRows;xm(t,C),c.useEffect(()=>{t.setViewport(o)},[t,o.height,o.width]),c.useEffect(()=>{let k=!0;p.current=!1,h.current=null,x.current=null,v.current=Rr(t.getState()),g.current&&(clearTimeout(g.current),g.current=null),S.current&&(clearInterval(S.current),S.current=null),y.current=!1,A.current=!1;const B=t.transport;if(typeof B?.getCurrentUserProfile!="function"||typeof B?.setCurrentUserProfileSettings!="function")return p.current=!0,()=>{k=!1};const H=async()=>{if(!(!k||y.current)){y.current=!0;try{const V=await B.getCurrentUserProfile();if(!k)return;const X=ot(V?.profileSettings);jt(X[ws()])&&(m.current=X[ws()]),v.current=Rr(t.getState(),m.current);const Se=zp(V?.profileSettings,v.current),$e=JSON.stringify(Se),Fe=tn(t.getState(),m.current),Ze=JSON.stringify(Fe),Pt=p.current&&h.current!=null&&Ze!==h.current;!(g.current||A.current||Pt)&&x.current!==$e&&(t.dispatch({type:"profileSettings/apply",settings:Se}),x.current=$e);const ct=tn(t.getState(),m.current);h.current=JSON.stringify(ct),p.current=!0}catch{if(!k)return;p.current=!0}finally{y.current=!1}}};return H().catch(()=>{}),S.current=setInterval(()=>{H().catch(()=>{})},Mp),()=>{k=!1,g.current&&(clearTimeout(g.current),g.current=null),S.current&&(clearInterval(S.current),S.current=null),y.current=!1}},[t]),c.useEffect(()=>{if(!p.current)return;const k=tn(d,m.current),B=JSON.stringify(k);h.current!==B&&(h.current=B,g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{g.current=null,A.current=!0,Yp(t,k).catch(()=>{}).finally(()=>{A.current=!1})},400))},[t,d.activeSessionId,d.activityPaneAdjust,d.chatViewMode,d.collapsedSessionIds,d.ownerFilter,d.paneAdjust,d.pinnedIds,d.portalSessionColumnAdjust,d.sessionPaneAdjust,d.themeId]),c.useEffect(()=>{Zp(d.themeId)},[d.themeId]);const F=c.useRef(null);c.useEffect(()=>{const k=F.current;F.current=d.focusRegion,k!==null&&k!==d.focusRegion&&C&&d.focusRegion!=="prompt"&&w(d.focusRegion==="activity"?"activity":d.focusRegion==="inspector"?"inspector":"workspace")},[C,d.focusRegion]),c.useEffect(()=>{const k=Zn(t);!k.includes(d.inspectorTab)&&k.length>0&&t.selectInspectorTab(k[0]).catch(()=>{})},[t,d.inspectorTab]);const L=c.useMemo(()=>Dt(o,d.paneAdjust,R,d.sessionPaneAdjust,d.activityPaneAdjust),[o,d.activityPaneAdjust,d.paneAdjust,R,d.sessionPaneAdjust]),M=d.filesFullscreen&&d.inspectorTab==="files",$=d.inspectorTab==="files"&&!!d.selectedArtifactId&&!M;c.useEffect(()=>{!M||!a||(l(!1),f(null))},[a,M]);const D=c.useCallback(()=>{l(k=>{const B=!k;return B?t.setFocus("chat"):f(null),B})},[t]),K=c.useCallback(k=>{f(B=>{const H=B===k?null:k;return t.setFocus(H||"chat"),H})},[t]),z=Math.max(0,(i.width||0)*.68),Y=r.width||z,Ie=Qp(Y,d.portalSessionColumnAdjust),Z=Xp(Ie),xe=Z==="hidden"?"0px":`clamp(0px, calc(${Jn*100}% + ${Number(d.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,b=c.createElement("div",{className:"ps-workspace-grid",style:{gridTemplateColumns:`minmax(0, ${L.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${L.rightWidth}fr)`}},c.createElement("div",{ref:n,className:`ps-workspace-main-grid is-session-${Z}`,style:{gridTemplateColumns:`${xe} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},Z!=="hidden"?c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},c.createElement(ri,{controller:t,structuredRows:!0})):null,c.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},c.createElement(ym,{controller:t,portalSessionColumnAdjust:d.portalSessionColumnAdjust})),c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},c.createElement(oi,{controller:t}))),c.createElement(gm,{controller:t,paneAdjust:d.paneAdjust}),c.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`${L.inspectorPaneHeight}fr var(--ps-resizer-track, 16px) ${L.activityPaneHeight}fr`}},c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},L.inspectorHidden?null:c.createElement(Bt,{controller:t,mobile:!1})),c.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},c.createElement(Sm,{controller:t,activityPaneAdjust:d.activityPaneAdjust})),c.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},$?c.createElement(ai,{controller:t,focused:!1,previewOnly:!0}):L.activityHidden?null:c.createElement(xn,{controller:t})))),O=c.createElement(fm,{controller:t,openPane:u,onTogglePane:K,onExitFocus:D,mobile:C}),G=c.createElement("div",{className:"ps-workspace-full"},c.createElement(Bt,{controller:t,mobile:!1}));let P=null;return M&&!C?P=c.createElement("div",{className:"ps-mobile-pane-fill"},c.createElement(Bt,{controller:t,mobile:!0})):I==="inspector"?P=c.createElement("div",{className:"ps-mobile-pane-fill"},c.createElement(Bt,{controller:t,mobile:!0})):I==="activity"?P=c.createElement("div",{className:"ps-mobile-pane-fill"},c.createElement(xn,{controller:t})):P=c.createElement(um,{controller:t}),c.createElement(Ra.Provider,{value:t},c.createElement("div",{ref:s,className:"ps-web-shell"},C&&(a||I==="inspector"||I==="activity")?null:c.createElement(mm,{controller:t,mobile:C,chatFocusMode:a,onToggleChatFocus:D,chatFocusDisabled:M}),c.createElement("div",{className:"ps-workspace"},d.adminVisible?c.createElement(Em,{controller:t}):M?G:a?O:C?P:b),C&&!a?c.createElement(bm,{activePane:I,setActivePane:w,controller:t}):null,C&&M?c.createElement(cm,{controller:t}):null,c.createElement(wm,{controller:t})))}export{Tm as P,c as R,ba as _,Za as a,Ku as b,Cm as c,Ya as g,Xr as r,Am as s};
|