pilotswarm 0.5.44 → 0.5.47
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/mcp/README.md +12 -0
- package/mcp/dist/src/context.d.ts.map +1 -1
- package/mcp/dist/src/context.js +9 -1
- package/mcp/dist/src/context.js.map +1 -1
- package/mcp/dist/src/tools/agent-packages.d.ts.map +1 -1
- package/mcp/dist/src/tools/agent-packages.js +31 -0
- package/mcp/dist/src/tools/agent-packages.js.map +1 -1
- package/mcp/dist/src/tools/providers.d.ts.map +1 -1
- package/mcp/dist/src/tools/providers.js +15 -3
- package/mcp/dist/src/tools/providers.js.map +1 -1
- package/mcp/dist/src/util/respond.d.ts.map +1 -1
- package/mcp/dist/src/util/respond.js +6 -0
- package/mcp/dist/src/util/respond.js.map +1 -1
- package/package.json +2 -2
- package/tui/src/agents-cli.js +35 -0
- package/tui/src/app.js +7 -11
- package/tui/src/node-sdk-transport.js +70 -0
- package/ui/core/src/controller.js +313 -74
- package/ui/core/src/history.js +65 -10
- package/ui/core/src/reducer.js +51 -4
- package/ui/core/src/selectors.js +101 -20
- package/ui/core/src/state.js +11 -0
- package/ui/react/src/components.js +1 -0
- package/ui/react/src/web-app.js +938 -127
- package/web/api/canvas-plane.js +18 -6
- package/web/api/ws.js +22 -2
- package/web/auth/index.js +8 -1
- package/web/auth/normalize/entra.js +5 -1
- package/web/dist/assets/{abnfDiagram-VRR7QNED-67Q0WWge.js → abnfDiagram-VRR7QNED-VPL8m_9W.js} +1 -1
- package/web/dist/assets/{arc-BvcYFngS.js → arc-T5I3-c1B.js} +1 -1
- package/web/dist/assets/{architectureDiagram-ZJ3FMSHR-CPBN0rk8.js → architectureDiagram-ZJ3FMSHR-DEP70bg6.js} +1 -1
- package/web/dist/assets/{blockDiagram-677ZJIJ3-D_hp1Oah.js → blockDiagram-677ZJIJ3-CvBu1MbO.js} +1 -1
- package/web/dist/assets/{c4Diagram-LMCZKHZV-DAOVGMIW.js → c4Diagram-LMCZKHZV-B5qwF4gm.js} +1 -1
- package/web/dist/assets/channel-D5LojeMw.js +1 -0
- package/web/dist/assets/{chunk-2Q5K7J3B-DajZuaot.js → chunk-2Q5K7J3B-zVW8dS7X.js} +1 -1
- package/web/dist/assets/{chunk-32BRIVSS-C6pXBsgt.js → chunk-32BRIVSS-DWctxZZS.js} +1 -1
- package/web/dist/assets/{chunk-5VM5RSS4-780edrmi.js → chunk-5VM5RSS4-Bq7_Vmf9.js} +1 -1
- package/web/dist/assets/{chunk-EX3LRPZG-C0e4NVuz.js → chunk-EX3LRPZG-B8CFB3v-.js} +1 -1
- package/web/dist/assets/{chunk-JWPE2WC7-uRe83I6C.js → chunk-JWPE2WC7-B7gLPjgZ.js} +1 -1
- package/web/dist/assets/{chunk-MOJQB5TN-B0WPoPjh.js → chunk-MOJQB5TN-B2x6q12r.js} +1 -1
- package/web/dist/assets/{chunk-RYQCIY6F-eRFuHHyG.js → chunk-RYQCIY6F-XorU9Stx.js} +1 -1
- package/web/dist/assets/{chunk-V7JOEXUC-C8FDXprk.js → chunk-V7JOEXUC-CsLa6pw5.js} +1 -1
- package/web/dist/assets/{chunk-VR4S4FIN-DPFpLQdB.js → chunk-VR4S4FIN-BBv9mwmj.js} +1 -1
- package/web/dist/assets/{chunk-XXDRQBXY-CoGQOPKW.js → chunk-XXDRQBXY-Cjm4mm6l.js} +1 -1
- package/web/dist/assets/classDiagram-OUVF2IWQ-C5edc5Or.js +1 -0
- package/web/dist/assets/classDiagram-v2-EOCWNBFH-C5edc5Or.js +1 -0
- package/web/dist/assets/{cose-bilkent-JH36ORCC-BTBSfO5v.js → cose-bilkent-JH36ORCC-Zw9ZQbVl.js} +1 -1
- package/web/dist/assets/{cynefin-VYW2F7L2-DgTkQEoK.js → cynefin-VYW2F7L2-BYnR9YLM.js} +1 -1
- package/web/dist/assets/{cynefinDiagram-TSTJHNR4-DiBMlKoP.js → cynefinDiagram-TSTJHNR4-Cx8L0dOv.js} +1 -1
- package/web/dist/assets/{dagre-VKFMJZFB-Qv-4dcbk.js → dagre-VKFMJZFB-7GaqVcqz.js} +1 -1
- package/web/dist/assets/{diagram-FQU43EPY-CgyAb7yx.js → diagram-FQU43EPY-BWSRPJvU.js} +1 -1
- package/web/dist/assets/{diagram-G47NLZAW-BxN-KcGp.js → diagram-G47NLZAW-BELuAE1e.js} +1 -1
- package/web/dist/assets/{diagram-NH7WQ7WH-BiellpWz.js → diagram-NH7WQ7WH-DGXhPpri.js} +1 -1
- package/web/dist/assets/{diagram-OA4YK3LP-C8Ktgrwv.js → diagram-OA4YK3LP-DV8HqN0T.js} +1 -1
- package/web/dist/assets/{diagram-WEI45ONY-Bj5K1X91.js → diagram-WEI45ONY-Clv1X3ZL.js} +1 -1
- package/web/dist/assets/{ebnfDiagram-CCIWWBDH-DNQI2XT9.js → ebnfDiagram-CCIWWBDH-TpQx36oi.js} +1 -1
- package/web/dist/assets/{erDiagram-Q63AITRT-D5Xkllu6.js → erDiagram-Q63AITRT-DVVWd00c.js} +1 -1
- package/web/dist/assets/{flowDiagram-23GEKE2U-DJpTtMuj.js → flowDiagram-23GEKE2U-Cdz_8_Dw.js} +1 -1
- package/web/dist/assets/{ganttDiagram-NO4QXBWP-C-EQlCJf.js → ganttDiagram-NO4QXBWP-zlco-o7u.js} +1 -1
- package/web/dist/assets/{gitGraphDiagram-IHSO6WYX-C8vpSbvW.js → gitGraphDiagram-IHSO6WYX-CfAZW1En.js} +1 -1
- package/web/dist/assets/index-CMtzFJre.css +1 -0
- package/web/dist/assets/index-tQXCQojP.js +24 -0
- package/web/dist/assets/{infoDiagram-FWYZ7A6U-CKNzsR3r.js → infoDiagram-FWYZ7A6U-0R-8efwI.js} +1 -1
- package/web/dist/assets/{ishikawaDiagram-FXEZZL3T-CjyQq3lf.js → ishikawaDiagram-FXEZZL3T-lPpoXGlp.js} +1 -1
- package/web/dist/assets/{journeyDiagram-5HDEW3XC-CK3EEkJt.js → journeyDiagram-5HDEW3XC-D05vSVqu.js} +1 -1
- package/web/dist/assets/{kanban-definition-HUTT4EX6-CHQ8YkPx.js → kanban-definition-HUTT4EX6-ClaDdESv.js} +1 -1
- package/web/dist/assets/{linear-CUYirs1h.js → linear-CUnhHMvY.js} +1 -1
- package/web/dist/assets/{mermaid.core-Di8sQC4g.js → mermaid.core-DaYS-X8Y.js} +4 -4
- package/web/dist/assets/{mindmap-definition-LN4V7U3C-D38dmHP5.js → mindmap-definition-LN4V7U3C-N480VHds.js} +1 -1
- package/web/dist/assets/{papaparse.min-DWBU_pXS.js → papaparse.min-CNTcNgd8.js} +1 -1
- package/web/dist/assets/{pegDiagram-2B236MQR-BU759QCo.js → pegDiagram-2B236MQR-CVWyJ5ck.js} +1 -1
- package/web/dist/assets/{pieDiagram-ENE6RG2P-BbpfHbsj.js → pieDiagram-ENE6RG2P-UR9uohPf.js} +1 -1
- package/web/dist/assets/pilotswarm-BG6hk0oE.js +97 -0
- package/web/dist/assets/{quadrantDiagram-ABIIQ3AL-BYZ3XHZn.js → quadrantDiagram-ABIIQ3AL-D2SIOetn.js} +1 -1
- package/web/dist/assets/{railroadDiagram-RFXS5EU6-D18gkZBJ.js → railroadDiagram-RFXS5EU6-OgN6qgOU.js} +1 -1
- package/web/dist/assets/{requirementDiagram-TGXJPOKE-D6vo26Ib.js → requirementDiagram-TGXJPOKE-BSUURBBz.js} +1 -1
- package/web/dist/assets/{sankeyDiagram-HTMAVEWB-CxQwXnRE.js → sankeyDiagram-HTMAVEWB-BBZhmSBZ.js} +1 -1
- package/web/dist/assets/{sequenceDiagram-DBY2YBRQ-CfGisw4A.js → sequenceDiagram-DBY2YBRQ-C10IDNdW.js} +1 -1
- package/web/dist/assets/{sizeCapture-X5ZJPWSS-BDK7-yA-.js → sizeCapture-X5ZJPWSS-B9787MHa.js} +1 -1
- package/web/dist/assets/{stateDiagram-2N3HPSRC-8IyidYSV.js → stateDiagram-2N3HPSRC-BmSBo7es.js} +1 -1
- package/web/dist/assets/stateDiagram-v2-6OUMAXLB-BqpsfoJI.js +1 -0
- package/web/dist/assets/{swimlanes-5IMT3BWC-CgNqXCvM.js → swimlanes-5IMT3BWC-DOXpv_KQ.js} +2 -2
- package/web/dist/assets/swimlanesDiagram-G3AALYLV-k8WG_bWt.js +8 -0
- package/web/dist/assets/{timeline-definition-FHXFAJF6-DAJsGj6d.js → timeline-definition-FHXFAJF6-SjhGfPdI.js} +1 -1
- package/web/dist/assets/{vennDiagram-L72KCM5P-DDVdvG5k.js → vennDiagram-L72KCM5P-BiujYen6.js} +1 -1
- package/web/dist/assets/{wardleyDiagram-EHGQE667-CiAs_m72.js → wardleyDiagram-EHGQE667-6nLXBvwc.js} +1 -1
- package/web/dist/assets/{xychartDiagram-FW5EYKEG-D6OLJtsD.js → xychartDiagram-FW5EYKEG-Di7ioTvW.js} +1 -1
- package/web/dist/index.html +3 -3
- package/web/runtime.js +192 -6
- package/web/server.js +22 -0
- package/web/dist/assets/channel-DiW7lUT8.js +0 -1
- package/web/dist/assets/classDiagram-OUVF2IWQ-CpAhBd5x.js +0 -1
- package/web/dist/assets/classDiagram-v2-EOCWNBFH-CpAhBd5x.js +0 -1
- package/web/dist/assets/index-C2ioXNJJ.js +0 -24
- package/web/dist/assets/index-CVYm02UI.css +0 -1
- package/web/dist/assets/pilotswarm-DrM3pXOV.js +0 -97
- package/web/dist/assets/stateDiagram-v2-6OUMAXLB-F7qYkvpr.js +0 -1
- package/web/dist/assets/swimlanesDiagram-G3AALYLV-CUKrHLkY.js +0 -8
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
function bd(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Mn={exports:{}},se={};var Li;function Sd(){if(Li)return se;Li=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),u=Symbol.for("react.activity"),f=Symbol.iterator;function m(A){return A===null||typeof A!="object"?null:(A=f&&A[f]||A["@@iterator"],typeof A=="function"?A:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,b={};function y(A,D,F){this.props=A,this.context=D,this.refs=b,this.updater=F||h}y.prototype.isReactComponent={},y.prototype.setState=function(A,D){if(typeof A!="object"&&typeof A!="function"&&A!=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,A,D,"setState")},y.prototype.forceUpdate=function(A){this.updater.enqueueForceUpdate(this,A,"forceUpdate")};function v(){}v.prototype=y.prototype;function E(A,D,F){this.props=A,this.context=D,this.refs=b,this.updater=F||h}var k=E.prototype=new v;k.constructor=E,g(k,y.prototype),k.isPureReactComponent=!0;var x=Array.isArray;function w(){}var S={H:null,A:null,T:null,S:null},C=Object.prototype.hasOwnProperty;function M(A,D,F){var K=F.ref;return{$$typeof:t,type:A,key:D,ref:K!==void 0?K:null,props:F}}function _(A,D){return M(A.type,D,A.props)}function O(A){return typeof A=="object"&&A!==null&&A.$$typeof===t}function R(A){var D={"=":"=0",":":"=2"};return"$"+A.replace(/[=:]/g,function(F){return D[F]})}var T=/\/+/g;function N(A,D){return typeof A=="object"&&A!==null&&A.key!=null?R(""+A.key):D.toString(36)}function j(A){switch(A.status){case"fulfilled":return A.value;case"rejected":throw A.reason;default:switch(typeof A.status=="string"?A.then(w,w):(A.status="pending",A.then(function(D){A.status==="pending"&&(A.status="fulfilled",A.value=D)},function(D){A.status==="pending"&&(A.status="rejected",A.reason=D)})),A.status){case"fulfilled":return A.value;case"rejected":throw A.reason}}throw A}function q(A,D,F,K,W){var Q=typeof A;(Q==="undefined"||Q==="boolean")&&(A=null);var J=!1;if(A===null)J=!0;else switch(Q){case"bigint":case"string":case"number":J=!0;break;case"object":switch(A.$$typeof){case t:case e:J=!0;break;case p:return J=A._init,q(J(A._payload),D,F,K,W)}}if(J)return W=W(A),J=K===""?"."+N(A,0):K,x(W)?(F="",J!=null&&(F=J.replace(T,"$&/")+"/"),q(W,D,F,"",function(ge){return ge})):W!=null&&(O(W)&&(W=_(W,F+(W.key==null||A&&A.key===W.key?"":(""+W.key).replace(T,"$&/")+"/")+J)),D.push(W)),1;J=0;var V=K===""?".":K+":";if(x(A))for(var Y=0;Y<A.length;Y++)K=A[Y],Q=V+N(K,Y),J+=q(K,D,F,Q,W);else if(Y=m(A),typeof Y=="function")for(A=Y.call(A),Y=0;!(K=A.next()).done;)K=K.value,Q=V+N(K,Y++),J+=q(K,D,F,Q,W);else if(Q==="object"){if(typeof A.then=="function")return q(j(A),D,F,K,W);throw D=String(A),Error("Objects are not valid as a React child (found: "+(D==="[object Object]"?"object with keys {"+Object.keys(A).join(", ")+"}":D)+"). If you meant to render a collection of children, use an array instead.")}return J}function Z(A,D,F){if(A==null)return A;var K=[],W=0;return q(A,K,"","",function(Q){return D.call(F,Q,W++)}),K}function ue(A){if(A._status===-1){var D=A._result;D=D(),D.then(function(F){(A._status===0||A._status===-1)&&(A._status=1,A._result=F)},function(F){(A._status===0||A._status===-1)&&(A._status=2,A._result=F)}),A._status===-1&&(A._status=0,A._result=D)}if(A._status===1)return A._result.default;throw A._result}var oe=typeof reportError=="function"?reportError:function(A){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var D=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof A=="object"&&A!==null&&typeof A.message=="string"?String(A.message):String(A),error:A});if(!window.dispatchEvent(D))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",A);return}console.error(A)},de={map:Z,forEach:function(A,D,F){Z(A,function(){D.apply(this,arguments)},F)},count:function(A){var D=0;return Z(A,function(){D++}),D},toArray:function(A){return Z(A,function(D){return D})||[]},only:function(A){if(!O(A))throw Error("React.Children.only expected to receive a single React element child.");return A}};return se.Activity=u,se.Children=de,se.Component=y,se.Fragment=s,se.Profiler=r,se.PureComponent=E,se.StrictMode=n,se.Suspense=c,se.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=S,se.__COMPILER_RUNTIME={__proto__:null,c:function(A){return S.H.useMemoCache(A)}},se.cache=function(A){return function(){return A.apply(null,arguments)}},se.cacheSignal=function(){return null},se.cloneElement=function(A,D,F){if(A==null)throw Error("The argument must be a React element, but you passed "+A+".");var K=g({},A.props),W=A.key;if(D!=null)for(Q in D.key!==void 0&&(W=""+D.key),D)!C.call(D,Q)||Q==="key"||Q==="__self"||Q==="__source"||Q==="ref"&&D.ref===void 0||(K[Q]=D[Q]);var Q=arguments.length-2;if(Q===1)K.children=F;else if(1<Q){for(var J=Array(Q),V=0;V<Q;V++)J[V]=arguments[V+2];K.children=J}return M(A.type,W,K)},se.createContext=function(A){return A={$$typeof:o,_currentValue:A,_currentValue2:A,_threadCount:0,Provider:null,Consumer:null},A.Provider=A,A.Consumer={$$typeof:i,_context:A},A},se.createElement=function(A,D,F){var K,W={},Q=null;if(D!=null)for(K in D.key!==void 0&&(Q=""+D.key),D)C.call(D,K)&&K!=="key"&&K!=="__self"&&K!=="__source"&&(W[K]=D[K]);var J=arguments.length-2;if(J===1)W.children=F;else if(1<J){for(var V=Array(J),Y=0;Y<J;Y++)V[Y]=arguments[Y+2];W.children=V}if(A&&A.defaultProps)for(K in J=A.defaultProps,J)W[K]===void 0&&(W[K]=J[K]);return M(A,Q,W)},se.createRef=function(){return{current:null}},se.forwardRef=function(A){return{$$typeof:l,render:A}},se.isValidElement=O,se.lazy=function(A){return{$$typeof:p,_payload:{_status:-1,_result:A},_init:ue}},se.memo=function(A,D){return{$$typeof:d,type:A,compare:D===void 0?null:D}},se.startTransition=function(A){var D=S.T,F={};S.T=F;try{var K=A(),W=S.S;W!==null&&W(F,K),typeof K=="object"&&K!==null&&typeof K.then=="function"&&K.then(w,oe)}catch(Q){oe(Q)}finally{D!==null&&F.types!==null&&(D.types=F.types),S.T=D}},se.unstable_useCacheRefresh=function(){return S.H.useCacheRefresh()},se.use=function(A){return S.H.use(A)},se.useActionState=function(A,D,F){return S.H.useActionState(A,D,F)},se.useCallback=function(A,D){return S.H.useCallback(A,D)},se.useContext=function(A){return S.H.useContext(A)},se.useDebugValue=function(){},se.useDeferredValue=function(A,D){return S.H.useDeferredValue(A,D)},se.useEffect=function(A,D){return S.H.useEffect(A,D)},se.useEffectEvent=function(A){return S.H.useEffectEvent(A)},se.useId=function(){return S.H.useId()},se.useImperativeHandle=function(A,D,F){return S.H.useImperativeHandle(A,D,F)},se.useInsertionEffect=function(A,D){return S.H.useInsertionEffect(A,D)},se.useLayoutEffect=function(A,D){return S.H.useLayoutEffect(A,D)},se.useMemo=function(A,D){return S.H.useMemo(A,D)},se.useOptimistic=function(A,D){return S.H.useOptimistic(A,D)},se.useReducer=function(A,D,F){return S.H.useReducer(A,D,F)},se.useRef=function(A){return S.H.useRef(A)},se.useState=function(A){return S.H.useState(A)},se.useSyncExternalStore=function(A,D,F){return S.H.useSyncExternalStore(A,D,F)},se.useTransition=function(){return S.H.useTransition()},se.version="19.2.4",se}var Oi;function za(){return Oi||(Oi=1,Mn.exports=Sd()),Mn.exports}var vd=za();const a=bd(vd);var Rn={exports:{}},$e={};var Fi;function wd(){if(Fi)return $e;Fi=1;var t=za();function e(c){var d="https://react.dev/errors/"+c;if(1<arguments.length){d+="?args[]="+encodeURIComponent(arguments[1]);for(var p=2;p<arguments.length;p++)d+="&args[]="+encodeURIComponent(arguments[p])}return"Minified React error #"+c+"; visit "+d+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(){}var n={d:{f:s,r:function(){throw Error(e(522))},D:s,C:s,L:s,m:s,X:s,S:s,M:s},p:0,findDOMNode:null},r=Symbol.for("react.portal");function i(c,d,p){var u=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:r,key:u==null?null:""+u,children:c,containerInfo:d,implementation:p}}var o=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,d){if(c==="font")return"";if(typeof d=="string")return d==="use-credentials"?d:""}return $e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,$e.createPortal=function(c,d){var p=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d||d.nodeType!==1&&d.nodeType!==9&&d.nodeType!==11)throw Error(e(299));return i(c,d,null,p)},$e.flushSync=function(c){var d=o.T,p=n.p;try{if(o.T=null,n.p=2,c)return c()}finally{o.T=d,n.p=p,n.d.f()}},$e.preconnect=function(c,d){typeof c=="string"&&(d?(d=d.crossOrigin,d=typeof d=="string"?d==="use-credentials"?d:"":void 0):d=null,n.d.C(c,d))},$e.prefetchDNS=function(c){typeof c=="string"&&n.d.D(c)},$e.preinit=function(c,d){if(typeof c=="string"&&d&&typeof d.as=="string"){var p=d.as,u=l(p,d.crossOrigin),f=typeof d.integrity=="string"?d.integrity:void 0,m=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;p==="style"?n.d.S(c,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:u,integrity:f,fetchPriority:m}):p==="script"&&n.d.X(c,{crossOrigin:u,integrity:f,fetchPriority:m,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},$e.preinitModule=function(c,d){if(typeof c=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var p=l(d.as,d.crossOrigin);n.d.M(c,{crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0})}}else d==null&&n.d.M(c)},$e.preload=function(c,d){if(typeof c=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var p=d.as,u=l(p,d.crossOrigin);n.d.L(c,p,{crossOrigin:u,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0,type:typeof d.type=="string"?d.type:void 0,fetchPriority:typeof d.fetchPriority=="string"?d.fetchPriority:void 0,referrerPolicy:typeof d.referrerPolicy=="string"?d.referrerPolicy:void 0,imageSrcSet:typeof d.imageSrcSet=="string"?d.imageSrcSet:void 0,imageSizes:typeof d.imageSizes=="string"?d.imageSizes:void 0,media:typeof d.media=="string"?d.media:void 0})}},$e.preloadModule=function(c,d){if(typeof c=="string")if(d){var p=l(d.as,d.crossOrigin);n.d.m(c,{as:typeof d.as=="string"&&d.as!=="script"?d.as:void 0,crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0})}else n.d.m(c)},$e.requestFormReset=function(c){n.d.r(c)},$e.unstable_batchedUpdates=function(c,d){return c(d)},$e.useFormState=function(c,d,p){return o.H.useFormState(c,d,p)},$e.useFormStatus=function(){return o.H.useHostTransitionStatus()},$e.version="19.2.4",$e}var Di;function Ed(){if(Di)return Rn.exports;Di=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),Rn.exports=wd(),Rn.exports}var Dr=Ed();const kd=a.createContext(null);function tt(){const t=a.useContext(kd);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function ee(t,e,s=Object.is){const n=a.useRef(e),r=a.useRef(s);n.current=e,r.current=s;const[i,o]=a.useState(()=>e(t.getState())),l=a.useRef(i);return a.useEffect(()=>{l.current=i},[i]),a.useEffect(()=>t.subscribe(c=>{const d=n.current(c);r.current(l.current,d)||(l.current=d,o(d))}),[t]),i}const Bi=[". ",".. ","..."],Hi=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function Wa(t,e=120){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!t){n(0);return}const r=setInterval(()=>{n(i=>(i+1)%Hi.length)},e);return()=>clearInterval(r)},[t,e]),t?Hi[s]:""}function qa(t,e=360){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!t){n(0);return}const r=setInterval(()=>{n(i=>(i+1)%Bi.length)},e);return()=>clearInterval(r)},[t,e]),t?Bi[s]:""}function Ka(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 $={SESSIONS:"sessions",CHAT:"chat",INSPECTOR:"inspector",ACTIVITY:"activity",PROMPT:"prompt",ADMIN:"admin"},ot=["sequence","logs","nodes","history","files","stats"],P={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",CLOSE_MODAL:"closeModal",MODAL_PREV:"modalPrev",MODAL_NEXT:"modalNext",MODAL_PANE_PREV:"modalPanePrev",MODAL_PANE_NEXT:"modalPaneNext",MODAL_CONFIRM:"modalConfirm",SEND_PROMPT:"sendPrompt",FOCUS_NEXT:"focusNext",FOCUS_PREV:"focusPrev",FOCUS_LEFT:"focusLeft",FOCUS_RIGHT:"focusRight",FOCUS_PROMPT:"focusPrompt",FOCUS_SESSIONS:"focusSessions",MOVE_SESSION_UP:"moveSessionUp",MOVE_SESSION_DOWN:"moveSessionDown",EXPAND_SESSION:"expandSession",COLLAPSE_SESSION:"collapseSession",NEXT_INSPECTOR_TAB:"nextInspectorTab",PREV_INSPECTOR_TAB:"prevInspectorTab",CYCLE_INSPECTOR_TAB:"cycleInspectorTab",GROW_LEFT_PANE:"growLeftPane",GROW_RIGHT_PANE:"growRightPane",GROW_SESSION_PANE:"growSessionPane",SHRINK_SESSION_PANE:"shrinkSessionPane",GROW_FOCUSED_PANE:"growFocusedPane",SHRINK_FOCUSED_PANE:"shrinkFocusedPane",OPEN_ARTIFACT_PICKER:"openArtifactPicker",OPEN_HELP:"openHelp",SEQUENCE_SELECT_PREV:"sequenceSelectPrev",SEQUENCE_SELECT_NEXT:"sequenceSelectNext",TOGGLE_SEQUENCE_TURN:"toggleSequenceTurn",TOGGLE_LOG_TAIL:"toggleLogTail",TOGGLE_STATS_VIEW:"toggleStatsView",OPEN_LOG_FILTER:"openLogFilter",OPEN_FILES_FILTER:"openFilesFilter",MOVE_FILE_UP:"moveFileUp",MOVE_FILE_DOWN:"moveFileDown",DOWNLOAD_SELECTED_FILE:"downloadSelectedFile",DELETE_SELECTED_FILE:"deleteSelectedFile",OPEN_SELECTED_FILE:"openSelectedFile",TOGGLE_FILE_PREVIEW_FULLSCREEN:"toggleFilePreviewFullscreen",TOGGLE_PANE_FULLSCREEN:"togglePaneFullscreen",SCROLL_UP:"scrollUp",SCROLL_DOWN:"scrollDown",PAGE_UP:"pageUp",PAGE_DOWN:"pageDown",EXPAND_HISTORY:"expandHistory",SCROLL_TOP:"scrollTop",SCROLL_BOTTOM:"scrollBottom",DONE_SESSION:"doneSession",CANCEL_SESSION:"cancelSession",STOP_TURN:"stopTurn",DELETE_SESSION:"deleteSession",REGENERATE_SESSION:"regenerateSession",PIN_SESSION:"pinSession",CYCLE_SESSION_VISIBILITY:"cycleSessionVisibility",OPEN_SHARE_SESSION:"openShareSession",TOGGLE_SELECT_MODE:"toggleSelectMode",TOGGLE_SESSION_SELECTION:"toggleSessionSelection",CLEAR_SESSION_SELECTION:"clearSessionSelection",OPEN_HISTORY_FORMAT:"openHistoryFormat",REFRESH_EXECUTION_HISTORY:"refreshExecutionHistory",EXPORT_EXECUTION_HISTORY:"exportExecutionHistory",OPEN_ADMIN_CONSOLE:"openAdminConsole",CLOSE_ADMIN_CONSOLE:"closeAdminConsole",ADMIN_REFRESH_PROFILE:"adminRefreshProfile",ADMIN_SHOW_GHCP:"adminShowGhcp",ADMIN_SHOW_PACKAGES:"adminShowPackages",ADMIN_SHOW_WORKERS:"adminShowWorkers",ADMIN_WORKERS_REFRESH:"adminWorkersRefresh",ADMIN_PACKAGES_REFRESH:"adminPackagesRefresh",ADMIN_PACKAGES_NEXT:"adminPackagesNext",ADMIN_PACKAGES_PREV:"adminPackagesPrev",ADMIN_BEGIN_EDIT_GHCP_KEY:"adminBeginEditGhcpKey",ADMIN_CANCEL_EDIT_GHCP_KEY:"adminCancelEditGhcpKey",ADMIN_SAVE_GHCP_KEY:"adminSaveGhcpKey",ADMIN_CLEAR_GHCP_KEY:"adminClearGhcpKey"};function Bt(t,e,s){const n=t.indexOf(e),i=((n===-1?0:n)+s+t.length)%t.length;return t[i]}function Br(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 hr(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 xd(t){const e=Br(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function Id(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=Br(t);return e==null?null:{text:`ctx ${hr(t.currentTokens)}/${hr(t.tokenLimit)} ${e}%`,color:xd(t)}}function Ad(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 Va(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function Cd(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function Ya(t,e,s={},n={}){if(!e)return null;const r=Va(t)||{},i=Cd(n.timestamp);return e==="session.usage_info"?typeof s.tokenLimit!="number"||typeof s.currentTokens!="number"||typeof s.messagesLength!="number"?null:(r.tokenLimit=s.tokenLimit,r.currentTokens=s.currentTokens,r.messagesLength=s.messagesLength,r.utilization=s.tokenLimit>0?s.currentTokens/s.tokenLimit:0,typeof s.systemTokens=="number"&&(r.systemTokens=s.systemTokens),typeof s.conversationTokens=="number"&&(r.conversationTokens=s.conversationTokens),typeof s.toolDefinitionsTokens=="number"&&(r.toolDefinitionsTokens=s.toolDefinitionsTokens),typeof s.isInitial=="boolean"&&(r.isInitial=s.isInitial),r):e==="assistant.usage"?(typeof s.inputTokens=="number"&&(r.lastInputTokens=s.inputTokens),typeof s.outputTokens=="number"&&(r.lastOutputTokens=s.outputTokens),typeof s.cacheReadTokens=="number"&&(r.lastCacheReadTokens=s.cacheReadTokens),typeof s.cacheWriteTokens=="number"&&(r.lastCacheWriteTokens=s.cacheWriteTokens),r):e==="session.compaction_start"?(r.compaction={...r.compaction||{},state:"running",startedAt:i,completedAt:void 0,error:void 0},r):e==="session.compaction_complete"?(r.compaction={...r.compaction||{},state:s.success===!1?"failed":"succeeded",completedAt:i,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 r.tokenLimit=="number"&&r.tokenLimit>0&&(r.currentTokens=s.postCompactionTokens,r.utilization=s.postCompactionTokens/r.tokenLimit),typeof s.preCompactionMessagesLength=="number"&&typeof s.messagesRemoved=="number"&&(r.messagesLength=Math.max(0,s.preCompactionMessagesLength-s.messagesRemoved)),typeof s.systemTokens=="number"&&(r.systemTokens=s.systemTokens),typeof s.conversationTokens=="number"&&(r.conversationTokens=s.conversationTokens),typeof s.toolDefinitionsTokens=="number"&&(r.toolDefinitionsTokens=s.toolDefinitionsTokens),r):null}function Nd(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 ${hr(s.tokensRemoved)}`,color:"gray"}]:[]]}const gr=/\{(\/?)([a-z-]+)\}/g,Td={color:null,bold:!1,underline:!1},Xs=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,Ui=/session:\/\/([A-Za-z0-9-]+)/g,Us=" (press a to download)",Pd={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function js(t){return{color:t.color,bold:t.bold,underline:t.underline}}function Md(t,e,s){const n=js(t);if(e==="bold")return n.bold=!s,n;if(e==="underline")return n.underline=!s,n;if(e.endsWith("-fg")){const r=e.slice(0,-3);return n.color=s?null:Pd[r]||null,n}return n}function Hr(t){return String(t||"").replace(gr,"")}function Xa(t){const e=[],n=String(t||"").split(`
|
|
2
|
-
`);for(const r of n){const i=[];let o=js(Td),l=0,c;for(;(c=gr.exec(r))!==null;){const[d,p,u]=c;c.index>l&&i.push({text:r.slice(l,c.index),...js(o)}),o=Md(o,u,p==="/"),l=c.index+d.length}(l<r.length||i.length===0)&&i.push({text:r.slice(l),...js(o)}),e.push(i),gr.lastIndex=0}return e}function we(t){return String(t||"").slice(0,8)}function ss(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}let $n=null,_n=null,Ln=null,On=null;function Rd(){return $n||($n=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})),$n}function Qa(){return _n||(_n=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})),_n}function $d(){return Ln||(Ln=new Intl.DateTimeFormat("en-GB",{month:"short"})),Ln}function _d(){return On||(On=new Intl.DateTimeFormat("en-GB",{month:"short",day:"numeric"})),On}function Za(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t);if(Number.isNaN(s.getTime()))return"";if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return Qa().format(s);const r=Rd().format(s),i=String(s.getDate()),o=$d().format(s),l=s.getFullYear()===e.getFullYear()?"":String(s.getFullYear()).slice(-2);return`${i}${o}${l} ${r}`}catch{return""}}function Fe(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t),n=Qa().format(s);if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return n;const i=_d().format(s),o=s.getFullYear()===e.getFullYear()?"":` ${s.getFullYear()}`;return`${i}${o} ${n}`}catch{return""}}function qt(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),r=e%60;return s>0?`${s}h ${n}m`:n>0?`${n}m ${r}s`:`${r}s`}function Ja(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function Ld(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function Qs(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function ji(t,e,s){const n=t[e+s.length]||"";if(!n||/\s/u.test(n))return!1;if(!s.includes("_"))return!0;const r=t[e-1]||"";return!(Qs(r)&&Qs(n))}function Od(t,e,s){const n=t[e-1]||"";if(!n||/\s/u.test(n))return!1;if(!s.includes("_"))return!0;const r=t[e+s.length]||"";return!(Qs(n)&&Qs(r))}function Gi(t,e,s){let n=s;for(;n<t.length;){const r=t.indexOf(e,n);if(r<0)return-1;if(Od(t,r,e))return r;n=r+e.length}return-1}function Fd(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 Dd(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function hs(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 yt(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 el(t){return(t||[]).map(e=>e?.text||"").join("")}function Gs(t){return Ze(el(t))}function Bd(t,e){const s=Math.max(0,Number(e)||0);if(s<=0)return[];const n=[];let r=s;for(const i of t||[]){if(r<=0)break;const o=String(i?.text||"");if(!o)continue;const l=Ns(o,r);l&&(n.push({...i,text:l}),r-=Ze(l))}return n}function tl(t,e){const s=Math.max(0,Number(e)||0),n=Bd(t,s),r=Gs(n),i=Math.max(0,s-r);return i>0&&n.push({text:" ".repeat(i),color:null,bold:!1,underline:!1}),n}function sl(t,e){const s=Math.max(1,Number(e)||1),n=[];let r=[],i=0;function o(){if(r.length===0){n.push([{text:"",color:null,bold:!1,underline:!1}]);return}n.push(r),r=[],i=0}for(const l of t||[]){let c=String(l?.text||"");if(c)for(;c.length>0;){const d=Math.max(1,s-i),p=Ns(c,d);if(!p)break;if(p.length===c.length||Ze(p)<d){r.push({...l,text:p}),i+=Ze(p),c=c.slice(p.length),i>=s&&o();continue}const u=p.lastIndexOf(" ");if(u>0&&(i>0||u>0)){const f=p.slice(0,u+1);r.push({...l,text:f}),i+=Ze(f),c=c.slice(f.length),o()}else r.push({...l,text:p}),i+=Ze(p),c=c.slice(p.length),i>=s&&o()}}return(r.length>0||n.length===0)&&o(),n}function zi(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function nl(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 Hd(t){const e=String(t||"");return Xs.lastIndex=0,[...e.matchAll(Xs)].map(s=>{const n=s[1],r=nl(s[2]);return!n||!r?null:{sessionId:n,filename:r,uri:`artifact://${n}/${r}`}}).filter(Boolean)}function Kt(t){const e=String(t||"");if(!e)return e;Xs.lastIndex=0;const s=e.replace(Xs,(n,r,i,o,l)=>{if(l.slice(Math.max(0,o-2),o)==="](")return n;const c=nl(i);return!r||!c?n:`[artifact: ${c}](artifact://${r}/${c})${Us}`});return Ui.lastIndex=0,s.replace(Ui,(n,r)=>r?`[session: ${we(r)}](session://${r})`:n)}function Ur(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const i=Dd(e,"`",n),o="`".repeat(i),l=Ld(e,o,n+i);if(l>n+i-1){yt(s,{type:"code",text:e.slice(n+i,l)}),n=l+i;continue}}if(e.startsWith("**",n)||e.startsWith("__",n)){const i=e.slice(n,n+2),o=ji(e,n,i)?Gi(e,i,n+2):-1;if(o>n+2){yt(s,{type:"strong",text:e.slice(n+2,o)}),n=o+2;continue}}if(e[n]==="["){const i=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(i){yt(s,{type:"link",text:i[1],href:i[2]}),n+=i[0].length;continue}}if(e.startsWith("<http://",n)||e.startsWith("<https://",n)){const i=e.indexOf(">",n+1);if(i>n+1){const o=e.slice(n+1,i);yt(s,{type:"link",text:o,href:o}),n=i+1;continue}}if(e.startsWith("http://",n)||e.startsWith("https://",n)){let i=n;for(;i<e.length&&!/\s/u.test(e[i]||"");)i+=1;const{url:o,trailing:l}=Fd(e.slice(n,i));if(o){yt(s,{type:"link",text:o,href:o}),l&&yt(s,{type:"text",text:l}),n=i;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&ji(e,n,e[n])){const i=e[n],o=Gi(e,i,n+1);if(o>n+1){yt(s,{type:"em",text:e.slice(n+1,o)}),n=o+1;continue}}let r=e.length;for(const i of["<https://","<http://","https://","http://","**","__","`","[","*","_"]){const o=e.indexOf(i,n+1);o!==-1&&o<r&&(r=o)}yt(s,{type:"text",text:e.slice(n,r)}),n=r}return s.length>0?s:[{type:"text",text:""}]}function Ud(t=""){return Ur(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 ws(t){const e=Ur(t),s=[];for(const n of e){if(n.type==="code"){hs(s,n.text,{color:"cyan"});continue}if(n.type==="strong"){hs(s,n.text,{bold:!0});continue}if(n.type==="em"){hs(s,n.text,{underline:!0});continue}if(n.type==="link"){hs(s,n.text,{color:"cyan",underline:!0,href:n.href});continue}hs(s,n.text)}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function Vt(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function Yt(t){const e=String(t||"").trim().replace(/^\|/,"").replace(/\|$/,""),s=[];let n="",r=!1;for(const i of e){if(r){n+=i,r=!1;continue}if(i==="\\"){r=!0;continue}if(i==="|"){s.push(n.trim()),n="";continue}n+=i}return s.push(n.trim()),s}function Zs(t){return t.length>0&&t.every(e=>/^:?-+:?$/.test(String(e||"").replace(/\s+/g,"")))}function Ze(t){return Array.from(String(t||"")).length}function Ns(t,e){if(e<=0)return"";let s="",n=0;for(const r of Array.from(String(t||""))){if(n+1>e)break;s+=r,n+=1}return s}function rl(t,e){const s=String(t||""),n=Math.max(0,e-Ze(s));return s+" ".repeat(n)}function il(t){return el(ws(t))}function jd(t,e){const s=il(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),r=[];let i="";const o=l=>{let c=l;for(;Ze(c)>e;){const d=Ns(c,e);if(!d)break;i&&(r.push(i),i=""),r.push(d),c=c.slice(d.length)}return c};for(const l of n){const c=o(l);if(!c)continue;if(!i){i=c;continue}const d=`${i} ${c}`;Ze(d)<=e?i=d:(r.push(i),i=c)}return i&&r.push(i),r.length>0?r:[""]}function Gd(t,e){const s=Math.max(1,...t.map(p=>p.length)),n=Math.max(s*3,e-(s*3+1)),r=Array.from({length:s},(p,u)=>Math.max(3,...t.map(f=>Ze(f[u]||"")))),i=Array.from({length:s},(p,u)=>Math.max(3,...t.map(f=>Math.max(0,...String(f[u]||"").split(/\s+/).filter(Boolean).map(m=>Ze(m)))))),o=Array.from({length:s},(p,u)=>Math.max(3,Math.min(Math.max(Ze(t[0]?.[u]||"")||3,i[u]),24)));if(r.reduce((p,u)=>p+u,0)<=n)return r;const c=o.slice();let d=n-c.reduce((p,u)=>p+u,0);if(d<0){const p=Math.max(3,Math.floor(n/s));return c.map((u,f)=>f===s-1?Math.max(3,n-p*(s-1)):p)}for(;d>0;){let p=0,u=-1/0;for(let f=0;f<s;f++){const m=r[f]-c[f];m>u&&(u=m,p=f)}if(u<=0){c[s-1]+=d;break}c[p]+=1,d-=1}return c}function zd(t,e){if(!t||t.length===0)return"";const s=Math.max(1,...t.map(f=>f.length)),r=t.map(f=>Array.from({length:s},(m,h)=>f[h]||"")).map(f=>f.map(m=>il(m))),i=Gd(r,e),o=[],l=`┌${i.map(f=>"─".repeat(f+2)).join("┬")}┐`,c=`├${i.map(f=>"─".repeat(f+2)).join("┼")}┤`,d=`└${i.map(f=>"─".repeat(f+2)).join("┴")}┘`,p=f=>{const m=f.map((g,b)=>jd(g,i[b])),h=Math.max(...m.map(g=>g.length));for(let g=0;g<h;g++){const b=m.map((y,v)=>rl(y[g]||"",i[v]));o.push(`│ ${b.join(" │ ")} │`)}};o.push(l),p(r[0]),o.push(c);const u=r.slice(1);for(const f of u)p(f);return o.push(d),o.join(`
|
|
3
|
-
`)}function Wd(t,e){const s=String(t||"").split(`
|
|
4
|
-
`),n=[];let r=!1;for(let i=0;i<s.length;i++){const o=s[i];if(o.trim().startsWith("```")){r=!r,n.push(o);continue}if(r){n.push(o);continue}const c=s[i+1];if(!Vt(o)||!Vt(c)){n.push(o);continue}const d=Yt(o),p=Yt(c);if(!Zs(p)||d.length!==p.length){n.push(o);continue}const u=[d];for(i+=1;i+1<s.length&&Vt(s[i+1]);){i+=1;const f=Yt(s[i]);Zs(f)||u.push(f)}n.push(zd(u,e))}return n.join(`
|
|
5
|
-
`)}function qd(t,e){const s=String(t||"");if(!s)return[""];const n=[];let r=s;for(;r.length>0;){const i=Ns(r,e);if(!i)break;n.push(i),r=r.slice(i.length)}return n.length>0?n:[""]}function Wi(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",r=Ns(n,Math.max(1,s-4)),i=Math.max(0,s-r.length-2);return[{text:`┌${r}${"─".repeat(i)}┐`,color:"gray"}]}function qi(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function Ki(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),r=[];for(const i of t){const o=qd(i,n);for(const l of o)r.push([{text:"│",color:"gray"},{text:rl(l,n),color:"cyan"},{text:"│",color:"gray"}]);o.length===0&&r.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}])}return r.length===0&&r.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}]),r}function ns(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),r=e.tableMode==="sentinel"?"sentinel":"boxArt",o=(r==="boxArt"?Wd(String(t||""),n):String(t||"")).split(`
|
|
6
|
-
`);let l=!1,c="",d=[];for(let p=0;p<o.length;p+=1){const u=o[p],f=u.trim();if(f.startsWith("```")){l?(s.push(Wi(c,Math.max(8,n))),s.push(...Ki(d,Math.max(8,n))),s.push(qi(Math.max(8,n))),l=!1,c="",d=[]):(l=!0,c=f.slice(3).trim(),d=[]);continue}if(l){d.push(u);continue}if(r==="sentinel"&&u&&Vt(u)){const y=o[p+1]||"";if(Vt(y)){const v=Yt(u),E=Yt(y);if(Zs(E)&&v.length===E.length){const k=[];let x=p+2;for(;x<o.length&&Vt(o[x]);){const w=Yt(o[x]);Zs(w)||k.push(w),x+=1}s.push({kind:"markdownTable",header:v,rows:k}),p=x-1;continue}}}if(!u){s.push([{text:"",color:null}]);continue}const m=/^(#{1,6})\s+(.*)$/.exec(u);if(m){s.push([{text:m[2],color:"white",bold:!0}]);continue}const h=/^>\s?(.*)$/.exec(u);if(h){s.push([{text:"> ",color:"gray"},...ws(h[1]).map(y=>({...y,color:y.color||"gray"}))]);continue}const g=/^\s*[-*]\s+(.*)$/.exec(u);if(g){s.push([{text:"• ",color:"gray"},...ws(g[1])]);continue}const b=/^\s*(\d+)\.\s+(.*)$/.exec(u);if(b){s.push([{text:`${b[1]}. `,color:"gray"},...ws(b[2])]);continue}s.push(ws(u))}return l&&(s.push(Wi(c,Math.max(8,n))),s.push(...Ki(d,Math.max(8,n))),s.push(qi(Math.max(8,n)))),s}function Ce({title:t="SYSTEM",timestamp:e="",body:s="",width:n=80,titleColor:r="yellow",borderColor:i="gray",bodyColor:o=null,fitToContent:l=!1,tableMode:c=null}={}){const d=Math.max(l?12:20,Number(n)||(l?12:20)),p=Math.max(1,d-4),u=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:r,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]];if(c==="sentinel"){const E=ns(String(s||""),{width:p,tableMode:c}),k=o?E.map(x=>Array.isArray(x)?zi(x,o):x):E;return[{kind:"cardStart",runs:u,borderColor:i},...k,{kind:"cardEnd"},[{text:"",color:null}]]}const f=ns(String(s||""),{width:p}),m=f.length>0?f.flatMap(E=>sl(E,p)):[[{text:"",color:null}]],h=o?m.map(E=>zi(E,o)):m,g=h.reduce((E,k)=>Math.max(E,Gs(k)),0),b=l?Math.min(d,Math.max(12,Gs(u)+3,g+4)):d,y=Math.max(1,b-4),v=Math.max(0,b-Gs(u)-3);return[[{text:"┌─",color:i},...u,{text:`${"─".repeat(v)}┐`,color:i}],...h.map(E=>[{text:"│ ",color:i},...tl(E,y),{text:" │",color:i}]),[{text:`└${"─".repeat(Math.max(1,b-2))}┘`,color:i}],[{text:"",color:null}]]}const jr="[canvas-action] ",Vi=2048,Yi=8192;function Kd(t){let e;try{e=JSON.stringify(t)||""}catch{return 1/0}return typeof TextEncoder<"u"?new TextEncoder().encode(e).length:e.length}function Vd(t,e){const s=t?.actions;if(!s||typeof s!="object")return{ok:!1,reason:"the current canvas declares no response contract"};if(!e||typeof e!="object"||e.type!=="canvas-action")return{ok:!1,reason:"not a canvas-action message"};const n=typeof e.action=="string"?e.action:"",r=Object.prototype.hasOwnProperty.call(s,n)?s[n]:null;if(!r||typeof r!="object")return{ok:!1,reason:`action ${JSON.stringify(n)} is not declared by the contract`};const i=e.data===void 0?{}:e.data;if(!i||typeof i!="object"||Array.isArray(i))return{ok:!1,reason:"data must be an object"};for(const l of Object.keys(i))if(!Object.prototype.hasOwnProperty.call(r,l))return{ok:!1,reason:`field ${JSON.stringify(l)} is not declared for action ${JSON.stringify(n)}`};const o={};for(const[l,c]of Object.entries(r)){const d=String(c||""),p=d.endsWith("?"),u=p?d.slice(0,-1):d,f=i[l];if(f==null){if(p)continue;return{ok:!1,reason:`required field ${JSON.stringify(l)} is missing`}}if(u==="json"){if(typeof f!="object")return{ok:!1,reason:`field ${JSON.stringify(l)} must be a JSON object or array`};o[l]=f;continue}if(typeof f!==u)return{ok:!1,reason:`field ${JSON.stringify(l)} must be a ${u}`};if(u==="string"&&f.length>Vi)return{ok:!1,reason:`field ${JSON.stringify(l)} exceeds ${Vi} characters`};if(u==="number"&&!Number.isFinite(f))return{ok:!1,reason:`field ${JSON.stringify(l)} must be a finite number`};o[l]=f}return Kd(o)>Yi?{ok:!1,reason:`action payload exceeds ${Yi} bytes`}:{ok:!0,action:n,data:o}}function Yd(t,e){return`${jr}${JSON.stringify({action:t,data:e})}`}function ol(t){return typeof t=="string"&&t.startsWith(jr)}function Xd(t){if(!ol(t))return null;try{const e=JSON.parse(t.slice(jr.length));return!e||typeof e!="object"||typeof e.action!="string"?null:{action:e.action,data:e.data&&typeof e.data=="object"?e.data:{}}}catch{return null}}function Qd({burst:t=3,windowMs:e=3e3}={}){const s=[];return function(r=Date.now()){for(;s.length&&r-s[0]>e;)s.shift();return s.length>=t?!1:(s.push(r),!0)}}function Ot(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 r=String(t?.title||"").trim();return/^pilotswarm(?: agent)?$/i.test(r)?s:/^sweeper agent$/i.test(r)||/^sweeper$/i.test(r)?"Sweeper Agent":/^resource manager agent$/i.test(r)||/^resourcemgr$/i.test(r)?"Resource Manager Agent":/^facts manager$/i.test(r)||/^facts-manager$/i.test(r)?"Facts Manager":r||"System Agent"}function al(t){const e=Ot(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}const be=300,Zd=[be,1e3,3e3,1e4],Jd=["user.message","assistant.message","system.message","session.epoch_committed","session.regenerate_refused","session.regenerate_failed","session.canvas_updated"];function ll(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:Fe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function cl(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:Fe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function dl(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:Fe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function He(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(be,Number(e)||be);return s.length>n?s.slice(-n):s}function gt(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 ul=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,eu=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function Gr(t){return ul.test(gt(t))}function wt(t){const e=String(t||"").replace(/\r\n/g,`
|
|
8
|
-
`).trim();if(!e)return"";const s=e.replace(eu,"").trimStart();return s!==e?s.trim():Gr(e)?e.replace(ul,"").trim():e}function pl(t){const e=String(t||"").replace(/\r\n/g,`
|
|
9
|
-
`).split(`
|
|
10
|
-
`),s=[];let n=[];function r(){n.length!==0&&(s.push({kind:"text",text:n.join(`
|
|
11
|
-
`)}),n=[])}for(let i=0;i<e.length;){const o=e[i];if(!/^\s*\[SYSTEM:/i.test(o)){n.push(o),i+=1;continue}const l=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(o);if(l){r(),s.push({kind:"system",text:l[1].trim()}),i+=1;continue}const c=[o.replace(/^\s*\[SYSTEM:\s*/i,"")];let d=-1;for(let p=i+1;p<e.length;p+=1){const u=e[p];if(u.trim()==="]"){d=p;break}if(/\]\s*$/.test(u.trim())){const f=u.replace(/\]\s*$/,"");f.trim()&&c.push(f),d=p;break}c.push(u)}if(d===-1){n.push(o),i+=1;continue}r(),s.push({kind:"system",text:c.join(`
|
|
12
|
-
`).trim()}),i=d+1}return r(),s}function fl(t,e){const s=String(t||"").replace(/\r\n/g,`
|
|
13
|
-
`);return e==="user"||e==="assistant"?pl(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
|
|
14
|
-
`).trim():s.trim()}function tu(t,e){return e!=="user"&&e!=="assistant"?[]:pl(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function Qi(t){const e=gt(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=fl(e,t.role);if(s)return s}return wt(e)}function zr(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 r=e.indexOf(n,s.length);if(r===-1)return null;const i=e.slice(s.length,r),o=e.slice(r+n.length,-1);return!i.trim()||!o.trim()?null:{question:i,answer:o}}function su(t){return gt(Hr(t)).length>0}function nu(t){const e=gt(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 ru(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(gt(t))}function Ht(t,e){const s=String(t||""),n=`${e}=`,r=s.indexOf(n);if(r<0)return"";const i=s.slice(r+n.length),o=[" request_id="," from="," subject="," reason="," expects_response="," expires_at="," verdict="];let l=i.length;for(const c of o){const d=i.indexOf(c);d>=0&&(l=Math.min(l,d))}return i.slice(0,l).trim()}function iu(t,e){const s=gt(e);if(!s)return null;const n=/^\[SESSION_MESSAGE\s+([^\]]+)\]\n?/i.exec(s);if(n){const i=n[1],o=`
|
|
17
|
-
Request body:
|
|
18
|
-
`,l=s.indexOf(o),c=l>=0?s.slice(l+o.length).trim():s.slice(n[0].length).trim(),d=Ht(i,"request_id"),p=Ht(i,"from"),u=Ht(i,"subject"),f=/\bexpects_response=true\b/i.test(i),m=[p?`From: session-${we(p)}`:"",d?`Request ID: ${d}`:"",u?`Subject: ${u}`:"",f?"Response: required":"Response: not required","",c].filter((h,g)=>g===4||String(h||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:m.join(`
|
|
19
|
-
`),time:Fe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:f?"Session Request":"Session Message",cardTitleColor:"cyan",cardBorderColor:"cyan"}}const r=/^\[SESSION_MESSAGE_RESPONSE\s+([^\]]+)\]\n?/i.exec(s);if(r){const i=r[1],o=/^This is the requested cross-session response\.[^\n]*\n\n?/i,l=s.slice(r[0].length).trim().replace(o,"").trim(),c=Ht(i,"request_id"),d=Ht(i,"from"),p=Ht(i,"verdict")||"answered",u=[d?`From: session-${we(d)}`:"",c?`Request ID: ${c}`:"",`Verdict: ${p}`,"",l].filter((f,m)=>m===3||String(f||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:u.join(`
|
|
20
|
-
`),time:Fe(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 ou(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&nu(s)?"system":e}function au(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(r=>n.includes(r))}function lu(t,e){if(!t||!e||t.role!==e.role)return!1;if(t.kind==="canvas-update"||e.kind==="canvas-update")return t.kind===e.kind&&t.id===e.id;const s=Qi(t),n=Qi(e);if(!s||!n||s!==n)return!1;const r=au(t,e);if(r!=null)return r;const i=Number(t.createdAt||0),o=Number(e.createdAt||0);return t.optimistic||e.optimistic?!0:!i||!o?!1:Math.abs(i-o)<=1e4}function Xt(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!lu(n,s)){e.push(s);continue}if(n?.optimistic&&!s?.optimistic){e[e.length-1]=s;continue}if(!n?.optimistic&&s?.optimistic)continue;const r=Number(n?.createdAt||0),i=Number(s?.createdAt||0),o=i>=r?s:n;if(o.role==="user"&&!n?.optimistic&&!s?.optimistic){const l=Math.min(Number(n?.firstDeliveredAt||r||1/0),Number(s?.firstDeliveredAt||i||1/0));e[e.length-1]={...o,redelivered:!0,...Number.isFinite(l)?{firstDeliveredAt:l}:{}};continue}e[e.length-1]=o}return e}function cu(t){return typeof t=="string"?t.replace(/^\[FROM:[^\]\n]*\]\n?/,""):t}function Qt(t,e){const s=cs(t),n=iu(t,s);if(n)return n;if(e==="user"&&ol(s)){const c=Xd(s);if(c)return{id:`${t.sessionId}:${t.seq}`,kind:"canvas-action",role:"user",action:c.action,data:c.data,text:s,time:Fe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...Array.isArray(t?.data?.clientMessageIds)&&t.data.clientMessageIds.length>0?{clientMessageIds:t.data.clientMessageIds}:{}}}const r=cu(fl(s,e));if(!su(r))return null;const i=Array.isArray(t?.data?.clientMessageIds)?t.data.clientMessageIds.filter(c=>typeof c=="string"&&c):[],o=t?.data?.sender&&typeof t.data.sender=="object"?t.data.sender:null,l=Array.isArray(t?.data?.attachments)?t.data.attachments.filter(c=>c&&typeof c.filename=="string"&&c.filename):[];return{id:`${t.sessionId}:${t.seq}`,role:ou(t,e,r),text:r,time:Fe(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...i.length>0?{clientMessageIds:i}:{},...o?{sender:o}:{},...l.length>0?{attachments:l}:{}}}function ml(t){return t?.eventType!=="system.message"?!1:!ru(cs(t))}function Js(t,e){return tu(cs(t),e).map((s,n)=>$t({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function du(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=gt(e.text),n=zr(e.text),r=n?gt(n.answer):"";let i=!1;return t.filter(o=>{if(i||!o?.optimistic||o.role!==e.role)return!0;const l=gt(o.text);return l!==s&&l!==r?!0:(i=!0,!1)})}function cs(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 Ja(e)}function hl(t){return(t||[]).map(e=>e?.text||"").join("")}function uu(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function Wr(t=[]){const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();if(!r)continue;const i=r.toLowerCase();e.has(i)||(e.add(i),s.push(r))}return s.join(" | ")}function pu(t,e=""){return Wr([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function fu(t,e=""){return Wr([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function mu(t,e=""){const s=cs(t),n=wt(e);return Wr([wt(s),n,t?.data?.detail,t?.data?.message])}function hu(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 gu(t,e){if(!e||typeof e!="object")return"";if(t==="wait"){const r=e.seconds!=null?`${e.seconds}s`:"?",i=e.preserveWorkerAffinity===!0?" preserve=true":"",o=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${r}${i}${o}`}if(t==="cron"){if(e.action==="cancel")return" cancel";const r=e.seconds!=null?`${e.seconds}s`:"?",i=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${r}${i}`}const s=Object.entries(e).slice(0,4).map(([r,i])=>`${r}=${hu(i)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function qr(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function me(t,e,s,n="",r="white"){return[...qr(t),{text:e,color:s},...n?[{text:` ${n}`,color:r}]:[]]}function yu(t,e=96){return uu(Hr(cs(t)),e)||""}function Fn(t,e,s="start"){const n=typeof e?.data?.toolCallId=="string"?e.data.toolCallId:"",r=typeof e?.data?.requestId=="string"?e.data.requestId:"",i=e?.data?.toolName||e?.data?.name||(n?`tool call ${n.slice(0,8)}`:r?`tool request ${r.slice(0,8)}`:"tool"),o=e?.data?.arguments||e?.data?.args,l=e?.data?.durableSessionId,c=gu(i,o),d=s==="start"?"▶":s==="partial"?"…":"✓",p=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...qr(t),{text:`${d} ${i}${c}`,color:p},...l?[{text:` [sess ${we(l)}]`,color:"gray"}]:[]]}function $t(t){const e=Fe(t.createdAt),s=yu(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"session.artifact_presented":{const r=(t?.data??{})||{},i=String(r.filename||"artifact"),o=typeof r.note=="string"&&r.note.trim()?` — ${r.note.trim()}`:"";n=me(e,"[show]","cyan",`${i}${o}`,"white");break}case"session.canvas_updated":{const r=(t?.data??{})||{},i=Number(r.rev)||0,o=typeof r.note=="string"&&r.note.trim()?` — ${r.note.trim()}`:"",l=typeof r.source?.filename=="string"&&r.source.filename.trim()?` from ${r.source.filename.trim()}`:"";n=me(e,"[canvas]","cyan",`rev ${i}${l}${o}`,"white");break}case"session.canvas_data":{const r=(t?.data??{})||{},i=Number(r.dataRev)||0,o=Number.isFinite(Number(r.sizeBytes))?` (${(Number(r.sizeBytes)/1024).toFixed(1)} KB)`:"",l=typeof r.note=="string"&&r.note.trim()?` — ${r.note.trim()}`:"";n=me(e,"[canvas]","cyan",`data tick ${i}${o}${l}`,"white");break}case"tool.execution_start":n=Fn(e,t,"start");break;case"tool.execution_complete":n=Fn(e,t,"complete");break;case"tool.execution_partial_result":n=Fn(e,t,"partial");break;case"tool.execution_progress":{const r=(t?.data??{})||{},i=r.toolName||r.name||"tool",o=typeof r.message=="string"&&r.message?r.message:typeof r.detail=="string"&&r.detail?r.detail:r.percent!=null?`${Math.round(Number(r.percent))}%`:"running…";n=me(e,"[tool]","cyan",`${i} ${o}`,"white");break}case"assistant.reasoning":n=me(e,"[reasoning]","gray",s||"…","white");break;case"assistant.intent":{const r=(t?.data??{})||{},i=typeof r.summary=="string"&&r.summary?r.summary:typeof r.intent=="string"&&r.intent?r.intent:s||"";n=me(e,"[intent]","gray",i||"…","white");break}case"assistant.turn_start":n=me(e,"[turn start]","gray",s);break;case"session.turn_completed":n=me(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=me(e,"[lossy handoff]","yellow",fu(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=me(e,"[dehydrated]","cyan",pu(t,s));break;case"session.hydrated":case"session.rehydrated":n=me(e,"[rehydrated]","green",s);break;case"session.wait_started":{const r=t?.data?.seconds!=null?`${t.data.seconds}s`:"?",i=typeof t?.data?.reason=="string"&&t.data.reason?` reason=${JSON.stringify(t.data.reason)}`:"",o=t?.data?.preserveAffinity?" preserve=true":"";n=me(e,"[wait]","yellow",`${r}${o}${i}`.trim());break}case"session.input_required_started":n=me(e,"[input]","yellow",s);break;case"session.agent_spawned":n=me(e,"[spawn]","cyan",t?.data?.agentId||we(t?.data?.childSessionId),"white");break;case"session.cron_started":n=me(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=me(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=me(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=me(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=me(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=me(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=me(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=me(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.model_changed":{const r=ss(t?.data?.oldModel)||"default",i=ss(t?.data?.newModel)||"default",o=t?.data?.newReasoningEffort,l=o&&o!==t?.data?.oldReasoningEffort,c=t?.data?.newContextTier,d=c&&c!==t?.data?.oldContextTier&&c!=="default",p=[...l?[`effort ${o}`]:[],...d?[`context ${c}`]:[]];n=me(e,"[model]","cyan",`${r} → ${i}${p.length?` (${p.join(", ")})`:""}`);break}case"session.compaction_start":case"session.compaction_complete":n=Nd(e,t.eventType,t.data||{});break;case"session.error":n=me(e,"[error]","red",s||"session error","white");break;case"system.message":Gr(cs(t))?n=me(e,"[rehydrated]","green",mu(t,s)||"conversation preserved"):n=me(e,"[system]","gray",s||"system message");break;default:n=[...qr(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:hl(n),line:n}}function bu(t=be){const e=Math.max(be,Number(t)||be);return Zd.find(n=>n>e)||Math.min(1e5,e*2)}function gl(t){const e=t.sessionId||null;return{id:`${t.sessionId||""}:${t.seq}:canvas`,kind:"canvas-update",role:"canvas-update",sessionId:e,rev:Number(t?.data?.rev)||0,note:typeof t?.data?.note=="string"?t.data.note:"",text:e?`artifact://${e}/canvas.html`:"",createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function yl(t,e){const s=Fe(t.createdAt),n=`action ${e.action}${Object.keys(e.data||{}).length?" "+Ja(e.data):""}`,r=me(s,"[canvas]","cyan",n,"white");return{id:`${t.sessionId}:${t.seq}:canvas-action`,eventType:t.eventType,time:s,seq:Number.isFinite(Number(t?.seq))?Number(t.seq):0,createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),text:hl(r),line:r}}function Rs(t=[],e={}){const s=Math.max(be,Number(e.requestedLimit??e.eventLimit??be)||be),n=[],r=[],i=[];for(const o of t){if(i.push(o),o.eventType==="user.message"){r.push(...Js(o,"user"));const c=Qt(o,"user");if(c&&n.push(c),c?.kind==="canvas-action"){const d=yl(o,c);d&&r.push(d)}continue}if(o.eventType==="session.canvas_updated"){n.push(gl(o));const c=$t(o);c&&r.push(c);continue}if(o.eventType==="assistant.message"){r.push(...Js(o,"assistant"));const c=Qt(o,"assistant");c&&n.push(c);continue}if(o.eventType==="system.message"){if(ml(o)){const c=$t(o);c&&r.push(c)}else{const c=Qt(o,"system");c&&n.push(c)}continue}if(o.eventType==="session.epoch_committed"){n.push(ll(o));continue}if(o.eventType==="session.regenerate_refused"){n.push(cl(o));continue}if(o.eventType==="session.regenerate_failed"){n.push(dl(o));continue}const l=$t(o);l&&r.push(l)}return{chat:Xt(n),activity:r,events:i.slice(-s),loadedEventLimit:s,loadedEventCount:i.length,hasOlderEvents:i.length>=s}}function Zi(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max(be,Number(t?.loadedEventLimit??be)||be),r=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),i={chat:He(t?.chat||[],n),activity:He(t?.activity||[],n),events:r,lastSeq:Number.isFinite(Number(e.seq))?e.seq:t?.lastSeq||0,loadedEventLimit:n,loadedEventCount:Math.max(Number(t?.loadedEventCount||0),r.length),hasOlderEvents:!!t?.hasOlderEvents,stoppedMessageIds:Array.isArray(t?.stoppedMessageIds)?t.stoppedMessageIds:[]};if(e.eventType==="session.turn_stopped"){const l=Array.isArray(e?.data?.clientMessageIds)?e.data.clientMessageIds.filter(c=>typeof c=="string"&&c):[];if(l.length>0){const c=new Set([...i.stoppedMessageIds,...l]);i.stoppedMessageIds=Array.from(c),i.chat=i.chat.map(d=>Array.isArray(d.clientMessageIds)&&d.clientMessageIds.some(p=>c.has(p))?{...d,stopped:!0}:d)}return i}if(e.eventType==="user.message"){i.activity.push(...Js(e,"user"));const l=Qt(e,"user");if(l?.kind==="canvas-action"){const c=yl(e,l);c&&i.activity.push(c)}return i.activity=He(i.activity,n),l&&(Array.isArray(l.clientMessageIds)&&l.clientMessageIds.some(c=>i.stoppedMessageIds.includes(c))&&(l.stopped=!0),i.chat=du(i.chat,l),i.chat.push(l),i.chat=He(Xt(i.chat),n)),i}if(e.eventType==="session.canvas_updated"){i.chat.push(gl(e)),i.chat=He(i.chat,n);const l=$t(e);return l&&(i.activity.push(l),i.activity=He(i.activity,n)),i}if(e.eventType==="assistant.message"){i.activity.push(...Js(e,"assistant")),i.activity=He(i.activity,n);const l=Qt(e,"assistant");return l&&(i.chat.push(l),i.chat=He(Xt(i.chat),n)),i}if(e.eventType==="system.message"){if(ml(e)){const l=$t(e);l&&(i.activity.push(l),i.activity=He(i.activity,n))}else{const l=Qt(e,"system");if(!l)return i;i.chat.push(l),i.chat=He(Xt(i.chat),n)}return i}if(e.eventType==="session.epoch_committed")return i.chat.push(ll(e)),i.chat=He(i.chat,n),i;if(e.eventType==="session.regenerate_refused")return i.chat.push(cl(e)),i.chat=He(i.chat,n),i;if(e.eventType==="session.regenerate_failed")return i.chat.push(dl(e)),i.chat=He(i.chat,n),i;const o=$t(e);return o&&(i.activity.push(o),i.activity=He(i.activity,n)),i}function Dn(t,e=null){const s=typeof e?.splash=="string"&&e.splash.trim()?e.splash:null,n=s||t?.splash;if(!n)return[];const r=s?e?.splashMobile:t?.splashMobile,i=typeof r=="string"&&r.trim()?r:null,o=e?.isSystem?Ot(e,t?.title||"PilotSwarm"):e?.title||t?.title||"PilotSwarm",l="{gray-fg}Start interacting with this session to replace the splash screen.{/gray-fg}";return[{id:`splash:${o}`,role:"system",text:`${n}
|
|
21
|
-
|
|
22
|
-
${l}`,...i?{mobileText:`${i}
|
|
23
|
-
|
|
24
|
-
${l}`}:{},time:"",splash:!0}]}const bl=.7,Su=30,Ji=36,Bn=18,zs=18,Hn=0,Sl=3,rs=6,wn=10,vu=.25,wu=.5,Zt=6,en=10,vl=.336,Un=Zt,jn=en,Gn=rs,zn=wn;function Gt(t,e,s){return Math.max(e,Math.min(s,t))}function Eu(t){return[$.SESSIONS,$.CHAT,$.INSPECTOR,$.ACTIVITY].includes(t)?t:null}function ku(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function Jt(t=""){const e=String(t||"").split(`
|
|
25
|
-
`).length;return Gt(e,1,Sl)}function wl(t){return Math.max(rs,Math.floor(t*vu))}function El(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*wu),n=Math.max(rs,e-wn);return Math.max(rs,Math.min(n,s))}function eo(t,e){const s=Math.max(0,Number(t)||0),n=Gt(Math.max(0,Number(e)||0),0,s),r=-(s/2);return{minAdjust:r,maxAdjust:Math.max(r,s/2-n)}}function Is(t,e=0,s=1,n=0,r=0,i=null){const o=ku(t),l=o.width,c=o.height,d=Gt(Number(s)||1,1,Sl),p=Eu(i),u=5+d,f=Math.max(18,c-u),h=Math.floor(l*bl)+(Number(e)||0),g=l-h-Hn;let b=!1,y=!1;h<=Bn&&g>zs?b=!0:g<=zs&&h>Bn?y=!0:h<=Bn&&g<=zs&&(y=e>=0,b=!y);let v,E;b?(v=0,E=l):y?(v=l,E=0):(v=Gt(h,Su,l-Ji-Hn),E=Math.max(Ji,l-v-Hn));const x=wl(f)+(Number(n)||0),w=f-x;let S=!1,C=!1;w<=zn&&x>Gn?C=!0:x<=Gn&&w>zn?S=!0:w<=zn&&x<=Gn&&(C=(Number(n)||0)>=0,S=!C);let M,_;if(S)M=0,_=f;else if(C)M=f,_=0;else{const ue=El(c,f);M=Gt(x,rs,ue),_=Math.max(wn,f-M)}const R=Math.max(Zt,Math.floor(f*vl))+(Number(r)||0),T=f-R;let N=!1,j=!1;T<=jn&&R>Un?N=!0:R<=Un&&T>jn?j=!0:T<=jn&&R<=Un&&(N=(Number(r)||0)>=0,j=!N);let q,Z;return N?(q=f,Z=0):j?(Z=f,q=0):(q=Gt(R,Zt,Math.max(Zt,f-en)),Z=Math.max(en,f-q)),{viewport:o,totalWidth:l,totalHeight:c,reservedRows:u,bodyHeight:f,promptRows:d,fullscreenPane:p,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(r)||0,leftHidden:b,rightHidden:y,inspectorHidden:N,activityHidden:j,sessionHidden:S,chatHidden:C,leftWidth:v,rightWidth:E,sessionPaneHeight:M,chatPaneHeight:_,activityPaneHeight:q,inspectorPaneHeight:Z}}function yr(t){if(t?.fullscreenPane)return[t.fullscreenPane,$.PROMPT];if(t?.leftHidden)return[$.INSPECTOR,$.ACTIVITY,$.PROMPT];if(t?.rightHidden)return[...t?.sessionHidden?[$.CHAT]:t?.chatHidden?[$.SESSIONS]:[$.SESSIONS,$.CHAT],$.PROMPT];if(t?.sessionHidden){const e=t?.inspectorHidden?[$.ACTIVITY]:t?.activityHidden?[$.INSPECTOR]:[$.INSPECTOR,$.ACTIVITY];return[$.CHAT,...e,$.PROMPT]}if(t?.chatHidden){const e=t?.inspectorHidden?[$.ACTIVITY]:t?.activityHidden?[$.INSPECTOR]:[$.INSPECTOR,$.ACTIVITY];return[$.SESSIONS,...e,$.PROMPT]}return t?.inspectorHidden?[$.SESSIONS,$.CHAT,$.ACTIVITY,$.PROMPT]:t?.activityHidden?[$.SESSIONS,$.CHAT,$.INSPECTOR,$.PROMPT]:[$.SESSIONS,$.CHAT,$.INSPECTOR,$.ACTIVITY,$.PROMPT]}function nt(t,e){const s=yr(e);return s.includes(t)?t:s[0]||$.PROMPT}function xu(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[$.PROMPT]:$.PROMPT,[$.ACTIVITY]:$.INSPECTOR,[$.INSPECTOR]:$.INSPECTOR}[t]||$.INSPECTOR:e?.rightHidden?{[$.PROMPT]:$.PROMPT,[$.CHAT]:e?.sessionHidden?$.CHAT:$.SESSIONS,[$.SESSIONS]:$.SESSIONS}[t]||(e?.sessionHidden?$.CHAT:$.SESSIONS):{[$.PROMPT]:e?.sessionHidden?$.CHAT:$.SESSIONS,[$.ACTIVITY]:e?.chatHidden?$.SESSIONS:$.CHAT,[$.INSPECTOR]:e?.chatHidden?$.SESSIONS:$.CHAT,[$.CHAT]:e?.sessionHidden?$.CHAT:$.SESSIONS,[$.SESSIONS]:$.SESSIONS}[t]||(e?.sessionHidden?$.CHAT:$.SESSIONS)}function Iu(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[$.PROMPT]:$.PROMPT,[$.INSPECTOR]:$.ACTIVITY,[$.ACTIVITY]:$.ACTIVITY}[t]||$.INSPECTOR:e?.rightHidden?{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:e?.chatHidden?$.SESSIONS:$.CHAT,[$.CHAT]:$.CHAT}[t]||(e?.chatHidden?$.SESSIONS:$.CHAT):e?.inspectorHidden?{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:$.CHAT,[$.CHAT]:$.ACTIVITY,[$.ACTIVITY]:$.ACTIVITY}[t]||$.CHAT:e?.activityHidden?{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:$.CHAT,[$.CHAT]:$.INSPECTOR,[$.INSPECTOR]:$.INSPECTOR}[t]||$.CHAT:{[$.PROMPT]:$.PROMPT,[$.SESSIONS]:$.CHAT,[$.CHAT]:$.INSPECTOR,[$.INSPECTOR]:$.ACTIVITY,[$.ACTIVITY]:$.ACTIVITY}[t]||$.CHAT}function kl(t){const e=String(t||"").trim();if(!e)return{error:"Paste a link to plugin.json or the folder that contains it."};let s;try{s=new URL(e)}catch{return{error:"That does not look like a URL — paste the browser link to plugin.json or its folder."}}const n=s.hostname.toLowerCase();if(n==="github.com"||n==="www.github.com"){const i=s.pathname.split("/").filter(Boolean);if(i.length<2)return{error:"GitHub links need at least github.com/org/repo."};const[o,l,c,d,...p]=i,u=l.replace(/\.git$/u,""),f=`https://github.com/${o}/${u}`;return c?c!=="blob"&&c!=="tree"?{error:`Unrecognized GitHub link shape (…/${c}/…) — use a /blob/ or /tree/ link, or the bare repo URL.`}:d?{kind:"github",repoUrl:f,ref:d,path:p.length?`/${p.join("/")}`:null}:{error:"That GitHub link is missing the branch segment."}:{kind:"github",repoUrl:f,ref:null,path:null}}if(n==="dev.azure.com"||n.endsWith(".visualstudio.com")){if(!s.pathname.includes("/_git/"))return{error:"Azure DevOps links must point at a repo (…/_git/<repo>…)."};const i=`${s.origin}${s.pathname.split("?")[0]}`.replace(/\/$/u,""),o=s.searchParams.get("path"),l=s.searchParams.get("version"),c=l&&/^G[BT]/u.test(l)?l.slice(2):l||null;return{kind:"ado",repoUrl:i,ref:c,path:o||null}}return{error:"Only GitHub and Azure DevOps links are recognized here — for a tarball use the URL tab."}}const tn=2*1024*1024,Au=new Set(["node_modules",".git"]);function br(t){const e=t instanceof Uint8Array?t:new Uint8Array(t);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let s="";const n=32768;for(let r=0;r<e.length;r+=n)s+=String.fromCharCode.apply(null,e.subarray(r,r+n));return btoa(s)}function xl(t){const e=String(t||"").replace(/\s+/gu,"");if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const s=atob(e),n=new Uint8Array(s.length);for(let r=0;r<s.length;r+=1)n[r]=s.charCodeAt(r);return n}function Il(t){return t.split("/").some(e=>Au.has(e))}function Al(t){const e=String(t||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.endsWith("/plugin.json")?e.slice(0,-12):e==="plugin.json"?"":e:""}function Cu(t,e){return t?`${t}/${e}`:e}function Cl(t,e){const s=String(e?.message||e||"");return new Error(`could not reach ${t} from the browser (${s||"network error"}) — the host may block cross-origin reads from this portal; use Upload folder instead`)}async function sn(t,e,s,n){let r;try{r=await t(e,{headers:{accept:"application/json",...s}})}catch(i){throw Cl(n,i)}if(!r.ok){const i=await r.text().catch(()=>"");throw new Error(`${n} returned HTTP ${r.status}${i?`: ${i.slice(0,200)}`:""}`)}return r.json()}async function Nl(t,e,s,n){let r;try{r=await t(e,{headers:s})}catch(o){throw Cl(n,o)}if(!r.ok)throw new Error(`${n} returned HTTP ${r.status} for ${e}`);const i=await r.arrayBuffer();return new Uint8Array(i)}function Nu(t){const e=new URL(t).pathname.split("/").filter(Boolean);if(e.length<2)throw new Error(`not a GitHub repository URL: ${t}`);return{owner:e[0],repo:e[1].replace(/\.git$/u,"")}}async function Tu({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:r,onProgress:i}){const{owner:o,repo:l}=Nu(t),c="https://api.github.com",d={"x-github-api-version":"2022-11-28",...r?{authorization:`Bearer ${r}`}:{}};let p=e;p||(i("resolving the default branch…"),p=(await sn(n,`${c}/repos/${o}/${l}`,d,"api.github.com"))?.default_branch||"main"),i(`reading the file tree of ${o}/${l}@${p}…`);const u=await sn(n,`${c}/repos/${o}/${l}/git/trees/${encodeURIComponent(p)}?recursive=1`,d,"api.github.com");if(u?.truncated)throw new Error("this repository's file tree is too large for the API listing — point the link at the package folder");const f=Array.isArray(u?.tree)?u.tree:[],m=Al(s),h=Cu(m,"plugin.json");if(!f.some(k=>k.type==="blob"&&k.path===h))throw new Error(`no plugin.json at ${h||"the repository root"} on ${p} — link to the folder that contains the manifest`);const g=m?`${m}/`:"",b=f.filter(k=>k.type==="blob"&&(!g||k.path.startsWith(g))&&!Il(k.path.slice(g.length))),y=[];let v=0,E=0;for(const k of b){E+=1;const x=k.path.slice(g.length);i(`fetching ${E}/${b.length}: ${x}`);const w=r?await Pu(n,c,o,l,k.sha,d):await Nl(n,`https://raw.githubusercontent.com/${o}/${l}/${encodeURIComponent(p)}/${k.path.split("/").map(encodeURIComponent).join("/")}`,{},"raw.githubusercontent.com");if(v+=w.length,v>tn)throw new Error(`package exceeds the ${Math.round(tn/1024)} KB upload limit at ${x}`);y.push({path:x,contentBase64:br(w)})}return y}async function Pu(t,e,s,n,r,i){const o=await sn(t,`${e}/repos/${s}/${n}/git/blobs/${r}`,i,"api.github.com"),l=String(o?.content||"").replace(/\s+/gu,"");if(o?.encoding&&o.encoding!=="base64")throw new Error(`unexpected blob encoding "${o.encoding}" from api.github.com`);return xl(l)}function Mu(t){const e=new URL(t),s=e.pathname.split("/").filter(Boolean),n=s.indexOf("_git");if(n<0||n===s.length-1)throw new Error(`not an Azure DevOps repository URL: ${t}`);const r=decodeURIComponent(s[n+1]),i=s.slice(0,n).map(decodeURIComponent),o=e.hostname.toLowerCase(),l=o.endsWith(".visualstudio.com")?o.split(".")[0]:i[0],c=o.endsWith(".visualstudio.com")?i[0]:i[1];if(!l||!c)throw new Error(`could not read org/project from ${t}`);return{org:l,project:c,repo:r}}async function Ru({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:r,tokenKind:i,onProgress:o}){if(!r)throw new Error("Azure DevOps needs a credential — sign-in did not yield a token; paste a PAT with Code (read)");const{org:l,project:c,repo:d}=Mu(t),p=`https://dev.azure.com/${encodeURIComponent(l)}/${encodeURIComponent(c)}/_apis/git/repositories/${encodeURIComponent(d)}`,f={authorization:i==="pat"?`Basic ${br(new TextEncoder().encode(`:${r}`))}`:`Bearer ${r}`},m=Al(s),h=`/${m}`,g=e?`&versionDescriptor.version=${encodeURIComponent(e)}&versionDescriptor.versionType=branch`:"";o(`reading ${d}${m?`/${m}`:""}…`);const b=await sn(n,`${p}/items?scopePath=${encodeURIComponent(h)}&recursionLevel=Full${g}&api-version=7.1`,f,"dev.azure.com"),v=(Array.isArray(b?.value)?b.value:[]).filter(C=>C?.gitObjectType==="blob"&&!C?.isFolder),E=m?`/${m}/`:"/";if(!v.find(C=>C.path===`${E}plugin.json`.replace("//","/")))throw new Error(`no plugin.json under ${h} — link to the folder that contains the manifest`);const x=[];let w=0,S=0;for(const C of v){const M=String(C.path||"").slice(E.length);if(!M||Il(M))continue;S+=1,o(`fetching ${S}/${v.length}: ${M}`);const _=await Nl(n,`${p}/blobs/${encodeURIComponent(C.objectId)}?api-version=7.1&$format=octetStream`,{...f,accept:"application/octet-stream"},"dev.azure.com");if(w+=_.length,w>tn)throw new Error(`package exceeds the ${Math.round(tn/1024)} KB upload limit at ${M}`);x.push({path:M,contentBase64:br(_)})}return x}async function $u(t,{fetchImpl:e=typeof fetch=="function"?fetch:null,token:s=null,tokenKind:n="bearer",onProgress:r=()=>{}}={}){if(typeof e!="function")throw new Error("no fetch implementation available");const i=kl(t);if(i.error)throw new Error(i.error);const o={fetchImpl:e,token:s,tokenKind:n,onProgress:r},l=i.kind==="github"?await Tu(i,o):await Ru(i,o);if(l.length===0)throw new Error("the package folder is empty");return{kind:i.kind,files:l}}function _u(t=[]){const e=(Array.isArray(t)?t:[]).find(s=>s?.path==="plugin.json");if(!e?.contentBase64)return null;try{const s=xl(e.contentBase64),n=JSON.parse(new TextDecoder().decode(s));return String(n?.name||"").trim()||null}catch{return null}}function to(t){return t?.isSystem?al(t):Number.MAX_SAFE_INTEGER}function Lu(t=[]){const e=new Map;for(let s=0;s<t.length;s+=1){const n=t[s]?.sessionId;!n||e.has(n)||e.set(n,s)}return e}function Ou(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return Lu(t);const e=new Map;for(const[s,n]of Object.entries(t||{}))!s||typeof n!="number"||Number.isNaN(n)||e.set(s,n);return e}function Fu(t){if(t instanceof Map)return t;const e=new Map;if(!Array.isArray(t))return e;for(let s=0;s<t.length;s+=1){const n=t[s];typeof n!="string"||!n||e.has(n)||e.set(n,s)}return e}function is(t){return!!(t&&!t.isSystem&&!t.parentSessionId)}function Du(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function so(t,e){return!!(Du(t)&&e&&e.has(t.sessionId))}function no(t,e){return t.isSystem?0:t.isGroup&&so(t,e)?1:so(t,e)?2:t.isGroup?3:4}function ro(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function io(t,e,s,n,r){const i=no(t,n),o=no(e,n);if(i!==o)return i-o;const l=to(t),c=to(e);if(l!==c)return l-c;if(r&&r.size>0&&is(t)&&is(e)){const y=r.has(t.sessionId)?r.get(t.sessionId):1/0,v=r.has(e.sessionId)?r.get(e.sessionId):1/0;if(y!==v)return y-v}const d=s.get(t.sessionId),p=s.get(e.sessionId);if(typeof d=="number"&&typeof p=="number"&&d!==p)return d-p;const u=ro(t),f=ro(e);if(u>0&&f>0&&u!==f)return u-f;const m=(t.createdAt||0)-(e.createdAt||0);if(m!==0)return m;const h=String(t.title||""),g=String(e.title||""),b=h.localeCompare(g);return b!==0?b:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function rt(t=[],e=new Set,s=[],n=null,r=null){const i=new Map,o=new Map,l=Ou(s),c=Fu(r),d=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const g of t)i.set(g.sessionId,g);const p=[];for(const g of t){if(g.isGroup||!g.groupId||g.parentSessionId)continue;const b=`group:${g.groupId}`;if(i.has(b))continue;const y={sessionId:b,groupId:g.groupId,isGroup:!0,title:"Group",status:"group",shortSummary:"reconnecting…",createdAt:0,updatedAt:0};i.set(b,y),p.push(y)}const u=new Set(p.map(g=>g.sessionId));p.length>0&&(t=[...t,...p]);for(const g of t){const b=!g.isGroup&&g.groupId&&!g.parentSessionId&&i.has(`group:${g.groupId}`)?`group:${g.groupId}`:null,y=g.parentSessionId||b;!y||!i.has(y)||(o.has(y)||o.set(y,[]),o.get(y).push(g))}for(const g of o.values())g.sort((b,y)=>io(b,y,l,d,c));const f=t.filter(g=>!(g.parentSessionId||!g.isGroup&&g.groupId)).sort((g,b)=>io(g,b,l,d,c)),m=[];function h(g,b){const y=o.get(g.sessionId)||[];if(m.push({sessionId:g.sessionId,depth:b,hasChildren:y.length>0,collapsed:e.has(g.sessionId),...u.has(g.sessionId)?{standIn:g}:{}}),!e.has(g.sessionId))for(const v of y)h(v,b+1)}for(const g of f)h(g,0);return m}const at="VS Code",ds="Retro",Ft="Others",oo=Object.freeze([at,ds,Ft]);function Bu(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function Wn(t){return Number.parseInt(t,16)/255}function Hu(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 qn(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function Uu(t){const e=Hu(t);if(!e)return 0;const s=qn(Wn(e.slice(1,3))),n=qn(Wn(e.slice(3,5))),r=qn(Wn(e.slice(5,7)));return .2126*s+.7152*n+.0722*r}function ju(t){const e=t?.page?.background||t?.tui?.background||t?.terminal?.background;return Uu(e)>=.5}function Ne({id:t,label:e,description:s,group:n=Ft,page:r,terminal:i,tui:o={},icon:l=null}){const c={background:r?.background||i?.background||"#000000",surface:i?.background||r?.background||"#000000",foreground:i?.foreground||r?.foreground||"#ffffff",white:i?.foreground||r?.foreground||"#ffffff",gray:r?.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 Bu({id:t,label:e,description:s,group:n,icon:l||null,page:r,terminal:i,tui:{...c,...o}})}const Gu=Ne({id:"github-dark",label:"GitHub Dark",description:"GitHub dark palette with soft blue accents and cool neutrals.",group:at,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"}}),zu=Ne({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",group:at,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"}}),Tl=Ne({id:"workspace-dark",label:"Workspace Dark",description:"Flat workspace chrome: tone surfaces and hairlines instead of panel borders.",group:Ft,page:{background:"#0d1117",foreground:"#e6edf3",overlayBackground:"#0d1117",overlayForeground:"#e6edf3",hintColor:"#8b949e",modalBackdrop:"rgba(1, 4, 9, 0.64)",modalBackground:"#161b22",modalBorder:"#272e37",modalForeground:"#e6edf3",modalMuted:"#8b949e",modalSelectedBackground:"#1f6feb33",modalSelectedBorder:"#2f81f7",modalSelectedForeground:"#79c0ff"},terminal:{background:"#0d1117",foreground:"#e6edf3",cursor:"#2f81f7",cursorAccent:"#0d1117",selectionBackground:"rgba(56, 139, 253, 0.28)",black:"#484f58",red:"#ff7b72",green:"#3fb950",yellow:"#d29922",blue:"#58a6ff",magenta:"#bc8cff",cyan:"#39c5cf",white:"#b1bac4",brightBlack:"#6e7681",brightRed:"#ffa198",brightGreen:"#56d364",brightYellow:"#e3b341",brightBlue:"#79c0ff",brightMagenta:"#d2a8ff",brightCyan:"#56d4dd",brightWhite:"#f0f6fc"},tui:{surface:"#161b22",border:"#272e37",activeHighlightBackground:"#1f4b7a",activeHighlightForeground:"#f0f6fc",selectionBackground:"#79c0ff",selectionForeground:"#0d1117",promptCursorBackground:"#2f81f7",promptCursorForeground:"#0d1117"}}),Wu=Ne({id:"cobalt2",label:"Cobalt2",description:"Electric blue shell with bright yellow accents and saturated syntax colors.",group:at,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"}}),qu=Ne({id:"dracula",label:"Dracula",description:"Classic Dracula contrast with neon green, pink, and violet accents.",group:at,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"}}),Ku=Ne({id:"catppuccin-mocha",label:"Catppuccin Mocha",description:"Creamy dark palette with soft pastels and high legibility.",group:at,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"}}),Vu=Ne({id:"hacker-x-matrix",label:"Hacker X - Matrix",description:"Black-and-phosphor terminal palette with vivid green glow and CRT-style contrast.",group:at,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"}}),Yu=Ne({id:"hacker-x-orion-prime",label:"Hacker X - Orion Prime",description:"Deep-space navy palette with electric cyan, violet, and amber accents.",group:at,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"}}),Xu=Ne({id:"gruvbox-dark",label:"Gruvbox Dark",description:"Retro warm palette with earthy browns, oranges, and high readability.",group:at,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"}}),Qu=Ne({id:"noctis",label:"Noctis",description:"Dark cyan-tinted palette with warm and cold medium contrast accents.",group:at,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"}}),Zu=Ne({id:"noctis-obscuro",label:"Noctis Obscuro",description:"Deep obsidian palette with cool blue accents and restrained contrast for long sessions.",group:at,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"}}),Ju=Ne({id:"terminal-green",label:"Terminal Green",description:"Classic black terminal with phosphor green text, amber warnings, and crisp operator contrast.",group:ds,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"}}),ep=Ne({id:"high-contrast-mono",label:"High Contrast Mono",description:"Accessibility-first monochrome theme with cobalt selection and severity colors only where they matter.",group:Ft,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"}}),tp=Ne({id:"win95",label:"Windows 95",description:"Authentic 3D-bevelled grey, navy title bars, teal desktop, and the 16-colour VGA terminal set.",group:ds,page:{background:"#008080",foreground:"#000000",overlayBackground:"#c0c0c0",overlayForeground:"#000000",hintColor:"#4a4a4a",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"}}),sp=Ne({id:"ms-dos",label:"MS-DOS 2.0",description:"CGA light-grey on black, the 16-colour CGA palette with brown, and CP437 box framing.",group:ds,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"}}),np=Ne({id:"doom",label:"DOOM",description:"STBAR brown metal, bone type, and the three keycards as the status palette.",group:ds,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#2a1d14"},{d:"M6 7h20v20H6z",fill:"#c89a6a"},{d:"M5 6h22v6H5z",fill:"#4a2f1a"},{d:"M9 15h5v3.4H9z",fill:"#1a1008"},{d:"M18 15h5v3.4h-5z",fill:"#1a1008"},{d:"M8.6 13.6l6 1 -.3 1.7-6-1z",fill:"#3a2412"},{d:"M23.4 13.6l-6 1 .3 1.7 6-1z",fill:"#3a2412"},{d:"M14.5 18.5h3v2.4h-3z",fill:"#a8734a"},{d:"M11 22h10v1.8H11z",fill:"#7a3a2a"}]},page:{background:"#100b09",foreground:"#d9cba8",overlayBackground:"#1c1310",overlayForeground:"#d9cba8",hintColor:"#a08d68",modalBackdrop:"rgba(16, 11, 9, 0.82)",modalBackground:"#1c1310",modalBorder:"#6f5432",modalForeground:"#d9cba8",modalMuted:"#a08d68",modalSelectedBackground:"#6f5432",modalSelectedBorder:"#a4885c",modalSelectedForeground:"#fff4d6"},terminal:{background:"#100b09",foreground:"#d9cba8",cursor:"#b81c1c",cursorAccent:"#100b09",selectionBackground:"#6f5432",black:"#100b09",red:"#c42222",green:"#3f9e3f",yellow:"#e8c020",blue:"#3a5ce0",magenta:"#a0446a",cyan:"#4a8f8f",white:"#d9cba8",brightBlack:"#a08d68",brightRed:"#ff3a1e",brightGreen:"#5fc45f",brightYellow:"#ffd84a",brightBlue:"#5a7ae8",brightMagenta:"#c46a94",brightCyan:"#6fb5b5",brightWhite:"#fff4d6"},tui:{border:"#6f5432",userChat:"#e8c020",userChatLabel:"#ffd84a",selectionBackground:"#6f5432",selectionForeground:"#fff4d6",activeHighlightBackground:"#6f5432",activeHighlightForeground:"#fff4d6",promptCursorBackground:"#b81c1c",promptCursorForeground:"#fff4d6"}}),rp=Ne({id:"winamp",label:"WinAMP",description:"Bevelled grey chrome, black glass panes, phosphor green, and the spectrum ramp as the status palette.",group:ds,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#000000"},{d:"M3 17h4v11H3z",fill:"#00e337"},{d:"M9 11h4v17H9z",fill:"#7ad91e"},{d:"M15 6h4v22h-4z",fill:"#b6e000"},{d:"M21 13h4v15h-4z",fill:"#ffb400"},{d:"M27 20h3v8h-3z",fill:"#ff3b00"},{d:"M3 15h4v1.6H3z",fill:"#d6d6cc"},{d:"M9 9h4v1.6H9z",fill:"#d6d6cc"},{d:"M15 4h4v1.6h-4z",fill:"#d6d6cc"},{d:"M21 11h4v1.6h-4z",fill:"#d6d6cc"},{d:"M27 18h3v1.6h-3z",fill:"#d6d6cc"}]},page:{background:"#000000",foreground:"#00e337",overlayBackground:"#1c1c1c",overlayForeground:"#00e337",hintColor:"#949494",modalBackdrop:"rgba(0, 0, 0, 0.82)",modalBackground:"#1c1c1c",modalBorder:"#5e5e5e",modalForeground:"#00e337",modalMuted:"#a0a0a0",modalSelectedBackground:"#0000c6",modalSelectedBorder:"#5e5e5e",modalSelectedForeground:"#ffffff"},terminal:{background:"#000000",foreground:"#00e337",cursor:"#ffb400",cursorAccent:"#000000",selectionBackground:"#0000c6",black:"#000000",red:"#ff3b00",green:"#00e337",yellow:"#ffb400",blue:"#4a7cf0",magenta:"#cc66cc",cyan:"#29c8c8",white:"#d6d6cc",brightBlack:"#949494",brightRed:"#ff6a3d",brightGreen:"#5cff7a",brightYellow:"#ffd24a",brightBlue:"#7fa5ff",brightMagenta:"#e08ae0",brightCyan:"#6fe0e0",brightWhite:"#ffffff"},tui:{border:"#5e5e5e",gray:"#949494",userChat:"#ffb400",userChatLabel:"#ffd24a",selectionBackground:"#0000c6",selectionForeground:"#ffffff",activeHighlightBackground:"#0000c6",activeHighlightForeground:"#ffffff",promptCursorBackground:"#ffb400",promptCursorForeground:"#000000"}}),ip=Ne({id:"rust",label:"Rust",description:"Graphite and iron oxide, Ferris in the corner, and rustc's diagnostic levels as the status palette.",group:Ft,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#241f1c"},{d:"M11.5 9.5h1.5v2h-1.5z",fill:"#d63a00"},{d:"M19 9.5h1.5v2h-1.5z",fill:"#d63a00"},{d:"M10.5 6h3.5v3.5h-3.5z",fill:"#ffe9dd"},{d:"M18 6h3.5v3.5H18z",fill:"#ffe9dd"},{d:"M11.5 7h1.5v1.5h-1.5z",fill:"#1a1210"},{d:"M19 7h1.5v1.5H19z",fill:"#1a1210"},{d:"M10 11.5h12v2H10z",fill:"#ff7a3d"},{d:"M7 13.5h18v3H7z",fill:"#f74c00"},{d:"M5 16.5h22v4H5z",fill:"#f74c00"},{d:"M7 20.5h18v1.8H7z",fill:"#f74c00"},{d:"M14.5 18h3v1.4h-3z",fill:"#c23c00"},{d:"M0 11h4.5v6.5H0z",fill:"#d63a00"},{d:"M0 13.2h3v2H0z",fill:"#241f1c"},{d:"M27.5 11h4.5v6.5h-4.5z",fill:"#d63a00"},{d:"M29 13.2h3v2h-3z",fill:"#241f1c"},{d:"M8.5 22.3h2.5v2.4H8.5z",fill:"#d63a00"},{d:"M14.75 22.3h2.5v2.4h-2.5z",fill:"#d63a00"},{d:"M21 22.3h2.5v2.4H21z",fill:"#d63a00"}]},page:{background:"#1c1917",foreground:"#e7e0d8",overlayBackground:"#262220",overlayForeground:"#e7e0d8",hintColor:"#a39a8f",modalBackdrop:"rgba(28, 25, 23, 0.82)",modalBackground:"#262220",modalBorder:"#4a4038",modalForeground:"#e7e0d8",modalMuted:"#a9a096",modalSelectedBackground:"#7c2d12",modalSelectedBorder:"#ce422b",modalSelectedForeground:"#ffeadf"},terminal:{background:"#1c1917",foreground:"#e7e0d8",cursor:"#f74c00",cursorAccent:"#1c1917",selectionBackground:"#7c2d12",black:"#1c1917",red:"#f3554a",green:"#6cc24a",yellow:"#e5b02b",blue:"#58a6ff",magenta:"#c98bdf",cyan:"#f74c00",white:"#e7e0d8",brightBlack:"#a39a8f",brightRed:"#ff7b70",brightGreen:"#8fdd6e",brightYellow:"#ffcc55",brightBlue:"#83c0ff",brightMagenta:"#dcaaef",brightCyan:"#ff7a3d",brightWhite:"#fdf6ee"},tui:{border:"#4a4038",userChat:"#ffb454",userChatLabel:"#ffd08a",selectionBackground:"#7c2d12",selectionForeground:"#ffeadf",activeHighlightBackground:"#7c2d12",activeHighlightForeground:"#ffeadf",promptCursorBackground:"#f74c00",promptCursorForeground:"#1c1917"}}),op="#a35838",ap="M4.14 33.09L4.14 18.89L5.7 15.77L30.05 1.4L33.95 1.4L43.32 6.56L57.99 15.3L59.08 16.7L59.71 18.58L59.71 45.27L59.08 47.14L56.9 49.64L41.44 58.38L38.32 60.57L33.64 62.91L30.52 62.91L27.71 61.66L14.6 53.7L6.79 49.48L5.54 48.23L4.45 46.2L4.14 44.49L4.14 33.09ZM55.8 26.07L55.8 19.36L55.02 18.42L33.8 6.09L31.45 5.78L30.05 6.24L8.51 18.89L8.51 45.11L10.22 46.67L18.03 50.89L30.05 58.22L31.77 58.85L33.17 58.69L53.93 46.67L55.65 44.96L55.8 26.07ZM17.09 34.81L16.78 33.56L13.19 32.62L13.19 27.0L17.09 26.54L18.97 23.26L16.94 19.67L21.0 15.61L24.43 17.95L27.86 16.86L29.11 12.8L34.58 12.8L35.51 16.86L38.63 17.95L39.57 17.8L42.69 15.61L46.6 19.67L46.28 20.92L44.88 22.95L44.88 23.73L46.28 26.38L50.65 27.16L50.65 32.47L47.69 33.4L47.06 34.03L42.54 32.0L42.54 29.97L41.91 27.63L40.82 25.6L38.63 23.26L34.73 21.39L32.55 21.07L29.11 21.39L26.3 22.48L23.96 24.35L22.4 26.54L21.31 29.97L21.31 33.25L22.87 37.46L24.12 39.18L27.4 41.83L24.59 42.77L19.9 42.93L16.0 41.68L15.22 40.12L17.72 37.31L17.09 34.81ZM36.76 35.59L35.51 32.62L35.82 32.0L50.19 39.34L49.25 41.99L43.32 51.2L42.54 51.04L41.6 46.2L35.51 49.64L31.3 50.58L28.49 50.58L21.93 49.01L18.97 47.3L16.47 45.11L16.78 44.8L19.12 45.58L22.09 45.74L25.21 45.42L28.18 44.33L29.74 44.49L33.48 42.46L37.39 39.18L37.85 37.93L36.76 35.59Z",lp=Ne({id:"duroxide",label:"Duroxide",description:"Iron oxide pressed into black felt - the durable-execution runtime's own mark, traced from the banner.",group:Ft,icon:{viewBox:"0 0 64 64",paths:[{d:ap,fill:op}]},page:{background:"#201e1f",foreground:"#e5e0dc",overlayBackground:"#2e2c2d",overlayForeground:"#e5e0dc",hintColor:"#a89f99",modalBackdrop:"rgba(23, 21, 23, 0.86)",modalBackground:"#2e2c2d",modalBorder:"#4d4643",modalForeground:"#e5e0dc",modalMuted:"#a89f99",modalSelectedBackground:"#7c3f26",modalSelectedBorder:"#a35838",modalSelectedForeground:"#ffeee4"},terminal:{background:"#282627",foreground:"#e5e0dc",cursor:"#d2764a",cursorAccent:"#201e1f",selectionBackground:"#7c3f26",black:"#201e1f",red:"#e86a5f",green:"#7fb069",yellow:"#d9a441",blue:"#6a9fd4",magenta:"#b98bc4",cyan:"#d2764a",white:"#e5e0dc",brightBlack:"#a89f99",brightRed:"#f4897f",brightGreen:"#9bc888",brightYellow:"#efc069",brightBlue:"#8fbce4",brightMagenta:"#d0a8d9",brightCyan:"#ba714c",brightWhite:"#fdf7f2"},tui:{border:"#6a615b",userChat:"#e0b070",userChatLabel:"#f0cf9a",selectionBackground:"#7c3f26",selectionForeground:"#ffeee4",activeHighlightBackground:"#7c3f26",activeHighlightForeground:"#ffeee4",promptCursorBackground:"#d2764a",promptCursorForeground:"#201e1f"}}),cp=Ne({id:"spongebob",label:"SpongeBob",description:"Bikini Bottom at depth, sponge-yellow accents, and the cast as the status palette.",group:Ft,icon:{viewBox:"0 0 32 32",paths:[{d:"M0 0h32v32H0z",fill:"#1a7fa8"},{d:"M7 2h18a3 3 0 0 1 3 3v15a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V5a3 3 0 0 1 3-3z",fill:"#ffe01b"},{d:"M6.2 6.4a1.4 1.4 0 1 0 2.8 0a1.4 1.4 0 1 0-2.8 0z",fill:"#e3c00c"},{d:"M23.4 4.8a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0z",fill:"#e3c00c"},{d:"M5.4 18.2a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0-3 0z",fill:"#e3c00c"},{d:"M24 19a1.3 1.3 0 1 0 2.6 0a1.3 1.3 0 1 0-2.6 0z",fill:"#e3c00c"},{d:"M7.3 10a4.2 4.2 0 1 0 8.4 0a4.2 4.2 0 1 0-8.4 0z",fill:"#ffffff"},{d:"M16.3 10a4.2 4.2 0 1 0 8.4 0a4.2 4.2 0 1 0-8.4 0z",fill:"#ffffff"},{d:"M9.4 10a2.1 2.1 0 1 0 4.2 0a2.1 2.1 0 1 0-4.2 0z",fill:"#3fa9d8"},{d:"M18.4 10a2.1 2.1 0 1 0 4.2 0a2.1 2.1 0 1 0-4.2 0z",fill:"#3fa9d8"},{d:"M10.5 10a1 1 0 1 0 2 0a1 1 0 1 0-2 0z",fill:"#10202b"},{d:"M19.5 10a1 1 0 1 0 2 0a1 1 0 1 0-2 0z",fill:"#10202b"},{d:"M10 16.6c2 3.6 10 3.6 12 0c-1.2 5-10.8 5-12 0z",fill:"#6b4e00"},{d:"M14 17.6h1.9v2.1H14z",fill:"#ffffff"},{d:"M16.1 17.6H18v2.1h-1.9z",fill:"#ffffff"},{d:"M6 23h20v3H6z",fill:"#ffffff"},{d:"M14.4 24.6h3.2v2h-3.2z",fill:"#d2232a"},{d:"M13 26.4h6l-3 5.2z",fill:"#d2232a"}]},page:{background:"#07293c",foreground:"#e6f4fb",overlayBackground:"#0e3852",overlayForeground:"#e6f4fb",hintColor:"#8fb9cf",modalBackdrop:"rgba(7, 41, 60, 0.84)",modalBackground:"#0e3852",modalBorder:"#1d6a8c",modalForeground:"#e6f4fb",modalMuted:"#95bed3",modalSelectedBackground:"#ffe01b",modalSelectedBorder:"#fff08a",modalSelectedForeground:"#07293c"},terminal:{background:"#07293c",foreground:"#e6f4fb",cursor:"#ffe01b",cursorAccent:"#07293c",selectionBackground:"#ffe01b",black:"#07293c",red:"#ff6152",green:"#7ed957",yellow:"#ffa62b",blue:"#7fd4c1",magenta:"#ff9bd2",cyan:"#ffe01b",white:"#e6f4fb",brightBlack:"#8fb9cf",brightRed:"#ff9084",brightGreen:"#a5e888",brightYellow:"#ffc46b",brightBlue:"#a8e5d8",brightMagenta:"#ffbde1",brightCyan:"#fff08a",brightWhite:"#ffffff"},tui:{border:"#1d6a8c",userChat:"#ffa62b",userChatLabel:"#ffc46b",selectionBackground:"#ffe01b",selectionForeground:"#07293c",activeHighlightBackground:"#ffe01b",activeHighlightForeground:"#07293c",promptCursorBackground:"#ffe01b",promptCursorForeground:"#07293c"}});function dp(t,e){const s=oo.indexOf(t.group),n=oo.indexOf(e.group),r=s===-1?Number.MAX_SAFE_INTEGER:s,i=n===-1?Number.MAX_SAFE_INTEGER:n;return r!==i?r-i:t.label.localeCompare(e.label,void 0,{sensitivity:"base"})}const Pl=Object.freeze([Tl,qu,Gu,zu,Wu,Yu,Vu,Ku,Xu,Qu,Zu,Ju,ep,tp,sp,np,rp,ip,lp,cp].sort(dp)),up=new Map(Pl.map(t=>[t.id,t])),pp=Tl.id;function fp(){return Pl}function pt(t){return t?up.get(t)??null:null}const mp=new Set(["agent","user","system"]);function nn(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 hp(t){if(typeof t=="string"){const r=t.trim();return r?{filename:r,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:mp.has(t.source)?t.source:"agent"}}function rn(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const r of e){const i=hp(r);!i||n.has(i.filename)||(n.add(i.filename),s.push(i))}return s}function gp(t,e){const s=String(e||"").trim();return s&&rn(t).find(n=>n.filename===s)||null}function Kr(t){const e=t&&typeof t=="object"?t:{},s=Number(e.paneAdjust),n=Number(e.sessionPaneAdjust),r=Number(e.portalSessionColumnAdjust),i=Number(e.activityPaneAdjust),o=Number(e.canvasPaneAdjust),l=Number(e.diagnosticsPaneAdjust),c=Number(e.diagnosticsSplitAdjust);return{paneAdjust:Number.isFinite(s)?Math.trunc(s):0,sessionPaneAdjust:Number.isFinite(n)?Math.trunc(n):0,portalSessionColumnAdjust:Number.isFinite(r)?Math.trunc(r):0,activityPaneAdjust:Number.isFinite(i)?Math.trunc(i):0,canvasPaneAdjust:Number.isFinite(o)?Math.trunc(o):0,diagnosticsPaneAdjust:Number.isFinite(l)?Math.trunc(l):0,diagnosticsSplitAdjust:Number.isFinite(c)?Math.trunc(c):0}}function on(t){if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();!r||e.has(r)||(e.add(r),s.push(r))}return s}function Vr(t){if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();!r||e.has(r)||(e.add(r),s.push(r))}return s}function Sr(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 yp(t){return t==="canvas"?"canvas":"panes"}function Ml(t,e){const s=t&&typeof t=="object"?t:null;return s&&(typeof s.canvasOpen=="boolean"||typeof s.diagnosticsOpen=="boolean")?{canvasOpen:s.canvasOpen===!0,diagnosticsOpen:s.diagnosticsOpen===!0,zen:s.zen===!0&&s.canvasOpen===!0}:{canvasOpen:e==="canvas",diagnosticsOpen:!1,zen:!1}}function Qe(t,e){const s=String(t||""),n=Number(e);return Number.isInteger(n)&&n>=2&&n<=5?`${s}#${n}`:s}function bp(t){const e=/^(.*)#([2-5])$/.exec(String(t||""));return e?{sessionId:e[1],slot:Number(e[2])}:{sessionId:String(t||""),slot:1}}function Yr(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[s,n]of Object.entries(t)){const r=String(s||"").trim();if(!r||!n||typeof n!="object")continue;const i=Number(n.lastViewedRev),o=Number(n.lastViewedDataRev),l=Number(n.zenRailPx);e[r]={optedOut:n.optedOut===!0,lastViewedRev:Number.isFinite(i)&&i>0?Math.floor(i):0,lastViewedDataRev:Number.isFinite(o)&&o>0?Math.floor(o):0,...Number.isFinite(l)&&l>0?{zenRailPx:Math.floor(l)}:{}}}return e}function Rl(t){if(t==null)return null;const e=String(t).trim();return e||null}const Sp=Object.freeze(["limit","allowance","hold","no_provider"]);function os(t){const e=t?.pauseState;if(!e||typeof e!="object")return null;const s=String(e.kind||"");if(!Sp.includes(s))return null;const n=i=>{const o=String(i??"").trim();return o||null},r=i=>Number.isFinite(Number(i))?Number(i):null;return{kind:s,provider:n(e.provider),period:["day","week","month"].includes(String(e.period))?String(e.period):null,modelQualified:n(e.modelQualified),limitTokens:r(e.limitTokens),usedTokens:r(e.usedTokens),ceilingTokens:r(e.ceilingTokens),yourUsedTokens:r(e.yourUsedTokens),resetsAtUtc:n(e.resetsAtUtc)}}const vp=Object.freeze(["day","week","month"]),an=Object.freeze([14,30,90]),Ee=14;function vr({mode:t="local",branding:e=null,docs:s=null,themeId:n=null,sessionOwnerFilter:r=null,layoutAdjustments:i=null,pinnedSessionIds:o=null,collapsedSessionIds:l=null,activeSessionId:c=null,sessionOrder:d=null,rightPaneMode:p=null,desktopPanes:u=null,canvasPrefs:f=null}={}){const m=Ml(u,yp(p)),h=r!=null,g=l!=null,b=Kr(i);return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},docs:{agentPackageGuideUrl:s?.agentPackageGuideUrl||"https://github.com/affandar/PilotSwarm/blob/main/docs/building-agent-packages.md"},auth:{principal:null,authorization:null},ui:{focusRegion:$.SESSIONS,budgetOpen:!1,inspectorTab:ot[0],nodeMapSelectedNode:null,sequenceExpandedTurns:[],sequenceSelectedTurn:null,rightPaneMode:m.canvasOpen?"canvas":"panes",canvasOpen:m.canvasOpen,diagnosticsOpen:m.diagnosticsOpen,canvasZen:m.zen,canvasMaximized:!1,statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:pt(n)?.id||pp,touchScale:!1,modal:null,fullscreenPane:null,layout:{...b,viewportWidth:120,viewportHeight:40},scroll:{chat:0,inspector:0,activity:0,filePreview:0},chatScrollBySession:{},followBottom:{inspector:!0,activity:!0}},connection:{mode:t,connected:!1,workersOnline:null,error:null},sessions:{byId:{},groupRows:[],flat:[],activeSessionId:Rl(c),collapsedIds:Sr(l),collapsedIdsExplicit:g,pinnedIds:on(o),manualOrder:Vr(d),listingSeen:!1,groupsListingSeen:!1,selectedIds:[],selectMode:!1,listDeselected:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:h,ownerFilter:nn(r),navigationIntent:null,filterExceptionId:null},history:{bySessionId:new Map},outbox:{bySessionId:{}},orchestration:{bySessionId:{}},executionHistory:{bySessionId:{},format:"pretty"},files:{bySessionId:{},fullscreen:!1,selectedArtifactId:null,markedIds:[],previewOrigin:null,restoreArtifactId:null,paneOpen:!1,paneRestoresToHidden:!1,htmlViewMode:"rendered",htmlZoom:1,htmlFitWidth:!1,filter:{scope:"selectedSession",query:""}},canvas:{bySessionId:{},prefs:Yr(f),flipSeq:0},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},budget:{loading:!1,refreshing:!1,loaded:!1,error:null,fetchedAt:0,grid:[],overall:!1,rangeDays:Ee,selectedProvider:null,selectedScope:"*",missingProvider:null,series:{provider:null,scope:"*",rangeDays:Ee,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:{provider:null,scope:"*",rangeDays:Ee,totals:null,days:[],breakdown:[],loading:!1,loaded:!1,error:null,fetchedAt:0},paused:[],pausedError:null},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},modelProviders:{loading:!1,error:null,page:"mine",providers:[],models:[],defaults:null,fetchedAt:0,mutation:{pending:null,error:null},selection:{focus:"providers",providerName:null,agentId:null},create:{editing:!1,stage:"name",name:"",typeId:"",shared:!1,draft:"",cursorIndex:0,saving:!1,error:null}},section:"providers",packages:{loading:!1,error:null,list:[],workerState:[],fetchedAt:0,selectedName:null,detail:null,detailLoading:!1,detailError:null,changelog:null,workspace:{tree:null,treeLoading:!1,treeError:null,expandedDirs:[],selectedPath:null,file:null,fileLoading:!1,fileError:null},action:{pending:null,error:null},addDialog:{open:!1,kind:"repo",scope:"user",updateName:null,repoUrl:"",ref:"",path:"",url:"",authToken:"",submitting:!1,progress:null,error:null}},workers:{loading:!1,error:null,list:[],fetchedAt:0,attempts:0,lastAttemptAt:0,lastSkip:null}}}}function $l(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function wp(t,e){return!(!$l(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const _l="activeHighlightBackground",Xr="activeHighlightForeground",Kn="userChat",Ep="userChatLabel",kp="otherUserChatLabel",ao=new WeakMap,lo=new WeakMap;function xp(t){return t||Xr}function Ll(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?xp(s?.color):Xr,backgroundColor:_l,bold:s?.bold??!0}))}function lt(t,{color:e=Xr,bold:s=!0}={}){return{text:t,color:e,backgroundColor:_l,bold:s}}function it(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Ip=72;function Ol(t){const e=Number(t)||0;return e>0&&e<=Ip}function Fl(t){if(!t)return"unknown";const e=t.status||"unknown",s=e==="waiting"||e==="idle"||e==="unknown";return s&&os(t)?"budget_paused":t.cronActive===!0&&s?"cron_waiting":s&&(Number(t.activeChildCount)||0)>0?"awaiting_children":e}const co={day:"daily",week:"weekly",month:"monthly"};function Dl(t){if(!t)return"paused";switch(t.kind){case"no_provider":return"no provider";case"hold":return"paused · hold";case"allowance":return"paused · allowance";default:return"paused · limit"}}function Ap(t,e=Date.now()){const s=t?.provider||"this session's provider",n=t?.resetsAtUtc?fi(t.resetsAtUtc,e):null,r=n?` Resets ${n}.`:"";switch(t?.kind){case"no_provider":return t?.provider?`No provider named ${t.provider}. This session waits until that name exists again, or until it is switched to another provider and model.`:"This session's model does not name a provider, so nothing can pay for it. Switch it to a provider and model.";case"hold":return t?.resetsAtUtc?`${s} is on hold.${r}`:`${s} is on hold until an administrator releases it.`;case"allowance":{const i=co[t?.period];return`Your ${i?`${i} `:""}allowance on ${s} is used up. The provider has room; your share of it does not.${r}`}default:{const i=co[t?.period],o=t?.modelQualified?` for ${t.modelQualified}`:"";return`${s} has reached its ${i?`${i} `:""}limit${o}.${r}`}}}function Cp(t,e){const s=os(t);if(s)return s;const n=t?.sessionId;if(!n)return null;const i=(Array.isArray(e?.budget?.paused)?e.budget.paused:[]).find(o=>o?.sessionId===n);return i?os({pauseState:i.pause}):null}function Np(t,e=null){const s=Cp(t,e);return s?{kind:s.kind,provider:s.provider,period:s.period,resetsAtUtc:s.kind==="no_provider"?null:s.resetsAtUtc,label:Dl(s),reason:Ap(s),clears:Zf(s),color:"red"}:null}function Tp(t,e){if(e==="budget_paused")return Dl(os(t));if(e==="cron_waiting")return"waiting";if(e==="awaiting_children"){const s=Number(t?.activeChildCount)||0;return s>0?`waiting on ${s}`:"waiting on children"}return e}function Pp(t){if(!t)return null;const e=t.updatedAt||t.summaryUpdatedAt||t.latestSummaryUpdatedAt||t.createdAt||0;return{status:Bl(t)||"unknown",timestampMs:e||null,relative:e?yi(e):"—"}}function Bl(t){const e=Hl(t);return!e||e==="unknown"?"":Tp(t,e)}function Hl(t){return t?.rowVisualStatus||Fl(t)}function Ul(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function Qr(t){const e=Fl(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&$l(t?.error)&&!Ul(t?.orchestrationStatus)?"warning":null}function Zr(t,e="local"){const s=Qr(t);if(s)return s;const n=Hl(t);if(e==="remote"&&Ul(t?.orchestrationStatus)&&n!=="cron_waiting"&&n!=="awaiting_children"&&n!=="waiting"&&n!=="input_required"){if(t?.orchestrationStatus==="Completed")return"completed";if(t?.orchestrationStatus==="Terminated")return"terminated"}return n==="terminated"?"terminated":n}function es(t,e="local"){switch(Zr(t,e)){case"running":return"green";case"budget_paused":return"red";case"cron_waiting":return"yellow";case"awaiting_children":return"magenta";case"waiting":return"yellow";case"input_required":return"cyan";case"cancelled":return"gray";case"warning":return"yellow";case"failed":return"red";case"terminated":return"gray";case"completed":return"gray";case"idle":return"white";default:return"white"}}function jl(t,e="local"){switch(Zr(t,e)){case"running":return"*";case"budget_paused":return"‖";case"cron_waiting":return"~";case"awaiting_children":return">";case"waiting":return"~";case"input_required":return"?";case"cancelled":return"x";case"warning":return"!";case"failed":case"terminated":return"x";case"idle":return"";default:return""}}function Ie(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function En(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Jr=Ie({provider:"system",subject:"system"});function uo(t){const e=String(t||"").trim();if(!e)return"";const s=e.replace(/@.*/u,"").split(/[^A-Za-z0-9]+/u).map(r=>r.trim()).filter(Boolean);return s.length>=2?`${s[0][0]}${s[1][0]}`.toUpperCase():(s[0]||e).replace(/[^A-Za-z0-9]/gu,"").slice(0,2).toUpperCase()}function wr(t){return uo(t?.displayName)||uo(t?.email)||"?"}function Mp(t,e=!1){return is(t)?e?t.isGroup?"pinned:folders":"pinned:sessions":t.isGroup?"folders":t.groupId?`g:${t.groupId}`:"":null}function Gl(t,{isMine:e=!1}={}){if(!t)return null;const s=En(t,t?.email||"");return{initials:wr(t),hue:Lp(Op(t,t?.email)),name:s||"unknown user",isMine:!!e}}function Rp(t){const e=new Map;for(const s of Object.values(t||{})){const n=s?.owner;if(!n?.subject||!n.displayName&&!n.email)continue;const r=Ie(n);r&&!e.has(r)&&e.set(r,n)}return e}function $p(t,e){if(t?.owner?.displayName||t?.owner?.email)return t.owner;const s=e?.get?.(Ie(t?.owner))||null;return s||(t?.createdBy?{email:t.createdBy}:null)}const _p=8;function Lp(t){const e=String(t||"").trim().toLowerCase();if(!e)return 0;let s=2166136261;for(let n=0;n<e.length;n+=1)s^=e.charCodeAt(n),s=Math.imul(s,16777619)>>>0;return s%_p}function Op(t,e){return String(e||t?.email||t?.displayName||(t?.provider&&t?.subject?`${t.provider}:${t.subject}`:"")||"").trim().toLowerCase()}function Fp(t,e=1/0){const s=t?.sessions?.byId,n=t?.sessions?.ownerFilter||{all:!0},r=t?.auth||{},i=new Set;for(const o of Object.values(s||{})){if(!o||o.isSystem||o.isGroup)continue;const l=Ie(o.owner);if(!(!l||l===Jr)&&kr(o,n,r)&&(i.add(l),i.size>=e))break}return i.size}function Er(t){return Fp(t,2)>1}function zl(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function zt(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of zl(t,e)){const r=Ie(n?.owner);r&&!s.has(r)&&s.set(r,n.owner)}return s.size===1?s.values().next().value:null}function po(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function fo(t,e){const s=po(t),n=po(e?.agentId);return!!(s&&n&&s===n)}function Dp(t){if(!t?.agentId||t?.isSystem)return null;const e=String(t?.title||"").trim();if(!e)return null;const s=" · ",n=e.lastIndexOf(s);if(n>0){const o=e.slice(0,n).trim(),l=e.slice(n+s.length).trim();if(o&&fo(l,t))return{displayTitle:o,agentTitle:l}}const r=/^(.+?)\s+[–—-]\s+(.+)$/u.exec(e);if(r){const o=r[1].trim(),l=r[2].trim();if(o&&l)return{displayTitle:l,agentTitle:o}}const i=e.indexOf(": ");if(i>0){const o=e.slice(0,i).trim(),l=e.slice(i+2).trim();if(l&&fo(o,t))return{displayTitle:l,agentTitle:o}}return null}function Bp(t){const e=String(t||""),s=e.indexOf(": ");if(s<=0)return null;const n=e.slice(0,s).trim(),r=e.slice(s+2).trim();return!n||!r?null:{userTitle:r,typeTitle:n}}const Hp=[[/</g,"<"],[/>/g,">"],[/"/g,'"'],[/�?39;/g,"'"],[/'/g,"'"],[/ /g," "],[/&/g,"&"]];function Up(t){let e=String(t??"");if(!e.includes("&"))return e;for(const[s,n]of Hp)e=e.replace(s,n);return e}function ei(t){return Up(jp(t))}function jp(t){const e=String(t?.title||"").trim(),s=Dp(t);if(!s)return e;const n=Bp(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function Wl(t,e){const s=we(t?.sessionId);if(t?.isSystem)return`${Ot(t,e)} (${s})`;const n=ei(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function kr(t,e={},s={},n=void 0){if(!e||e.all===!0||t?.isGroup)return!0;if(t?.isSystem)return e.includeSystem===!0;const r=Ie(n!==void 0?n:t?.owner);if(!r)return e.includeUnowned===!0;if(r===Jr)return e.includeSystem===!0;const i=Ie(s?.principal);return e.includeMe&&i&&r===i||e.includeShared===!0&&r!==i?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(r)}function ql(t,e={},s={},n=null){const r=zt(t,n||{});if(kr(t,e,s,r))return!0;if(!n)return!1;if(t?.isGroup)return zl(t,n).some(l=>ql(l,e,s,n));let i=t,o=0;for(;i?.parentSessionId&&o<16;){const l=n[i.parentSessionId];if(!l)return!1;if(kr(l,e,s))return!0;i=l,o+=1}return!1}function Gp(t){return(t||[]).map(e=>e?.text||"").join("")}function ti(t){const e=new Map,s=new Map;for(const n of Object.values(t||{})){const r=n?.parentSessionId;r&&(s.set(n.sessionId,r),e.has(r)||e.set(r,[]),e.get(r).push(n.sessionId))}return{childMap:e,parentMap:s}}function mo(t){const{childMap:e}=ti(t),s=new Map,n=new Set;function r(i){if(s.has(i))return s.get(i);if(n.has(i))return 0;n.add(i);const l=(e.get(i)||[]).reduce((c,d)=>c+1+r(d),0);return n.delete(i),s.set(i,l),l}for(const i of Object.keys(t||{}))r(i);return s}function ho(t=[],e={}){const{parentMap:s}=ti(e),n=new Map;for(const r of t){let i=s.get(r.sessionId);for(;i;)n.set(i,(n.get(i)||0)+1),i=s.get(i)}return n}function si(t={}){if(!t||typeof t!="object")return mo(t);const e=ao.get(t);if(e)return e;const s=mo(t);return ao.set(t,s),s}function ni(t=[],e={}){if(!Array.isArray(t))return ho(t,e);const s=lo.get(t);if(s)return s;const n=ho(t,e);return lo.set(t,n),n}function Kl(t,e,s,n){const r=s.get(t)||0,i=n.get(t)||0,o=Math.max(0,r-i),l=e?.collapsed?r:o;return l?{text:`[+${l}]`,color:"cyan"}:null}function ln(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 zp(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${ln(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${qt(t.cronInterval)}]`,color:"magenta"}:null}function Vl(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Wp(t,e){const s=[];typeof t?.regenStage=="string"&&t.regenStage&&s.push({text:`↻ regen:${t.regenStage}`,color:"magenta"});const n=Bl(t);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:es(t,e)}));const r=di(t?.model,t?.reasoningEffort);r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r,color:"cyan"}));const i=Id(t?.contextUsage);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i.text,color:i.color}));const o=Ad(t?.contextUsage);return o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color})),s}function qp(t,e,s,n,r){const i=[],o=s.connection?.mode||"local",l=t.depth>0?`${" ".repeat(Math.max(0,t.depth-1))}└ `:"";l&&i.push({text:l,color:"gray",role:"depth"});const c=new Set(Array.isArray(s.sessions?.pinnedIds)?s.sessions.pinnedIds:[]),d=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),p=!!s.sessions?.selectMode,u=d.has(t.sessionId),f=c.has(t.sessionId);if(u&&i.push({text:"▌",color:"cyan",bold:!0,role:"selection"}),t.depth===0&&Vl(e)&&c.size>0&&(f&&!e?.isSystem?i.push({text:"📌 ",color:"yellow"}):i.push({text:" ",color:"gray"})),e?.isGroup)i.push({text:"🗂 ",color:"cyan",bold:!0});else if(e?.isSystem)i.push({text:"⚙ ",color:"yellow",bold:!0});else if(e?.serviceKind)i.push({text:"⚗ ",color:"magenta",bold:!0});else{const q=jl(e,o);i.push({text:q?`${q} `:" ",color:es(e,o),role:"status"})}const m=e?.isGroup?"cyan":e?.isSystem?"yellow":es(e,o),h=zt(e,s.sessions?.byId||{}),g=we(e?.sessionId),b=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,y=b?zm(b):"",v=di(e?.model,e?.reasoningEffort),E=e?.isSystem?Ot(e,s.branding?.title||"PilotSwarm"):ei(e),k=!!(e?.isSystem||e?.isGroup||E&&E.trim()),x=[...i];if(Er(s)&&!e?.isSystem&&!e?.isGroup){const q=Ie(s?.auth?.principal),Z=!!(q&&Ie(h)===q),ue=h?wr(h):"?";x.push({text:`[${ue}] `,color:Z?"green":"cyan",bold:!0,ownerChip:!0})}k?x.push({text:E,color:m,bold:!!(e?.isSystem||e?.isGroup)}):(x.push({text:g,color:m}),y&&(x.push({text:" · ",color:"gray"}),x.push({text:y,color:"gray"})),v&&(x.push({text:" · ",color:"gray"}),x.push({text:v,color:"green"})));const w=Kl(e?.sessionId,t,n,r);w&&x.push({text:` ${w.text}`,color:w.color,bold:w.bold});const S=Zr(e,o)==="budget_paused"||e?.status==="waiting"?Np(e,s):null;S&&x.push({text:` ${S.label}`,color:S.color});const C=zp(e);C&&x.push({text:" ⏱",color:"magenta"});const M=[],_=e?.contextUsage?.compaction?.state,O=Br(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&M.push({text:`${e.memberCount}`,color:"gray"}):_==="running"?M.push({text:"⇊",color:"magenta"}):_==="failed"?M.push({text:"!",color:"red"}):O!=null?M.push({text:`${O}%`,color:O>=85?"red":O>=70?"yellow":"green"}):M.push({text:"—",color:"gray"});const R=[];e?.isGroup&&e?.memberCount!=null&&(R.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),y&&(R.push({text:" · ",color:"gray"}),R.push({text:y,color:"gray"})));const T=[],N=()=>{T.length&&T.push({text:" · ",color:"gray"})};if(e?.isGroup)T.push(...R);else{k&&(T.push({text:g,color:"cyan"}),y&&(N(),T.push({text:y,color:"gray"})),v&&(N(),T.push({text:v,color:"green"})));const q=e?.contextUsage;q&&Number.isFinite(q.currentTokens)&&Number.isFinite(q.tokenLimit)&&q.tokenLimit>0&&(N(),T.push({text:`ctx ${te(q.currentTokens)}/${te(q.tokenLimit)}`,color:"gray"}));const Z=n?.[e?.sessionId];Z&&(N(),T.push({text:`${Z} child${Z===1?"":"ren"}`,color:"gray"})),C&&(N(),T.push({text:C.text,color:C.color})),S&&(N(),T.push({text:S.reason,color:S.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(N(),T.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...x,...k&&y&&!e?.isGroup?[{text:" ",color:"gray"},{text:y,color:"gray"}]:[],...M.length&&!e?.isGroup?[{text:" · ",color:"gray"},...M]:[],...e?.isGroup&&R.length?[{text:" ",color:"gray"},...R]:[]],titleRuns:x,ctxRuns:M,metaRuns:R,badgeRuns:[],selectedMetaRuns:T,detailRuns:T,childCount:n?.get?.(e?.sessionId)||0,chrome:{kind:e?.isGroup?"group":e?.isSystem?"system":e?.serviceKind?"service":"session",title:k?E:g,untitled:!k,statusColor:es(e,o),accentColor:m,pinned:f,selectMode:p,checked:u,owner:Er(s)&&!e?.isSystem&&!e?.isGroup?{initials:h?wr(h):"?",isMine:!!(Ie(s?.auth?.principal)&&Ie(h)===Ie(s?.auth?.principal))}:null,childBadge:w?{text:w.text,color:w.color}:null,pause:S,cron:!!C,age:y||null,model:v||null,shortId:g,ctx:M.length>0?{text:M[0].text,color:M[0].color}:null}}}function Yl(t){return String(t||"").trim().toLowerCase()}function Pt(t,e){const s=Yl(e);return s?String(t||"").toLowerCase().includes(s):!0}function Kp(t){const e=t?.filterExceptionId||null,s=t?.byId||{};if(!e||!s[e])return null;const n=new Set([e]);let r=s[e],i=0;for(;r&&i<16;){let o=null;if(r.parentSessionId&&s[r.parentSessionId]?o=r.parentSessionId:!r.isGroup&&r.groupId&&s[`group:${r.groupId}`]&&(o=`group:${r.groupId}`),!o||n.has(o))break;n.add(o),r=s[o],i+=1}return n}const go=new WeakMap;function Vp(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 as(t){const e=si(t.sessions.byId),s=ni(t.sessions.flat,t.sessions.byId),n=Yl(t.sessions?.filterQuery||""),r=t.sessions?.ownerFilter||{all:!0},i=t.auth||{},o=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),l=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]),c=Kp(t.sessions);let d=go.get(t.sessions.flat);return d||(d=new Map,go.set(t.sessions.flat,d)),t.sessions.flat.filter(p=>!!(t.sessions.byId[p.sessionId]||p.standIn)).map(p=>{const u=t.sessions.byId[p.sessionId]||p.standIn,f=p.sessionId===t.sessions.activeSessionId&&!t.sessions.listDeselected,m=o.has(p.sessionId),h=l.has(p.sessionId),g=[p,u,f,m,h,n,r,i,t.connection?.mode,t.sessions.selectMode,e,s,t.branding?.title,t.canvas?.bySessionId?.[p.sessionId],t.canvas?.prefs?.[p.sessionId],u?.pauseState,t.budget?.paused],b=d.get(p.sessionId);if(b&&Vp(b.deps,g))return b.row;const y=qp(p,u,t,e,s),v={sessionId:p.sessionId,text:Gp(y.runs),...y,depth:p.depth,status:u?.status,statusColor:es(u,t.connection?.mode||"local"),active:f,groupId:u?.groupId||p?.groupId||null,isSystem:!!u?.isSystem,isGroup:!!u?.isGroup,hasChildren:p.hasChildren,collapsed:p.collapsed,pinned:m,selected:h,canPin:Vl(u),ownerBadge:Er(t)&&!u?.isSystem&&!u?.isGroup&&zt(u,t.sessions.byId)?Gl(zt(u,t.sessions.byId),{isMine:!!(Ie(t?.auth?.principal)&&Ie(zt(u,t.sessions.byId))===Ie(t?.auth?.principal))}):null,orderable:is(u),orderContainer:Mp(u,m),canvasMark:Af(t,p.sessionId),pause:y.chrome?.pause||null};return d.set(p.sessionId,{deps:g,row:v}),v}).filter(p=>{if(c?.has(p.sessionId))return!0;const u=t.sessions.byId[p.sessionId];if(!ql(u,r,i,t.sessions.byId))return!1;const f=zt(u,t.sessions.byId),m=f?`${En(f,"")} ${f.email||""}`:"";return Pt(p.text,n)||Pt(p.sessionId,n)||Pt(m,n)||Pt("",n)})}function xr(t,e=8){const s=as(t);if(s.length===0)return[];const n=new Set(s.map(u=>u.sessionId)),r=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(u=>n.has(u.sessionId)),i=r.findIndex(u=>u.sessionId===t.sessions.activeSessionId),o=Math.max(0,i);if(r.length<=e)return s;const l=Math.floor(e/2);let c=Math.max(0,o-l),d=Math.min(r.length,c+e);d>r.length&&(d=r.length,c=Math.max(0,d-e));const p=r.slice(c,d);return si(t.sessions.byId),ni(r,t.sessions.byId),s.filter(u=>p.some(f=>f.sessionId===u.sessionId))}function Je(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function Yp(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 VS(t){const e=t.sessions?.filterExceptionId||null;return!e||!t.sessions?.byId?.[e]?null:"Showing linked session outside your current filters."}function Xl(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function Xp(t){const e=t?.pendingQuestion;if(!e?.question)return null;const s=[String(e.question).trim()],n=Array.isArray(e.choices)?e.choices.filter(r=>typeof r=="string"&&r.trim()):[];if(n.length>0){s.push("","Choices:");for(const r of n)s.push(`- ${r}`)}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 Qp(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),r=String(s?.answer||"").trim();if(!n||!r||Ql(e,n))return null;const i=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: "${r}"`,time:"",createdAt:o,optimistic:!0,pendingPhase:i}}function Zp(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 Ql(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>zr(n?.text||"")?.question?.trim()===s):!1}function Jp(t){const e=String(t?.error||"").trim();if(!e)return null;const s=Qr(t);if(!s)return null;const n=s==="failed",r=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:r,time:"",createdAt:t.updatedAt||Date.now(),cardTitle:n?"Error":"Warning",cardTitleColor:n?"red":"yellow",cardBorderColor:n?"red":"yellow"}}function yo(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 ef(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function tf(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 r=s.length-1;r>=0;r-=1){const i=s[r];if(!i||n.has(i.eventType)||Number(i?.seq||0)<=e)continue;const o=ef(i.text);if(o)return{...i,summaryText:o}}return null}function sf(t,e,s=[],n=[]){if(!t||t?.pendingQuestion?.question)return null;const r=String(t?.status||"").toLowerCase();if(r==="completed"||r==="failed"||r==="cancelled")return null;const i=(s||[]).filter(x=>x?.role==="user"||x?.role==="assistant"),o=i[i.length-1]||null,l=o?.role==="user",c=l&&o?.optimistic===!0,d=(n||[]).filter(x=>x?.phase==="pending").length,p=(n||[]).filter(x=>x?.phase==="queued").length,u=(n||[]).filter(x=>x?.phase==="cancelling").length,f=Array.isArray(e?.events)?e.events:[],m=yo(f,"user.message"),h=yo(f,"assistant.message"),g=m>h;if(r==="waiting"||r==="input_required"||!l&&!g&&r!=="running"&&!c)return null;const b=Math.max(m,h),y=f.filter(x=>x?.eventType==="assistant.reasoning"&&Number(x?.seq||0)>b),v=y[y.length-1]||null,E=String(v?.data?.content||v?.data?.text||v?.data?.message||"").trim();if(E)return{kind:"thinking",label:"Thinking",text:E,createdAt:v?.createdAt||t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:h,tokenSeq:v?.seq||0};const k=tf(e,b);return k?.summaryText?{kind:r==="running"?"working":"sending",label:r==="running"?"Working":"Sending",text:k.summaryText,createdAt:k.createdAt||t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:h,tokenSeq:k.seq||0}:d>0?{kind:"pending",label:d===1?"Pending":`Pending ${d}`,text:d===1?"One prompt is waiting to be sent.":`${d} prompts are waiting to be sent.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:h,tokenSeq:0}:p>0?{kind:"queued",label:p===1?"Queued":`Queued ${p}`,text:p===1?"One prompt is durably queued, waiting for the LLM to receive it.":`${p} prompts are durably queued, waiting for the LLM to receive them.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:h,tokenSeq:0}:u>0?{kind:"cancelling",label:u===1?"Cancelling":`Cancelling ${u}`,text:u===1?"One queued prompt is waiting for cancellation confirmation.":`${u} queued prompts are waiting for cancellation confirmation.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:h,tokenSeq:0}:c?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:o?.createdAt||t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:h,tokenSeq:0}:r==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:t.updatedAt||Date.now(),lastUserSeq:m,lastAssistantSeq:h,tokenSeq:0}:null}function ri(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return Dn(t.branding);if(s?.isGroup){const d=Object.values(t.sessions.byId||{}).filter(m=>m&&!m.isGroup&&m.groupId===s.groupId&&!m.parentSessionId),p=m=>String(m??"").replace(/\|/g,"\\|").replace(/[\r\n]+/g," ").trim()||" ",u=d.map(m=>`| ${p(m.title||m.sessionId)} | ${p(m.status||"unknown")} |`),f=[`# ${s.title||s.groupId}`,s.shortSummary||"","","| Metric | Count |","|---|---:|",`| Members | ${s.memberCount??d.length} |`,`| Running | ${s.runningCount??0} |`,`| Waiting | ${s.waitingCount??0} |`,`| Completed | ${s.completedCount??0} |`,`| Failed | ${s.failedCount??0} |`,`| Cancelled | ${s.cancelledCount??0} |`,"","## Members",...u.length>0?["| Session | Status |","|---|---|",...u]:["_No top-level members._"]];return[{id:`group-details:${s.sessionId}`,role:"system",noChrome:!0,text:f.filter((m,h)=>h===1||String(m||"").length>0).join(`
|
|
30
|
-
`),createdAt:s.updatedAt||Date.now()}]}const n=t.history.bySessionId.get(e),r=n?.chat||[],i=s?.pendingQuestion?.question&&!Ql(r,s.pendingQuestion.question)?Xp(s):null,o=Qp(s,r),l=Jp(s);if((!n||r.length===0)&&!i&&!o&&!l)return Dn(t.branding,s);const c=r.length>0?[...r]:Dn(t.branding,s);return i&&c.push(i),o&&c.push(o),l&&c.push(l),c}function Vn(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function nf(t,e={}){const s=Fe(t?.createdAt||t?.time),n=t?.sender,r=n?.kind==="user"?Ie(n):null,i=e?.viewerKey||null,o=e?.ownerKey||null,l=e?.sharedContext===!0,c=t?.role==="user",p=l&&c&&r&&!(c&&r&&i&&r===i),f=l&&c&&o&&(r&&r===o||!r&&i&&i===o)?" (owner)":"",m=c?(p?n.display||n.subject||"User":"You")+f:t?.role==="assistant"?"Agent":t?.role==="system"?"System":"PilotSwarm";let h=null,g=null;t?.pendingPhase==="pending"?(h="○",g="yellow"):t?.pendingPhase==="queued"?(h="✓",g="cyan"):t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?(h="x",g="red"):t?.role==="user"&&!t?.optimistic&&!t?.pendingPhase&&(t?.stopped?(h="⊘",g="yellow"):t?.redelivered?(h="✓✓↻",g="yellow"):(h="✓✓",g="green"));const b=t?.pendingPhase==="pending"?"yellow":t?.pendingPhase==="queued"?"cyan":t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?"red":p?kp:t?.role==="user"?Ep:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white";return{time:s,glyph:h,glyphColor:g,roleLabel:m,roleColor:b,fromOtherPerson:p}}function rf(t,e={}){const{time:s,glyph:n,glyphColor:r,roleLabel:i,roleColor:o}=nf(t,e),l=s?`[${s}] `:"",c=[...Vn(l,"gray")];return n&&c.push(...Vn(`${n} `,r)),c.push(...Vn(`${i}: `,o,{bold:!0})),c}function Et(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function Zl(){return[{text:"",color:null}]}function of(t){const e=(t||[]).find(n=>Et(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=Et(e).trimStart();return/^[┌│└]/.test(s)}function cn(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(Et(s).trim().length>0)break;e.shift()}return e}function af(t){const e=String(t||"").replace(/\r\n/g,`
|
|
31
|
-
`),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(`
|
|
32
|
-
|
|
33
|
-
[SYSTEM:`);if(n>=0&&e.trimEnd().endsWith("]")){const r=e.slice(0,n).trimEnd(),i=e.slice(n+2).trim();if(i.startsWith("[SYSTEM:"))return{leadingText:r,systemText:i.slice(8,-1).trim()}}return lf.test(s)?{leadingText:"",systemText:s}:null}const lf=/^(?: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 Jl(t){const e=af(t);if(e){const o=[];e.leadingText&&o.push({kind:"text",text:e.leadingText});const l=wt(e.systemText);return l&&o.push({kind:"system",text:l}),o}const s=String(t||"").replace(/\r\n/g,`
|
|
34
|
-
`).split(`
|
|
35
|
-
`),n=[];let r=[];function i(){r.length!==0&&(n.push({kind:"text",text:r.join(`
|
|
36
|
-
`)}),r=[])}for(let o=0;o<s.length;){const l=s[o];if(!/^\s*\[SYSTEM:/i.test(l)){r.push(l),o+=1;continue}const c=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(l);if(c){i();const f=wt(c[1].trim());if(!f){o+=1;continue}n.push({kind:"system",text:f}),o+=1;continue}const d=[l.replace(/^\s*\[SYSTEM:\s*/i,"")];let p=-1;for(let f=o+1;f<s.length;f+=1){const m=s[f];if(m.trim()==="]"){p=f;break}if(/\]\s*$/.test(m.trim())){const h=m.replace(/\]\s*$/,"");h.trim()&&d.push(h),p=f;break}d.push(m)}if(p===-1){r.push(l),o+=1;continue}i();const u=wt(d.join(`
|
|
37
|
-
`).trim());if(!u){o=p+1;continue}n.push({kind:"system",text:u}),o=p+1}return i(),n}function cf(t){return t?t?.role==="system"?!Gr(t?.text||"")||!!wt(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:Jl(t?.text||"").some(e=>e.kind==="system"):!1}function bo(t){return cf(t)?"system":t?.role||"other"}function ec(t,e){return!t||!e?!1:bo(t)!==bo(e)}function df(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 r=/^(.{1,160}?[.!?])(?:\s|$)/.exec(e)?.[1]?.trim()||e;return r.length>=e.length?r.length>160?`${r.slice(0,159).trimEnd()}…`:r:`${r}…`}function uf(t,e=""){const s=df(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:Kt(t),color:"gray"}}function So({title:t,summary:e,body:s,timestamp:n="",color:r="gray"}){const i=String(t||"System").trim()||"System",o=String(e||"").replace(/\s+/g," ").trim();return{kind:"systemNotice",text:`${n?`[${n}] `:""}${i}${o?`: ${o}`:""}`,summary:o,body:Kt(s||o),color:r}}function pf(t){return t?.label?[{text:t.label,color:t.kind==="working"?"yellow":"cyan",bold:!0}]:null}function ff(t,e){return e?(t||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||e})):s):t}function mf(t){const e=(t||[]).find(s=>Et(s).trim().length>0);return e?Et(e).trimStart().startsWith("┌"):!1}function dn(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&mf(e)&&Et(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function hf(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 r=[],i=/(?:^|\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=i.exec(e))!==null;)r.push({agentId:o[1],task:o[2],status:o[3],result:o[4].trim()});return r.length===0?null:s||r.length===1?{kind:"subAgentSingle",...r[0]}:{kind:"subAgentMulti",agents:r}}function gf(t,e,s){const n=Math.max(20,Number(s)||20),r=Fe(e?.createdAt||e?.time),i=hf(t),o=l=>{const c=String(l||"").replace(/^session-/i,"");return we(c)||c||String(l||"")};if(i?.kind==="subAgentSingle"){const l=o(i.agentId),c=[i.task?`**Task:** ${i.task}`:"",i.status?`**Status:** ${i.status}`:"","",i.result||"_(no result)_"].filter((d,p)=>p===2||d).join(`
|
|
38
|
-
`);return[So({title:`Sub-agent Response — ${l}`,summary:i.status||"completed",timestamp:r,body:c,color:"cyan"})]}if(i?.kind==="subAgentMulti"){const l=i.agents.map(d=>{const p=o(d.agentId),u=d.task?`**Task:** ${d.task}`:"",f=d.status?`**Status:** ${d.status}`:"";return`${[`### ${p}`,u,f].filter(Boolean).join(`
|
|
39
|
-
`)}
|
|
40
|
-
|
|
41
|
-
${d.result||"_(no result)_"}`}),c=i.agents.map(d=>`${o(d.agentId)} ${d.status||"completed"}`).join(" · ");return[So({title:`Sub-agent Responses (${i.agents.length})`,summary:c,timestamp:r,body:l.join(`
|
|
42
|
-
|
|
43
|
-
---
|
|
44
|
-
|
|
45
|
-
`),color:"cyan"})]}return Ce({title:"System",timestamp:r,body:t,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function yf(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),r=Fe(t?.createdAt||t?.time),i=String(t?.thinkingLabel||"Thinking…").trim()||"Thinking…",o=t?.progressKind==="working"?"yellow":(t?.progressKind==="sending","cyan"),l=he([{text:` ⠋ ${i} `,color:o,bold:!0},...r?[{text:` ${r} `,color:"gray"}]:[]],Math.max(1,s-3)),c=l.reduce((f,m)=>f+String(m?.text||"").length,0),d=Math.max(0,s-c-3),p=String(t?.text||"").trim()?cn(ns(Kt(t.text),{width:n})).flatMap(f=>sl(f,n)):[],u=[[{text:"┌─",color:"gray"},...l,{text:`${"─".repeat(d)}┐`,color:"gray"}]];for(const f of p)u.push([{text:"│ ",color:"gray"},...tl(f.map(m=>({...m,color:m?.color&&m.color!=="white"?m.color:"gray"})),n),{text:" │",color:"gray"}]);return u.push([{text:`└${"─".repeat(Math.max(1,s-2))}┘`,color:"gray"}]),u.push([{text:"",color:null}]),u}function bf(t){return String(t||"").split(`
|
|
46
|
-
`).reduce((e,s)=>Math.max(e,Hr(s).length),0)}function un(t,e,s={}){if(t?.splash){const d=t.mobileText&&bf(t.text)>e;return[{kind:"markup",value:d?t.mobileText:t.text,splashAlt:!d&&t.mobileText?t.mobileText:null}]}if(t?.thinking)return yf(t,e);if(t?.noChrome)return cn(ns(Kt(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const d=zr(t?.text||"");if(d)return[...Ce({title:"Question",timestamp:Fe(t?.createdAt||t?.time),body:d.question,width:Math.max(20,e),titleColor:Kn,borderColor:Kn,tableMode:s.tableMode}),...un({...t,text:d.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const d=Jl(t?.text||"");if(d.some(p=>p.kind==="system")){const p=[];let u=!1;for(const m of d)m.kind!=="system"&&m.text.trim()&&(dn(p,un({...t,text:m.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:u})),u=!0);if(p.length>0)return p;const f=[];for(const m of d)m.kind!=="system"||!m.text.trim()||dn(f,gf(m.text,t,e));if(f.length>0)return f}}if(t?.role!=="user"&&t?.role!=="assistant"){const d=wt(t?.text||"");if(t?.role==="system"&&!d)return[];const p=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!p)return[uf(d||t?.text||"",Fe(t?.createdAt||t?.time))];const u=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return Ce({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:Fe(t?.createdAt||t?.time),body:Kt(t?.text||""),width:Math.max(20,e),titleColor:t?.cardTitleColor||(t?.role==="system"?"yellow":"cyan"),borderColor:t?.cardBorderColor||"gray",tableMode:s.tableMode,...u?{bodyColor:"gray",fitToContent:!0}:{}})}const n=cn(ns(Kt(t?.text||""),{width:e,tableMode:s.tableMode})),r=ff(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?Kn:null),i=s.skipPrefix?[]:rf(t,s),o=Sf(t,s);if(r.length===0){const d=i.length>0?[i]:[];return o.length>0?[...d,...o]:d}if(of(r)){const d=i.length>0?[i,...r]:r;return o.length>0?[...d,...o]:d}const l=[];let c=i.length===0;for(const d of r){if(!Array.isArray(d)){c||(l.push(i),c=!0),l.push(d);continue}c?l.push(d):(l.push([...i,...d]),c=!0)}return l.push(...o),l}function Sf(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 r=Number(n?.sizeBytes)||0,i=r>=1024*1024?`${(r/(1024*1024)).toFixed(1)} MB`:r>=1024?`${Math.round(r/1024)} KB`:`${r} B`;return[{text:" ",color:null},{text:`[image: ${n.filename}${r>0?` · ${i}`:""}]`,color:"cyan"}]})}const vf=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 wf(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 r=Math.floor(s/60),i=s%60;return`${r}h ${String(i).padStart(2,"0")}m`}const Ef=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),kf=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function xf(t,e){const s=String(t||"").toLowerCase();return s==="search_skills"||s.includes("skill")?e?"loading skills…":"loaded skills":Ef.has(s)?e?"reading facts…":"read facts":kf.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 If(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 r=xf(n,e==="tool.execution_start");if(r)return r;const i=n.length>28?`${n.slice(0,27)}…`:n;return e==="tool.execution_start"?`running tool: ${i}…`:`finished tool: ${i}`}switch(e){case"skill.invoked":return"loading skills…";case"learned_skill.read":return"loading skills…";case"skills.searched":return"loading skills…";case"facts.searched":case"facts.similar":return"reading facts…";case"graph.searched":case"graph.node_searched":case"graph.node_loaded":return"reading the graph…";case"graph.namespace_mutated":return"writing to the graph…";case"assistant.reasoning":return"thinking…";case"assistant.intent":return"planning…";case"assistant.message_start":case"assistant.message":return"writing reply…";case"session.compaction_start":return"compacting context…";case"session.compaction_complete":return"context compacted";case"session.dehydrated":return"dehydrating…";case"session.hydrated":case"session.rehydrated":return"rehydrating…";case"session.agent_spawned":return"coordinating agents…";case"session.wait_started":return"waiting…";case"session.input_required_started":return"awaiting input…";case"session.lossy_handoff":return"moving to a new worker…";case"session.error":return"recovering from an error…";default:return""}}function ii(t,e={}){const s=Je(t);if(!s||s.isGroup)return[];if(String(s?.status||"").toLowerCase()!=="running")return[];const r=t.history?.bySessionId?.get(s.sessionId)||null,i=Array.isArray(r?.chat)?r.chat:[];let o=0;for(let v=i.length-1;v>=0;v-=1)if(i[v]?.role==="user"){o=Number(i[v]?.createdAt||0);break}const l=Array.isArray(r?.activity)?r.activity:[];let c=0,d=0;for(let v=l.length-1;v>=0;v-=1){const E=l[v],k=E?.eventType,x=Number(E?.createdAt||0);if(!c&&k==="assistant.turn_start"&&(c=x),!d&&(k==="assistant.turn_end"||k==="session.turn_completed")&&(d=x),c&&d)break}let p=0;o>d?p=o:c>d&&(p=c);let u=null;for(let v=l.length-1;v>=0;v-=1){const E=l[v];if(!(!E||vf.has(E.eventType))){if(Number(E.createdAt||0)<=d)break;u=E;break}}const f=Number.isFinite(e.now)?e.now:Date.now(),m=p>0?wf(f-p):"",h=String(e.spinnerFrame||"").trim()||"●",g=u?If(u):"",b=[{text:`${h} `,color:"cyan"},{text:"Working",color:"cyan"},...m?[{text:` · ${m}`,color:"gray"}]:[],...g?[{text:` — ${g}`,color:"gray"}]:[]],y=Math.max(24,Math.min(120,Math.floor(Number(e.maxWidth)||80)));return[he(b,y)]}const vo=4;let $s=[];function oi(t,e=80,s={}){const n=t?.sessions?.activeSessionId??null,r={sessionId:n,session:n?t?.sessions?.byId?.[n]??null:null,byId:t?.sessions?.byId??null,chat:t?.history?.bySessionId?.get?.(n)?.chat??null,branding:t?.branding??null,principal:t?.auth?.principal??null,maxWidth:e,tableMode:s?.tableMode??null};for(const h of $s)if(h.sessionId===r.sessionId&&h.session===r.session&&h.byId===r.byId&&h.chat===r.chat&&h.viewMode===r.viewMode&&h.branding===r.branding&&h.principal===r.principal&&Object.is(h.maxWidth,r.maxWidth)&&h.tableMode===r.tableMode)return h.lines;const i=h=>($s.unshift({...r,lines:h}),$s.length>vo&&($s.length=vo),h),o=ri(t);if(!o||o.length===0)return i([{text:"No messages yet.",color:"gray"}]);const l=Ie(t?.auth?.principal),c=t?.sessions?.activeSessionId,d=c?t?.sessions?.byId?.[c]:null,p=Ie(d?.owner),u=!!(d&&(d.visibility&&d.visibility!=="private"||p&&l&&p!==l)),f={...s?.tableMode?{tableMode:s.tableMode}:{},...l?{viewerKey:l}:{},...p?{ownerKey:p}:{},...u?{sharedContext:!0}:{}},m=[];for(const[h,g]of o.entries()){if(g?.kind==="epoch-divider")m.push(Tf(g,e));else if(g?.kind==="regen-refused")m.push(Mf(g,e));else if(g?.kind==="regen-failed")m.push(Rf(g,e));else if(g?.kind==="canvas-update")m.push(Nf(g,g.sessionId||n));else if(g?.kind==="canvas-action")m.push(Cf(g));else{const y=un(g,e,f);dn(m,y)}const b=o[h+1];b&&ec(g,b)&&Et(m[m.length-1]).trim().length>0&&m.push(Zl())}return i(m.length>0?m:[{text:"No messages yet.",color:"gray"}])}function Af(t,e){if(!e)return null;let s=null;for(let n=1;n<=5;n+=1){const r=Qe(e,n),i=t?.canvas?.bySessionId?.[r],o=t?.canvas?.prefs?.[r];if(!i){(o?.lastViewedRev||0)>0&&(s=s||"canvas");continue}const l=i.latestRev||0;if(l<=0||i.sizeBytes===0)continue;if(l>(o?.lastViewedRev||0)||(i.latestDataRev||0)>(o?.lastViewedDataRev||0))return"unseen";s="canvas"}return s}function ai(t){const e=t?.sessions?.activeSessionId||null,s=Number(t?.ui?.canvasSlot)||1,n=t?.canvas?.bySessionId||{},r=[];if(e)for(let g=1;g<=5;g+=1){const b=n[Qe(e,g)];if(!b||(b.latestRev||0)<=0||b.sizeBytes===0)continue;const y=t?.canvas?.prefs?.[Qe(e,g)];r.push({slot:g,name:typeof b.name=="string"?b.name:"",latestRev:b.latestRev||0,unseen:(b.latestRev||0)>(y?.lastViewedRev||0)||(b.latestDataRev||0)>(y?.lastViewedDataRev||0)})}const i=r.some(g=>g.slot===s)?s:1,o=e?Qe(e,i):null,l=o?n[o]:null,c=o?t?.canvas?.prefs?.[o]:null,d=l?.latestRev||0,p=c?.lastViewedRev||0,u=l?.latestDataRev||0,f=c?.lastViewedDataRev||0,m=t?.ui?.canvasOpen?"canvas":"panes",h=d>0&&l?.sizeBytes!==0;return{sessionId:e,slot:i,slots:r,name:typeof l?.name=="string"?l.name:"",mode:m,exists:h,latestRev:d,note:l?.note||"",sizeBytes:l?.sizeBytes??null,snapshotLoaded:!!l?.snapshotLoaded,optedOut:!!c?.optedOut,lastViewedRev:p,flipSeq:t?.canvas?.flipSeq||0,responseContract:l?.responseContract||null,latestDataRev:u,lastViewedDataRev:f,dataPayload:l?.dataPayload||null,dataPatch:l?.dataPatch||null,planeSeq:l?.planeSeq||0,unseen:h&&(d>p||u>f)&&m!=="canvas"}}function Cf(t){const e=t?.data&&typeof t.data=="object"?Object.keys(t.data):[],s=e.length===1&&typeof t.data[e[0]]=="string"?t.data[e[0]].slice(0,120):e.length?JSON.stringify(t.data).slice(0,120):"";return{runs:[{text:"[canvas] ",color:"cyan",bold:!0},{text:`${t.action||"action"}`,color:"white"},...s?[{text:` — ${s}`,color:"gray"}]:[]],canvasAction:!0}}function Nf(t,e){const s=Number(t?.rev)||0,n=typeof t?.note=="string"&&t.note.trim()?` — ${t.note.trim()}`:"",r=[{text:"[canvas] ",color:"cyan",bold:!0},{text:`rev ${s}${n} `,color:"white"}];return e&&(r.push({text:"[artifact: canvas.html]",color:"cyan",underline:!0,href:`artifact://${e}/canvas.html`}),r.push({text:" (press a to download)",color:"gray"})),{runs:r,canvasUpdate:!0}}function li(t,e,s){const r=Math.max(24,Number(s)||80)-t.length;if(r<2)return[{text:t.trim(),color:e,bold:!0}];const i=Math.min(6,Math.floor(r/2));return i<1?[{text:t.trim(),color:e,bold:!0}]:[{text:"─".repeat(i),color:e},{text:t,color:e,bold:!0},{text:"─".repeat(i),color:e}]}function Tf(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 li(n,"magenta",e)}const Pf={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 Mf(t,e){const s=String(t?.reason||"unknown"),r=` ↻ regeneration refused · ${Pf[s]||s.replace(/_/g," ")} `;return li(r,"yellow",e)}function Rf(t,e){const s=String(t?.stage||"unknown"),n=String(t?.error||"").split(`
|
|
47
|
-
`)[0],r=n.length>120?`${n.slice(0,117)}…`:n,i=` ✕ regeneration failed at ${s}${r?` · ${r}`:""} `;return li(i,"red",e)}function $f(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>Zp(e,s)).filter(Boolean):[]:[]}function ci(t,e=80,s={}){const n=$f(t);if(!n||n.length===0)return[];const r=Math.max(20,Number(e)||80),i=n.filter(h=>h.pendingPhase==="queued").length,o=n.filter(h=>h.pendingPhase==="pending").length,l=n.filter(h=>h.pendingPhase==="cancelling").length,c=n.filter(h=>h.pendingPhase==="rejected").length,d=[];o>0&&d.push(`${o} pending`),i>0&&d.push(`${i} queued`),l>0&&d.push(`${l} cancelling`),c>0&&d.push(`${c} rejected`);const f=[[{text:` queued prompts: ${d.length>0?d.join(" · "):"queued prompts"} `,color:"gray",trailingRule:!0}]],m=s?.tableMode?{tableMode:s.tableMode}:{};for(const[h,g]of n.entries()){dn(f,un(g,r,m));const b=n[h+1];b&&ec(g,b)&&Et(f[f.length-1]).trim().length>0&&f.push(Zl())}return f}function _f(t){const e=ri(t),s=[],n=new Set;for(const r of e||[])for(const i of Hd(r?.text||"")){const o=`${i.sessionId}/${i.filename}`;n.has(o)||(n.add(o),s.push(i))}return s}function Lf(t){const e=ri(t),s=[],n=new Set;for(const r of e||[])for(const i of Ud(r?.text||"")){const o=String(i.href||"").trim();!o||n.has(o)||(n.add(o),s.push({href:o,text:String(i.text||o).trim()||o}))}return s}function di(t,e){const s=ss(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function Of(t){return ss(t)||"(unknown)"}function tc(t,e={}){const s=Je(t),n=t.sessions?.byId||{},r=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],i=si(n),o=ni(r,n),l=Ol(e?.width);if(!s)return{color:"cyan",title:it("Chat","cyan"),titleRight:null,animateTitleRight:!1};const c=we(s.sessionId),d=s.isSystem?"yellow":"cyan",p=it(s.isSystem?`⚙ ${Ot(s,t.branding?.title||"PilotSwarm")}`:ei(s)||"Chat",d),u=r.find(k=>k.sessionId===s.sessionId),f=Kl(s.sessionId,u,i,o);f&&p.push({text:` ${f.text}`,color:f.color}),l||p.push({text:` [${c}]`,color:"gray"});const m=t.history?.bySessionId?.get(s.sessionId)||null,h=Array.isArray(t.outbox?.bySessionId?.[s.sessionId])?t.outbox.bySessionId[s.sessionId]:[],g=sf(s,m,m?.chat||[],h),b=t.connection?.mode||"local",y=Wp(s,b),v=pf(g),E=v?[...y,...y.length?[{text:" · ",color:"gray"}]:[],...v]:y;return{color:s.isSystem?"yellow":"cyan",title:p,titleRight:E.length?E:null,animateTitleRight:!!g}}function Ff(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function sc(t){const e=dc(t),s=e.selected?e.nodes.find(o=>o.label===e.selected):null,n=it("Worker","gray");if(!s)return n.push({text:" none",color:"gray"}),{title:n,lines:[{text:e.degraded&&e.registryError?`No worker selected — ${e.registryError}`:"No workers to show yet.",color:"gray"}]};n.push({text:` ${s.label}`,color:"cyan"});const r=[],i=(o,l,c="white")=>{l==null||l===""||r.push([{text:`${o.padEnd(10)} `,color:"gray"},{text:String(l),color:c}])};if(s.registered){if(i("Node",s.workerNodeId),i("Phase",s.phase,s.phase==="draining"?"red":s.phase==="starting"?"yellow":"green"),i("Pool",s.pool),s.owner&&i("Owner",s.owner),i("Heartbeat",s.live?`${s.agoText??"now"} · live`:`${s.agoText??"unknown"} · stale`,s.live?"green":"red"),i("Uptime",s.uptimeText),i("Memory",[s.rssText?`rss ${s.rssText}`:null,s.heapText?`heap ${s.heapText}`:null].filter(Boolean).join(" · ")||null),i("Loop p99",s.eventLoopText),i("SDK",s.sdkVersion),i("Runtime",s.substrate),s.capabilities.length&&i("Caps",s.capabilities.join(", ")),s.consumes.length&&i("Consumes",s.consumes.join(", ")),s.pkgEpoch!==null){const o=s.pkgInstalled.filter(c=>c.status==="ok").length,l=s.pkgInstalled.length-o;i("Packages",`epoch ${s.pkgEpoch} · ${o} ok${l?` · ${l} error`:""}`,l?"red":"white");for(const c of s.pkgInstalled)r.push([{text:" ",color:"gray"},{text:`${c.status==="error"?"✗":"✓"} `,color:c.status==="error"?"red":"green"},{text:`${c.name}${c.semver?`@${c.semver}`:""}`,color:c.status==="error"?"red":"white"}]),c.error&&r.push([{text:` ${c.error}`,color:"red"}]);s.pkgLastError&&r.push([{text:` last refresh error: ${s.pkgLastError}`,color:"red"}])}}else r.push({text:"Not in the worker registry — derived from recent activity only.",color:"gray"});r.push({text:"",color:"gray"}),r.push([{text:`EXECUTING (${s.executing.length})`,color:"cyan",bold:!0}]);for(const o of s.executing)r.push(o.active?lt(o.text):{text:o.text,color:o.color,bold:o.bold});return s.executing.length===0&&r.push({text:`Nothing executing in the ${e.windowLabel} window.`,color:"gray"}),{title:n,lines:r}}function ui(t,e=12){const s=Ff(t),n=Je(t),r=it("Activity","gray");return n?.isGroup?{title:r,disabled:!0,lines:[{text:fc,color:"gray"}]}:(n?.statusVersion!=null&&r.push({text:` [current session v${n.statusVersion}]`,color:"gray"}),{title:r,lines:s.length>0?s.map(i=>i.line||[{text:i.text,color:"white"}]):[{text:"No activity yet",color:"gray"}]})}function nc(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 rc(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":nc(e)}function Df(t){return t==="raw"?"raw summary":"pretty text"}function Bf(t){return t?.sessionId?`session-${t.sessionId}`:null}function Hf(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},r=Bf(e);return s.filter(i=>!(!i||n.source==="currentOrchestration"&&r&&i.orchId!==r||n.level&&n.level!=="all"&&String(i.level||"").toLowerCase()!==n.level))}function Uf(t){const e=Ts(t?.podName)||t?.podName||"node",s=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):""),n=String(t?.level||"info").toUpperCase(),r=t?.category==="orchestration"?"◆":t?.category==="activity"?"●":"•";return[{text:`[${t?.time||"--:--:--"}] `,color:"gray"},{text:`${r} `,color:rc(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${we(s)}] `,color:"gray"}]:[],{text:`${n} `,color:nc(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function jf(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${we(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:rc(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function Gf(t,e){const s=t.logs||{},n=s.filter||{},r=[{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:Df(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"},r];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"},r];const i=Hf(t,e);return i.length===0?[{text:"Tailing logs…",color:"cyan"},{text:"No logs match the current filter yet.",color:"gray"},{text:"",color:"gray"},r]:[r,{text:"",color:"gray"},...i.map(o=>n.format==="raw"?Uf(o):jf(o))]}function wo(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function zf(t){return/\.(json|jsonl)$/i.test(String(t||""))}function Wf(t){return ot.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function qf(t=""){const e=String(t||"").split(`
|
|
48
|
-
`);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function Eo(t,{selected:e=!1,width:s=24,label:n=null}={}){const r=Math.max(8,s),i=wo(t)?"# ":zf(t)?"{ ":"• ",o=ic(`${i}${n||t}`,r).padEnd(r," ");return e?lt(o):{text:o,color:wo(t)?"cyan":"white",bold:!1}}function Ye(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function Kf(t,e={}){if(!t)return new Set;const{childMap:s}=ti(e),n=new Set([t]),r=[t];for(;r.length>0;){const i=r.shift(),o=s.get(i)||[];for(const l of o)!l||n.has(l)||(n.add(l),r.push(l))}return n}function pn(t,e=Ye(t)){const s=Je(t)?.sessionId||null,n=Array.isArray(t.sessions?.flat)?t.sessions.flat.map(c=>c?.sessionId||c).filter(Boolean):[],r=Object.keys(t.files?.bySessionId||{}).filter(Boolean);if(e==="allSessions")return[...new Set([...n,...r])];const i=Kf(s,t.sessions?.byId||{});if(i.size===0)return[];const o=[],l=new Set;for(const c of[s,...n,...Object.keys(t.sessions?.byId||{}),...r])!c||l.has(c)||!i.has(c)||(o.push(c),l.add(c));for(const c of i)l.has(c)||o.push(c);return o}function ko(t){const s=Je(t)?.sessionId;if(!s)return[];const r=t.history?.bySessionId?.get?.(s)?.events||[],i=new Set,o=[],l=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{})\]]+)/g;for(const c of r){const d=typeof c?.data?.content=="string"?c.data.content:"";if(!d)continue;l.lastIndex=0;let p;for(;(p=l.exec(d))!==null;){const u=`${p[1]}/${p[2]}`;i.has(u)||(i.add(u),o.push(u))}}return o}function Mt(t){const e=Ye(t);Je(t)?.sessionId;const s=t.files?.filter?.query||"",n=pn(t,e),r=e==="allSessions"||n.length>1,i=[];for(const o of n){const l=rn(t.files?.bySessionId?.[o]?.entries);for(const c of l){const d=c.filename;i.push({id:`${o}/${d}`,sessionId:o,filename:d,entry:c,label:r?`[${we(o)}] ${d}`:d})}}return i.filter(o=>Pt(o.filename,s)||Pt(o.sessionId,s)||Pt(o.label,s))}function St(t){const e=Mt(t);if(e.length===0)return null;const s=t.files?.selectedArtifactId||null;if(s){const o=e.find(l=>l.id===s);if(o)return o}if(Ye(t)==="allSessions"){const o=Je(t)?.sessionId||null,l=o&&t.files?.bySessionId?.[o]?.selectedFilename||null;if(o&&l){const c=e.find(d=>d.sessionId===o&&d.filename===l);if(c)return c}return e[0]}const r=Je(t)?.sessionId||null,i=r&&t.files?.bySessionId?.[r]?.selectedFilename||null;return e.find(o=>o.sessionId===r&&o.filename===i)||e[0]}function pi(t,e={}){const s=Je(t),n=Math.max(12,Number(e?.listWidth)||Number(e?.width)||24),r=Math.max(18,Number(e?.previewWidth)||Number(e?.width)||36),i=e?.showHints!==!1,o=s?.sessionId||null,l=Ye(t),c=t.files?.filter?.query||"",d=Mt(t),p=St(t),u=p?.filename||null,f=Math.max(0,d.findIndex(R=>R.id===p?.id)),m=p?.sessionId&&u&&t.files?.bySessionId?.[p.sessionId]?.previews?.[u]||null,h=m||p?.entry||null,g=s?we(s.sessionId):"",b=pn(t,l),y=l!=="allSessions"&&b.some(R=>R&&R!==o),v=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(R=>R?.sessionId||R):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),E=l==="allSessions"&&v.some(R=>!t.files?.bySessionId?.[R]?.loaded||t.files?.bySessionId?.[R]?.loading),k=l==="allSessions"&&v.map(R=>t.files?.bySessionId?.[R]?.error).find(Boolean)||null,x=[Wf("files"),...s||l==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(l==="allSessions")E&&d.length===0?x.push({text:"Loading exported files across all sessions…",color:"gray"}):k&&d.length===0?x.push({text:k,color:"red"}):d.length===0?(x.push({text:c?`No artifacts matched "${c}" across any session.`:"No exported files across any session yet.",color:"gray"}),x.push({text:c?"Clear the query or switch back to the selected session.":"Switch the filter back to the selected session or wait for agents to export artifacts.",color:"gray"})):x.push(...d.map((R,T)=>Eo(R.filename,{selected:T===f,width:n,label:R.label})));else if(s){const R=o?t.files?.bySessionId?.[o]:null;Array.isArray(R?.entries)&&R.entries;const T=d.filter(N=>b.includes(N.sessionId));R?.loading?x.push({text:"Loading exported files…",color:"gray"}):R?.error?x.push({text:R.error,color:"red"}):T.length===0&&b.every(N=>{const j=t.files?.bySessionId?.[N]?.entries;return!Array.isArray(j)||j.length===0})?(x.push({text:c?`No artifacts matched "${c}" for this ${y?"session tree":"session"}.`:`No exported files for this ${y?"session tree":"session"} yet.`,color:"gray"}),x.push({text:c?"Clear the query or upload an artifact to this session.":y?"Artifacts exported by this session or any child session will appear here.":"Agents must write/export artifacts before they appear here.",color:"gray"})):x.push(...T.map((N,j)=>Eo(N.filename,{selected:j===f,width:n,label:N.label})))}let w,S;!s&&l!=="allSessions"?(S=[{text:"Preview",color:"cyan",bold:!0}],w=[{text:"No session selected.",color:"gray"}]):u?m?.loading?(S=[{text:`Preview: ${u}`,color:"cyan",bold:!0},...(l==="allSessions"||p?.sessionId&&p.sessionId!==o)&&p?.sessionId?[{text:` · ${we(p.sessionId)}`,color:"gray"}]:[]],w=[{text:"Loading file preview…",color:"gray"}]):m?.error?(S=[{text:`Preview: ${u}`,color:"cyan",bold:!0},...(l==="allSessions"||p?.sessionId&&p.sessionId!==o)&&p?.sessionId?[{text:` · ${we(p.sessionId)}`,color:"gray"}]:[]],w=[{text:m.error,color:"red"}]):(S=[{text:`Preview: ${u}`,color:"cyan",bold:!0},...(l==="allSessions"||p?.sessionId&&p.sessionId!==o)&&p?.sessionId?[{text:` · ${we(p.sessionId)}`,color:"gray"}]:[],...m?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:m?.isBinary===!0?[{text:" [file]",color:"gray"}]:m?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],w=m?.renderMode==="markdown"?cn(ns(m?.content||"",{width:r})):qf(m?.content||"")):(S=[{text:"Preview",color:"cyan",bold:!0}],w=[{text:"Select a file to preview it here.",color:"gray"}]);const C=l==="allSessions"?"Files: all sessions":s?`Files: ${g}${y?" tree":""}`:"Files",M=l==="allSessions"?"all sessions":s?`${g}${y?" tree":""}`:"Files",_=l==="allSessions"?`Artifacts${d.length>0?` [${d.length}]`:""}`:`Artifacts${y?" tree":""}${d.length>0?` [${d.length}]`:""}`,O=c?` · @${c}`:"";return{panelTitle:[{text:`${C}${O}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${M}${O}`,color:"magenta",bold:!0}],listTitle:[{text:`${_}${O}`,color:"cyan",bold:!0}],listLines:x,listBodyLines:x.slice(1),selectedIndex:f,selectedFilename:u,selectedSessionId:p?.sessionId||null,scope:l,previewTitle:S,previewLines:w,previewContent:m?.content||"",previewContentType:m?.contentType||"",previewRenderMode:m?.renderMode||null,previewIsBinary:h?.isBinary===!0,previewSizeBytes:h?.sizeBytes??null,previewUploadedAt:h?.uploadedAt||"",previewSource:h?.source||null,previewError:m?.error||null,previewLoading:!!m?.loading,previewScrollOffset:t.ui.scroll.filePreview||0,fullscreen:!!t.files?.fullscreen,fullscreenTitle:[{text:C,color:"magenta",bold:!0},...u?[{text:" · ",color:"gray"},{text:u,color:"cyan",bold:!0}]:[],...i?[{text:" [f filter] [u upload] [a download] [x delete] [o open] [v/esc close fullscreen]",color:"gray"}]:[]]}}function xo(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);return Number.isNaN(e.getTime())?"—":e.toISOString().slice(0,10)}function Wt(t){const e=Number(t)||0;return e<=0?"0 B":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Vf(t){const e=String(t||"").toLowerCase();return e.endsWith(".md")?"markdown":e.endsWith(".json")?"json":/\.(mjs|cjs|js)$/.test(e)?"javascript":"text"}function vt(t){const e=t.admin||{},s=e.profile||null,n=e.ghcpKey||{editing:!1,draft:"",saving:!1,error:null},r=s?{provider:s.provider||"",subject:s.subject||"",email:s.email||null,displayName:s.displayName||null}:t.auth?.principal||null,i=e.systemGhcpKey||{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null},o=!!s?.isAdmin,l=e.modelProviders||{},c=Array.isArray(l.providers)?l.providers:[],d=Array.isArray(l.models)?l.models:[],p=c.filter(I=>I?.class!=="shared"&&(I?.mine===!0||I?.usableByMe===!0)),u=c.filter(I=>I?.class==="shared"),f=I=>I.flatMap(U=>d.filter(H=>H?.providerId===U.name||H?.providerId===U.typeId).map(H=>{const X=H?.modelName||H?.name||String(H?.qualifiedName||"").split(":").pop(),ae=H?.providerId===U.name&&H?.qualifiedName?H.qualifiedName:`${U.name}:${X}`;return{provider:U.name,providerClass:U.class,model:X,qualifiedName:ae,supportedReasoningEfforts:Array.isArray(H?.supportedReasoningEfforts)?H.supportedReasoningEfforts:[],defaultReasoningEffort:H?.defaultReasoningEffort||null,supportedContextTiers:Array.isArray(H?.supportedContextTiers)?H.supportedContextTiers:[],defaultContextTier:H?.defaultContextTier||null}})),m=l.defaults||{},h=new Map;for(const I of d)!I?.providerId||h.has(I.providerId)||h.set(I.providerId,{id:I.providerId,label:I.providerType||I.providerId});const g=I=>({name:I.name,typeId:I.typeId||I.type||null,class:I.class==="shared"?"shared":"personal",hasCredential:!!I.hasCredential,usableByMe:I.usableByMe!==!1,systemUseEnabled:!!I.systemUseEnabled,systemEligible:!!I.systemEligible,isClusterDefault:!!I.isClusterDefault,isMyDefault:!!I.isMyDefault,isSystemDefault:!!I.isSystemDefault}),b=o&&Array.isArray(m.systemOverrides)?m.systemOverrides:[],y=new Map(b.map(I=>[I.agentId,I])),v=new Map;for(const I of Object.values(t.sessions?.byId||{}))!I?.isSystem||!I?.agentId||v.has(I.agentId)||v.set(I.agentId,{agentId:I.agentId,title:Ot(I,t.branding?.title||"PilotSwarm")});for(const I of b)v.has(I.agentId)||v.set(I.agentId,{agentId:I.agentId,title:I.agentId});const E=m.system?.effective||null,k=[...v.values()].sort((I,U)=>I.title.localeCompare(U.title)).map(I=>{const U=y.get(I.agentId)||null;return{...I,effectiveModel:(U||E)?.model||null,source:U?"agent_override":E?.source||"system_default",override:U}}),x=l.selection||{},w=l.page==="shared"&&o?"shared":"mine",S={loading:!!l.loading,error:l.error||null,page:w,providerTypes:[...h.values()].sort((I,U)=>I.id.localeCompare(U.id)),myProviders:p.map(I=>({...g(I),selected:I.name===x.providerName})),sharedProviders:u.map(I=>({...g(I),selected:I.name===x.providerName})),userChoices:f([...u.filter(I=>I.usableByMe!==!1),...p.filter(I=>I.usableByMe!==!1)]),clusterChoices:o?f(u):[],systemChoices:o?f([...u,...p.filter(I=>I.systemUseEnabled===!0)]):[],mySessionDefault:m.userSession||{configured:null,effective:null},clusterSessionDefault:o?m.clusterSession||{configured:null,effective:null}:null,systemSessionDefault:o?m.system||{configured:null,effective:null}:null,systemAgentOverrides:b,systemAgentRoutes:o?k.map(I=>({...I,selected:I.agentId===x.agentId})):[],selection:{focus:x.focus==="agents"?"agents":"providers",providerName:x.providerName||(w==="shared"?u[0]?.name:p[0]?.name)||null,agentId:x.agentId||k[0]?.agentId||null},mutation:{pending:l.mutation?.pending||null,error:l.mutation?.error||null}},C=o&&!!n.storeAsSystem,M=C?!!i.configured:!!s?.githubCopilotKeySet,_=C?"System key":"key",O=i.configured&&i.changedBy?` (set by ${i.changedBy})`:"",R=n.saving?"Saving...":n.editing?"Editing — Enter to save, Esc to cancel":C?i.configured?`System key configured — ownerless system sessions use it for GitHub Copilot models${O}`:"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)",T=e.packages||{},N=Array.isArray(T.list)?T.list:[],j=I=>!!(o||I?.owner&&r&&I.owner.provider===r.provider&&I.owner.subject===r.subject),q=Rp(t?.sessions?.byId),Z=new Set;for(const I of N){if(I?.scope==="shared")continue;const U=Ie(I?.owner)||String(I?.createdBy||"").trim().toLowerCase();!U||U===Jr||Z.add(U)}const ue=Z.size>1,oe=(I,U,H)=>`${I}${U==="shared"?"shared":"user"}${U==="shared"?"":H?.subject??""}`,de=T.selectedName?oe(T.selectedName,T.selectedSelector?.scope??null,T.selectedSelector?.owner??r??null):null,A=I=>e.section!=="packages"||T.selectedName!==I.name?!1:T.selectedSelector?.scope?oe(I.name,I.scope,I.owner)===de:!0,D=I=>({name:I.name,scope:I.scope==="shared"?"shared":"user",owner:I.owner??null,enabled:!!I.enabled,semver:I.active?.semver||null,sha7:I.active?.sha256?String(I.active.sha256).slice(0,7):null,agentCount:Array.isArray(I.active?.manifest?.agents)?I.active.manifest.agents.length:0,canManage:j(I),ownerBadge:I.scope==="shared"||!ue?null:Gl($p(I,q)),selected:A(I)}),F=I=>!!(I?.owner&&r&&I.owner.provider===r.provider&&I.owner.subject===r.subject),K=t.sessions?.ownerFilter,W=I=>{if(!K||K.all===!0)return!0;const U=Ie(I?.owner);return U?Array.isArray(K.ownerKeys)&&K.ownerKeys.includes(U):K.includeUnowned===!0},Q=N.filter(I=>I.scope==="shared").map(D),J=N.filter(I=>I.scope!=="shared"&&F(I)).map(D),V=N.filter(I=>I.scope!=="shared"&&!F(I)&&W(I)).map(I=>({...D(I),ownerLabel:I?.createdBy||I?.owner?.subject||"another user"})),Y=["providers","packages","workers"].includes(e.section)?e.section:"providers",ge=[{id:"providers",kind:"section",depth:0,label:"Model Providers",selected:!1},{id:"myProviders",kind:"subsection",depth:1,label:"My Providers",selected:Y==="providers"&&w==="mine"},...o?[{id:"sharedProviders",kind:"subsection",depth:1,label:"Shared Providers",selected:Y==="providers"&&w==="shared"}]:[],{id:"agents",kind:"section",depth:0,label:"Agents",selected:Y==="packages"&&!T.selectedName},{id:"group:shared",kind:"group",depth:1,label:"Shared",count:Q.length},...Q.map(I=>({id:`pkg:shared:${I.name}`,kind:"package",depth:2,label:I.name,...I})),{id:"group:user",kind:"group",depth:1,label:"User",count:J.length},...J.map(I=>({id:`pkg:user:${I.name}`,kind:"package",depth:2,label:I.name,...I})),...V.length>0?[{id:"group:others",kind:"group",depth:1,label:"Other users",count:V.length},...V.map(I=>({id:`pkg:user:${I.owner?.subject??"?"}:${I.name}`,kind:"package",depth:2,label:I.name,...I}))]:[],...o?[{id:"workers",kind:"section",depth:0,label:"Workers",selected:Y==="workers"}]:[]],fe=T.detail||null;let ye=null;if(T.selectedName){const I=N.filter(re=>re.name===T.selectedName),U=(T.selectedSelector?.scope?I.find(re=>oe(re.name,re.scope,re.owner)===de):I[0])??I[0]??null,H=fe?.versions?.find(re=>re.versionId===fe.activeVersionId)||null,X=H?.manifest||U?.active?.manifest||{},le=Date.now()-9e4,Ae=(Array.isArray(T.workerState)?T.workerState:[]).filter(re=>{const ms=re?.updatedAt instanceof Date?re.updatedAt:new Date(re?.updatedAt??0);return!Number.isNaN(ms.getTime())&&ms.getTime()>=le}),ve=Ae.length,Ke=re=>{const ms=re.installed||{},gd=fe?.scope||U?.scope||T.selectedSelector?.scope||null,_i=fe?.owner?.subject||U?.owner?.subject||T.selectedSelector?.owner?.subject||"",yd=gd==="user"?`${T.selectedName}#user${_i?`:${_i.slice(0,8)}`:""}`:`${T.selectedName}#shared`;return ms[yd]??ms[T.selectedName]},ce=H?Ae.filter(re=>Ke(re)?.semver===H.semver&&Ke(re)?.status==="ok").length:0,st=fe?j(fe):U?j(U):!1;ye={name:T.selectedName,loading:!!T.detailLoading,error:T.detailError||null,scope:(fe?.scope||U?.scope)==="shared"?"shared":"user",enabled:fe?!!fe.enabled:!!U?.enabled,canManage:st,createdBy:fe?.createdBy||U?.createdBy||null,createdAtText:xo(fe?.createdAt||U?.createdAt),description:typeof X.description=="string"?X.description:"",activeSemver:H?.semver||U?.active?.semver||null,activeSha12:H?.sha256?String(H.sha256).slice(0,12):null,sizeText:Wt(H?.sizeBytes??U?.active?.sizeBytes),agents:Array.isArray(X.agents)?X.agents.map(re=>({name:re.name,description:re.description||"",toolCount:Array.isArray(re.tools)?re.tools.length:0,skillCount:Array.isArray(re.skills)?re.skills.length:0})):[],versions:(fe?.versions||[]).map(re=>({semver:re.semver,sha12:String(re.sha256||"").slice(0,12),dateText:xo(re.createdAt),active:re.versionId===fe?.activeVersionId})),fleet:ve>0&&H?{current:ce,total:ve,text:`${ce}/${ve} workers current`}:null,actionPending:T.action?.pending||null,actionError:T.action?.error||null,hasSharedCounterpart:I.some(re=>re.scope==="shared"),hasOwnUserCounterpart:I.some(re=>re.scope!=="shared"&&F(re)),copyCount:I.length}}const Te=T.workspace||{};let Re=null;if(T.selectedName){const I=Te.tree,U=new Set(Te.expandedDirs||[]),H=[];if(I){const ae=ce=>{const st=ce.split("/");for(let re=1;re<st.length;re++)if(!U.has(st.slice(0,re).join("/")))return!1;return!0},le=Array.isArray(I.dirs)?I.dirs:[],Ae=Array.isArray(I.files)?I.files:[],ve=ce=>String(ce).split("/").join("\0"),Ke=[...le.map(ce=>({type:"dir",path:ce})),...Ae.map(ce=>({type:"file",path:ce.path,size:ce.size}))].sort((ce,st)=>ve(ce.path)<ve(st.path)?-1:1);for(const ce of Ke){if(!ae(ce.path))continue;const st=ce.path.split("/").length-1;H.push({type:ce.type,path:ce.path,label:ce.path.split("/").pop()+(ce.type==="dir"?"/":""),depth:st,expanded:ce.type==="dir"?U.has(ce.path):void 0,sizeText:ce.type==="file"?Wt(ce.size):null,selected:Te.selectedPath===ce.path})}}const X=Te.file;Re={loading:!!Te.treeLoading,error:Te.treeError||null,semver:Te.tree?.semver||null,treeRows:H,file:X?{path:X.path,sizeText:Wt(X.size),truncated:!!X.truncated,isBinary:X.encoding==="base64",text:X.encoding==="base64"?null:String(X.content||""),language:Vf(X.path)}:null,fileLoading:!!Te.fileLoading,fileError:Te.fileError||null,selectedPath:Te.selectedPath||null}}const Le=e.workers||{},De=Array.isArray(Le.list)?Le.list:[],Be=9e4,ct=Date.now(),We=I=>!Number.isFinite(I)||I<0?"—":I<6e4?`${Math.round(I/1e3)}s ago`:I<36e5?`${Math.round(I/6e4)}m ago`:`${Math.round(I/36e5)}h ago`,G=I=>{if(!Number.isFinite(I)||I<0)return null;if(I<60)return`${Math.round(I)}s`;if(I<3600)return`${Math.floor(I/60)}m`;const U=Math.floor(I/3600);return U<48?`${U}h ${Math.floor(I%3600/60)}m`:`${Math.floor(U/24)}d ${U%24}h`},ne=De.map(I=>{const U=I?.updatedAt instanceof Date?I.updatedAt:new Date(I?.updatedAt??0),H=Number.isNaN(U.getTime())?Number.NaN:ct-U.getTime(),X=I?.health||{},ae=I?.info||{},le=I?.state?.["agent-packages"]||null,Ae=le?.installed&&typeof le.installed=="object"?Object.values(le.installed):[],ve=Ae.filter(Ke=>Ke?.status==="error").length;return{id:String(I?.workerNodeId??""),pool:String(I?.pool??"default"),phase:["starting","ready","draining"].includes(I?.phase)?I.phase:"ready",live:Number.isFinite(H)&&H<=Be,agoText:We(H),uptimeText:G(X.uptimeS),rssText:Wt(X.rssBytes),sessions:Number.isFinite(X.activeSessions)?X.activeSessions:null,eventLoopText:Number.isFinite(X.eventLoopDelayP99Ms)?`${X.eventLoopDelayP99Ms}ms`:null,sdkVersion:typeof ae.sdkVersion=="string"?ae.sdkVersion:null,substrate:typeof ae.runtime?.substrate=="string"?ae.runtime.substrate:null,consumes:Array.isArray(ae.consumes)?ae.consumes:[],owner:I?.owner?.subject?String(I.owner.subject):null,pkgEpoch:Number.isFinite(le?.epoch)?le.epoch:null,pkgText:le?`${Ae.length-ve} ok${ve?` · ${ve} error`:""}`:null}}).sort((I,U)=>I.pool===U.pool?I.id<U.id?-1:1:I.pool<U.pool?-1:1),Se=ne.filter(I=>I.live),B={loading:!!Le.loading,error:Le.error||null,empty:ne.length===0&&!Le.loading,rows:ne,counts:{registered:ne.length,live:Se.length,ready:Se.filter(I=>I.phase==="ready").length,starting:Se.filter(I=>I.phase==="starting").length,draining:Se.filter(I=>I.phase==="draining").length,pools:[...new Set(Se.map(I=>I.pool))].length},summaryText:ne.length?`${Se.length} live / ${ne.length} registered`:null},z={loading:!!T.loading,error:T.error||null,empty:N.length===0&&!T.loading,sharedCount:Q.length,userCount:J.length,selectedName:T.selectedName||null,detail:ye,workspace:Re,changelog:T.changelog||null,addDialog:{open:!!T.addDialog?.open,kind:T.addDialog?.kind||"repo",scope:T.addDialog?.scope||"user",repoUrl:T.addDialog?.repoUrl||"",ref:T.addDialog?.ref||"",path:T.addDialog?.path||"",url:T.addDialog?.url||"",authToken:T.addDialog?.authToken||"",submitting:!!T.addDialog?.submitting,progress:T.addDialog?.progress||null,error:T.addDialog?.error||null}},L=[];return Y==="workers"?(L.push({id:"workersRefresh",label:"Refresh workers",key:"r"}),L.push({id:"showPackages",label:"Agents",key:"a"}),L.push({id:"showProviders",label:"Model Providers",key:"m"}),L.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:r,isAdmin:o,section:Y,settingsTree:ge,packages:z,workers:B,modelProviders:S,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:M,storeAsSystem:C,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:R},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:L}):Y==="packages"?(L.push({id:"packagesRefresh",label:"Refresh packages",key:"r"}),L.push({id:"packagesNext",label:"Next package",key:"j"}),L.push({id:"packagesPrev",label:"Previous package",key:"k"}),L.push({id:"showProviders",label:"Model Providers",key:"m"}),L.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:r,isAdmin:o,section:Y,settingsTree:ge,packages:z,workers:B,modelProviders:S,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:M,storeAsSystem:C,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:R},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:L}):Y==="providers"?(L.push({id:"addProvider",label:"Add GitHub provider",key:"e"}),L.push({id:"cycleUserDefault",label:"Cycle my default",key:"u"}),o&&(L.push({id:"cycleClusterDefault",label:"Cycle cluster default",key:"l"}),L.push({id:"cycleSystemDefault",label:"Cycle system default",key:"s"}),L.push({id:"toggleSystemUse",label:"Toggle system use",key:"t"}),L.push({id:"cycleSystemOverride",label:"Cycle system-agent override",key:"o"})),L.push({id:"refreshProviders",label:"Refresh",key:"r"}),L.push({id:"showPackages",label:"Agents",key:"a"}),L.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:r,isAdmin:o,section:Y,settingsTree:ge,packages:z,workers:B,modelProviders:S,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:M,storeAsSystem:C,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:R},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:L}):(n.editing?(L.push({id:"save",label:"Save",key:"Enter"}),L.push({id:"cancel",label:"Cancel",key:"Esc"})):(L.push({id:"edit",label:M?`Replace ${_}`:`Set ${_}`,key:"e"}),M&&L.push({id:"clear",label:`Clear ${_}`,key:"c"}),L.push({id:"refresh",label:"Refresh",key:"r"})),L.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),Y==="ghcp"&&L.splice(L.length-1,0,{id:"showPackages",label:"Agents",key:"a"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:r,isAdmin:o,section:Y,settingsTree:ge,packages:z,workers:B,modelProviders:S,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:M,storeAsSystem:C,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:R},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:L})}const Yf={day:"Day",week:"Week",month:"Month"};function Xf(t){const e=t.auth?.authorization?.role;return e==="admin"||e==="anonymous"||!!t.admin?.profile?.isAdmin}function Qf(t){const e=/T(\d{2}:\d{2})/.exec(String(t||""));return e?`${e[1]} UTC`:null}function fi(t,e=Date.now()){const s=t?Date.parse(t):NaN;if(!Number.isFinite(s))return null;const n=Qf(t),r=n?` (${n})`:"",i=s-e;if(i<=0)return`now${r}`;const o=Math.floor(i/6e4);if(o<60)return`in ${Math.max(1,o)}m${r}`;const l=Math.floor(o/60);return l<24?`in ${l}h ${String(o%60).padStart(2,"0")}m${r}`:`in ${Math.floor(l/24)}d ${String(l%24).padStart(2,"0")}h${r}`}function Zf(t){return t?.kind==="no_provider"||t?.kind==="hold"||t?.resetsAtUtc?null:"waits until someone changes it"}function Jf(t,e){return new Date(t-e*864e5).toISOString().slice(0,10)}function As(t,e,s){return t===1?e:s}function Yn(t,e,s){const n=e?t?.quotaTokens:t?.yourQuotaTokens,r=e?t?.usedTokens:t?.yourUsedTokens,i=n==null?null:Number(n),o=r==null?null:Number(r),l=Number.isFinite(o),c=Number.isFinite(i)&&i>0,d=l&&c?Math.round(o/i*100):null,p=l?te(o):"—",u=Number.isFinite(i)?te(i):"∞",f=Number(t?.quotaTokens),m=Number(t?.usedTokens),h=Number.isFinite(f)&&f>0&&Number.isFinite(m)&&m>=f,g=!e&&h&&(d==null||d<100);return{providerExhausted:g,ruleId:t?.ruleId||null,usedTokens:l?o:null,quotaTokens:Number.isFinite(i)?i:null,usedLabel:p,quotaLabel:u,text:`${p} / ${u}`,known:l,uncapped:!Number.isFinite(i),pct:d,meterPct:d==null?null:Math.max(0,Math.min(100,d)),tone:d==null?g?"red":"idle":d>100||g?"red":d>=90?"amber":"plain",windowStartUtc:t?.windowStartUtc||null,resetsAtUtc:t?.resetsAtUtc||null,resetsLabel:fi(t?.resetsAtUtc,s)}}function em(t,{overall:e,selectedProvider:s,selectedScope:n="*",nowMs:r,overModels:i=0}){const o=String(t?.providerName||""),l=t?.rowKind==="model"?"model":"provider",c=String(t?.scope||"*"),d=t?.class==="shared",p=Number.isFinite(Number(t?.allowancePct))?Number(t.allowancePct):100,u=t?.holdUntilUtc||null,f=t?.holdIndefinite===!0,m=f||(u?Date.parse(u)>r:!1),h=l==="provider"&&Number(t?.modelRowCount)||0,g=t?.ownedByMe!==!1,b=t?.manageable===!0,y=typeof t?.ownerLabel=="string"&&t.ownerLabel?t.ownerLabel:null,v=o===s&&(l==="provider"?n==="*":c===n),E=t?.periods||{};return{key:`${o}${c}`,providerName:o,kind:l,scope:c,label:l==="provider"?o:c.startsWith(`${o}:`)?c.slice(o.length+1):c,subject:l==="provider"?y?`${o} (${y})`:o:`${o} · ${c.startsWith(`${o}:`)?c.slice(o.length+1):c}`,class:d?"shared":"personal",ownedByMe:g,manageable:b,ownerLabel:l==="provider"?y:null,classLabel:l!=="provider"?null:d?"Shared":"User",allowancePct:p,allowanceLabel:l==="provider"&&e&&p<100&&g?["day","week","month"].some(k=>t?.periods?.[k]?.quotaTokens!=null)?`Per-user allowance: ${p}% of each limit`:`Per-user allowance: ${p}%, but no limit is set to divide`:null,hold:m?{indefinite:f||!u,untilUtc:u,label:f||!u?"lifts when an administrator releases it":`lifts ${fi(u,r)}`}:null,modelRowCount:h,selected:v,expanded:o===s&&h>0,expandLabel:h===0?null:o===s?`hide ${h} ${As(h,"model","models")}`:i>0?`show ${h} ${As(h,"model","models")} — ${i} over limit`:`show ${h} ${As(h,"model","models")}`,overModels:l==="provider"?i:0,cells:{day:Yn(E.day,e,r),week:Yn(E.week,e,r),month:Yn(E.month,e,r)}}}function tm(t){const e=t.budget||{},s=Date.now(),n=Xf(t),r=e.overall===!0,i=an.includes(Number(e.rangeDays))?Number(e.rangeDays):Ee,o=Array.isArray(e.grid)?e.grid:[],l=e.error||null,c=e.loaded===!0,d=e.selectedProvider||null,p=e.selectedScope||"*",u=o.reduce((F,K)=>F+(K?.rowKind==="model"?0:1),0),f=[],m=new Map;for(const F of o){if(F?.rowKind!=="model")continue;["day","week","month"].some(W=>{const Q=F?.periods?.[W],J=Number(Q?.quotaTokens),V=Number(r?Q?.usedTokens:Q?.yourUsedTokens);return Number.isFinite(J)&&J>0&&Number.isFinite(V)&&V>J})&&m.set(F.providerName,(m.get(F.providerName)||0)+1)}for(const F of o)F?.rowKind==="model"&&F?.providerName!==d||f.push(em(F,{overall:r,selectedProvider:d,selectedScope:p,nowMs:s,overModels:m.get(F?.providerName)||0}));const h=f.find(F=>F.selected)||f.find(F=>F.kind==="provider"&&F.providerName===d)||null,g=f.find(F=>F.kind==="provider"&&F.providerName===d)||null,b=Array.isArray(e.paused)?e.paused:[],y=new Map;for(const F of b){const W=os({pauseState:F?.pause})?.provider||null;W&&y.set(W,(y.get(W)||0)+1)}const v=[...y.entries()].sort((F,K)=>K[1]-F[1]||F[0].localeCompare(K[0]))[0]||null,E=b.length,k=v&&v[1]===E?v[0]:null,x=e.pausedError||null,w={count:E,error:x,stale:!!x&&E>0,provider:v?v[0]:null,sentence:E===0?null:`${E} ${As(E,"session is","sessions are")} waiting${k?` on ${k}`:""}.`},S=e.missingProvider||null,C=S&&y.get(S)||0,M=C>0?{provider:S,count:C,sentence:`No provider is named ${S}, and ${C} ${As(C,"session waits","sessions wait")} on it. They run again as soon as a provider takes that name.`}:null,_=e.series||{},O=new Map((Array.isArray(_.days)?_.days:[]).map(F=>[String(F?.dayUtc||"").slice(0,10),F])),R=[];for(let F=i-1;F>=0;F-=1){const K=Jf(s,F),W=O.get(K);R.push({dayUtc:K,label:K.slice(5),tokens:Number(W?.tokensTotal)||0,turns:Number(W?.turns)||0})}const T=R.reduce((F,K)=>Math.max(F,K.tokens),0),N=h?.cells?.day||null,j=N?.quotaTokens??null,q=Math.max(T,j||0);for(const F of R)F.pct=q>0?Math.round(F.tokens/q*100):0;const Z=_.error||null,ue=_.loaded===!0,oe={provider:_.provider||null,days:R,peak:T,peakLabel:te(T),scaleMax:q,quotaTokens:j,quotaLabel:N?.quotaLabel??"∞",quotaPct:j!=null&&q>0?Math.round(j/q*100):null,rangeDays:i,rangeLabel:`Last ${i} days`,loading:_.loading===!0,loaded:ue,error:Z,failed:!!Z&&!ue,stale:!!Z&&ue,empty:ue&&!Z&&T===0,mixedScope:!1},de=e.systemUsage||{},A=n&&h&&de.provider===d&&(de.scope||"*")===p&&(de.rangeDays||Ee)===i,D=!n||!h?null:{loading:A&&de.loading===!0,loaded:A&&de.loaded===!0,error:A&&de.error||null,stale:A&&!!de.error&&de.loaded===!0,rangeDays:i,rangeLabel:`Last ${i} days`,tokens:Number(A?de.totals?.tokensTotal:0)||0,tokensLabel:te(Number(A?de.totals?.tokensTotal:0)||0),turns:Number(A?de.totals?.turns:0)||0,models:(A&&Array.isArray(de.breakdown)?de.breakdown:[]).map(F=>({key:String(F?.key||F?.label||"unknown"),label:String(F?.label||F?.key||"Unknown model"),tokens:Number(F?.tokensTotal)||0,tokensLabel:te(Number(F?.tokensTotal)||0),turns:Number(F?.turns)||0})).sort((F,K)=>K.tokens-F.tokens||F.label.localeCompare(K.label))};return{open:!!t.ui?.budgetOpen,isAdmin:n,loading:!!e.loading,refreshing:!!e.refreshing,loaded:c,error:l,fetchedAt:Number(e.fetchedAt)||0,failed:!!l&&!c,stale:!!l&&c,empty:c&&!l&&u===0,overall:r,rangeDays:i,rangeOptions:an.map(F=>({value:F,label:`${F}d`})),overallLabel:"Show all user spend",usageHeading:r?"All user spend":"My spend",columns:vp.map(F=>({id:F,label:Yf[F]})),rows:f,providerCount:u,selectedProvider:d,selectedScope:p,selected:h,selectedProviderRow:g,paused:w,missing:M,series:oe,systemSpend:D}}function sm(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=Je(t),r=!!n?.pendingQuestion?.question,i=n?.sessionId&&Array.isArray(t.outbox?.bySessionId?.[n.sessionId])?t.outbox.bySessionId[n.sessionId]:[],o=i.length>0,l=i.some(b=>b?.phase==="pending"),c=t.ui.promptEdit?.sessionId===n?.sessionId,d=c&&t.ui.promptEdit?.phase==="queued",p=c&&t.ui.promptEdit?.phase==="cancelling",u=s===e?"v/esc close fullscreen":"v fullscreen";if(t.ui.modal?.type==="artifactUpload")return{left:"Upload a local file into this session's artifact store",right:"type path · left/right move · enter upload · esc cancel"};if(t.ui.modal?.type==="renameSession")return{left:"Rename the selected session title",right:"type title · left/right move · enter save · esc cancel"};if(t.ui.modal?.type==="shareSession")return{left:"Share the selected session",right:"name [r|w] grants · -name revokes · enter apply · esc close"};if(t.ui.modal?.type==="artifactPicker")return{left:"Select a linked artifact or URL",right:"up/down move · enter open/download · a/esc close"};if(t.ui.modal?.type==="modelPicker")return{left:"Select a model for the new session",right:"up/down move · enter next · esc cancel"};if(t.ui.modal?.type==="reasoningEffortPicker")return{left:"Select reasoning effort for the new session",right:"up/down move · enter create · esc cancel"};if(t.ui.modal?.type==="themePicker")return{left:"Select a shared portal/TUI theme",right:"up/down move · enter apply · esc close"};if(t.ui.modal?.type==="sessionAgentPicker")return{left:"Select an agent for the new session",right:"up/down move · ←/→ open/close · enter start · esc cancel"};if(t.ui.modal?.type==="sessionGroupPicker")return{left:"Move selected session(s) to a group",right:"up/down move · enter choose · esc cancel"};if(t.ui.modal?.type==="sessionGroupName")return{left:"Name the new group",right:"type name · left/right move · enter create · esc cancel"};if(t.ui.modal?.type==="logFilter")return{left:"Adjust log filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="filesFilter")return{left:"Adjust files browser filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="sessionOwnerFilter")return{left:"Adjust session filters",right:"up/down choose · space toggle · esc close"};const f=!!t.sessions?.selectMode,m=Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds.length:0;if(f&&e===$.SESSIONS)return{left:`Select mode · ${m} selected`,right:"up/down move · space toggle · ctrl-g group · c cancel · d complete · D hard delete · V/esc exit"};const h={[$.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",[$.CHAT]:`j/k scroll · ctrl-u/ctrl-d page · e older history · g/G top/bottom · d done · ${u} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane · p prompt`,[$.INSPECTOR]:t.ui.inspectorTab==="logs"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · t tail · f filter · ${u} · 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 · ${u} · 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 · ${u} · 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 · ${u} · 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 · ${u} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · h/l focus · a linked items · drag copy · m next tab · tab next pane`,[$.ACTIVITY]:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${u} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · h left · tab next pane`,[$.PROMPT]:r?`type answer · enter reply · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:c?d?`queued prompt selected · d delete · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:p?`cancelling prompt selected · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:`edit pending prompt · enter send batch · up/down cycle pending · esc cancel · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:l?`type message · enter queues · enter on empty sends batch · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:o?`type message · enter queues behind durable items · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:`type message · enter send · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`};let g=h[e]||h[$.SESSIONS];return Xl(Je(t))&&(g=`ctrl-x stop · ${g}`),{left:t.ui.statusText,right:g}}function Dt(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function he(t,e){if(e<=0)return[];const s=[];let n=e;for(const r of t||[]){if(n<=0)break;const i=String(r?.text||"");if(!i)continue;const o=i.length>n&&n>1?`${i.slice(0,n-1)}…`:i.slice(0,n);o&&(s.push({...r,text:o}),n-=o.length)}return s}function ze(t){return Array.from(String(t||"")).length}function ic(t,e){const s=String(t||"");return e<=0?"":ze(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function ts(t,e){const s=ic(t,e),n=Math.max(0,e-ze(s));return s+" ".repeat(n)}function ie(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function Me(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 Io(t,e){const s=Number(t),n=Number(e);if(!Number.isFinite(s)||!Number.isFinite(n)||s<=0||n<=0)return null;const r=s/n;return`${r>=10?r.toFixed(0):r.toFixed(1)}×`}function oc(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?ze(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function nm(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 ac(t=[]){const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();if(!r)continue;const i=r.toLowerCase();e.has(i)||(e.add(i),s.push(r))}return s.join(" | ")}function rm(t,e=""){return ac([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function im(t,e=""){return ac([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function Ts(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 om=300*1e3,am="last 5m";function mi(t){let e=0;for(const s of t.history.bySessionId.values())for(const n of s?.events||[]){const r=n?.createdAt instanceof Date?n.createdAt.getTime():new Date(n?.createdAt||0).getTime();Number.isFinite(r)&&(e=Math.max(e,r))}return(!Number.isFinite(e)||e<=0)&&(e=Date.now()),{startMs:e-om,endMs:e,label:am}}function lm(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 lc(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 cm=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done","model"]);function dm(t){return cm.has(t)}function um(t){const e=Za(t?.createdAt),s=Ts(t?.workerNodeId),n=nm(t),r=oc(n,20),i=t?.createdAt instanceof Date?t.createdAt.getTime():new Date(t?.createdAt||0).getTime(),o={time:e,createdAtMs:Number.isFinite(i)?i:0,nodeLabel:s,color:"white",detail:"",type:"other"};switch(t?.eventType){case"session.turn_started":return{...o,type:"turn_start",color:"gray",detail:`turn ${t?.data?.iteration??"?"}`};case"session.turn_completed":{const l=Number(t?.data?.turnIndex??t?.data?.iteration);return{...o,type:"turn_end",color:"gray",detail:`turn ${t?.data?.iteration??"?"} done`,...Number.isFinite(l)?{completedTurn:l}:{}}}case"user.message":return{...o,type:"user_msg",color:"white",detail:r?`>> ${r}`:">> user"};case"assistant.message":return{...o,type:"response",color:"green",detail:r?`< ${r}`:"< response"};case"system.message":return{...o,type:"system",color:"yellow",detail:r||"system"};case"session.wait_started":return{...o,type:"wait",color:"yellow",detail:`wait ${qt(t?.data?.seconds??0)}`};case"session.wait_completed":return{...o,type:"timer",color:"yellow",detail:`${qt(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const l=im(t,r);return{...o,type:"dehydrate",color:"yellow",detail:l?`lossy ${l}`:"lossy handoff"}}case"session.dehydrated":return{...o,type:"dehydrate",color:"cyan",detail:`ZZ ${rm(t,r)}`.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||we(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${qt(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${ln(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 ${ln(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.model_changed":{const l=ss(t?.data?.oldModel)||"default",c=ss(t?.data?.newModel)||"default",d=t?.data?.newReasoningEffort,p=d&&d!==t?.data?.oldReasoningEffort;return{...o,type:"model",color:"cyan",detail:`model ${l} → ${c}${p?`:${d}`:""}`}}case"session.error":return{...o,type:"error",color:"red",detail:r||"error"};default:return null}}function cc(t=[]){const e=[];for(const s of t||[]){const n=um(s);n&&e.push({...n,nodeLabel:dm(n.type)?"orch":n.nodeLabel||"orch"})}return e}function pm(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 r=1;for(;s+r<t.length;){const i=t[s+r];if(i?.type!=="spawn"||i?.nodeLabel!=="orch"||i?.time!==n.time)break;r+=1}if(r===1){e.push(n);continue}e.push({...n,detail:`spawn x${r}`}),s+=r-1}return e}function fm(t){const e=String(t?.error||"").trim();if(!e)return null;const s=Qr(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),r=Number.isFinite(n)?n:Date.now();return{time:Za(r),createdAtMs:r,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${oc(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function mm(t,e){const s=fm(e);return!s||(t||[]).some(r=>!r||r.nodeLabel!=="orch"||r.detail!==s.detail?!1:Math.abs(Number(r.createdAtMs||0)-s.createdAtMs)<=6e4)?t:[...t||[],s]}function hm(t,e,s){if(!Number.isFinite(e)||!Number.isFinite(s)||s<e)return[];const n=new Set;for(const r of t.history.bySessionId.values()){const i=cc(r?.events||[]);for(const o of i){if(!o?.nodeLabel||o.nodeLabel==="orch")continue;const l=Number(o.createdAtMs||0);Number.isFinite(l)&&(l<e||l>s||n.add(o.nodeLabel))}}return Array.from(n).sort((r,i)=>r.localeCompare(i))}function gm(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const r of n?.events||[]){if(!lc(r,e))continue;const i=Ts(r?.workerNodeId);i&&s.add(i)}return Array.from(s).sort((n,r)=>n.localeCompare(r))}function hi(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 Ao(t){return Array.isArray(t?.runs)?t.runs.reduce((e,s)=>e+ze(String(s.text??"")),0):Array.isArray(t)?t.reduce((e,s)=>e+ze(String(s.text??"")),0):ze(String(t?.text??""))}function ym(t,e,s){const n=[{text:ts("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((r,i)=>{i>0&&n.push({text:" ",color:null}),n.push({text:ts(r,s),color:"white",bold:!0})}),hi(n)}function bm(t,e,s,n=1/0){const r=`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`;return ie(Number.isFinite(n)?r.slice(0,Math.max(e,n)):r,"gray")}function Sm(t,e,s){const n=t?.orchestration?.bySessionId?.[e?.sessionId]||null;let r="loading orchestration stats...";if(n)if(n.loading&&!n.stats)r="loading orchestration stats...";else if(!n.stats)r="orchestration stats unavailable";else{const i=n.stats,o=[],l=[];if(typeof i.orchestrationVersion=="string"&&i.orchestrationVersion&&(o.push(`v ${i.orchestrationVersion}`),l.push(`v${i.orchestrationVersion}`)),i.historyEventCount!=null&&(o.push(`hist ${Number(i.historyEventCount)||0} ev`),l.push(`h${Number(i.historyEventCount)||0}`)),i.historySizeBytes!=null){const c=Me(i.historySizeBytes);o.push(c),l.push(c)}i.queuePendingCount!=null&&(o.push(`q ${Number(i.queuePendingCount)||0}`),l.push(`q${Number(i.queuePendingCount)||0}`)),i.kvUserKeyCount!=null&&(o.push(`kv ${Number(i.kvUserKeyCount)||0} keys`),l.push(`kv${Number(i.kvUserKeyCount)||0}`)),i.kvTotalValueBytes!=null&&o.push(Me(i.kvTotalValueBytes)),r=s<=40?l.join(" · "):o.join(" | "),r||(r="orchestration stats unavailable")}return Ce({title:"Stats",body:r,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function vm(t,e,s,n){const r=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],i=[{text:ts(t.time||"",s),color:"white"},{text:" ",color:null}];return e.forEach((o,l)=>{l>0&&i.push({text:" ",color:null}),o===r?i.push({text:ts(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):i.push({text:ts("│",n),color:"gray"})}),hi(i)}const wm=new Set(["none","minimal","low","medium","high","xhigh","max"]);function Em(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(),r=s.length>1&&wm.has(n)?s.length-2:s.length-1;return s[Math.max(0,r)]||s[0]||"unknown"}function Co(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 It(t){return Number(t||0).toLocaleString("en-US")}function km(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 xm(t,{expanded:e,selected:s,maxWidth:n}){const r=e?"v":">",i=Em(t?.model),o=t?.durationMs!=null?`${(Number(t.durationMs)/1e3).toFixed(1)}s`:"n/a",l=`${r} Mod: ${i} tok ${Co(t?.tokensInput)}/${Co(t?.tokensOutput)} dur ${o}`,c=[];if(s?c.push(lt(ts(l,Math.max(18,n)))):c.push([{text:l,color:"magenta"}]),e){const d=[["model",t?.reasoningEffort?`${t?.model||"(unknown)"}:${t.reasoningEffort}`:t?.model||"(unknown)"],["duration",t?.durationMs!=null?`${It(t.durationMs)} ms`:null],["tokens",`${It(t?.tokensInput)} in / ${It(t?.tokensOutput)} out`],["cache",`${It(t?.tokensCacheRead)} read / ${It(t?.tokensCacheWrite)} write`],["tools",`${It(t?.toolCalls)} calls / ${It(t?.toolErrors)} errors`],["names",Array.isArray(t?.toolNames)&&t.toolNames.length?t.toolNames.join(", "):null],["worker",t?.workerNodeId||null],["result",t?.resultType||null],["error",t?.errorMessage||null]].filter(([,p])=>p!=null&&p!=="");for(const[p,u]of d)c.push([{text:` ${p}: `,color:"gray"},{text:String(u),color:"white"}])}return c}function Im(t,e,s,n={}){const r=!!n?.allowWideColumns,i=Sm(t,e,s),o=t.history.bySessionId.get(e.sessionId),l=mm(pm(cc(o?.events||[])),e);if(l.length===0)return{stickyLines:i,lines:[ie("No events yet - interact with this session to populate the sequence diagram.")]};const c=mi(t),d=l.filter(O=>lm(O,c)),p=(d.length>0?d:l).slice(-48),u=hm(t,c.startMs,c.endMs),f=Array.from(new Set(p.map(O=>O.nodeLabel).filter(O=>O&&O!=="orch"))).sort((O,R)=>O.localeCompare(R)),m=u.length>0?u:f,h=Math.min(13,Math.max(8,...p.map(O=>ze(String(O.time||""))))),g=Math.max(18,s),b=Math.max(1,Math.floor((g-h-1)/6));let y=["orch",...m];if(!r&&y.length>b){const O=Math.max(1,b-1);y=[...y.slice(0,O),"…"]}const v=Math.max(0,y.length-1),E=Math.max(4,Math.floor((g-h-1-v)/Math.max(1,y.length))),k=n?.sequenceExpansion||null,x=k?km(o?.events||[]):null,w=k?new Set((k.expandedTurns||[]).map(Number)):null,S=k&&k.selectedTurn!=null?Number(k.selectedTurn):null,C=[];for(const O of p)if(C.push(vm(O,y,h,E)),k&&O.completedTurn!=null){const R=Number(O.completedTurn),T=x.get(R);if(T)for(const N of xm(T,{expanded:w.has(R),selected:S===R,maxWidth:g}))C.push(N)}const M=ym(y,h,E),_=C.reduce((O,R)=>Math.max(O,Ao(R)),Ao(M));return{stickyLines:[...i,ie(`Window: ${c.label}`,"gray"),M,bm(y,h,E,_)],lines:C}}function Am(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 Cm(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!lc(s[n],e))continue;const r=Ts(s[n]?.workerNodeId);if(r)return r}return null}function Nm(t){return!Number.isFinite(t)||t<0?null:t<6e4?`${Math.round(t/1e3)}s ago`:t<36e5?`${Math.round(t/6e4)}m ago`:`${Math.round(t/36e5)}h ago`}function Tm(t){if(!Number.isFinite(t)||t<0)return null;if(t<60)return`${Math.round(t)}s`;if(t<3600)return`${Math.floor(t/60)}m`;const e=Math.floor(t/3600);return e<48?`${e}h ${Math.floor(t%3600/60)}m`:`${Math.floor(e/24)}d ${e%24}h`}function Pm(t,e,s){const n=t?.isSystem?Ot(t,e):t?.title||we(t?.sessionId),r=t?.isSystem?"⚙ ":t?.serviceKind?"⚗ ":`${jl(t)||"."} `;return{sessionId:t?.sessionId||null,text:`${r}${n}`,color:t?.isSystem?"yellow":es(t),bold:!!t?.isSystem,active:!!s}}function dc(t){const e=mi(t),s=t.branding?.title||"PilotSwarm",n=t.sessions.activeSessionId,r=Array.isArray(t.admin?.workers?.list)?t.admin.workers.list:[],i=Date.now(),o=9e4,l=new Map;for(const m of r){const h=Ts(m?.workerNodeId);if(!h)continue;const g=m?.updatedAt instanceof Date?m.updatedAt.getTime():new Date(m?.updatedAt??0).getTime(),b=Number.isFinite(g)?i-g:Number.NaN,y=m?.health||{};l.set(h,{label:h,workerNodeId:String(m?.workerNodeId??""),registered:!0,live:Number.isFinite(b)&&b<=o,phase:["starting","ready","draining"].includes(m?.phase)?m.phase:"ready",pool:String(m?.pool??"default"),agoText:Nm(b),uptimeText:Tm(y.uptimeS),rssText:Number.isFinite(y.rssBytes)?Wt(y.rssBytes):null,heapText:Number.isFinite(y.heapUsedBytes)?Wt(y.heapUsedBytes):null,eventLoopText:Number.isFinite(y.eventLoopDelayP99Ms)?`${y.eventLoopDelayP99Ms}ms`:null,sessions:Number.isFinite(y.activeSessions)?y.activeSessions:null,sdkVersion:typeof m?.info?.sdkVersion=="string"?m.info.sdkVersion:null,substrate:typeof m?.info?.runtime?.substrate=="string"?m.info.runtime.substrate:null,capabilities:m?.info?.capabilities&&typeof m.info.capabilities=="object"?Object.entries(m.info.capabilities).filter(([,v])=>!!v).map(([v])=>v).sort():[],consumes:Array.isArray(m?.info?.consumes)?m.info.consumes:[],owner:m?.owner?.subject?String(m.owner.subject):null,pkgEpoch:Number.isFinite(m?.state?.["agent-packages"]?.epoch)?m.state["agent-packages"].epoch:null,pkgInstalled:m?.state?.["agent-packages"]?.installed&&typeof m.state["agent-packages"].installed=="object"?Object.entries(m.state["agent-packages"].installed).map(([v,E])=>({name:v,semver:E?.semver??null,status:E?.status==="error"?"error":"ok",error:E?.error?String(E.error):null})):[],pkgLastError:m?.state?.["agent-packages"]?.lastError?String(m.state["agent-packages"].lastError):null,executing:[]})}for(const m of gm(t,e))l.has(m)||l.set(m,{label:m,workerNodeId:null,registered:!1,live:!0,phase:null,pool:null,agoText:null,uptimeText:null,rssText:null,heapText:null,eventLoopText:null,sessions:null,sdkVersion:null,substrate:null,capabilities:[],consumes:[],owner:null,pkgEpoch:null,pkgInstalled:[],pkgLastError:null,executing:[]});let c=0;for(const m of Am(t)){const h=t.sessions.byId[m];if(!h)continue;const g=t.history.bySessionId.get(m);g?.events||(c+=1);const b=Cm(g,e),y=b?l.get(b):null;y&&y.executing.push(Pm(h,s,m===n))}const d=Array.from(l.values()).sort((m,h)=>{if(m.registered!==h.registered)return m.registered?-1:1;if(m.live!==h.live)return m.live?-1:1;const g=String(m.pool??"~").localeCompare(String(h.pool??"~"));return g!==0?g:m.label.localeCompare(h.label)});d.forEach((m,h)=>{m.ordinal=h+1});const p=d.filter(m=>m.registered),u=t.ui?.nodeMapSelectedNode,f=u&&d.some(m=>m.label===u)?u:d[0]?.label??null;return{windowLabel:e.label,degraded:p.length===0,registryError:t.admin?.workers?.error||null,registryFetchedAt:t.admin?.workers?.fetchedAt||0,registryLoading:!!t.admin?.workers?.loading,registryAttempts:t.admin?.workers?.attempts||0,registryLastAttemptAt:t.admin?.workers?.lastAttemptAt||0,registryLastSkip:t.admin?.workers?.lastSkip||null,registered:p.length,liveCount:p.filter(m=>m.live).length,executingTotal:d.reduce((m,h)=>m+h.executing.length,0),missingHistoryCount:c,selected:f,nodes:d}}function Mm(t,e,s={}){const n=dc(t);if(n.nodes.length===0)return[ie(n.degraded?`No workers registered and no worker activity in the ${n.windowLabel} window.`:`No worker activity in the ${n.windowLabel} window.`,"gray")];const r=[];if(r.push([{text:n.degraded?`Nodes (activity-derived) · window ${n.windowLabel}`:`Nodes · ${n.liveCount} live / ${n.registered} registered · window ${n.windowLabel}`,color:"gray"}]),n.degraded)if(n.registryError)r.push([{text:`! worker registry unavailable: ${n.registryError}`,color:"red"}]);else if(n.registryFetchedAt)r.push([{text:"registry reachable but EMPTY — no worker has heartbeated in the last hour",color:"yellow"}]);else if(n.registryLoading)r.push([{text:"registry request in flight… (times out red after 10s)",color:"yellow"}]);else if(n.registryAttempts===0)r.push([{text:"registry refresh has NEVER been attempted in this tab — reload; if it persists the refresh call is not reaching the controller",color:"red"}]);else{const i=n.registryLastAttemptAt?Math.round((Date.now()-n.registryLastAttemptAt)/1e3):null;r.push([{text:`registry attempted ${n.registryAttempts}× (last ${i===null?"?":`${i}s`} ago${n.registryLastSkip?`, skipped: ${n.registryLastSkip}`:""}) but no rows and no error — reload if this persists`,color:"yellow"}])}r.push(ie("","gray"));for(const i of n.nodes){const o=i.label===n.selected,l=i.live?"●":"○",c=i.live?i.phase==="draining"?"red":i.phase==="starting"?"yellow":"green":"gray",d=[{text:o?"› ":" ",color:"green",bold:o,nodeSelect:i.label,nodeSelected:o},{text:i.ordinal<=9?`${i.ordinal} `:" ",color:"gray",nodeSelect:i.label},{text:`${l} `,color:c,nodeSelect:i.label},{text:i.label.padEnd(7),color:o||i.live?"white":"gray",bold:o,nodeSelect:i.label}];if(i.registered){d.push({text:` ${(i.phase||"").padEnd(8)}`,color:c,nodeSelect:i.label}),d.push({text:` ${i.pool}`,color:"gray",nodeSelect:i.label});const p=[i.executing.length?`${i.executing.length} sess`:null,i.rssText,i.uptimeText?`up ${i.uptimeText}`:null,i.agoText].filter(Boolean).join(" · ");p&&d.push({text:` ${p}`,color:"gray",nodeSelect:i.label})}else d.push({text:" activity only",color:"gray",nodeSelect:i.label}),i.executing.length&&d.push({text:` · ${i.executing.length} sess`,color:"gray",nodeSelect:i.label});r.push(hi(d))}return r.push(ie("","gray")),r.push(ie("Click a node (or press 1-9) — its details fill the pane below.","gray")),n.missingHistoryCount>0&&r.push(ie(`Loading worker history for ${n.missingHistoryCount} session(s)…`,"gray")),r}function Rm(t,e=72){const s=t.ui.modal;if(!s||s.type!=="modelPicker")return null;const n=Array.isArray(s.groups)?s.groups:[],r=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(24,e-4),o=[],l=[];let c=0;for(const m of n){const h=he([{text:`${m.providerId}`,color:"cyan",bold:!0},{text:` (${m.providerType||"provider"})`,color:"gray"}],i);o.push(h),l.push(null);for(const g of m.models||[]){const b=Array.isArray(s.items)?s.items.findIndex(x=>x.id===g.id):-1,y=b===r,v=!!g.disabled,E=he([{text:"· ",color:"gray"},{text:g.modelName||g.qualifiedName||g.id,color:v?"gray":"white",bold:!!g.isDefault&&!v},...g.cost?[{text:` [${g.cost}]`,color:"gray"}]:[],...v?[{text:" ⊘ needs GitHub key",color:"yellow"}]:[],...g.isDefault?[{text:" ← current default",color:"gray"}]:[]],i),k=y?lt(E.map(x=>x.text).join("").padEnd(i," ")):E;y&&(c=o.length),o.push(k),l.push(b>=0?b:null)}}const d=Array.isArray(s.items)&&s.items[r]||null,p=Array.isArray(d?.supportedReasoningEfforts)?d.supportedReasoningEfforts.filter(Boolean):[],u=typeof d?.defaultReasoningEffort=="string"?d.defaultReasoningEffort:null,f=d?[[{text:d.modelName||d.qualifiedName||d.id,color:"white",bold:!0}],[{text:`${d.providerId} (${d.providerType||"provider"})`,color:"gray"}],...d.cost?[[{text:`Cost: ${d.cost}`,color:"gray"}]]:[],...p.length>0?[[{text:`Reasoning: ${p.join(", ")}`,color:"gray"}]]:[],...u?[[{text:`Default reasoning: ${u}`,color:"gray"}]]:[],...d.disabled?[[{text:"Unavailable: add a personal provider in Admin Console, then reopen this picker.",color:"yellow"}]]:[],[{text:"",color:"gray"}],[{text:d.description||"No description available for this model.",color:d.description?"white":"gray"}]]:[[{text:"No model selected.",color:"gray"}]];return{title:s.title||"Select model for new session",rows:o,rowItemIndexes:l,selectedRowIndex:c,detailsTitle:"Model Details",detailsLines:f,idealWidth:Math.min(Math.max(46,o.reduce((m,h)=>Array.isArray(h)?Math.max(m,Dt(h)):Math.max(m,String(h?.text||"").length),0)+4),e)}}function $m(t,e=76){const s=t.ui.modal;if(!s||s.type!=="sessionAgentPicker")return null;const n=Array.isArray(s.items)?s.items:[],r=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(24,e-4),o=[],l=[];n.forEach((m,h)=>{const g=h===r,b=" ".repeat(Math.max(0,Number(m?.depth)||0)*2);let y;if(m?.kind==="section"){const v=m.collapsed?"▸":"▾",E=m.sectionKind==="package"&&m.packageScope==="user"&&!m.mine?" [private]":"";y=he([{text:`${b}${v} `,color:"cyan"},{text:m.title||"Section",color:"white",bold:!0},...E?[{text:E,color:"cyan"}]:[],...m.meta?[{text:` · ${m.meta}`,color:"gray"}]:[]],i)}else{const v=m?.kind==="generic"||m?.supportsDirectStart!==!1,E=m?.kind==="generic"?"○ ":(m?.depth||0)>0&&m?.parentAgentName?"└ ":"★ ";y=he([{text:`${b}${E}`,color:v?"yellow":"gray"},{text:m?.title||m?.agentName||m?.id||"Agent",color:v?"white":"gray",bold:v}],i)}o.push(g?lt(y.map(v=>v.text).join("").padEnd(i," ")):y),l.push(h)});const c=n[r]||null,d=s.sessionOptions?.model||null,p=s.sessionOptions?.reasoningEffort||null,u=c?.kind==="section"?[[{text:c.title||"Section",color:"white",bold:!0}],...c.sectionKind==="package"?[[{text:`${c.packageName||"package"}@${c.packageSemver||"?"}`,color:"gray"}],...c.ownerLabel?[[{text:`Published by ${c.ownerLabel}`,color:"gray"}]]:[]]:[[{text:c.sectionKind==="builtin"?"Agents baked into this deployment.":"Agent packages installed on this deployment.",color:"gray"}]],[{text:"",color:"gray"}],[{text:c.meta||"",color:"gray"}],[{text:"",color:"gray"}],[{text:c.collapsed?"Enter or → to open.":"Enter or ← to close.",color:"gray"}]]:c?[[{text:c.title||c.agentName||c.id||"Agent",color:"white",bold:!0}],...c.kind==="generic"?[[{text:"Open-ended session",color:"gray"}]]:[[{text:c.agentName||c.id||"agent",color:"gray"}]],...c.packageName?[[{text:`Package: ${c.packageName}@${c.packageSemver||"?"} · ${c.packageScope||"shared"}`,color:"gray"}]]:c.kind==="agent"?[[{text:"Built-in agent",color:"gray"}]]:[],...c.startedBy?.length?[[{text:`Started by: ${c.startedBy.join(", ")}`,color:"gray"}]]:[],...c.kind!=="generic"&&c.supportsDirectStart===!1?[[{text:"Cannot be started on its own",color:"yellow"}]]:[],...d?[[{text:`Model: ${d}`,color:"gray"}]]:[],...p?[[{text:`Reasoning: ${p}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:c.description||(c.kind==="generic"?"Create a general-purpose session without a specialized named agent.":"No description available for this agent."),color:c.description?"white":"gray"}],[{text:"",color:"gray"}],[{text:c.tools?.length?`Tools: ${c.tools.join(", ")}`:"Tools: system defaults only",color:"gray"}]]:[[{text:"No agent selected.",color:"gray"}]],f=l.indexOf(r);return{title:s.title||"Select agent for new session",rows:o,rowItemIndexes:l,selectedRowIndex:f>=0?f:0,detailsTitle:"Agent Details",detailsLines:u,idealWidth:Math.min(Math.max(52,o.reduce((m,h)=>Array.isArray(h)?Math.max(m,Dt(h)):Math.max(m,String(h?.text||"").length),0)+4),e)}}function _m(t,e=64){const s=t.ui.modal;if(!s||s.type!=="reasoningEffortPicker")return null;const n=Array.isArray(s.items)?s.items:[],r=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(24,e-4),o=n.map((p,u)=>{const f=u===r,m=he([{text:"· ",color:"gray"},{text:String(p?.label||p?.id||"effort"),color:"white",bold:!0},...p?.isDefault?[{text:" ← model default",color:"gray"}]:[]],i);return f?lt(m.map(h=>h.text).join("").padEnd(i," ")):m}),l=n[r]||null,c=s.modelItem||null,d=[[{text:c?.modelName||c?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${c?.providerId||"provider"} (${c?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:l?.id?`Using reasoning effort: ${l.id}`:"Choose an effort.",color:"white"}]];return{title:s.title||"Select reasoning effort",rows:o,selectedRowIndex:r,detailsTitle:"Reasoning Details",detailsLines:d,idealWidth:Math.min(Math.max(46,o.reduce((p,u)=>Array.isArray(u)?Math.max(p,Dt(u)):Math.max(p,String(u?.text||"").length),0)+4),e)}}function Lm(t,e=64){const s=t.ui.modal;if(!s||s.type!=="contextTierPicker")return null;const n=Array.isArray(s.items)?s.items:[],r=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(24,e-4),o=n.map((u,f)=>{const m=f===r,h=he([{text:"· ",color:"gray"},{text:String(u?.label||u?.id||"tier"),color:"white",bold:!0},...u?.isDefault?[{text:" ← model default",color:"gray"}]:[]],i);return m?lt(h.map(g=>g.text).join("").padEnd(i," ")):h}),l=n[r]||null,c=s.modelItem||null,d=l?.label||l?.id,p=[[{text:c?.modelName||c?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${c?.providerId||"provider"} (${c?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:d?`Using context window: ${d}`:"Choose a context window.",color:"white"}],[{text:"Long context costs more per token.",color:"gray"}]];return{title:s.title||"Select context window",rows:o,selectedRowIndex:r,detailsTitle:"Context Window",detailsLines:p,idealWidth:Math.min(Math.max(46,o.reduce((u,f)=>Array.isArray(f)?Math.max(u,Dt(f)):Math.max(u,String(f?.text||"").length),0)+4),e)}}function Om(t,e=72){const s=t.ui.modal;if(!s||s.type!=="sessionGroupPicker")return null;const n=Array.isArray(s.items)?s.items:[],r=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(24,e-4),o=Array.isArray(s.sessionIds)?s.sessionIds.length:0,l=n.map((p,u)=>{const f=u===r,m=p?.kind==="noGroup"?"○ ":p?.kind==="newGroup"?"+ ":"🗂 ",h=he([{text:m,color:p?.kind==="group"?"cyan":"gray",bold:p?.kind!=="noGroup"},{text:p?.label||p?.groupId||"Group",color:"white",bold:!0},...p?.kind==="group"?[{text:` (${p.memberCount??0})`,color:"gray"}]:[]],i);return f?lt(h.map(g=>g.text).join("").padEnd(i," ")):h}),c=n[r]||null,d=c?[[{text:c.label||c.groupId||"Group",color:"white",bold:!0}],[{text:`${o} session${o===1?"":"s"} selected`,color:"gray"}],...c.kind==="group"?[[{text:`${c.memberCount??0} current member${c.memberCount===1?"":"s"}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:c.description||"Move selected session(s) to this group.",color:"white"}]]:[[{text:"No group selected.",color:"gray"}]];return{title:s.title||"Move to Group",rows:l,selectedRowIndex:r,detailsTitle:"Move Details",detailsLines:d,idealWidth:Math.min(Math.max(50,l.reduce((p,u)=>Array.isArray(u)?Math.max(p,Dt(u)):Math.max(p,String(u?.text||"").length),0)+4),e)}}function Fm(t,e=76){const s=t.ui.modal;if(!s||s.type!=="renameSession")return null;const n=String(s.value||""),r=typeof s.agentTitlePrefix=="string"&&s.agentTitlePrefix.trim()?s.agentTitlePrefix.trim():null,i=String(s.currentTitle||"").trim(),o=n.trim()?r?`${r}: ${n.trim()}`:n.trim():r?`${r}: …`:"…",l=[[{text:"Current: ",color:"gray"},{text:i||"(untitled session)",color:i?"white":"gray"}],[{text:"Saved as: ",color:"gray"},{text:o,color:"white",bold:!0}],...r?[[{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:r?"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"}],...s.isGroup?[]:[[{text:"",color:"gray"}],[{text:"Manual titles stop future automatic LLM title changes for this session.",color:"gray"}]]],detailsLines:l,idealWidth:Math.min(Math.max(56,ze(i||"(untitled session)")+18,ze(o)+18),e)}}function Dm(t,e=76){const s=t.ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=String(s.value||""),r=Array.isArray(s.sessionIds)?s.sessionIds.length:0,i=n.trim()||"…",o=s.mode==="rename";return{title:s.title||(o?"Rename Group":"New Group"),mode:o?"rename":"create",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:o?" rename ":" create and move ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],o?[{text:"Only the group's name changes; its sessions stay put.",color:"gray"}]:[{text:`The new group will contain ${r} selected session${r===1?"":"s"}.`,color:"gray"}]],detailsLines:[[{text:o?"Rename to: ":"New group: ",color:"gray"},{text:i,color:"white",bold:!0}],[{text:"Groups are containers only; session actions remain per-session.",color:"gray"}]],idealWidth:Math.min(Math.max(56,ze(i)+18),e)}}function Bm(t,e=82){const s=t.ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=String(s.value||""),r=s.sessionId||t.ui.promptAttachments?.[0]?.sessionId||t.sessions?.activeSessionId||null,i=r&&t.sessions?.byId?.[r]||null,o=r?i?Wl(i,t.branding?.title):we(r):"A new session will be created on upload",l=[[{text:"Target: ",color:"gray"},{text:o,color:r?"white":"gray",bold:!!r}]];return{title:s.title||"Upload Artifact",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:"~/path/to/file.md",helpTitle:"Upload Rules",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" upload ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],[{text:"The file is uploaded into this session's artifact store immediately.",color:"gray"}],[{text:"Use the files browser or @-driven browsing in the prompt to reference it after upload.",color:"gray"}]],detailsLines:l,idealWidth:Math.min(Math.max(60,ze(n||"~/path/to/file.md")+20,ze(o)+20),e)}}function gi(t,e={},s=96,n="Filters",r="Choose how this pane is filtered and rendered."){const i=Array.isArray(t.items)?t.items:[],o=Math.max(0,Number(t.selectedIndex)||0),l=i[o]||null,c=i.map((d,p)=>{const u=e?.[d.id]||d.options?.[0]?.id,f=(d.options||[]).map(m=>m.id===u?lt(m.label):{text:m.label,color:"white"});return{id:d.id,title:d.label,focused:p===o,description:d.description||"",lines:f.length>0?f:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(d.label||"").length+4,...(d.options||[]).map(m=>String(m?.label||"").length+4))}});return{title:t.title||n,panes:c,helpTitle:l?.label||n,helpLines:[[{text:l?.description||r,color:"white"}],[{text:"",color:"gray"}],[{text:"Tab/Shift-Tab",color:"cyan",bold:!0},{text:" switch filter ",color:"gray"},{text:"Up/Down",color:"cyan",bold:!0},{text:" change value ",color:"gray"},{text:"Enter",color:"cyan",bold:!0},{text:" close ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}]],footerRuns:[{text:"Tab/Shift-Tab",color:"cyan",bold:!0},{text:" switch filter · ",color:"gray"},{text:"Up/Down",color:"cyan",bold:!0},{text:" change value · ",color:"gray"},{text:"Enter",color:"cyan",bold:!0},{text:" close · ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],idealWidth:Math.min(Math.max(72,c.reduce((d,p)=>d+p.idealWidth,0)+Math.max(0,c.length-1)*2+4),s)}}function uc(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&&!!Ie(s?.principal):t.kind==="shared"?e?.includeShared===!0:t.kind==="owner"?Array.isArray(e?.ownerKeys)&&e.ownerKeys.includes(t.ownerKey):!1:!1}function No(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(r=>r?.kind!=="all"&&uc(r,e,s)).map(r=>r.kind==="me"?"Me":r.label);return n.length>0?n.join(" + "):"All sessions"}function Hm(t,e=88){const s=t.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return null;const n=Array.isArray(s.items)?s.items:[],r=t.sessions?.ownerFilter||{all:!0},i=t.auth||{},o=Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1))),l=n[o]||null,c=n.map((p,u)=>{const f=uc(p,r,i),m=p.kind==="system"?"yellow":p.kind==="unowned"?"gray":p.kind==="all"?"cyan":"white",h=[{text:f?"[x] ":"[ ] ",color:f?"cyan":"gray",bold:f},{text:p.label||p.id,color:m,bold:f}];return u===o?Ll(h,{preserveColors:!0}):h}),d=[[{text:"Active: ",color:"gray"},{text:No(n,r,i),color:"white",bold:!0}],[{text:"",color:"gray"}],[{text:l?.description||"Toggle which session owners appear in the session list.",color:"white"}],[{text:"",color:"gray"}],[{text:"Space",color:"cyan",bold:!0},{text:" toggle ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" close",color:"gray"}]];return{title:s.title||"Session Filter",rows:c.length>0?c:[{text:"No filter entries available.",color:"gray"}],selectedRowIndex:o,detailsTitle:l?.label||"Session Filter",detailsLines:d,idealWidth:Math.min(Math.max(48,c.reduce((p,u)=>Math.max(p,Array.isArray(u)?Dt(u):ze(u?.text||"")),0)+8,ze(No(n,r,i))+16),e)}}function Um(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:gi(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function jm(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:gi(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function Gm(t,e=88){const s=t.ui.modal;if(!s||s.type!=="artifactPicker")return null;const n=Array.isArray(s.items)?s.items:[],r=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(28,e-4),o=n.filter(m=>m.kind==="artifact"),l=n.filter(m=>m.kind==="url"),c=o.reduce((m,h)=>{const g=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];return m+(g?.localPath?1:0)},0),d=Math.max(0,o.length-c),p=n.map((m,h)=>{let g;if(m.kind==="downloadAll")g=he([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${d} pending]`,color:"gray"}],i);else if(m.kind==="url")g=he([{text:"go ",color:"cyan",bold:!0},{text:m.text&&m.text!==m.href?m.text:m.href,color:"white",bold:!0},...m.text&&m.text!==m.href?[{text:` ${m.href}`,color:"gray"}]:[]],i);else{const b=t.files?.bySessionId?.[m.sessionId]?.downloads?.[m.filename];g=he([{text:b?.localPath?"ok ":"dl ",color:b?.localPath?"green":"cyan",bold:!0},{text:`${we(m.sessionId)}/`,color:"gray"},{text:m.filename,color:"white"}],i)}return h!==r?g:lt(g.map(b=>b.text).join("").padEnd(i," "))}),u=n[r]||null;let f=[[{text:"No linked item selected.",color:"gray"}]];if(u?.kind==="downloadAll")f=[[{text:`${o.length} artifacts available`,color:"white",bold:!0}],...l.length>0?[[{text:`${l.length} links available`,color:"gray"}]]:[],[{text:`${c} already downloaded`,color:"gray"}],[{text:`${d} pending download`,color:"gray"}],...s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:"Press Enter to download all pending artifacts.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(u?.kind==="url")f=[[{text:u.text||u.href,color:"white",bold:!0}],[{text:u.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(u?.kind==="artifact"){const m=t.sessions?.byId?.[u.sessionId]||null,h=t.files?.bySessionId?.[u.sessionId]?.downloads?.[u.filename]||null;f=[[{text:u.filename,color:"white",bold:!0}],[{text:m?Wl(m,t.branding?.title):we(u.sessionId),color:"gray"}],...h?.localPath?[[{text:`Saved to: ${h.localPath}`,color:"white"}]]:s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:h?.localPath?"Press Enter to download this artifact again.":"Press Enter to download this artifact.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]]}return{title:s.title||"Linked Items",rows:p.length>0?p:[{text:"No linked items available.",color:"gray"}],selectedRowIndex:r,detailsTitle:"Linked Item Details",detailsLines:f,confirmLabel:l.length>0?o.length>0?"Open / Download":"Open":"Download",idealWidth:Math.min(Math.max(54,p.reduce((m,h)=>Array.isArray(h)?Math.max(m,Dt(h)):Math.max(m,String(h?.text||"").length),0)+4),e)}}function te(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 yi(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 zm(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 r=Math.floor(n/24);return r<14?`${r}d${String(n%24).padStart(2,"0")}h`:`${Math.floor(r/7)}w`}function To(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"—";const s=e.toLocaleDateString(void 0,{month:"short",day:"numeric"}),n=e.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",second:"2-digit"});return`${s}, ${n}`}function Po(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);return Number.isNaN(e.getTime())?"—":e.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit",timeZoneName:"short"})}function Es(t){return["session","fleet","users"].includes(t)?t:"session"}function kn(t,e){const s=Es(t),n=[{text:"View ",color:"cyan",bold:!0}];for(const r of["session","fleet","users"])n.push({text:r===s?`[${r}]`:r,color:r===s?"magenta":"gray",bold:r===s}),n.push({text:" ",color:"gray"});return n.push({text:" [f cycle]",color:"gray"}),he(n,e)}function Wm(t,e,s){if(!e)return[ie("No session selected.")];const n=t.sessionStats?.bySessionId?.[e.sessionId]||null;if(!n||n.loading&&!n.summary)return[ie("Loading session stats...")];const r=n.summary;if(!r)return[ie("Session stats unavailable.")];const i=[],o=Math.max(24,s);i.push(kn("session",o)),i.push(ie("")),i.push(he([{text:"Session ",color:"cyan",bold:!0},{text:we(e.sessionId),color:"white"}],o));const l=e.isSystem?"system":e.owner?"user":"unowned",c=e.isSystem?"system":e.owner?En(e.owner):"(?) unowned",d=e.owner?.email||"—";i.push(he([{text:"Owner ",color:"cyan",bold:!0},{text:c,color:e.owner?"white":"gray"}],o)),i.push(he([{text:"Email ",color:"cyan",bold:!0},{text:d,color:e.owner?.email?"white":"gray"}],o)),i.push(he([{text:"Type ",color:"cyan",bold:!0},{text:l,color:l==="user"?"white":"gray"}],o)),r.agentId&&i.push(he([{text:"Agent ",color:"cyan",bold:!0},{text:r.agentId,color:"white"}],o));const p=di(r.model||e.model,r.reasoningEffort||e.reasoningEffort);p&&i.push(he([{text:"Model ",color:"cyan",bold:!0},{text:p,color:"white"}],o)),e.createdAt&&i.push(he([{text:"Created ",color:"cyan",bold:!0},{text:Po(e.createdAt),color:"white"}],o)),e.updatedAt&&i.push(he([{text:"Updated ",color:"cyan",bold:!0},{text:Po(e.updatedAt),color:"white"}],o)),i.push(ie(""));const u=Array.isArray(n.tokensByModel)?n.tokensByModel:[];u.length>1&&(i.push(...Ce({title:"Models",body:u.map(O=>`${Of(O.model)} · ${O.turnCount||0} turns · ${te(O.totalTokensInput)} in / ${te(O.totalTokensOutput)} out`).join(`
|
|
49
|
-
`),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(ie("")));const f=(r.tokensInput||0)+(r.tokensOutput||0),m=r.cacheHitRatio,h=m==null?"—":`${(m*100).toFixed(1)}%`;i.push(...Ce({title:"Tokens",body:_t([["Input",te(r.tokensInput)],["Output",te(r.tokensOutput)],["Total",te(f)],["Cache Read",te(r.tokensCacheRead)],["Cache Write",te(r.tokensCacheWrite)],["Hit Ratio",h]],{maxWidth:Math.max(12,o-4)}),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0})),i.push(ie(""));const g=Number(r.regenCount)||0,b=r.lastRegenStats&&typeof r.lastRegenStats=="object"?r.lastRegenStats:null,y=Number.isFinite(b?.toEpoch)?b.toEpoch:g,v=b?b.distillMode==="deterministic"||!b.distillMode&&!b.distillerModel?"fast":String(b.distillerModel||"llm").replace(/^[^:]*:/,""):null,E=b?`${b.turnsArchived??0} turn${b.turnsArchived===1?"":"s"} · ${(Number(b.totalMs)/1e3).toFixed(1)}s${v?` · ${v}`:""}`:null;i.push(...Ce({title:"Persistence",body:_t([["Epoch",String(y)],["Regens",g>0?String(g):null],["Last Regen",E],["Snapshot",Me(r.snapshotSizeBytes)],["Uncompressed",r.rawSizeBytes?Me(r.rawSizeBytes):null],["Compression",Io(r.rawSizeBytes,r.snapshotSizeBytes)],["Dehydrations",String(r.dehydrationCount)],["Hydrations",String(r.hydrationCount)],["Lossy Handoffs",String(r.lossyHandoffCount)],["Last Dehydrated",r.lastDehydratedAt?To(r.lastDehydratedAt):null],["Last Hydrated",r.lastHydratedAt?To(r.lastHydratedAt):null]],{maxWidth:Math.max(12,o-4)}),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const k=n.treeStats?.tree;if(k&&k.sessionCount>1){const O=k.cacheHitRatio,R=O==null?"—":`${(O*100).toFixed(1)}%`,T=(k.totalTokensInput||0)+(k.totalTokensOutput||0);i.push(ie("")),i.push(...Ce({title:`Tree (${k.sessionCount} sessions)`,body:_t([["Input",te(k.totalTokensInput)],["Output",te(k.totalTokensOutput)],["Total",te(T)],["Cache Read",te(k.totalTokensCacheRead)],["Cache Write",te(k.totalTokensCacheWrite)],["Hit Ratio",R],["Snapshot",Me(k.totalSnapshotSizeBytes)],["Uncompressed",k.totalRawSizeBytes?Me(k.totalRawSizeBytes):null],["Compression",Io(k.totalRawSizeBytes,k.totalSnapshotSizeBytes)],["Dehydrations",String(k.totalDehydrationCount)],["Hydrations",String(k.totalHydrationCount)]]),width:o,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const N=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];N.length>1&&(i.push(ie("")),i.push(...Ce({title:"Tree By Model",body:Qm(N),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const x=Array.isArray(n.skillUsage)?n.skillUsage:[];x.length>0&&(i.push(ie("")),i.push(...Ce({title:`Skills (${x.length})`,body:Mo(x,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const w=n.treeSkillUsage,S=Array.isArray(w?.rolledUp)?w.rolledUp:[],C=Array.isArray(w?.perSession)?w.perSession.length:0;S.length>0&&C>1&&(i.push(ie("")),i.push(...Ce({title:`Tree Skills (${S.length})`,body:Mo(S,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const M=n.factsStats,_=n.treeFactsStats;if(M&&Array.isArray(M.rows)&&M.rows.length>0){i.push(ie(""));const O=pc(M.rows),R=O?O.split(`
|
|
50
|
-
`).length:0,T=`${M.totalCount} · ${Me(M.totalBytes)}`;let N=O;_&&_.totalCount>M.totalCount&&(N+=`
|
|
51
|
-
Tree (${_.sessionIds.length} sessions): ${_.totalCount} · ${Me(_.totalBytes)}`),R>0&&i.push(...Ce({title:`Facts (${T})`,body:N,width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return i}function _t(t,e={}){const s=e.gap??2,n=(t||[]).filter(d=>Array.isArray(d)&&d[1]!=null&&d[1]!=="");if(n.length===0)return"";const r=n.reduce((d,[p])=>Math.max(d,String(p).length),0),i=n.reduce((d,[,p])=>Math.max(d,String(p).length),0),o=" ".repeat(s),l=Number(e.maxWidth),c=!Number.isFinite(l)||r+s+i<=l;return n.map(([d,p])=>c?`${String(d).padEnd(r)}${o}${String(p).padStart(i)}`:`${String(d).padEnd(r)}${o}${String(p)}`).join(`
|
|
52
|
-
`)}function xn(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 Ps(t,e={}){const s=e.gap??2,n=(t||[]).filter(l=>Array.isArray(l)&&l.length>0);if(n.length===0)return"";const r=n.reduce((l,c)=>Math.max(l,c.length),0),i=new Array(r).fill(0);for(const l of n)for(let c=0;c<r;c+=1){const d=l[c]==null?"":String(l[c]);d.length>i[c]&&(i[c]=d.length)}const o=" ".repeat(s);return n.map(l=>l.map((c,d)=>{const p=c==null?"":String(c);return d===0?p.padEnd(i[d]):p.padStart(i[d])}).join(o)).join(`
|
|
53
|
-
`)}function Mo(t,e){const s=t.slice().sort((u,f)=>(f.invocations||0)-(u.invocations||0)).slice(0,12),n=s.map(u=>`${u.invocations||0} inv`),r=n.reduce((u,f)=>Math.max(u,f.length),0),l=4+2+r,c=Number.isFinite(e)&&e>0?Math.max(8,Math.floor(e)-l):1/0,d=s.map((u,f)=>{const m=u.kind==="learned"?"L":"S",h=String(u.name||"(unknown)");return[xn(`${m} ${h}`,c),n[f]]}),p=Ps(d);return t.length>s.length?`${p}
|
|
54
|
-
… ${t.length-s.length} more`:p}function pc(t){const s=t.slice().sort((n,r)=>(r.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),Me(n.totalValueBytes||0)]);return Ps(s)}function qm(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":qt(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return Ps([["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 Km(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 Vm(t,e){const s=t.slice().sort((u,f)=>(Number(f.calls)||0)-(Number(u.calls)||0)).slice(0,12),n=s.map(u=>`${Number(u.calls)||0} calls`),r=s.map(u=>`${Number(u.totalResults)||0} res`),i=n.reduce((u,f)=>Math.max(u,f.length),0),o=r.reduce((u,f)=>Math.max(u,f.length),0),l=6+i+2+o,c=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-l):1/0,d=s.map((u,f)=>{const m=u.namespace?` ${u.namespace}`:"";return[xn(`${Km(u.operation)}${m}`,c),n[f],r[f]]}),p=Ps(d);return t.length>s.length?`${p}
|
|
55
|
-
… ${t.length-s.length} more`:p}function Ym(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.data)return[ie("Loading fleet stats...")];const n=s.data;if(!n)return[ie("Fleet stats unavailable.")];const r=[],i=Math.max(24,e);r.push(kn("fleet",i)),r.push(ie(""));const o=n.windowStart?`Since: ${yi(n.windowStart).replace(" ago","")}`:"All time",l=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";r.push(he([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],i)),r.push(he([{text:`Sessions: ${n.totals.sessionCount}`,color:"white"},{text:` Tokens: ${te(n.totals.totalTokensInput)} in / ${te(n.totals.totalTokensOutput)} out`,color:"white"}],i)),r.push(ie(""));const c=new Map;for(const g of n.byAgent||[]){const b=g.model||"(default)",y=c.get(b)||{totalTokensInput:0,totalTokensOutput:0,totalTokensCacheRead:0,totalTokensCacheWrite:0,totalSnapshotSizeBytes:0,turnCount:0};y.totalTokensInput+=Number(g.totalTokensInput)||0,y.totalTokensOutput+=Number(g.totalTokensOutput)||0,y.totalTokensCacheRead+=Number(g.totalTokensCacheRead)||0,y.totalTokensCacheWrite+=Number(g.totalTokensCacheWrite)||0,y.totalSnapshotSizeBytes+=Number(g.totalSnapshotSizeBytes)||0,y.turnCount+=Number(g.turnCount)||0,c.set(b,y)}if(c.size>0){const g=[];for(const[b,y]of c.entries()){const v=y.totalTokensInput>0?y.totalTokensCacheRead/y.totalTokensInput:null;g.push(b),g.push(bi(y,v)),g.push("")}r.push(...Ce({title:"Tokens By Model",body:g.join(`
|
|
56
|
-
`).trimEnd(),width:i,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),r.push(ie(""))}const d=n.totals.cacheHitRatio,p=d==null?"—":`${(d*100).toFixed(1)}%`;r.push(...Ce({title:"Fleet Totals",body:_t([["Sessions",String(n.totals.sessionCount)],["Tokens In",te(n.totals.totalTokensInput)],["Tokens Out",te(n.totals.totalTokensOutput)],["Total Tokens",te(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",te(n.totals.totalTokensCacheRead)],["Cache Write",te(n.totals.totalTokensCacheWrite)],["Hit Ratio",p],["Snapshots",Me(n.totals.totalSnapshotSizeBytes)]]),width:i,titleColor:"green",borderColor:"gray",fitToContent:!0}));const u=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(g=>!(g&&g.agentId==="facts-manager"&&String(g.name||"").startsWith("skills/")));u.length>0&&(r.push(ie("")),r.push(...Ce({title:`Fleet Skills (${u.length})`,body:Xm(u,e),width:i,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const f=Array.isArray(s.retrievalUsage?.rows)?s.retrievalUsage.rows:[];if(f.length>0){const g=f.reduce((b,y)=>b+(Number(y.calls)||0),0);r.push(ie("")),r.push(...Ce({title:`Fleet Retrieval (${te(g)})`,body:Vm(f,e),width:i,titleColor:"magenta",borderColor:"gray",fitToContent:!0}))}const m=s.sharedFactsStats;if(m&&Array.isArray(m.rows)&&m.rows.length>0){r.push(ie(""));const g=`${m.totalCount} · ${Me(m.totalBytes)}`;r.push(...Ce({title:`Shared Facts (${g})`,body:pc(m.rows),width:i,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const h=s.factsTombstoneStats;return h&&Number(h.pendingTotal)>0&&(r.push(ie("")),r.push(...Ce({title:`Fact Tombstones (${Number(h.pendingTotal)||0})`,body:qm(h),width:i,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),r}function Xm(t,e){const n=t.slice().sort((h,g)=>{const b=x=>x==="learned"?1:0,y=b(h.kind)-b(g.kind);if(y!==0)return y;const v=h.agentId?0:1,E=g.agentId?0:1;if(v!==E)return v-E;const k=String(h.agentId||"").localeCompare(String(g.agentId||""));return k!==0?k:String(h.name||"").localeCompare(String(g.name||""))}).slice(0,15),r=n.map(h=>`${h.invocations||0} inv`),i=n.map(h=>`${h.sessionCount||0} sess`),o=r.reduce((h,g)=>Math.max(h,g.length),0),l=i.reduce((h,g)=>Math.max(h,g.length),0),c=4,d=2,p=c+d+o+d+l,u=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-p):1/0,f=n.map((h,g)=>{const b=h.kind==="learned"?"L":"S",y=h.agentId||".",v=String(h.name||"(unknown)");return[xn(`${b} ${y}/${v}`,u),r[g],i[g]]}),m=Ps(f);return t.length>n.length?`${m}
|
|
57
|
-
… ${t.length-n.length} more`:m}function Qm(t){const e=t.slice().sort((n,r)=>(r.totalTokensInput||0)-(n.totalTokensInput||0)),s=[];for(const n of e){const r=n.cacheHitRatio;s.push(`${String(n.model||"(unknown)")} · ${n.sessionCount||0} sess · ${n.turnCount||0} turns`),s.push(bi(n,r)),s.push("")}return s.join(`
|
|
58
|
-
`).trimEnd()}function bi(t,e){const s=e==null?"—":`${(e*100).toFixed(1)}%`,n=(Number(t.totalTokensInput)||0)+(Number(t.totalTokensOutput)||0),r=[["Input",te(t.totalTokensInput||0)],["Output",te(t.totalTokensOutput||0)],["Total",te(n)],["Turns",te(t.turnCount||0)],["Cache Read",te(t.totalTokensCacheRead||0)],["Cache Write",te(t.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",Me(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&r.push(["Orch",Me(t.totalOrchestrationHistorySizeBytes||0)]),_t(r).split(`
|
|
59
|
-
`).map(o=>` ${o}`).join(`
|
|
60
|
-
`)}function Ir(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":En(t?.owner,"Unknown User")}function Zm(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=Ir(t);return e&&e!==s?e:""}function Jm(t,e){const s=Array.isArray(t?.byModel)?t.byModel:[];if(s.length===0)return"";const n=s.slice().sort((i,o)=>(o.totalTokensInput||0)-(i.totalTokensInput||0)).slice(0,6),r=[];for(const i of n){const o=xn(String(i.model||"(default)"),Math.max(12,e-10));r.push(`${o} · ${i.sessionCount||0} sess · ${i.turnCount||0} turns`),r.push(bi(i,i.cacheHitRatio)),r.push("")}return s.length>n.length&&r.push(`… ${s.length-n.length} more models`),r.join(`
|
|
61
|
-
`).trimEnd()}function eh(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.userStats)return[ie("Loading user stats...")];const n=s.userStats;if(!n)return[ie("User stats unavailable.")];const r=[],i=Math.max(24,e);r.push(kn("users",i)),r.push(ie(""));const o=n.windowStart?`Since: ${yi(n.windowStart).replace(" ago","")}`:"All time",l=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";r.push(he([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],i)),r.push(he([{text:`Users: ${Array.isArray(n.users)?n.users.length:0}`,color:"white"},{text:` Sessions: ${n.totals.sessionCount||0}`,color:"white"}],i)),r.push(ie(""));const c=n.totals.cacheHitRatio,d=c==null?"—":`${(c*100).toFixed(1)}%`;r.push(...Ce({title:"User Totals",body:_t([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",te(n.totals.totalTokensInput||0)],["Tokens Out",te(n.totals.totalTokensOutput||0)],["Total Tokens",te((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",te(n.totals.totalTokensCacheRead||0)],["Cache Write",te(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",d],["Snapshots",Me(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",Me(n.totals.totalOrchestrationHistorySizeBytes||0)]]),width:i,titleColor:"green",borderColor:"gray",fitToContent:!0}));const p=Array.isArray(n.users)?n.users:[],u=p.slice().sort((f,m)=>(m.totalTokensInput||0)-(f.totalTokensInput||0)||(m.totalSnapshotSizeBytes||0)-(f.totalSnapshotSizeBytes||0)).slice(0,8);for(const f of u){const m=Zm(f),h=f.cacheHitRatio,g=h==null?"—":`${(h*100).toFixed(1)}%`,b=m?`${Ir(f)} <${m}>`:Ir(f),y=_t([["Sessions",String(f.sessionCount||0)],["Tokens In",te(f.totalTokensInput||0)],["Tokens Out",te(f.totalTokensOutput||0)],["Total Tokens",te((f.totalTokensInput||0)+(f.totalTokensOutput||0))],["Cache Read",te(f.totalTokensCacheRead||0)],["Cache Write",te(f.totalTokensCacheWrite||0)],["Hit Ratio",g],["Snapshots",Me(f.totalSnapshotSizeBytes||0)],["Orch Size",Me(f.totalOrchestrationHistorySizeBytes||0)]]),v=Jm(f,i);r.push(ie("")),r.push(...Ce({title:`${b} (${f.sessionCount||0})`,body:v?`${y}
|
|
62
|
-
|
|
63
|
-
${v}`:y,width:i,titleColor:f.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return p.length>u.length&&(r.push(ie("")),r.push(ie(`… ${p.length-u.length} more users`))),r}function kt(t,e={}){const s=Je(t),n=t.ui.inspectorTab,r=Math.max(18,Number(e?.width)||36),i=!!e?.allowWideColumns,o=Ol(r);if(s?.isGroup)return{title:it("Inspector","magenta"),activeTab:n,tabs:ot,disabled:!0,stickyLines:[],lines:[ie(fc,"gray")]};const l=s?we(s.sessionId):"",c=n==="sequence"||n==="nodes"?mi(t):null,d=n==="nodes"?[...it("Node Map","magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:s?n==="sequence"?[...it(o?"Sequence":`Sequence: ${l}`,"magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:n==="logs"?[...it(o?"Logs":`Logs: ${l}`,"magenta")]:n==="history"?[...it(o?"Duroxide Events":`Duroxide Event History: ${l}`,"magenta")]:n==="stats"?[...it(o?"Stats":`Stats: ${l}`,"magenta"),{text:` [${Es(t.ui?.statsViewMode)}]`,color:"gray"}]:[...it(o?"Files":`Files: ${l}`,"magenta")]:n==="stats"?`Stats: ${Es(t.ui?.statsViewMode).replace(/^./u,f=>f.toUpperCase())}`:"No session selected";let p,u=[];switch(n){case"sequence":{const f=s?Im(t,s,r,{allowWideColumns:i,sequenceExpansion:e?.sequenceExpansion||null}):{stickyLines:[],lines:["No session selected."]};u=f.stickyLines||[],p=f.lines;break}case"logs":p=s?Gf(t,s):["No session selected."];break;case"nodes":p=Mm(t,r,{});break;case"files":p=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":p=s?rh(t,s):["No session selected."];break;case"stats":p=Es(t.ui?.statsViewMode)==="users"?eh(t,r):Es(t.ui?.statsViewMode)==="fleet"?Ym(t,r):s?Wm(t,s,r):[kn("session",Math.max(24,r)),ie(""),ie("No session selected. Press f to cycle to fleet or users view.")];break;default:p=["Inspector view is scaffolded in the new architecture."];break}return{title:d,activeTab:n,tabs:ot,stickyLines:u,lines:p}}const th={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"},fc="Select a session to see details.";function sh(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=th[t.kind]||"gray",n=[],r=[{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&&r.push({text:` ←#${t.sourceEventId}`,color:"cyan"}),n.push(r),t.data)try{const i=JSON.parse(t.data);if(typeof i=="object"&&i!==null)for(const[o,l]of Object.entries(i)){const c=typeof l=="string"?l:JSON.stringify(l),d=c.length>100?c.slice(0,97)+"...":c;n.push([{text:` ${o}: `,color:"yellow"},{text:d,color:"white"}])}else n.push({text:` ${String(i).slice(0,120)}`,color:"white"})}catch{const i=t.data.length>120?t.data.slice(0,117)+"...":t.data;n.push({text:` ${i}`,color:"white"})}return n}function nh(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function rh(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 r=t.executionHistory?.format||"pretty",i=[];if(i.push({text:`${n.length} event(s) · format: ${r}`,color:"gray"}),i.push(""),r==="raw")for(let o=0;o<n.length;o++){const l=nh(n[o]).split(`
|
|
64
|
-
`);for(const c of l)i.push({text:c,color:"gray"});o<n.length-1&&i.push({text:"────────────────────────────────",color:"gray"})}else for(let o=0;o<n.length;o++){const l=sh(n[o]);for(const c of l)i.push(c);o<n.length-1&&i.push({text:"────────────────────────────────",color:"gray"})}return i}function ih(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:gi(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function Ro(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 oh(t,e=80){const s=t.ui.modal;if(!s||s.type!=="themePicker")return null;const n=Array.isArray(s.items)?s.items:[],r=Math.max(0,Number(s.selectedIndex)||0),i=n[r]||null,o=s.currentThemeId||t.ui.themeId||null,l=n.find(f=>f.id===o)||null,c=i&&i.id!==o,d=Math.max(24,e-4),p=n.map((f,m)=>{const h=f.id===o?" [current]":"",g=`${f.label}${h}`.slice(0,d);return m===r?lt(g.padEnd(d," ")):[{text:g,color:f.id===o?"cyan":"white",bold:f.id===o}]}),u=i?[[{text:`theme: ${i.description||"Shared theme for the portal and native TUI."}`,color:"white"}],...i.group?[[{text:`group: ${i.group}`,color:"gray"}]]:[],{text:"",color:"gray"},[{text:c?`Previewing now. Cancel reverts to ${l?.label||"the previous theme"}.`:"Currently active in this TUI session.",color:c?"yellow":"green"}],Ro([{label:"bg",color:i.tui?.background||i.terminal?.background||"#000000"},{label:"surface",color:i.tui?.surface||i.terminal?.background||"#000000"},{label:"fg",color:i.tui?.white||i.terminal?.foreground||"#ffffff"}]),Ro([{label:"blue",color:i.tui?.blue||i.terminal?.blue||"#5555ff"},{label:"green",color:i.tui?.green||i.terminal?.green||"#55ff55"},{label:"magenta",color:i.tui?.magenta||i.terminal?.magenta||"#ff55ff"},{label:"yellow",color:i.tui?.yellow||i.terminal?.yellow||"#ffff55"}]),{text:"",color:"gray"},[{text:"Selecting previews immediately. Apply Theme keeps it; Cancel restores the previous theme.",color:"gray"}]]:[{text:"No themes available.",color:"gray"}];return{title:s.title||"Theme Picker",idealWidth:Math.max(60,Math.min(e,80)),rows:p,selectedRowIndex:r,detailsTitle:"Theme Details",detailsLines:u}}function ah(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 gs(t,e){return t.selectedName!==e.name?!0:typeof e.seq=="number"?(t.selectionSeq??0)!==e.seq:!1}function bt(t){const e=String(t??"").trim();return e||null}function $o(t){return new Map(t)}function ks(t){return new Set(t)}function lh(t){return Array.isArray(t)?[...t]:[]}function ch(t){return Array.isArray(t)?[...t]:[]}const dh=5e3;function _o(t,e){const s=[],n=new Set;for(const r of t||[])!r||n.has(r)||e[r]&&(n.add(r),s.push(r));return s}function mc(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function _s(t,e){const s=[],n=new Set;for(const r of t||[]){if(!r||n.has(r))continue;n.add(r);const i=e?.[r];(!i||mc(i))&&s.push(r)}return s}function uh(t,e,s){const n={},r=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(const i of r){const o=(e||{})[i],l=(t||{})[i],c={optedOut:o?o.optedOut:!!l?.optedOut,lastViewedRev:Math.max(o?.lastViewedRev||0,l?.lastViewedRev||0),lastViewedDataRev:Math.max(o?.lastViewedDataRev||0,l?.lastViewedDataRev||0),...l?.zenRailPx||o?.zenRailPx?{zenRailPx:l?.zenRailPx||o?.zenRailPx}:{}};if(!c.optedOut&&c.lastViewedRev===0&&c.lastViewedDataRev===0&&!c.zenRailPx)continue;const d=s?.[bp(i).sessionId];d&&d.isGroup||(n[i]=c)}return n}function hc(t){return ks(t)}function ph(t,e){const s=[],n=new Set([t]);let r=e?.[t]||null;for(;r;){let i=null;if(r.parentSessionId&&e?.[r.parentSessionId]?i=r.parentSessionId:!r.isGroup&&r.groupId&&e?.[`group:${r.groupId}`]&&(i=`group:${r.groupId}`),!i||n.has(i))break;s.push(i),n.add(i),r=e[i]||null}return s}function Lo(t,e,s){const n=hc(t);if(!s||!e?.[s])return n;for(const r of ph(s,e))n.delete(r);return n}function Oo(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 fh(t){return{...t||{}}}function dt(t){return{...t||{}}}function Fo(t){return{...t||{}}}function Ls(t){return{...t||{}}}function Xn(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function mh(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function hh(t){return[$.SESSIONS,$.CHAT,$.INSPECTOR,$.ACTIVITY].includes(t)?t:null}function Qn(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(be,Number(e)||be);return s.length>n?s.slice(-n):s}function Ar(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 r=0;r<t.length;r+=1)if(!Ar(t[r],e[r]))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 r of s)if(!Object.prototype.hasOwnProperty.call(e,r)||!Ar(t[r],e[r]))return!1;return!0}function Do(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 gh(t,e){const s=Do(t),n=Do(e);return s>0&&n>0&&n<=s}const yh=new Set(["completed","failed","cancelled","error"]);function bh(t,e){const s=String(e?.status??"").toLowerCase();if(t?.status!=="running"||s==="running"||yh.has(s))return!1;const n=Number(t?.statusVersion),r=Number(e?.statusVersion);return Number.isFinite(n)&&n>0&&Number.isFinite(r)&&r>0?r<=n:gh(t,e)}function Bo(t={},e={}){let s=t||{};const n=bh(t,e);for(const[r,i]of Object.entries(e||{}))if(i!==void 0&&!(r==="status"&&n)){if(r==="pendingQuestion"&&wh(t,i)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}Ar(t?.[r],i)||(s===t&&(s={...t||{}}),s[r]=i)}return s}function Ho(t){if(!t)return"unknown";const e=t.status||"unknown",s=e==="waiting"||e==="idle"||e==="unknown";return s&&os(t)?"budget_paused":t.cronActive===!0&&s?"cron_waiting":s&&(Number(t.activeChildCount)||0)>0?"awaiting_children":e}function Sh(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=Ho(e),r=t?.rowVisualStatus||Ho(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===r)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>=dh?{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0}:e.rowVisualStatus===r&&e.rowVisualStatusCandidate===n&&Number(e.rowVisualStatusCandidateSince)===o?e:{...e,rowVisualStatus:r,rowVisualStatusCandidate:n,rowVisualStatusCandidateSince:o}}const vh=new Set(["running","input_required"]);function Zn(t){const e=new Map;for(const r of Object.values(t||{})){if(!r?.sessionId||r.isGroup||!vh.has(r.status))continue;const i=new Set([r.sessionId]);let o=r.parentSessionId;for(;o&&t[o]&&!i.has(o);)i.add(o),e.set(o,(e.get(o)||0)+1),o=t[o].parentSessionId}let s=!1;const n={};for(const[r,i]of Object.entries(t||{})){const o=e.get(r)||0,l=Number(i?.activeChildCount)||0;if(o===l){n[r]=i;continue}s=!0,n[r]=o>0?{...i,activeChildCount:o}:{...i,activeChildCount:void 0}}return s?n:t}function Uo(t={},e={},s){let n=!1;const r={};for(const[i,o]of Object.entries(e)){const l=Sh(t[i],o,s);r[i]=l,l!==o&&(n=!0)}return n?r:e}function jo(t){return String(t?.question||"").trim()}function wh(t,e){const s=jo(t?.answeredPendingQuestion),n=jo(e);return!!(s&&n&&s===n)}function Eh(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&al(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function Go(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 r=n.parentSessionId;r&&e.has(r)&&s.add(r)}return s}function zo(t={}){const e=String(t?.filterQuery||"").trim(),s=nn(t?.ownerFilter);return!!e||s.all!==!0}function kh(t,e=[]){const s=as(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(i=>i.sessionId===n)||t.sessions?.navigationIntent||n&&t.sessions?.byId?.[n]&&!zo(t.sessions)||n&&!t.sessions?.listingSeen)return n;if(zo(t.sessions))return s[0]?.sessionId||null;const r=s.length>0?s.map(i=>t.sessions?.byId?.[i.sessionId]||null).filter(Boolean):e;return Eh(r)}function xh(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 At(t,e){let s=e;const n=s.navigationIntent||null,r=n&&n.status!=="failed"&&s.byId?.[n.sessionId]?n.sessionId:null;r&&(s={...s,activeSessionId:r,listDeselected:!1,navigationIntent:n.status==="resolved"?n:{sessionId:n.sessionId,status:"resolved"}});const i=s.activeSessionId||null;if(i&&s.byId?.[i]){const u=Lo(s.collapsedIds,s.byId,i);Oo(u,s.collapsedIds)||(s={...s,collapsedIds:u,flat:rt(Object.values(s.byId||{}),u,s.orderById,s.pinnedIds,s.manualOrder)})}r&&s.filterExceptionId!==r&&(as({...t,sessions:s}).some(f=>f.sessionId===r)||(s={...s,filterExceptionId:r}));const o={...t,sessions:s},l=kh(o,Object.values(s.byId||{})),c=Lo(s.collapsedIds,s.byId,l);return{sessions:{...!Oo(c,s.collapsedIds)?{...s,collapsedIds:c,flat:rt(Object.values(s.byId||{}),c,s.orderById,s.pinnedIds,s.manualOrder)}:s,activeSessionId:l},ui:xh(t,l)}}function Jn(t={},e=0,s=[]){const n=fh(t);let r=Number.isFinite(e)?e:0;for(const i of s||[]){const o=i?.sessionId;o&&typeof n[o]!="number"&&(n[o]=r,r+=1)}return{orderById:n,nextOrderOrdinal:r}}function Ih(t=[],e=[]){const s=rt(t,new Set,{},e),n={};let r=0;for(const i of s){const o=i?.sessionId;!o||typeof n[o]=="number"||(n[o]=r,r+=1)}for(const i of t||[]){const o=i?.sessionId;!o||typeof n[o]=="number"||(n[o]=r,r+=1)}return{orderById:n,nextOrderOrdinal:r}}function Ah(t,e,s=null){const n=String(t||""),r=Number.isFinite(e)?e:Number.isFinite(s)?s:n.length;return Math.max(0,Math.min(r,n.length))}function Wo(t,e){const s=String(t||"");return(Array.isArray(e)?e.filter(Boolean):[]).filter(r=>{if(r?.kind==="image")return!0;const i=String(r?.token||"").trim();return i&&s.includes(i)})}function Ch(t,e){switch(e.type){case"connection/ready":return{...t,connection:{...t.connection,connected:!0,workersOnline:e.workersOnline??t.connection.workersOnline,error:null},ui:{...t.ui,statusText:e.statusText??t.ui.statusText??"Ready"}};case"connection/error":return{...t,connection:{...t.connection,connected:!1,error:e.error},ui:{...t.ui,statusText:e.statusText||e.error||"Connection error"}};case"auth/context":return{...t,auth:{principal:e.principal??null,authorization:e.authorization??null}};case"ui/status":return{...t,ui:{...t.ui,statusText:e.text}};case"ui/theme":return{...t,ui:{...t.ui,themeId:e.themeId||t.ui.themeId}};case"ui/touchScale":return!!e.enabled==!!t.ui.touchScale?t:{...t,ui:{...t.ui,touchScale:!!e.enabled}};case"profileSettings/apply":{const s=e.settings&&typeof e.settings=="object"&&!Array.isArray(e.settings)?e.settings:{},n=Object.prototype.hasOwnProperty.call(s,"themeId")&&typeof s.themeId=="string"&&s.themeId.trim(),r=Object.prototype.hasOwnProperty.call(s,"sessionOwnerFilter"),i=Object.prototype.hasOwnProperty.call(s,"layoutAdjustments"),o=Object.prototype.hasOwnProperty.call(s,"touchScale")&&typeof s.touchScale=="boolean",l=Object.prototype.hasOwnProperty.call(s,"rightPaneMode")&&(s.rightPaneMode==="canvas"||s.rightPaneMode==="panes"),c=Object.prototype.hasOwnProperty.call(s,"desktopPanes")&&s.desktopPanes&&typeof s.desktopPanes=="object",d=c||l?Ml(c?s.desktopPanes:null,l?s.rightPaneMode:null):null,p=Object.prototype.hasOwnProperty.call(s,"canvasPrefs"),u=Object.prototype.hasOwnProperty.call(s,"pinnedSessionIds"),f=Object.prototype.hasOwnProperty.call(s,"collapsedSessionIds"),m=Object.prototype.hasOwnProperty.call(s,"sessionOrder"),h=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.status!=="failed"),g=Object.prototype.hasOwnProperty.call(s,"activeSessionId")&&!h,b=Object.keys(t.sessions.byId||{}).length>0,y=i?{...t.ui.layout||{},...Kr(s.layoutAdjustments)}:t.ui.layout,v=u?b?_s(on(s.pinnedSessionIds),t.sessions.byId):on(s.pinnedSessionIds):t.sessions.pinnedIds,E=f?b?hc(Sr(s.collapsedSessionIds),t.sessions.byId):Sr(s.collapsedSessionIds):t.sessions.collapsedIds,k=m?Vr(s.sessionOrder):t.sessions.manualOrder,x=g?Rl(s.activeSessionId):t.sessions.activeSessionId,w={...t.sessions,...r?{ownerFilter:nn(s.sessionOwnerFilter),ownerFilterExplicit:!0}:{},pinnedIds:v,manualOrder:k,collapsedIds:E,collapsedIdsExplicit:f?!0:t.sessions.collapsedIdsExplicit,activeSessionId:x,flat:u||f||m?rt(Object.values(t.sessions.byId),E,t.sessions.orderById,v,k):t.sessions.flat},S=b&&(r||u||f||g)?At(t,w):{sessions:w,ui:t.ui};return{...t,sessions:S.sessions,ui:{...S.ui,themeId:n?s.themeId.trim():S.ui.themeId,touchScale:o?s.touchScale:S.ui.touchScale,rightPaneMode:l?s.rightPaneMode:S.ui.rightPaneMode,...d?{canvasOpen:d.canvasOpen,diagnosticsOpen:d.diagnosticsOpen,canvasZen:d.zen===!0}:{},layout:y},canvas:p?{...t.canvas,prefs:uh(t.canvas.prefs,Yr(s.canvasPrefs),b?t.sessions.byId:null)}:t.canvas}}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,r=Math.max(40,e.width??s),i=Math.max(18,e.height??n);return r===s&&i===n?t:{...t,ui:{...t.ui,layout:{...t.ui.layout||{},viewportWidth:r,viewportHeight:i}}}}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/canvasPaneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},canvasPaneAdjust:Number(e.canvasPaneAdjust)||0}}};case"ui/diagnosticsSplitAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},diagnosticsSplitAdjust:Number(e.diagnosticsSplitAdjust)||0}}};case"ui/diagnosticsPaneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},diagnosticsPaneAdjust:Number(e.diagnosticsPaneAdjust)||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,requestedFocusRegion:e.requestedFocusRegion??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=At(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:nn(e.filter),navigationIntent:null,filterExceptionId:null},n=At(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,listDeselected:!1,navigationIntent:{sessionId:s,status:"pending"},filterExceptionId:null},r=At(t,n);return{...t,sessions:r.sessions,ui:r.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)),r=s.type==="themePicker"?s.items[n]?.id:null;return{...t,ui:{...t.ui,...r?{themeId:r}:{},modal:{...s,selectedIndex:n}}}}case"ui/scroll":return{...t,ui:{...t.ui,scroll:{...t.ui.scroll,[e.pane]:Math.max(0,e.offset??0)}}};case"ui/followBottom":{if(e.pane!=="inspector"&&e.pane!=="activity")return t;const s=!!e.followBottom;return t.ui.followBottom?.[e.pane]===s?t:{...t,ui:{...t.ui,followBottom:{...t.ui.followBottom||{},[e.pane]:s}}}}case"ui/nodeMapSelect":return e.label?{...t,ui:{...t.ui,nodeMapSelectedNode:String(e.label)}}:t;case"ui/inspectorTab":return{...t,ui:{...t.ui,inspectorTab:e.inspectorTab,fullscreenPane:e.inspectorTab==="files"&&t.ui.fullscreenPane===$.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:Ah(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:Jt(e.prompt),promptAttachments:Wo(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:Wo(t.ui.prompt,e.attachments)}};case"sessions/gone":{const s=e.sessionId;if(!s)return t;const n=!!t.sessions.byId[s],r=t.sessions.activeSessionId===s;if(!n&&!r)return t;const i={...t.sessions.byId};delete i[s];const o=Zn(i),l=Array.isArray(t.sessions.selectedIds)?t.sessions.selectedIds.filter(c=>c!==s):t.sessions.selectedIds;return{...t,sessions:{...t.sessions,byId:o,selectedIds:l,activeSessionId:r?null:t.sessions.activeSessionId}}}case"sessions/loaded":{const s={};let n=!1;const r=Date.now();for(const w of t.sessions.groupRows||[])s[w.sessionId]=t.sessions.byId[w.sessionId]||w;for(const w of e.sessions){const S=t.sessions.byId[w.sessionId];s[w.sessionId]=Bo(S,w)}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 i=Zn(s),o=Uo(t.sessions.byId,i,r);for(const[w,S]of Object.entries(o))if(S!==t.sessions.byId[w]){n=!0;break}const l=Object.keys(t.sessions.byId),c=Object.keys(o);if(l.length!==c.length&&(n=!0),!n){for(const w of c)if(!t.sessions.byId[w]){n=!0;break}}if(!n)return t;const d=Object.values(o),p=Object.keys(t.sessions.orderById||{}).length>0,u=Go(d),f=!!t.sessions.collapsedIdsExplicit,{orderById:m,nextOrderOrdinal:h}=p?Jn(t.sessions.orderById,t.sessions.nextOrderOrdinal,d):Ih(d,t.sessions.pinnedIds),g=f?ks(t.sessions.collapsedIds):u,b=t.sessions.listingSeen===!0;if(f&&b){const w=Go(Object.values(t.sessions.byId));for(const S of u)w.has(S)||g.add(S)}const y=_s(t.sessions.pinnedIds,o),v=_o(t.sessions.selectedIds,o),E=rt(d,g,m,y,t.sessions.manualOrder),k={...t.sessions,byId:o,collapsedIds:g,collapsedIdsExplicit:f,listingSeen:!0,pinnedIds:y,selectedIds:v,selectMode:t.sessions.selectMode&&v.length>0,flat:E,activeSessionId:t.sessions.activeSessionId,orderById:m,nextOrderOrdinal:h},x=At(t,k);return{...t,sessions:x.sessions,ui:x.ui}}case"sessions/groupsLoaded":{const s=Array.isArray(e.groups)?e.groups:[],n={...t.sessions.byId},r=Array.isArray(e.sessions)?e.sessions:Object.values(t.sessions.byId),i=new Set(r.filter(h=>h&&!h.isGroup&&h.groupId&&!h.parentSessionId).map(h=>`group:${h.groupId}`)),o=[];for(const h of Object.keys(n))if(n[h]?.isGroup&&!s.some(g=>g.sessionId===h)){if(i.has(h)){o.push(n[h]);continue}delete n[h]}for(const h of s)n[h.sessionId]={...n[h.sessionId]||{},...h};const l=_s(t.sessions.pinnedIds,n),{orderById:c,nextOrderOrdinal:d}=Jn(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(n)),p=t.sessions.groupsListingSeen===!0,u=ks(t.sessions.collapsedIds);for(const h of s)p&&(t.sessions.byId[h.sessionId]||u.add(h.sessionId));const f={...t.sessions,groupRows:[...s,...o],byId:n,pinnedIds:l,orderById:c,nextOrderOrdinal:d,collapsedIds:u,groupsListingSeen:!0,flat:rt(Object.values(n),u,c,l,t.sessions.manualOrder)},m=At(t,f);return{...t,sessions:m.sessions,ui:m.ui}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=Bo(s,e.session),r=Uo(t.sessions.byId,Zn({...t.sessions.byId,[e.session.sessionId]:n}),Date.now());let i=!1;for(const[u,f]of Object.entries(r))if(f!==t.sessions.byId[u]){i=!0;break}if(!i)return t;const o=_s(t.sessions.pinnedIds,r),{orderById:l,nextOrderOrdinal:c}=Jn(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(r)),d={...t.sessions,byId:r,pinnedIds:o,flat:rt(Object.values(r),t.sessions.collapsedIds,l,o,t.sessions.manualOrder),activeSessionId:t.sessions.activeSessionId,orderById:l,nextOrderOrdinal:c},p=At(t,d);return{...t,sessions:p.sessions,ui:p.ui}}case"sessions/selected":{t={...t,sessions:{...t.sessions,listDeselected:!1}};const s=t.sessions.activeSessionId,n={...t.ui.chatScrollBySession||{}};s&&s!==e.sessionId&&(n[s]=Number(t.ui.scroll?.chat)||0);const r=s!==e.sessionId,i={...t.ui.promptDraftBySession||{}};let o=t.ui.prompt,l=t.ui.promptCursor,c=t.ui.promptAttachments,d=t.ui.promptEdit??null;if(r){if(!!!t.ui.promptEdit&&s){const m={prompt:String(t.ui.prompt||""),attachments:Array.isArray(t.ui.promptAttachments)?t.ui.promptAttachments:[]};m.prompt||m.attachments.length>0?i[s]=m:delete i[s]}const f=e.sessionId?i[e.sessionId]:null;delete i[e.sessionId],o=f?.prompt||"",l=o.length,c=Array.isArray(f?.attachments)?f.attachments:[],d=null}const p=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.sessionId!==e.sessionId);return{...t,sessions:{...t.sessions,activeSessionId:e.sessionId,...p?{navigationIntent:null,filterExceptionId:null}:{}},ui:{...t.ui,chatScrollBySession:n,promptDraftBySession:i,prompt:o,promptCursor:l,promptRows:Jt(o),promptAttachments:c,promptEdit:d,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=hh(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=ks(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:rt(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds,t.sessions.manualOrder)}}}case"sessions/expand":{const s=ks(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:rt(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds,t.sessions.manualOrder)}}}case"sessions/pinToggle":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=t.sessions.byId[s];if(!mc(n))return t;const r=lh(t.sessions.pinnedIds),o=r.indexOf(s)>=0?r.filter(l=>l!==s):[...r,s];return{...t,sessions:{...t.sessions,pinnedIds:o,flat:rt(Object.values(t.sessions.byId),t.sessions.collapsedIds,t.sessions.orderById,o,t.sessions.manualOrder)}}}case"sessions/reorder":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=t.sessions.byId[s];if(!is(n))return t;const r=e.beforeSessionId==null?null:String(e.beforeSessionId).trim()||null;if(r===s)return t;const o=(Array.isArray(t.sessions.manualOrder)&&t.sessions.manualOrder.length>0?t.sessions.manualOrder:(t.sessions.flat||[]).map(p=>p.sessionId).filter(p=>is(t.sessions.byId[p]))).filter(p=>p!==s),l=r?o.indexOf(r):-1,c=l>=0?[...o.slice(0,l),s,...o.slice(l)]:[...o,s];return c.length===(t.sessions.manualOrder||[]).length&&c.every((p,u)=>p===t.sessions.manualOrder[u])?t:{...t,sessions:{...t.sessions,manualOrder:c,flat:rt(Object.values(t.sessions.byId),t.sessions.collapsedIds,t.sessions.orderById,t.sessions.pinnedIds,c)}}}case"sessions/selectMode":{const s=!!e.enabled;return s===!!t.sessions.selectMode&&(s||t.sessions.selectedIds.length===0)?t:{...t,sessions:{...t.sessions,selectMode:s,selectedIds:s?t.sessions.selectedIds:[]}}}case"sessions/selectToggle":{const s=String(e.sessionId||"").trim(),n=s?t.sessions.byId[s]:null;if(!n||n.isSystem||n.isGroup)return t;const r=ch(t.sessions.selectedIds),o=r.indexOf(s)>=0?r.filter(l=>l!==s):[...r,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=_o(s,t.sessions.byId).filter(r=>!t.sessions.byId[r]?.isSystem&&!t.sessions.byId[r]?.isGroup);return{...t,sessions:{...t.sessions,selectedIds:n,selectMode:n.length>0?!0:t.sessions.selectMode}}}case"sessions/listReselect":return t.sessions.listDeselected?{...t,sessions:{...t.sessions,listDeselected:!1}}:t;case"sessions/listDeselect":return{...t,sessions:{...t.sessions,listDeselected:!0,selectedIds:[],selectMode:!1}};case"sessions/selectClear":return t.sessions.selectedIds.length===0&&!t.sessions.selectMode?t:{...t,sessions:{...t.sessions,selectedIds:[],selectMode:!1}};case"history/set":{const s=t.history.bySessionId.get(e.sessionId)||null,n=s?.chat||[],r=Math.max(be,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??be)||be),i=Qn(Xt(e.history?.chat||[]),r),o=n[n.length-1]?.id||null,l=i[i.length-1]?.id||null,c=e.sessionId===t.sessions.activeSessionId&&l!==o,d=$o(t.history.bySessionId);return d.set(e.sessionId,{...e.history||{},chat:i,activity:Qn(e.history?.activity||[],r),events:Qn(e.history?.events||[],r),loadedEventLimit:r}),{...t,history:{...t.history,bySessionId:d},ui:c?{...t.ui,scroll:{...t.ui.scroll,chat:0}}:t.ui}}case"history/evict":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=$o(t.history.bySessionId);for(const l of s)n.delete(l);const r=Fo(t.outbox?.bySessionId);for(const l of s)delete r[l];const i={...t.ui.chatScrollBySession||{}};for(const l of s)delete i[l];const o={...t.ui.promptDraftBySession||{}};for(const l of s)delete o[l];return{...t,history:{...t.history,bySessionId:n},outbox:{...t.outbox,bySessionId:r},ui:{...t.ui,chatScrollBySession:i,promptDraftBySession:o}}}case"outbox/setSessionItems":{const s=e.sessionId;if(!s)return t;const n=Array.isArray(e.items)?e.items.filter(Boolean):[],r=Fo(t.outbox?.bySessionId);return n.length===0?delete r[s]:r[s]=n,{...t,outbox:{...t.outbox,bySessionId:r}}}case"orchestration/statsLoading":{const s=Ls(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=Ls(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=Ls(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=Ls(t.orchestration.bySessionId);for(const r of s)delete n[r];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||[],r=1e3,i=n.length>r?n.slice(-r):n;return s[e.sessionId]={loading:!1,error:null,fetchedAt:e.fetchedAt||Date.now(),events:i},{...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 r of s)delete n[r];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&&!(s&&t.ui.budgetOpen)?t:{...t,ui:s&&t.ui.budgetOpen?{...t.ui,budgetOpen:!1}:t.ui,admin:{...t.admin,visible:s,ghcpKey:s?t.admin.ghcpKey:{editing:!1,draft:"",saving:!1,error:null,lastSavedAt:t.admin.ghcpKey.lastSavedAt},modelProviders:s?t.admin.modelProviders:{...t.admin.modelProviders,create:{...t.admin.modelProviders.create,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null}}}}}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,r=Math.max(0,Math.min(n,s.length));return s===t.admin.ghcpKey.draft&&r===t.admin.ghcpKey.cursorIndex?t:{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,draft:s,cursorIndex:r,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/modelProviders/loading":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,loading:!0,error:null}}};case"admin/modelProviders/loaded":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,loading:!1,error:null,providers:Array.isArray(e.providers)?e.providers:[],models:Array.isArray(e.models)?e.models:[],defaults:e.defaults||null,fetchedAt:Date.now()}}};case"admin/modelProviders/loadFailed":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,loading:!1,error:e.error?String(e.error):"Failed to load model providers"}}};case"admin/modelProviders/mutationPending":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,mutation:{pending:e.pending||"change",error:null}}}};case"admin/modelProviders/mutationDone":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,mutation:{pending:null,error:null}}}};case"admin/modelProviders/mutationFailed":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,mutation:{pending:null,error:e.error?String(e.error):"The provider change failed"}}}};case"admin/modelProviders/select":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,selection:{focus:e.focus==="agents"?"agents":"providers",providerName:e.providerName??t.admin.modelProviders.selection?.providerName??null,agentId:e.agentId??t.admin.modelProviders.selection?.agentId??null}}}};case"admin/modelProviders/page":{const s=e.page==="shared"?"shared":"mine";return s===t.admin.modelProviders.page?t:{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,page:s,selection:{...t.admin.modelProviders.selection,focus:"providers",providerName:null}}}}}case"admin/modelProviders/createBegin":{const s=String(e.name||"");return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,create:{editing:!0,stage:"name",name:"",typeId:String(e.typeId||""),shared:e.shared===!0,draft:s,cursorIndex:s.length,saving:!1,error:null}}}}}case"admin/modelProviders/createDraft":{const s=String(e.draft||"").replace(/\r?\n/gu,""),n=Math.max(0,Math.min(Number(e.cursorIndex)||0,s.length));return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,create:{...t.admin.modelProviders.create,draft:s,cursorIndex:n,error:null}}}}}case"admin/modelProviders/createType":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,create:{...t.admin.modelProviders.create,typeId:String(e.typeId||""),error:null}}}};case"admin/modelProviders/createCredential":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,create:{...t.admin.modelProviders.create,stage:"credential",name:String(e.name||""),draft:"",cursorIndex:0,error:null}}}};case"admin/modelProviders/createSaving":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,create:{...t.admin.modelProviders.create,draft:"",cursorIndex:0,saving:!0,error:null}}}};case"admin/modelProviders/createFailed":{const s=t.admin.modelProviders.create,n=s.stage==="credential";return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,create:{...s,draft:n?"":s.draft,cursorIndex:n?0:s.cursorIndex,saving:!1,error:e.error?String(e.error):"The provider could not be created"}}}}}case"admin/modelProviders/createEnd":return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,create:{editing:!1,stage:"name",name:"",typeId:"",shared:!1,draft:"",cursorIndex:0,saving:!1,error:null}}}};case"admin/section":{const s=["packages","workers","ghcp"].includes(e.section)?e.section:"ghcp";return{...t,admin:{...t.admin,section:s}}}case"admin/workers/attempt":{const s=t.admin.workers||{};return{...t,admin:{...t.admin,workers:{...s,attempts:(s.attempts||0)+1,lastAttemptAt:Date.now(),lastSkip:e.skip||null}}}}case"admin/workers/loading":return{...t,admin:{...t.admin,workers:{...t.admin.workers,loading:!0,error:null}}};case"admin/workers/loaded":return{...t,admin:{...t.admin,workers:{loading:!1,error:null,list:Array.isArray(e.list)?e.list:[],fetchedAt:Date.now()}}};case"admin/workers/loadFailed":return{...t,admin:{...t.admin,workers:{...t.admin.workers,loading:!1,error:e.error||"Failed to load workers"}}};case"admin/packages/loading":return{...t,admin:{...t.admin,packages:{...t.admin.packages,loading:!0,error:null}}};case"admin/packages/loaded":{const s=t.admin.packages,n=Array.isArray(e.list)?e.list:[],r=s.selectedName&&n.some(i=>i.name===s.selectedName);return{...t,admin:{...t.admin,packages:{...s,loading:!1,error:null,list:n,workerState:Array.isArray(e.workerState)?e.workerState:[],fetchedAt:Date.now(),selectedName:r?s.selectedName:null,selectedSelector:r?s.selectedSelector??null:null,...r?{}:{detail:null,workspace:{...s.workspace,tree:null,selectedPath:null,file:null}}}}}}case"admin/packages/loadFailed":return{...t,admin:{...t.admin,packages:{...t.admin.packages,loading:!1,error:e.error||"Failed to load agent packages"}}};case"admin/packages/select":return{...t,admin:{...t.admin,section:"packages",packages:{...t.admin.packages,selectedName:e.name||null,selectedSelector:e.selector||null,selectionSeq:(t.admin.packages.selectionSeq??0)+1,detail:null,detailLoading:!!e.name,detailError:null,changelog:null,action:{pending:null,error:null},workspace:{tree:null,treeLoading:!!e.name,treeError:null,expandedDirs:[],selectedPath:null,file:null,fileLoading:!1,fileError:null}}}};case"admin/packages/detail/loaded":return gs(t.admin.packages,e)?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,detail:e.detail,detailLoading:!1,detailError:null}}};case"admin/packages/detail/loadFailed":return gs(t.admin.packages,e)?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,detail:null,detailLoading:!1,detailError:e.error||"Failed to load package"}}};case"admin/packages/changelog/loaded":return gs(t.admin.packages,e)?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,changelog:e.content||null}}};case"admin/packages/tree/loaded":{if(gs(t.admin.packages,e))return t;const s=Array.isArray(e.tree?.dirs)?e.tree.dirs.filter(n=>!n.includes("/")):[];return{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,tree:e.tree,treeLoading:!1,treeError:null,expandedDirs:s}}}}}case"admin/packages/tree/loadFailed":return gs(t.admin.packages,e)?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,treeLoading:!1,treeError:e.error||"Failed to load package files"}}}};case"admin/packages/toggleDir":{const s=t.admin.packages.workspace,n=new Set(s.expandedDirs);return n.has(e.dir)?n.delete(e.dir):n.add(e.dir),{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...s,expandedDirs:[...n]}}}}}case"admin/packages/file/loading":return{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,selectedPath:e.path,file:null,fileLoading:!0,fileError:null}}}};case"admin/packages/file/loaded":return t.admin.packages.workspace.selectedPath!==e.file?.path||typeof e.seq=="number"&&(t.admin.packages.selectionSeq??0)!==e.seq?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,file:e.file,fileLoading:!1,fileError:null}}}};case"admin/packages/file/loadFailed":return t.admin.packages.workspace.selectedPath!==e.path||typeof e.seq=="number"&&(t.admin.packages.selectionSeq??0)!==e.seq?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,fileLoading:!1,fileError:e.error||"Failed to load file"}}}};case"admin/packages/action/pending":return{...t,admin:{...t.admin,packages:{...t.admin.packages,action:{pending:e.action,error:null}}}};case"admin/packages/action/done":return{...t,admin:{...t.admin,packages:{...t.admin.packages,action:{pending:null,error:null}}}};case"admin/packages/action/failed":return{...t,admin:{...t.admin,packages:{...t.admin.packages,action:{pending:null,error:e.error||"Action failed"}}}};case"admin/packages/addDialog/open":{const s={...vr().admin.packages.addDialog,open:!0,updateName:e.updateName||null,scope:e.scope==="shared"?"shared":"user"};return{...t,admin:{...t.admin,section:"packages",packages:{...t.admin.packages,addDialog:s}}}}case"admin/packages/addDialog/close":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...vr().admin.packages.addDialog,open:!1}}}};case"admin/packages/addDialog/setField":{const s=t.admin.packages.addDialog;return e.field in s?{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...s,[e.field]:e.value,error:null}}}}:t}case"admin/packages/addDialog/submitting":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,submitting:!0,progress:null,error:null}}}};case"admin/packages/addDialog/progress":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,progress:e.message||null}}}};case"admin/packages/addDialog/failed":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,submitting:!1,progress:null,error:e.error||"Failed to import package"}}}};case"admin/systemGhcpKey/saved":{const s=e.status||{};return{...t,admin:{...t.admin,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:Date.now(),storeAsSystem:!!t.admin.ghcpKey.storeAsSystem},systemGhcpKey:{supported:!0,loading:!1,configured:!!s.configured,changedBy:s.changedBy||null,changedAt:s.changedAt||null,error:null}}}}case"files/evictPreviews":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=dt(t.files.bySessionId);for(const r of s)n[r]&&(n[r]={...n[r],previews:{}});return{...t,files:{...t.files,bySessionId:n}}}case"files/sessionLoading":{const s=dt(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=dt(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},r=rn(e.entries),i=Number(e.fetchedAt)||0,o=c=>r.some(d=>d.filename===c),l=n.selectedFilename&&o(n.selectedFilename)?n.selectedFilename:e.selectedFilename&&o(e.selectedFilename)?e.selectedFilename:r[0]?.filename||null;return s[e.sessionId]={...n,entries:r,selectedFilename:l,loading:!1,loaded:!0,fetchedAt:i,error:null},{...t,files:{...t.files,bySessionId:s}}}case"files/sessionError":{const s=dt(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=dt(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/pane":return{...t,files:{...t.files,paneOpen:!!e.open,paneRestoresToHidden:e.open?t.files.paneOpen?t.files.paneRestoresToHidden:!!e.restoresToHidden:!1}};case"ui/rightPaneMode":{const s=e.mode==="canvas"?"canvas":"panes",n=e.sessionId||t.sessions.activeSessionId||null;let r=t.canvas.prefs;if(n){const i=r[n]||{optedOut:!1,lastViewedRev:0};s==="canvas"&&i.optedOut?r={...r,[n]:{...i,optedOut:!1}}:s==="panes"&&e.manual&&!i.optedOut&&(r={...r,[n]:{...i,optedOut:!0}})}return{...t,ui:{...t.ui,rightPaneMode:s,canvasOpen:s==="canvas"},canvas:{...t.canvas,prefs:r}}}case"ui/canvasOpen":{const s=typeof e.open=="boolean"?e.open:!t.ui.canvasOpen,n=e.sessionId||t.sessions.activeSessionId||null;let r=t.canvas.prefs;if(n){const i=r[n]||{optedOut:!1,lastViewedRev:0};s&&i.optedOut?r={...r,[n]:{...i,optedOut:!1}}:!s&&e.manual&&!i.optedOut&&(r={...r,[n]:{...i,optedOut:!0}})}return{...t,ui:{...t.ui,canvasOpen:s,rightPaneMode:s?"canvas":"panes",...s?{}:{canvasMaximized:!1,canvasZen:!1}},canvas:{...t.canvas,prefs:r}}}case"ui/canvasZen":{const s=typeof e.on=="boolean"?e.on:!t.ui.canvasZen;return s===!!t.ui.canvasZen?t:{...t,ui:{...t.ui,canvasZen:s,...s?{canvasOpen:!0,rightPaneMode:"canvas"}:{}}}}case"canvas/zenRail":{const s=String(e.sessionId||"").trim(),n=Number(e.px);if(!s||!Number.isFinite(n))return t;const r=t.canvas.prefs[s]||{optedOut:!1,lastViewedRev:0},i=Math.max(260,Math.min(720,Math.round(n)));return{...t,canvas:{...t.canvas,prefs:{...t.canvas.prefs,[s]:{...r,zenRailPx:i}}}}}case"ui/canvasMaximized":{const s=typeof e.on=="boolean"?e.on:!t.ui.canvasMaximized;return s===!!t.ui.canvasMaximized?t:{...t,ui:{...t.ui,canvasMaximized:s}}}case"ui/diagnosticsOpen":{const s=typeof e.open=="boolean"?e.open:!t.ui.diagnosticsOpen;return s===t.ui.diagnosticsOpen?t:{...t,ui:{...t.ui,diagnosticsOpen:s}}}case"ui/budgetOpen":{const s=typeof e.open=="boolean"?e.open:!t.ui.budgetOpen,n=e.provider===void 0?void 0:bt(e.provider),r=s&&n!==void 0?{...t.budget,selectedProvider:n}:t.budget,i=s&&t.admin.visible;return s===t.ui.budgetOpen&&r===t.budget&&!i?t:{...t,ui:{...t.ui,budgetOpen:s},admin:i?{...t.admin,visible:!1}:t.admin,budget:r}}case"budget/loading":{const s=e.refresh===!0||t.budget.loaded===!0;return{...t,budget:{...t.budget,loading:!s,refreshing:s,error:null}}}case"budget/loaded":{const s=t.budget,n=Array.isArray(e.grid),r=n?e.grid:s.grid,i=n&&s.selectedProvider&&!e.grid.some(u=>u?.providerName===s.selectedProvider),o=i?null:s.selectedProvider,l=s.selectedScope||"*",c=n&&!i&&l!=="*"&&!e.grid.some(u=>u?.providerName===s.selectedProvider&&u?.rowKind==="model"&&u?.scope===l),d=i||c?"*":l,p=i?s.selectedProvider:n?null:s.missingProvider||null;return{...t,budget:{...s,loading:!1,refreshing:!1,loaded:n?!0:s.loaded,error:n?null:s.error,fetchedAt:n?Date.now():s.fetchedAt,grid:r,paused:Array.isArray(e.paused)?e.paused:s.paused,pausedError:Array.isArray(e.paused)?null:s.pausedError||null,selectedProvider:o,selectedScope:d,missingProvider:p,series:o===s.selectedProvider&&d===l?s.series:{provider:null,scope:"*",rangeDays:s.rangeDays??Ee,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:o===s.selectedProvider&&d===l?s.systemUsage:{provider:null,scope:"*",rangeDays:s.rangeDays??Ee,totals:null,days:[],breakdown:[],loading:!1,loaded:!1,error:null,fetchedAt:0}}}}case"budget/pausedFailed":{const s=e.error?String(e.error?.message||e.error):"";return{...t,budget:{...t.budget,loading:!1,refreshing:!1,pausedError:s||"Could not read what is waiting"}}}case"budget/loadFailed":{const s=e.error?String(e.error?.message||e.error):"";return{...t,budget:{...t.budget,loading:!1,refreshing:!1,error:s||"Could not read providers and budgets"}}}case"budget/overall":{const s=typeof e.overall=="boolean"?e.overall:!t.budget.overall;return s===t.budget.overall?t:{...t,budget:{...t.budget,overall:s}}}case"budget/rangeDays":{const s=Number(e.rangeDays);return!an.includes(s)||s===t.budget.rangeDays?t:{...t,budget:{...t.budget,rangeDays:s,series:{provider:null,scope:"*",rangeDays:s,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:{provider:null,scope:"*",rangeDays:s,totals:null,days:[],breakdown:[],loading:!1,loaded:!1,error:null,fetchedAt:0}}}}case"budget/selectProvider":{const s=bt(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=t.budget.selectedProvider,i=t.budget.selectedScope||"*";let o=s,l=n;return s===r&&n===i&&(n==="*"&&(o=null),l="*"),o===r&&l===i?t:{...t,budget:{...t.budget,selectedProvider:o,selectedScope:l,missingProvider:null,series:{provider:null,scope:"*",rangeDays:t.budget.rangeDays??Ee,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:{provider:null,scope:"*",rangeDays:t.budget.rangeDays??Ee,totals:null,days:[],breakdown:[],loading:!1,loaded:!1,error:null,fetchedAt:0}}}}case"budget/series/loading":{const s=bt(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=Number(e.rangeDays)||t.budget.rangeDays||Ee;return{...t,budget:{...t.budget,series:{...t.budget.series,provider:s,scope:n,rangeDays:r,loading:!0,error:null}}}}case"budget/series/loaded":{const s=bt(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=e.rangeDays===void 0?t.budget.rangeDays||Ee:Number(e.rangeDays);return s!==t.budget.selectedProvider||n!==(t.budget.selectedScope||"*")||r!==(t.budget.rangeDays||Ee)?t:{...t,budget:{...t.budget,series:{provider:s,scope:n,rangeDays:r,days:Array.isArray(e.days)?e.days:[],loading:!1,loaded:!0,error:null,fetchedAt:Date.now()}}}}case"budget/series/failed":{const s=bt(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=e.rangeDays===void 0?t.budget.rangeDays||Ee:Number(e.rangeDays);if(s!==t.budget.selectedProvider||n!==(t.budget.selectedScope||"*")||r!==(t.budget.rangeDays||Ee))return t;const i=e.error?String(e.error?.message||e.error):"";return{...t,budget:{...t.budget,series:{...t.budget.series,provider:s,scope:n,rangeDays:r,loading:!1,error:i||"Could not read the daily usage"}}}}case"budget/systemUsage/loading":{const s=bt(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=Number(e.rangeDays)||t.budget.rangeDays||Ee;return{...t,budget:{...t.budget,systemUsage:{...t.budget.systemUsage,provider:s,scope:n,rangeDays:r,loading:!0,error:null}}}}case"budget/systemUsage/loaded":{const s=bt(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=e.rangeDays===void 0?t.budget.rangeDays||Ee:Number(e.rangeDays);if(s!==t.budget.selectedProvider||n!==(t.budget.selectedScope||"*")||r!==(t.budget.rangeDays||Ee))return t;const i=e.report||{};return{...t,budget:{...t.budget,systemUsage:{provider:s,scope:n,rangeDays:r,totals:i.totals||{tokensTotal:0,turns:0,sessions:0},days:Array.isArray(i.daily)?i.daily:[],breakdown:Array.isArray(i.breakdown)?i.breakdown:[],loading:!1,loaded:!0,error:null,fetchedAt:Date.now()}}}}case"budget/systemUsage/failed":{const s=bt(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=e.rangeDays===void 0?t.budget.rangeDays||Ee:Number(e.rangeDays);if(s!==t.budget.selectedProvider||n!==(t.budget.selectedScope||"*")||r!==(t.budget.rangeDays||Ee))return t;const i=e.error?String(e.error?.message||e.error):"";return{...t,budget:{...t.budget,systemUsage:{...t.budget.systemUsage,provider:s,scope:n,rangeDays:r,loading:!1,error:i||"Could not read system spend"}}}}case"canvas/flip":{const s=Number.isInteger(Number(e.slot))&&Number(e.slot)>=1&&Number(e.slot)<=5?Number(e.slot):1;return{...t,ui:{...t.ui,rightPaneMode:"canvas",canvasOpen:!0,canvasSlot:s},canvas:{...t.canvas,flipSeq:(t.canvas.flipSeq||0)+1}}}case"ui/canvasSlot":{const s=Number.isInteger(Number(e.slot))&&Number(e.slot)>=1&&Number(e.slot)<=5?Number(e.slot):1;return s===(t.ui.canvasSlot||1)?t:{...t,ui:{...t.ui,canvasSlot:s}}}case"canvas/viewed":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=Number(e.rev),r=Number(e.dataRev),i=Qe(s,e.slot),o=t.canvas.prefs[i]||{optedOut:!1,lastViewedRev:0,lastViewedDataRev:0},l=Number.isFinite(n)&&n>(o.lastViewedRev||0)?n:o.lastViewedRev||0,c=Number.isFinite(r)&&r>(o.lastViewedDataRev||0)?r:o.lastViewedDataRev||0;return l===(o.lastViewedRev||0)&&c===(o.lastViewedDataRev||0)?t:{...t,canvas:{...t.canvas,prefs:{...t.canvas.prefs,[i]:{...o,lastViewedRev:l,lastViewedDataRev:c}}}}}case"canvas/seed":{const s=Array.isArray(e.entries)?e.entries:[];if(!s.length)return t;let n=null;for(const r of s){const i=String(r?.sessionId||"").trim(),o=Number(r?.latestRev),l=Number(r?.slot);if(!i||!Number.isFinite(o)||o<=0||!Number.isInteger(l)||l<1||l>5)continue;const c=Qe(i,l),d=(n||t.canvas.bySessionId)[c]||{};(d.latestRev||0)>=o&&d.name!==void 0||(n=n||{...t.canvas.bySessionId},n[c]={...d,slot:l,latestRev:Math.max(d.latestRev||0,o),...typeof r.name=="string"&&d.name===void 0?{name:r.name}:{},...d.sizeBytes===void 0&&r.sizeBytes!==void 0?{sizeBytes:r.sizeBytes}:{}})}return n?{...t,canvas:{...t.canvas,bySessionId:n}}:t}case"canvas/updated":{const s=String(e.sessionId||"").trim(),n=Number(e.rev);if(!s||!Number.isFinite(n)||n<=0)return t;const r=Number.isInteger(Number(e.slot))&&Number(e.slot)>=1&&Number(e.slot)<=5?Number(e.slot):1,i=Qe(s,r),o=t.canvas.bySessionId[i]||{};return(o.latestRev||0)>=n?t:{...t,canvas:{...t.canvas,bySessionId:{...t.canvas.bySessionId,[i]:{...o,slot:r,...typeof e.name=="string"?{name:e.name}:{},latestRev:n,note:typeof e.note=="string"?e.note:"",sizeBytes:Number.isFinite(Number(e.sizeBytes))?Number(e.sizeBytes):null,responseContract:e.responseContract&&typeof e.responseContract=="object"?e.responseContract:null}}}}}case"canvas/data":{const s=String(e.sessionId||"").trim(),n=Number.isInteger(Number(e.slot))&&Number(e.slot)>=1&&Number(e.slot)<=5?Number(e.slot):1,r=Qe(s,n),i=Number(e.dataRev);if(!s||!Number.isFinite(i)||i<=0)return t;const o=t.canvas.bySessionId[r]||{},l=Number(e.planeSeq),c=Number.isFinite(l)&&l>0;if(c){if((o.planeSeq||0)>=l)return t}else if(o.planeSeq||(o.latestDataRev||0)>=i)return t;return{...t,canvas:{...t.canvas,bySessionId:{...t.canvas.bySessionId,[r]:{...o,latestDataRev:Math.max(i,o.latestDataRev||0),...c?{planeSeq:l}:{},dataPayload:e.payload&&typeof e.payload=="object"?e.payload:null,dataPatch:c&&e.patch&&typeof e.patch=="object"?e.patch:null}}}}}case"canvas/planeReleased":{const s=String(e.sessionId||"").trim();if(!s)return t;let n=!1;const r={...t.canvas.bySessionId};for(let i=1;i<=5;i++){const o=Qe(s,i),l=r[o];if(l&&l.planeSeq){const{planeSeq:c,...d}=l;r[o]=d,n=!0}}return n?{...t,canvas:{...t.canvas,bySessionId:r}}:t}case"canvas/snapshot":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=Number.isInteger(Number(e.slot))&&Number(e.slot)>=1&&Number(e.slot)<=5?Number(e.slot):1,r=Qe(s,n),i=t.canvas.bySessionId[r]||{},o=Number(e.rev)||0;return{...t,canvas:{...t.canvas,bySessionId:{...t.canvas.bySessionId,[r]:{...i,slot:n,...typeof e.name=="string"&&(i.latestRev||0)<=o?{name:e.name}:{},latestRev:Math.max(i.latestRev||0,o),note:(i.latestRev||0)>o?i.note:typeof e.note=="string"?e.note:i.note||"",sizeBytes:(i.latestRev||0)>o?i.sizeBytes:Number.isFinite(Number(e.sizeBytes))?Number(e.sizeBytes):i.sizeBytes??null,responseContract:(i.latestRev||0)>o?i.responseContract??null:e.responseContract&&typeof e.responseContract=="object"?e.responseContract:null,snapshotLoaded:!0}}}}}case"canvas/snapshotInvalidate":{const s=String(e.sessionId||"").trim(),n=t.canvas.bySessionId[s];return!s||!n?.snapshotLoaded?t:{...t,canvas:{...t.canvas,bySessionId:{...t.canvas.bySessionId,[s]:{...n,snapshotLoaded:!1}}}}}case"files/htmlViewMode":return{...t,files:{...t.files,htmlViewMode:e.mode==="source"?"source":"rendered"}};case"files/htmlFitWidth":return{...t,files:{...t.files,htmlFitWidth:!!e.enabled}};case"files/htmlZoom":{const s=Number(e.zoom),n=Number.isFinite(s)?Math.min(3,Math.max(.5,Math.round(s*100)/100)):1;return{...t,files:{...t.files,htmlZoom:n}}}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=dt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},r={...n.previews||{},[e.filename]:{...n.previews?.[e.filename]||{},loading:!0,error:null}};return s[e.sessionId]={...n,previews:r},{...t,files:{...t.files,bySessionId:s}}}case"files/previewLoaded":{const s=dt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},r={...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:r},{...t,files:{...t.files,bySessionId:s}}}case"files/previewError":{const s=dt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},r={...n.previews||{},[e.filename]:{...n.previews?.[e.filename]||{},loading:!1,error:e.error||"Failed to load file preview"}};return s[e.sessionId]={...n,previews:r},{...t,files:{...t.files,bySessionId:s}}}case"files/downloaded":{const s=dt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},r={...n.downloads||{},[e.filename]:{localPath:e.localPath||null,downloadedAt:e.downloadedAt||Date.now()}};return s[e.sessionId]={...n,downloads:r},{...t,files:{...t.files,bySessionId:s}}}case"files/deleted":{t={...t,files:{...t.files,markedIds:(t.files.markedIds||[]).filter(u=>u!==`${e.sessionId}/${e.filename}`)}};const s=dt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},r=rn(n.entries).filter(u=>u.filename!==e.filename),i=n.selectedFilename===e.filename?r[0]?.filename||null:n.selectedFilename,{[e.filename]:o,...l}=n.previews||{},{[e.filename]:c,...d}=n.downloads||{},p=e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:null;return s[e.sessionId]={...n,entries:r,previews:l,downloads:d,selectedFilename:i},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:t.files.selectedArtifactId===p?i?`${e.sessionId}/${i}`:null:t.files.selectedArtifactId},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}}}case"files/fullscreen":return{...t,files:{...t.files,fullscreen:!!e.fullscreen},ui:e.fullscreen?{...t.ui,focusRegion:"inspector",fullscreenPane:null}:t.ui};case"files/filter":return{...t,files:{...t.files,filter:{...Xn(t.files.filter),...Xn(e.filter)},...Xn(e.filter).scope==="selectedSession"?{}:{selectedArtifactId:t.files.selectedArtifactId||null}},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}};case"logs/config":return{...t,logs:{...t.logs,available:!!e.available,availabilityReason:e.availabilityReason||t.logs.availabilityReason}};case"logs/tailing":return{...t,logs:{...t.logs,tailing:!!e.tailing}};case"logs/filter":return{...t,logs:{...t.logs,filter:{...t.logs.filter,...e.filter||{}}}};case"logs/set":return{...t,logs:{...t.logs,entries:mh(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],r=n.length>1e3?n.slice(-1e3):n;return{...t,logs:{...t.logs,entries:r}}}default:return t}}function Si(t,e){const s=Array.isArray(e)?e.filter(r=>r?.origin&&r?.label):[];if(s.length<2)return[{label:null,url:String(t||"")}];let n;try{const r=new URL(String(t||""));n=`${r.pathname}${r.search}${r.hash}`}catch{return[{label:null,url:String(t||"")}]}return s.map(r=>({label:String(r.label),url:`${r.origin}${n}`}))}function gc(t){const e=Array.isArray(t)?t:[];return e.length<=1?String(e[0]?.url||""):e.map(s=>`${s.label}: ${s.url}`).join(`
|
|
65
|
-
`)}function Nh(t,e){let s=e;const n=new Set;return{getState(){return s},dispatch(r){const i=t(s,r);if(Object.is(i,s))return r;s=i;for(const o of n)o(s,r);return r},subscribe(r){return n.add(r),()=>n.delete(r)}}}function Th(t){return t?{...t.scope==="shared"||t.scope==="user"?{scope:t.scope}:{},...t.scope==="user"&&t.owner?.provider&&t.owner?.subject?{owner:{provider:t.owner.provider,subject:t.owner.subject}}:{}}:null}const Ph=2e4,Mh=2e4,Rh=3e4,$h=30,qo="Session refresh failed",_h=3,Lh=200,Oh=5,Fh=new Set([$.SESSIONS,$.CHAT,$.INSPECTOR,$.ACTIVITY]);function Dh(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 er(t){return!t?.sessionId||t.isGroup?t:{...t,groupId:t.viewerGroupId??null,parentSessionId:t.parentSessionId??null}}function Ws(t){return String(t||"").startsWith("group:")?String(t).slice(6):null}function ys(t){return Ws(t)!==null}function Bh(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 tr(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 bs(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||s==="NOT_FOUND"}async function Hh(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<Oh;n+=1){const r=await t.listSessionsPage({limit:Lh,cursor:s}),i=Array.isArray(r?.sessions)?r.sessions:[];if(e.push(...i),!r?.hasMore||!r?.nextCursor)break;s=r.nextCursor}return e}function Uh(t=[]){const e=[],s=new Map;for(const n of t){const r=n?.providerId||"models";let i=s.get(r);i||(i={providerId:r,providerType:n?.providerType||"provider",models:[]},s.set(r,i),e.push(i)),i.models.push(n)}return e}function Ko(t,e){let s=t.findIndex(n=>n.qualifiedName===e&&!n.disabled);return s<0&&(s=t.findIndex(n=>!n.disabled)),s<0?0:s}function qs(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 Vo(t){const e=qs(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 Ks(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 jh(t){const e=Ks(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 yc={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function Gh(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 zh(t,e){const s=Gh(e);return s?t==="long_context"?`Long context (${s} tokens, higher cost)`:`Default (${s} tokens)`:yc[t]||t}function Cr(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 r=typeof n.newModel=="string"&&n.newModel?n.newModel:typeof n.model=="string"&&n.model?n.model:void 0;if(r)return{model:r,...typeof n.newReasoningEffort=="string"||n.newReasoningEffort===null?{reasoningEffort:n.newReasoningEffort}:{}}}}function Wh(t){return Cr([t])}function Yo(t,e=[]){let s=Va(t);for(const n of e){const r=Ya(s,n?.eventType,n?.data,{timestamp:n?.createdAt});r&&(s=r)}return s}function fn(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 r=0;r<t.length;r+=1)if(!fn(t[r],e[r]))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 r of s)if(!Object.prototype.hasOwnProperty.call(e,r)||!fn(t[r],e[r]))return!1;return!0}function Xo(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 vi(t,e){const s=Xo(t?.updatedAt),n=Xo(e?.updatedAt);return s>0&&n>0&&n<=s}function qh(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function Kh(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&qh(e?.status)&&vi(t,e)}function Vh(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!Sc(e?.status)&&!bc(e?.orchestrationStatus)&&vi(t,e)}function Yh(t,e){if(!e?.sessionId)return null;const s={sessionId:e.sessionId};let n=!1;for(const[l,c]of Object.entries(e))l==="sessionId"||c===void 0||fn(t?.[l],c)||(s[l]=c,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&!vi(t,e)&&(s.pendingQuestion=null,n=!0),Kh(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),wp(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),Vh(t,e))for(const l of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[l]!=null&&(fn(s[l],t[l])||(s[l]=t[l],n=!0));else if(e.cronActive!==!0){t?.cronReason&&(s.cronReason=null,n=!0);for(const l of["cronKind","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[l]!=null&&e[l]===void 0&&(s[l]=null,n=!0);t?.cronInterval!=null&&e.cronInterval===void 0&&(s.cronInterval=null,n=!0)}if((Sc(e.status)||bc(e.orchestrationStatus))&&t?.contextUsage?.compaction?.state==="running"&&e.contextUsage===void 0){const l={...t.contextUsage};delete l.compaction,s.contextUsage=Object.keys(l).length>0?l:null,n=!0}return n?s:null}function Qo(t){return String(t||"").replace(/\r\n/g,`
|
|
66
|
-
`).trim()}function bc(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function Sc(t){return t==="completed"||t==="failed"||t==="cancelled"}function Oe(t){return String(t||"").slice(0,8)}function mn(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function Os(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Xh=mn({provider:"system",subject:"system"});function Zo(t){const e=t.auth?.principal||null,s=mn(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 i=Os(e,"current user");n.push({id:"me",kind:"me",label:`Me (${i})`,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 r=new Map;for(const i of Object.values(t.sessions?.byId||{})){const o=i?.owner,l=mn(o);!l||l===s||l===Xh||r.has(l)||r.set(l,o)}for(const[i,o]of[...r.entries()].sort((l,c)=>Os(l[1]).localeCompare(Os(c[1])))){const l=Os(o),c=String(o?.email||"").trim();n.push({id:`owner:${i}`,kind:"owner",ownerKey:i,label:c&&c!==l?`${l} <${c}>`:l,description:"Show sessions owned by this user."})}return n}function hn(t){return mn(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,includeShared:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function Qh(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||t?.includeShared||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function Zh(t,e,s){const n=t||hn(s);if(!e)return n;if(e.kind==="all")return n.all?hn(s):{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]};const r={...n,all:!1,ownerKeys:Array.isArray(n.ownerKeys)?[...n.ownerKeys]:[]};if(e.kind==="system"&&(r.includeSystem=!r.includeSystem),e.kind==="unowned"&&(r.includeUnowned=!r.includeUnowned),e.kind==="me"&&(r.includeMe=!r.includeMe),e.kind==="shared"&&(r.includeShared=!r.includeShared),e.kind==="owner"&&e.ownerKey){const i=r.ownerKeys.indexOf(e.ownerKey);i>=0?r.ownerKeys.splice(i,1):r.ownerKeys.push(e.ownerKey)}return Qh(r)?r:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function wi(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}function Jh(t){const e=wi(t);return e?Math.max(1,60-`${e}: `.length):60}function eg(t){const e=String(t?.title||"").trim();if(!e)return"";const s=wi(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===Oe(t?.sessionId)?"":n}return e===Oe(t?.sessionId)?"":e}function Jo(t,e){const s=String(e||"").trim();if(s)return s;const n=String(t||"").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):"Agent"}const xs="builtin",vc="installed:shared",wc="installed:mine";function Ec(t){const e=String(t?.packageScope||t?.scope||"shared"),s=String(t?.ownerLabel||"");return`pkg:${e}:${s}:${String(t?.packageName||"")}`}function Fs(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/g,"")}function ea(t){const e=new Map;for(const p of t)p?.agentName&&e.set(Fs(p.agentName),p);const s=new Map,n=new Map;for(const p of t){const u=Fs(p.agentName),f=(p.startedBy||[]).map(h=>Fs(h)).filter(h=>h&&e.has(h)&&h!==u);if(f.length===0)continue;const m=f[0];n.set(p,m),s.has(m)||s.set(m,[]),s.get(m).push(p)}const r=p=>n.has(p),i=p=>typeof p.supportsDirectStart=="boolean"?p.supportsDirectStart:!r(p),o=[],l=new Set,c=(p,u,f)=>{if(!l.has(p)){l.add(p),o.push({...p,depth:u,parentAgentName:f||null,supportsDirectStart:i(p)});for(const m of s.get(Fs(p.agentName))||[])c(m,u+1,p.agentName)}};for(const p of t)r(p)||c(p,0,null);const d=p=>{const u=new Set;let f=p;for(;f&&!u.has(f);)if(u.add(f),f=e.get(n.get(f)),f===p)return!0;return!1};for(const p of t)!l.has(p)&&d(p)&&c(p,0,null);for(const p of t)c(p,0,null);return o}function tg(t=[]){const e=t.findIndex(n=>n.kind!=="section");if(e>=0)return e;const s=t.findIndex(n=>n.kind==="section"&&n.collapsed);return s>=0?s:0}function ta(t=[],e=[],s=null){const n=new Set(e),r=[],i=t.filter(l=>l.builtin),o=t.filter(l=>!l.builtin);if(s&&r.push({...s,depth:0}),i.length>0){const l=ea(i);r.push({id:`section:${xs}`,kind:"section",sectionKind:"builtin",sectionKey:xs,title:"Built-in",meta:`${l.length} agent${l.length===1?"":"s"}`,collapsed:n.has(xs),depth:0}),n.has(xs)||r.push(...l.map(c=>({...c,depth:c.depth+1})))}for(const[l,c,d]of[[vc,"Installed · Shared",p=>p.group!=="mine"],[wc,"Installed · Yours",p=>p.group==="mine"]]){const p=o.filter(d);if(p.length===0)continue;const u=new Map;for(const m of p){const h=Ec(m);u.has(h)||u.set(h,[]),u.get(h).push(m)}if(r.push({id:`section:${l}`,kind:"section",sectionKind:"installed",sectionKey:l,title:c,meta:`${u.size} package${u.size===1?"":"s"}`,collapsed:n.has(l),depth:0}),n.has(l))continue;const f=[...u.keys()].sort((m,h)=>{const g=u.get(m)[0],b=u.get(h)[0];return String(g.packageTitle||g.packageName||"").localeCompare(String(b.packageTitle||b.packageName||""))});for(const m of f){const h=ea(u.get(m)),g=h[0]||{},b=h.filter(y=>y.depth===0).length;r.push({id:`section:${m}`,kind:"section",sectionKind:"package",sectionKey:m,title:g.packageTitle||g.packageName||"Package",packageName:g.packageName||null,packageSemver:g.packageSemver||null,packageScope:g.packageScope||null,ownerLabel:g.ownerLabel||null,mine:g.group==="mine",meta:`${b} ${b===1?"entry":"entries"} · ${h.length} agent${h.length===1?"":"s"}`,collapsed:n.has(m),depth:1}),!n.has(m)&&r.push(...h.map(y=>({...y,depth:y.depth+2})))}}return r}function sa(t){return`📎 ${String(t||"").trim()}`}function na(t,e){const s=String(t||""),n=ke(s,e,s.length),i=s.slice(0,n).match(/(^|\s)(@@?)([^\s]*)$/u);if(!i)return null;const o=i[2],l=String(i[3]||"");return{kind:o==="@@"?"sessions":"artifacts",query:l,signature:`${o}${l}`,tokenStart:(i.index||0)+String(i[1]||"").length,tokenEnd:n}}function sg(t,e,s,n){const r=String(t||""),i=ke(r,e),o=ke(r,s),l=String(n||"");return{prompt:`${r.slice(0,i)}${l}${r.slice(o)}`,cursor:i+l.length}}function ng(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function rg(t){const e=String(t?.sessionId||"").trim(),s=Oe(e)||"session";return`Referenced session: ${ng(t?.title,s)} — session://${e}`}function ra(t,e,s){if(!e)return mt(t,String(t||"").length,s);const n=String(t||""),r=n.slice(e.tokenEnd,e.tokenEnd+1),i=!r||/\s/u.test(r);return sg(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${i?" ":""}`)}function ig(t,e=[]){let s=String(t||"");for(const n of e||[]){const r=String(n?.token||"").trim();r&&(s=s.split(r).join(" "))}return s.replace(/[ \t]+\n/g,`
|
|
67
|
-
`).replace(/\n[ \t]+/g,`
|
|
68
|
-
`).replace(/[ \t]{2,}/g," ").trim()}const ia=new Set(["image/png","image/jpeg","image/gif","image/webp"]),oa=4*1024*1024,sr=4;function og(t,e=[]){const s=Array.isArray(e)?e.filter(i=>i?.sessionId&&i?.filename&&i?.kind!=="image"):[];if(s.length===0)return String(t||"");const n=s.map(i=>`[Attached file: ${i.filename} — artifact://${i.sessionId}/${i.filename}]`),r=ig(t,s);return n.join(`
|
|
69
|
-
`)+(r?`
|
|
70
|
-
|
|
71
|
-
${r}`:"")}function Ut(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function kc(t){return Array.from(String(t||"")).length}function ag(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=Xa(s.value||"");for(const r of n)e.push(r);continue}if(Array.isArray(s)){e.push(s);continue}e.push(s)}return e}function lg(t,e){const s=Math.max(1,Number(e)||1),n=kc(t);return Math.max(1,Math.ceil(n/s))}function jt(t,e){const s=Math.max(1,Number(e)||1);return ag(t).reduce((n,r)=>{if(!r)return n+1;if(Array.isArray(r)){const i=r.reduce((o,l)=>o+kc(l?.text||""),0);return n+Math.max(1,Math.ceil(i/s))}return n+lg(r.text||"",s)},0)}function ke(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function xc(t){return String(t||"").split(`
|
|
72
|
-
`)}function cg(t,e){const n=String(t||"").slice(0,ke(t,e)).split(`
|
|
73
|
-
`),r=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:r.length}}function dg(t,e,s){const n=xc(t),r=Math.max(0,Math.min(Number(e)||0,Math.max(0,n.length-1))),i=Math.max(0,Math.min(Number(s)||0,n[r]?.length||0));let o=0;for(let l=0;l<r;l+=1)o+=(n[l]?.length||0)+1;return ke(t,o+i)}function mt(t,e,s){const n=String(t||""),r=ke(n,e),i=String(s||"");return{prompt:`${n.slice(0,r)}${i}${n.slice(r)}`,cursor:r+i.length}}function Ct(t,e){const s=String(t||""),n=ke(s,e);return n<=0?{prompt:s,cursor:n}:{prompt:`${s.slice(0,n-1)}${s.slice(n)}`,cursor:n-1}}function Ds(t){return/\s/u.test(t||"")}function Ic(t,e,s){const n=String(t||"");let r=ke(n,e);if(s<0){for(;r>0&&Ds(n[r-1]);)r-=1;for(;r>0&&!Ds(n[r-1]);)r-=1;return r}for(;r<n.length&&Ds(n[r]);)r+=1;for(;r<n.length&&!Ds(n[r]);)r+=1;return r}function ug(t,e){const s=String(t||""),n=ke(s,e),r=Ic(s,n,-1);return r===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,r)}${s.slice(n)}`,cursor:r}}function pg(t,e,s){const n=xc(t);if(n.length<=1)return ke(t,e);const r=cg(t,e),i=Math.max(0,Math.min(r.line+s,n.length-1));return i===r.line?ke(t,e):dg(t,i,r.column)}const Nr=3e3,fg=new Set(["logs","sequence"]),mg=2e5,hg=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),gg=new Set([".json",".jsonl"]),yg=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function Ac(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function bg(t,e=""){const s=Ac(t),n=String(e||"").toLowerCase();return yg.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}const nr=12e4;function aa(t,e=mg){const s=String(t??"");return s.length<=e?s:`${s.slice(0,e)}
|
|
74
|
-
|
|
75
|
-
[Preview truncated at ${e.toLocaleString()} characters. Open the artifact directly if you need the full file.]`}function Sg(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 vg(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${Sg(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
|
|
76
|
-
`)}function la(t,e,s="",n=null){const r=String(s||"").toLowerCase(),i=Ac(t);if(n?.isBinary===!0||bg(t,s))return{content:vg(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=aa(e);if(hg.has(i)||r.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(gg.has(i)||r.includes("json"))try{return{content:aa(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 wg=1e4,Eg=140,kg=1500,xg={day:"Daily",week:"Weekly",month:"Monthly"};function Bs(t){const e=typeof t?.message=="string"?t.message.trim():"";return e||String(t??"").trim()||"The request failed."}function Ig(t,e,s=Date.now()){if(t?.hasCredential===!1)return{state:"no_credential",text:"no credential — nothing can run on it"};if(t?.holdIndefinite===!0||(t?.holdUntilUtc?Date.parse(t.holdUntilUtc)>s:!1))return{state:"hold",text:"on hold — new turns wait until it is released"};if(!e)return{state:"unknown",text:"budget unknown"};const r=Array.isArray(e.rules)?e.rules:[];if(r.length===0)return{state:"no_limits",text:"no limit"};const o=[...r.map(l=>{const c=Number(l?.limitTokens)||0,d=Number(l?.usedTokens)||0,p=l?.ceilingTokens==null?null:Number(l.ceilingTokens),u=Number(l?.yourUsedTokens)||0;return{periodLabel:xg[l?.period]||String(l?.period||""),pct:c>0?Math.floor(d/c*100):0,atLimit:c>0&&d>=c,atCeiling:p!=null&&p>0&&u>=p}})].sort((l,c)=>(l.atLimit||l.atCeiling?0:1)-(c.atLimit||c.atCeiling?0:1)||c.pct-l.pct)[0];return o.atLimit?{state:"at_limit",text:`at its ${o.periodLabel.toLowerCase()} limit — a session here waits for the reset`}:o.atCeiling?{state:"at_limit",text:`your share of its ${o.periodLabel.toLowerCase()} limit is used up`}:{state:"under_limit",text:`${o.pct}% of its ${o.periodLabel.toLowerCase()} limit used`}}class Ag{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)}`,r=s==="queued"||s==="cancelling"?s:"pending";return{id:n,text:String(e||""),createdAt:Date.now(),phase:r,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 r=this.getNavigableOutboxItems(e).find(c=>c.id===s);if(!r)return!1;const i=this.getState().ui,o=this.getPromptEditSessionMatch(e),l=o?{...o,itemId:s,phase:r.phase}:{sessionId:e,itemId:s,phase:r.phase,draftPrompt:i.prompt,draftCursor:i.promptCursor};return this.dispatch({type:"ui/promptEdit",promptEdit:l}),this.setPrompt(r.text,r.text.length),this.setFocus($.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 r=s.findIndex(i=>i.id===n.itemId);return r<=0?!1:this.enterPendingPromptEdit(e,s[r-1].id)}selectNextPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e),n=this.getPromptEditSessionMatch(e);if(!n)return!1;const r=s.findIndex(i=>i.id===n.itemId);return r===-1||r>=s.length-1?this.exitPendingPromptEdit({restoreDraft:!0}):this.enterPendingPromptEdit(e,s[r+1].id)}async cancelSelectedOutboxPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const n=this.getSessionOutbox(e.sessionId).find(i=>i.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(i=>i.id===e.itemId&&i.phase==="pending"))return!1;const r=s.filter(i=>i.id!==e.itemId);return this.setSessionOutboxItems(e.sessionId,r),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),r=n.find(o=>o.id===s);if(!r||r.phase==="cancelling")return!1;this.getPromptEditSessionMatch(e)?.itemId===s&&this.exitPendingPromptEdit({restoreDraft:!0});const i=Array.isArray(r.clientMessageIds)&&r.clientMessageIds.length>0?r.clientMessageIds:[r.id];if(r.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,i),this.dispatch({type:"ui/status",text:"Cancelling queued prompt"})}catch(o){return this.setSessionOutboxItems(e,n),this.dispatch({type:"ui/status",text:o?.message||String(o)}),!1}else this.dispatch({type:"ui/status",text:"Queued prompt marked cancelling (local only — transport has no cancel)"});else{const o=n.filter(l=>l.id!==s);if(this.setSessionOutboxItems(e,o),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,i)}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 r=this.buildOutboxItem(s,"pending");return Array.isArray(n?.attachments)&&n.attachments.length>0&&(r.attachments=n.attachments),this.setSessionOutboxItems(e,[...this.getSessionOutbox(e),r]),r}addPendingImageFiles(e){const s=Array.from(e||[]).filter(Boolean),n=this.getPromptAttachments(),r=n.filter(l=>l?.kind==="image"),i=[],o=[];for(const l of s){const c=String(l.type||"").toLowerCase();if(!ia.has(c)){o.push({name:l.name||"image",reason:"unsupported type"});continue}if((Number(l.size)||0)>oa){o.push({name:l.name||"image",reason:"over 4 MB"});continue}if(r.length+i.length>=sr){o.push({name:l.name||"image",reason:`max ${sr} images`});continue}i.push({kind:"image",file:l,filename:String(l.name||"image"),contentType:c,sizeBytes:Number(l.size)||0})}return i.length>0&&this.setPromptAttachments([...n,...i]),o.length>0&&this.dispatch({type:"ui/status",text:`Skipped ${o.map(l=>`${l.name} (${l.reason})`).join(", ")}`}),{accepted:i.length,rejected:o}}stageUploadedImageAttachment(e,s){const n=String(e?.contentType||"").toLowerCase();return!ia.has(n)||(Number(e?.sizeBytes)||0)>oa||this.getPromptAttachments().filter(i=>i?.kind==="image").length>=sr?!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),r=await this.finalizeArtifactUpload(n,{sessionId:s,suppressStatus:!0});return this.stageUploadedImageAttachment(r,s)?(this.dispatch({type:"ui/status",text:`Clipboard image attached to your next message (${r.filename})`}),!0):(this.dispatch({type:"ui/status",text:`Uploaded ${r.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(),r=s.filter(i=>i?.kind==="image")[e];r&&this.setPromptAttachments(s.filter(i=>i!==r))}async uploadPendingImageAttachments(e,s,n){const r=[],i=String(n||Date.now()).replace(/[^a-zA-Z0-9_-]/g,"").slice(-24)||"img";let o=0;for(const l of s){if(!l.file){l.uploaded&&l.filename&&r.push({filename:l.filename});continue}o+=1;const c={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[l.contentType]||"png",d=`attach-${i}-${o}.${c}`;await this.transport.uploadArtifactFromFile(e,l.file,d),r.push({filename:d})}return r}acknowledgeOutboxPrompt(e,s,n=null){if(!e)return!1;const r=this.getSessionOutbox(e);if(n){const c=r.findIndex(d=>(d?.phase==="pending"||d?.phase==="queued"||d?.phase==="cancelling")&&Array.isArray(d.clientMessageIds)&&d.clientMessageIds.includes(n));if(c!==-1){const d=r[c];return this.setSessionOutboxItems(e,r.filter((p,u)=>u!==c)),this.getPromptEditSessionMatch(e)?.itemId===d?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const i=Qo(s);if(!i)return!1;const o=r.findIndex(c=>(c?.phase==="pending"||c?.phase==="queued"||c?.phase==="cancelling")&&Qo(c.text)===i);if(o===-1)return!1;const l=r[o];return this.setSessionOutboxItems(e,r.filter((c,d)=>d!==o)),this.getPromptEditSessionMatch(e)?.itemId===l?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}acknowledgeCancelledOutboxPrompt(e,s=[]){if(!e)return!1;const n=new Set((s||[]).filter(c=>typeof c=="string"&&c));if(n.size===0)return!1;const r=this.getSessionOutbox(e),i=r.filter(c=>c?.phase!=="cancelling"?!0:!(Array.isArray(c.clientMessageIds)?c.clientMessageIds:[c.id]).some(p=>n.has(p)));if(i.length===r.length)return!1;const o=new Set(r.filter(c=>!i.some(d=>d.id===c.id)).map(c=>c.id));this.setSessionOutboxItems(e,i);const l=this.getPromptEditSessionMatch(e);return l&&o.has(l.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}scheduleOutboxDispatch(e){if(!e||(this._outboxDispatchTimers||(this._outboxDispatchTimers=new Map),this._outboxDispatchTimers.has(e)))return;const s=setTimeout(()=>{this._outboxDispatchTimers.delete(e),this.dispatchPendingOutbox(e).catch(()=>{})},10);this._outboxDispatchTimers.set(e,s)}async dispatchPendingOutbox(e){if(!e)return!1;await Promise.resolve();const s=this.outboxFlushPromises.get(e);if(s)return await s.catch(()=>{}),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e),!1;const n=this.getPendingOutboxItems(e),r=n.find(h=>h?.attempted===!0),i=r?[r]:n.filter(h=>h?.attempted!==!0);if(i.length===0)return!1;const o=i.flatMap(h=>Array.isArray(h.clientMessageIds)&&h.clientMessageIds.length>0?h.clientMessageIds:[h.id]),l=i.map(h=>String(h.text||"")).join(`
|
|
77
|
-
|
|
78
|
-
`),c=i.flatMap(h=>Array.isArray(h.attachments)?h.attachments:[]),d={id:i[0].id,text:l,createdAt:i[0].createdAt||Date.now(),phase:"pending",attempted:!0,clientMessageIds:o,...c.length>0?{attachments:c}:{}},p=new Set(i.map(h=>h.id)),u=this.getSessionOutbox(e).filter(h=>!p.has(h.id));this.setSessionOutboxItems(e,[...u,d]);const f=this.getPromptEditSessionMatch(e);f&&p.has(f.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const m=(async()=>{await this.transport.sendMessage(e,d.text,{enqueueOnly:!0,clientMessageIds:d.clientMessageIds,...Array.isArray(d.attachments)&&d.attachments.length>0?{attachments:d.attachments}:{}});const g=this.getSessionOutbox(e).map(b=>b.id===d.id?{...b,phase:"queued"}:b);return this.setSessionOutboxItems(e,g),this.syncSessionEvents(e).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(h=>{const g=h?.code==="FORBIDDEN"||h?.code==="UNAUTHORIZED"||h?.status===403||h?.status===401,b=this.getSessionOutbox(e);if(g){const y=b.map(v=>v.id===d.id?{...v,phase:"rejected"}:v);this.setSessionOutboxItems(e,y),setTimeout(()=>{const v=this.getSessionOutbox(e),E=v.filter(k=>!(k.id===d.id&&k.phase==="rejected"));E.length!==v.length&&this.setSessionOutboxItems(e,E)},6e3)}else{const y=b.map(v=>v.id===d.id?{...d,phase:"pending",attempted:!0}:v);this.setSessionOutboxItems(e,y)}throw this.dispatch({type:"ui/status",text:h?.message||String(h)}),h}).finally(()=>{this.outboxFlushPromises.delete(e),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e)});return this.outboxFlushPromises.set(e,m),await m}async flushQueuedOutbox(e){return await this.dispatchPendingOutbox(e)}maybeFlushQueuedOutbox(e){return!e||this.getPendingOutboxItems(e).length===0?!1:(this.scheduleOutboxDispatch(e),!0)}getPromptReferenceContext(){const e=this.getState();return na(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=St(s),r=n?.sessionId||s.sessions.activeSessionId||null,i=n?.filename||null;if(!r||!i)return!1;const o=sa(i),l=ra(s.ui.prompt,e,o),c=this.getPromptAttachments(),d=c.findIndex(f=>f?.sessionId===r&&f?.filename===i),p={...d>=0?c[d]:{},id:`${r}/${i}`,sessionId:r,filename:i,resolvedPath:i,token:o},u=d>=0?c.map((f,m)=>m===d?p:f):[...c,p];return this.setPrompt(l.prompt,l.cursor),this.setPromptAttachments(u),this.setFocus($.PROMPT),this.dispatch({type:"ui/status",text:`Attached ${i}`}),!0}acceptSessionPromptReference(e=this.getPromptReferenceContext()){if(!e||e.kind!=="sessions")return!1;const s=this.getState(),r=as(s)[0]||null,i=r?.sessionId&&s.sessions.byId[r.sessionId]||null;if(!i?.sessionId)return!1;const o=rg(i),l=ra(s.ui.prompt,e,o);return this.setPrompt(l.prompt,l.cursor),this.setFocus($.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${Oe(i.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}openSessionOwnerFilter(){const e=this.getState(),s=Zo(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 r=e==null?Math.max(0,Number(n.selectedIndex)||0):Math.max(0,Number(e)||0),i=n.items?.[r];if(!i)return;const o=Zh(s.sessions.ownerFilter,i,s.auth?.principal);this.dispatch({type:"sessions/ownerFilter",filter:o}),this.dispatch({type:"ui/modalSelection",index:r}),this.dispatch({type:"ui/status",text:`Session filter updated: ${i.label||i.id||"selection"}`})}refreshOpenSessionOwnerFilterModal(){const e=this.getState(),s=e.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return;const n=Zo(e),r=Array.isArray(s.items)?s.items:[];if(r.length===n.length&&r.every((d,p)=>d?.id===n[p]?.id))return;const o=r[Math.max(0,Number(s.selectedIndex)||0)]?.id,l=o!=null?n.findIndex(d=>d.id===o):-1,c=l>=0?l:Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1)));this.dispatch({type:"ui/modal",modal:{...s,items:n,selectedIndex:c}})}setFilesFilter(e={}){this.dispatch({type:"files/filter",filter:e})}clearPromptReferenceBrowser(){this.promptReferenceSignature=null,this.promptReferenceSyncVersion+=1,this.getState().sessions.filterQuery&&this.setSessionFilterQuery(""),this.getState().files.filter?.query&&this.setFilesFilter({query:""})}syncPromptReferenceBrowser(){const e=this.getState(),s=na(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 r=++this.promptReferenceSyncVersion;this.ensureFilesForScope("selectedSession").then(async()=>{if(this.promptReferenceSyncVersion!==r)return;const i=new Set(pn(this.getState(),"selectedSession")),l=Mt(this.getState()).filter(c=>i.has(c.sessionId))[0]||null;l?.filename&&(this.dispatch({type:"files/select",sessionId:l.sessionId,filename:l.filename}),await this.ensureFilePreview(l.sessionId,l.filename).catch(()=>{}))}).catch(()=>{})}async start({initialSessionId:e=null}={}){await this.transport.start();const s=typeof this.transport.getAuthContext=="function"?this.transport.getAuthContext():null;this.dispatch({type:"auth/context",principal:s?.principal??null,authorization:s?.authorization??null}),this.getState().sessions.ownerFilterExplicit||this.dispatch({type:"sessions/ownerFilter",filter:hn(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 r=String(e||"").trim();r&&this.dispatch({type:"sessions/navigationIntent",sessionId:r}),await this.refreshSessions(),this.catalogTimer=setInterval(()=>{this.refreshSessions().catch(i=>{this.dispatch({type:"connection/error",error:i?.message||String(i),statusText:qo})})},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&&(ys(e)||(this.activeSessionSubscriptionId===e&&this.detachActiveSession(),this.activeSessionDetailSessionId===e&&this.activeSessionDetailTimer&&(clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null),this.dispatch({type:"sessions/gone",sessionId:e})))}detachLogStream(){this.logUnsubscribe&&(this.logUnsubscribe(),this.logUnsubscribe=null)}async refreshSessions(){this.refreshWorkerRegistryIfStale().catch(()=>{});const e=this.sessionRefreshSeq=(this.sessionRefreshSeq||0)+1,s=this.getState(),n=!s.connection.connected||!!s.connection.error,r=s.ui.statusText===qo,i=this.getState().sessions.activeSessionId;let o=(await Hh(this.transport)).map(er),l=null;if(typeof this.transport.listSessionGroups=="function")try{const m=await this.transport.listSessionGroups();l=(Array.isArray(m)?m:[]).map(Dh).filter(Boolean)}catch(m){console.warn(`[PilotSwarmUi] session-group fetch failed, keeping the known folders: ${m?.message||m}`)}const c=s.sessions.navigationIntent;if(c?.status==="pending"&&!o.some(m=>m?.sessionId===c.sessionId)&&typeof this.transport.getSession=="function")try{const m=await this.transport.getSession(c.sessionId);m?.sessionId?o=[...o,er(m)]:this.dispatch({type:"sessions/navigationIntentFailed",sessionId:c.sessionId,errorKind:"not_found"})}catch(m){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:c.sessionId,errorKind:tr(m)})}const d=i;if(d&&!ys(d)&&!o.some(m=>m?.sessionId===d)&&typeof this.transport.getSession=="function"){const m=await this.transport.getSession(d).catch(()=>null);m?.sessionId&&(o=[...o,er(m)])}if(e!==this.sessionRefreshSeq)return;n&&this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,...r?{statusText:"Connected"}:{}}),l&&this.dispatch({type:"sessions/groupsLoaded",groups:l,sessions:o});const p=[];for(const m of o)for(const h of Array.isArray(m?.canvases)?m.canvases:[])p.push({sessionId:m.sessionId,slot:h.slot,name:h.name,latestRev:h.latestRev,sizeBytes:h.sizeBytes});p.length&&this.dispatch({type:"canvas/seed",entries:p}),this.dispatch({type:"sessions/loaded",sessions:o}),this.refreshBudgetPausesIfStale(o).catch(()=>{}),this.refreshOpenSessionOwnerFilterModal();const u=this.getState().sessions.activeSessionId,f=new Set;if(u){if(u!==i){if(!this.getState().sessions.byId[u]?.isGroup){const b=this.getState().sessions.navigationIntent;if(b&&b.sessionId===u&&b.status!=="failed")try{await this.loadSession(u)}catch(y){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:u,errorKind:tr(y)})}else await this.loadSession(u)}return}if(this.getState().sessions.byId[u]?.isGroup)return;this.getState().history.bySessionId.get(u)?.events?.length||await this.ensureSessionHistory(u,{force:!0}).catch(()=>{}),this.ensureCanvasSnapshot(u).catch(()=>{}),this.activeSessionSubscriptionId!==u&&this.attachActiveSession(u),await this.syncSessionDetail(u).catch(()=>{}),await this.syncSessionEvents(u).catch(()=>{}),f.add(u);const h=this.getState(),g=h.sessions.byId[u]||null;if(g?.parentSessionId&&typeof this.transport.getSession=="function"){const b=Object.values(h.sessions.byId).filter(y=>y?.parentSessionId===g.parentSessionId).map(y=>y.sessionId).filter(y=>y&&y!==u).slice(0,6);await Promise.all(b.map(y=>this.syncSessionDetail(y).catch(()=>{})));for(const y of b)f.add(y)}}await this.syncVisibleSessionDetails(f).catch(()=>{}),this.ensureInspectorData().catch(()=>{}),this.evictStaleSessionState()}async refreshWorkerRegistryIfStale(){const e=this.getState().admin?.workers;if(e?.loading){this.dispatch({type:"admin/workers/attempt",skip:"already in flight"});return}if(e?.fetchedAt&&Date.now()-e.fetchedAt<2e4){this.dispatch({type:"admin/workers/attempt",skip:"fresh"});return}this.dispatch({type:"admin/workers/attempt",skip:null}),await this.refreshAdminWorkers()}evictStaleSessionState(){const e=this.getState(),s=e.sessions.activeSessionId,n=Date.now(),r=6e4,i=20,o=Object.entries(e.orchestration.bySessionId||{});if(o.length>i){const p=o.filter(([u,f])=>u!==s&&!f?.loading).sort((u,f)=>(u[1]?.fetchedAt||0)-(f[1]?.fetchedAt||0)).slice(0,o.length-i).filter(([,u])=>n-(u?.fetchedAt||0)>r);p.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:p.map(([u])=>u)})}const l=Object.entries(e.executionHistory?.bySessionId||{});if(l.length>i){const p=l.filter(([u,f])=>u!==s&&!f?.loading).sort((u,f)=>(u[1]?.fetchedAt||0)-(f[1]?.fetchedAt||0)).slice(0,l.length-i).filter(([,u])=>n-(u?.fetchedAt||0)>r);p.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:p.map(([u])=>u)})}const c=Object.entries(e.files.bySessionId||{});if(c.length>i){const p=c.filter(([u])=>u!==s).slice(0,c.length-i);p.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:p.map(([u])=>u)})}const d=[...e.history.bySessionId.entries()];if(d.length>i*2){const p=d.filter(([u])=>u!==s).slice(0,d.length-i*2).map(([u])=>u);p.length>0&&this.dispatch({type:"history/evict",sessionIds:p})}}async syncVisibleSessionDetails(e=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=Is({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??Jt(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),r=this.getSessionListMaxRows(n),i=xr(s,r),o=[...new Set(i.map(l=>l.sessionId).filter(l=>l&&!ys(l)&&!e.has(l)))];o.length!==0&&await Promise.all(o.map(l=>this.syncSessionDetail(l).catch(()=>{})))}async catchUpSessionHistory(e,s,n){let i;try{i=await this.transport.getSessionEvents(e,n,1e3)}catch(p){return bs(p)&&this.handleSessionGone(e),null}if(!Array.isArray(i)||i.length>=1e3)return null;if(i.length===0)return s;let o=s;for(const p of i)o=Zi(o,p);o={...o,loadedEventLimit:Math.max(Number(s.loadedEventLimit)||0,Array.isArray(o.events)?o.events.length:0)},this.dispatch({type:"history/set",sessionId:e,history:o});for(const p of i)this.reconcileOutboxAgainstEvent(e,p);const l=Cr(i),c=this.getState().sessions.byId[e]||{},d=Yo(c.contextUsage,i);return(l||d)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...l||{},...d?{contextUsage:d}:{}}}),o}async ensureSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),r=Math.min(kg,Math.max(be,Number(n?.loadedEventLimit??be)||be));if(!s&&n?.events)return n;if(!s&&this.sessionHistoryLoads.has(e))return this.sessionHistoryLoads.get(e);const i=Number(n?.lastSeq)||0;if(s&&i>0&&Array.isArray(n?.events)&&n.events.length>0){const l=await this.catchUpSessionHistory(e,n,i);if(l)return l}const o=(async()=>{let l;try{l=await this.transport.getSessionEvents(e,void 0,r)}catch(f){if(bs(f))return this.handleSessionGone(e),null;throw f}const c={...Rs(l,{requestedLimit:r}),lastSeq:l[l.length-1]?.seq||0};this.dispatch({type:"history/set",sessionId:e,history:c});for(const f of l||[])this.reconcileOutboxAgainstEvent(e,f);const d=Cr(l),p=this.getState().sessions.byId[e]||{},u=Yo(p.contextUsage,l);return(d||u)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...d||{},...u?{contextUsage:u}:{}}}),c})().finally(()=>{this.sessionHistoryLoads.delete(e)});return this.sessionHistoryLoads.set(e,o),o}async ensureInspectorData(e=this.getState().ui.inspectorTab){if(e==="sequence"){const s=this.getState().sessions.activeSessionId;if(!s)return;await this.ensureSessionHistory(s).catch(()=>{}),await this.ensureOrchestrationStats(s).catch(()=>{});return}if(e==="nodes"){this.refreshWorkerRegistryIfStale().catch(()=>{});const s=this.getState(),n=Is({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??Jt(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),r=this.getSessionListMaxRows(n),i=xr(s,r),o=[...new Set(i.map(l=>l.sessionId).filter(Boolean))];if(o.length===0)return;await Promise.allSettled(o.map(l=>this.ensureSessionHistory(l)));return}if(e==="files"&&await this.ensureFilesForScope(Ye(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,r=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&r-n.fetchedAt<Ph)return n;if(!s&&this.sessionOrchestrationStatsLoads.has(e))return this.sessionOrchestrationStatsLoads.get(e);this.dispatch({type:"orchestration/statsLoading",sessionId:e});const i=(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 bs(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,i),i}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,r=Date.now();if(!(!e&&n?.loading)&&!(!e&&n&&Number.isFinite(n.fetchedAt)&&r-n.fetchedAt<Mh)){this.dispatch({type:"sessionStats/loading",sessionId:s});try{const[i,o,l,c,d,p,u]=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:i,tokensByModel:o,treeStats:l,skillUsage:c,treeSkillUsage:d,factsStats:p,treeFactsStats:u})}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<Rh)){this.dispatch({type:"fleetStats/loading"});try{const i={since:new Date(Date.now()-$h*864e5),includeDeleted:!0},[o,l,c,d,p,u]=await Promise.all([this.transport.getFleetStats(i),typeof this.transport.getUserStats=="function"?this.transport.getUserStats(i).catch(()=>null):null,typeof this.transport.getFleetSkillUsage=="function"?this.transport.getFleetSkillUsage(i).catch(()=>null):null,typeof this.transport.getFleetRetrievalUsage=="function"?this.transport.getFleetRetrievalUsage(i).catch(()=>null):null,typeof this.transport.getSharedFactsStats=="function"?this.transport.getSharedFactsStats().catch(()=>null):null,typeof this.transport.getFactsTombstoneStats=="function"?this.transport.getFactsTombstoneStats().catch(()=>null):null]);this.dispatch({type:"fleetStats/loaded",data:o,userStats:l,skillUsage:c,retrievalUsage:d,sharedFactsStats:p,factsTombstoneStats:u})}catch{this.dispatch({type:"fleetStats/loaded",data:null,userStats:null,skillUsage:null,retrievalUsage:null,sharedFactsStats:null,factsTombstoneStats:null})}}}async openAdminConsole(){this.dispatch({type:"admin/visibility",visible:!0}),await this.refreshAdminProfile().catch(()=>{}),this.refreshAdminModelProviders().catch(()=>{}),this.refreshAdminAgentPackages().catch(()=>{})}closeAdminConsole(){this.dispatch({type:"admin/visibility",visible:!1})}revealCreatedSession(){this.getState().admin?.visible&&this.closeAdminConsole(),this.setFocus($.PROMPT)}async refreshAdminProfile(){if(typeof this.transport.getCurrentUserProfile!="function")return this.dispatch({type:"admin/profile/loadFailed",error:"Admin Console is not available on this transport."}),null;this.dispatch({type:"admin/profile/loading"});try{const e=await this.transport.getCurrentUserProfile();return this.dispatch({type:"admin/profile/loaded",profile:e}),await this.refreshSystemGhcpKeyStatus(e),e||null}catch(e){return this.dispatch({type:"admin/profile/loadFailed",error:e?.message||String(e)}),null}}async refreshSystemGhcpKeyStatus(e=null){if(!(e||this.getState().admin?.profile||null)?.isAdmin||typeof this.transport.getSystemGitHubCopilotKeyStatus!="function")return null;this.dispatch({type:"admin/systemGhcpKey/loading"});try{const n=await this.transport.getSystemGitHubCopilotKeyStatus();return this.dispatch({type:"admin/systemGhcpKey/loaded",status:n}),n||null}catch(n){return this.dispatch({type:"admin/systemGhcpKey/loadFailed",error:n?.message||String(n)}),null}}setAdminGhcpKeyStoreAsSystem(e){e&&!this.getState().admin?.profile?.isAdmin||this.dispatch({type:"admin/ghcpKey/setSystemTarget",value:!!e})}async refreshAdminModelProviders(){if(["listProviders","getModelDefaults"].some(s=>typeof this.transport[s]!="function"))return this.dispatch({type:"admin/modelProviders/loadFailed",error:"Model provider management is not available on this transport."}),null;this.dispatch({type:"admin/modelProviders/loading"});try{const[s,n,r]=await Promise.all([this.transport.listProviders(),typeof this.transport.getModelsByProvider=="function"?this.transport.getModelsByProvider():this.transport.listModels(),this.transport.getModelDefaults()]),i=Array.isArray(n)&&n.some(l=>Array.isArray(l?.models))?n.flatMap(l=>(l.models||[]).map(c=>({...c,providerId:l.providerId,providerType:l.type||c.providerType}))):n,o=Array.isArray(s)?s:Array.isArray(s?.providers)?s.providers:[];return this.dispatch({type:"admin/modelProviders/loaded",providers:o,models:Array.isArray(i)?i:[],defaults:r}),{providers:o,models:i,defaults:r}}catch(s){return this.dispatch({type:"admin/modelProviders/loadFailed",error:s?.message||String(s)}),null}}async _runAdminModelProviderMutation(e,s){this.dispatch({type:"admin/modelProviders/mutationPending",pending:e});try{const n=await s();return this.dispatch({type:"admin/modelProviders/mutationDone"}),await this.refreshAdminModelProviders(),{ok:!0,result:n??null,error:null}}catch(n){const r=n?.message||String(n);return this.dispatch({type:"admin/modelProviders/mutationFailed",error:r}),{ok:!1,result:null,error:r}}}async createAdminProvider({name:e,type:s,credentials:n,baseUrl:r=null,shared:i=!1}={}){const o=i?"createProvider":"createMyProvider";return typeof this.transport[o]!="function"?(this.dispatch({type:"admin/modelProviders/mutationFailed",error:"Provider creation is not available on this transport."}),{ok:!1,result:null,error:"Provider creation is not available on this transport."}):this._runAdminModelProviderMutation("create",()=>this.transport[o]({name:e,type:s,credentials:n,baseUrl:r}))}async deleteAdminProvider(e,{shared:s=!1}={}){const n=s?"deleteProvider":"deleteMyProvider";return typeof this.transport[n]!="function"?{ok:!1,result:null,error:"Provider deletion is not available on this transport."}:this._runAdminModelProviderMutation("delete",()=>this.transport[n](e))}async setAdminProviderSystemUse(e,s){return typeof this.transport.setProviderSystemUse!="function"?{ok:!1,result:null,error:"System-use controls are not available on this transport."}:this._runAdminModelProviderMutation("systemUse",()=>this.transport.setProviderSystemUse({provider:e,enabled:s===!0}))}async setAdminModelDefault(e,s=null){return typeof this.transport.setModelDefault!="function"?{ok:!1,result:null,error:"Model defaults are not available on this transport."}:this._runAdminModelProviderMutation(`${e}Default`,()=>this.transport.setModelDefault({scope:e,provider:s?.provider??null,model:s?.qualifiedName??s?.model??null,reasoningEffort:s?.reasoningEffort??s?.defaultReasoningEffort??null,contextTier:s?.contextTier??s?.defaultContextTier??null}))}async setAdminSystemModelDefault(e=null,{restartDisposition:s=null}={}){return typeof this.transport.setSystemModelDefault!="function"?{ok:!1,result:null,error:"The system model default is not available on this transport."}:this._runAdminModelProviderMutation("systemDefault",()=>this.transport.setSystemModelDefault({provider:e?.provider??null,model:e?.qualifiedName??e?.model??null,reasoningEffort:e?.reasoningEffort??e?.defaultReasoningEffort??null,contextTier:e?.contextTier??e?.defaultContextTier??null,restartExisting:s?{disposition:s}:!1}))}async setAdminSystemAgentModel(e,s){return typeof this.transport.setSystemSessionModel!="function"?{ok:!1,result:null,error:"System-agent overrides are not available on this transport."}:this._runAdminModelProviderMutation("systemOverride",()=>this.transport.setSystemSessionModel({agentId:e,provider:s?.provider,model:s?.qualifiedName??s?.model,reasoningEffort:s?.reasoningEffort??s?.defaultReasoningEffort??null,contextTier:s?.contextTier??s?.defaultContextTier??null}))}async clearAdminSystemAgentModel(e){return typeof this.transport.clearSystemSessionModel!="function"?{ok:!1,result:null,error:"System-agent overrides are not available on this transport."}:this._runAdminModelProviderMutation("systemOverride",()=>this.transport.clearSystemSessionModel(e))}beginAdminCreateProvider({shared:e=!1}={}){const s=this.getState().admin?.modelProviders||{},n=(s.models||[]).find(d=>/github/i.test(d?.providerId||""))?.providerId||s.models?.[0]?.providerId||"github-copilot",r=new Set((s.providers||[]).map(d=>String(d?.name||"").toLowerCase())),i=String(this.getState().admin?.profile?.subject||"").replace(/[^A-Za-z0-9]/gu,"").slice(-10).toLowerCase(),o=i?`ghcp-${i}`:"my-ghcp";let l=o,c=2;for(;r.has(l.toLowerCase());)l=`${o}-${c}`,c+=1;this.dispatch({type:"admin/modelProviders/createBegin",name:l,typeId:n,shared:e})}beginAdminCreateGithubProvider(){this.beginAdminCreateProvider({shared:!1})}cycleAdminProviderCreateType(){const e=vt(this.getState()).modelProviders,s=this.getState().admin?.modelProviders?.create;if(!s?.editing||s.saving||s.stage!=="name")return;const n=e.providerTypes||[];if(!n.length)return;const r=Math.max(0,n.findIndex(i=>i.id===s.typeId));this.dispatch({type:"admin/modelProviders/createType",typeId:n[(r+1)%n.length].id})}setAdminProviderCreateDraft(e,s=String(e||"").length){this.dispatch({type:"admin/modelProviders/createDraft",draft:e,cursorIndex:s})}insertAdminProviderCreateText(e){const s=this.getState().admin?.modelProviders?.create;if(!s?.editing||s.saving)return;const n=String(e||"").replace(/\r?\n/gu,""),r=mt(s.draft||"",s.cursorIndex||0,n);this.setAdminProviderCreateDraft(r.prompt,r.cursor)}deleteAdminProviderCreateChar(){const e=this.getState().admin?.modelProviders?.create;if(!e?.editing||e.saving)return;const s=Ct(e.draft||"",e.cursorIndex||0);this.setAdminProviderCreateDraft(s.prompt,s.cursor)}moveAdminProviderCreateCursor(e){const s=this.getState().admin?.modelProviders?.create;if(!s?.editing||s.saving)return;const n=s.draft||"";this.setAdminProviderCreateDraft(n,ke(n,(s.cursorIndex||0)+e))}moveAdminProviderCreateCursorToBoundary(e){const s=this.getState().admin?.modelProviders?.create;if(!s?.editing||s.saving)return;const n=s.draft||"";this.setAdminProviderCreateDraft(n,e==="start"?0:n.length)}advanceAdminProviderCreate(){const e=this.getState().admin?.modelProviders?.create;if(!e?.editing||e.saving||e.stage!=="name")return;const s=String(e.draft||"").trim();if(!s||s.length>64||!/^[A-Za-z0-9._-]+$/u.test(s)){this.dispatch({type:"admin/modelProviders/createFailed",error:"Use 1-64 letters, numbers, dots, dashes, or underscores for the provider name."});return}this.dispatch({type:"admin/modelProviders/createCredential",name:s})}async saveAdminProviderCreate(){const e=this.getState().admin?.modelProviders?.create;if(!e?.editing||e.saving||e.stage!=="credential")return;const s=String(e.draft||"").trim();if(!s){this.dispatch({type:"admin/modelProviders/createFailed",error:"Enter a provider credential."});return}const n={name:e.name,type:e.typeId,credentials:/github/i.test(e.typeId)?{githubToken:s}:{apiKey:s},shared:e.shared===!0};this.dispatch({type:"admin/modelProviders/createSaving"});const r=await this.createAdminProvider(n);this.dispatch(r?.ok?{type:"admin/modelProviders/createEnd"}:{type:"admin/modelProviders/createFailed",error:r?.error})}cancelAdminProviderCreate(){this.dispatch({type:"admin/modelProviders/createEnd"})}setAdminModelProviderSelection({focus:e,providerName:s,agentId:n}={}){this.dispatch({type:"admin/modelProviders/select",focus:e,providerName:s,agentId:n})}setAdminModelProviderPage(e){e==="shared"&&!this.getState().admin?.profile?.isAdmin||this.dispatch({type:"admin/modelProviders/page",page:e})}stepAdminModelProviderSelection(e){const s=vt(this.getState()).modelProviders,n=s.selection?.focus==="agents"?"agents":"providers",r=n==="agents"?s.systemAgentRoutes:s.page==="shared"?s.sharedProviders:s.myProviders;if(!r.length)return;const i=n==="agents"?s.selection?.agentId:s.selection?.providerName;let o=r.findIndex(c=>(n==="agents"?c.agentId:c.name)===i);o<0&&(o=0);const l=r[(o+e+r.length)%r.length];this.setAdminModelProviderSelection(n==="agents"?{focus:n,agentId:l.agentId}:{focus:n,providerName:l.name})}async toggleSelectedAdminProviderSystemUse(){const e=vt(this.getState()).modelProviders,s=e.myProviders.find(n=>n.name===e.selection?.providerName);if(!(!s||!this.getState().admin?.profile?.isAdmin))return this.setAdminProviderSystemUse(s.name,!s.systemUseEnabled)}async deleteSelectedAdminProvider(){const e=vt(this.getState()).modelProviders,s=[...e.myProviders,...e.sharedProviders].find(n=>n.name===e.selection?.providerName);if(s)return this.deleteAdminProvider(s.name,{shared:s.class==="shared"})}requestDeleteSelectedAdminProvider(){const e=vt(this.getState()).modelProviders,s=[...e.myProviders,...e.sharedProviders].find(n=>n.name===e.selection?.providerName);s&&this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Model Provider",message:`Delete ${s.name}? Sessions using it will wait until that provider name exists again.`,confirmLabel:"Delete Provider",action:"deleteAdminProvider",previousFocus:$.ADMIN}})}async cycleAdminModelDefault(e,{restartDisposition:s=null}={}){const n=vt(this.getState()).modelProviders,r=e==="user"?n.userChoices:e==="cluster"?n.clusterChoices:n.systemChoices,i=e==="user"?n.mySessionDefault?.configured?.model:e==="cluster"?n.clusterSessionDefault?.configured?.model:n.systemSessionDefault?.configured?.model,o=[null,...r],l=Math.max(0,o.findIndex(d=>d?.qualifiedName===i)),c=o[(l+1)%o.length];return e==="system"?this.setAdminSystemModelDefault(c,{restartDisposition:s}):this.setAdminModelDefault(e,c)}async cycleSelectedAdminSystemAgentOverride(){const e=vt(this.getState()).modelProviders,s=e.systemAgentRoutes.find(l=>l.agentId===e.selection?.agentId)||e.systemAgentRoutes[0];if(!s)return;const n=[null,...e.systemChoices],r=s.override?.model||null,i=Math.max(0,n.findIndex(l=>l?.qualifiedName===r)),o=n[(i+1)%n.length];return o?this.setAdminSystemAgentModel(s.agentId,o):this.clearAdminSystemAgentModel(s.agentId)}setAdminSection(e){this.dispatch({type:"admin/section",section:e}),e==="providers"&&(this.getState().admin?.modelProviders?.fetchedAt||this.refreshAdminModelProviders().catch(()=>{})),e==="packages"&&(this.getState().admin?.packages?.fetchedAt||this.refreshAdminAgentPackages().catch(()=>{})),e==="workers"&&this.refreshAdminWorkers().catch(()=>{})}selectNodeMapNode(e){this.dispatch({type:"ui/nodeMapSelect",label:e?String(e):null})}async refreshAdminWorkers(){if(typeof this.transport.listWorkers!="function"){this.dispatch({type:"admin/workers/loadFailed",error:"The worker registry is not available on this deployment."});return}this.dispatch({type:"admin/workers/loading"});try{const e=await Promise.race([Promise.resolve().then(()=>this.transport.listWorkers()),new Promise((s,n)=>{const r=setTimeout(()=>n(new Error("request timed out after 10s (connection or auth renewal wedged — try a hard refresh)")),1e4);typeof r?.unref=="function"&&r.unref()})]);console.info(`[PilotSwarmUi] worker registry: ${Array.isArray(e)?e.length:0} row(s)`),this.dispatch({type:"admin/workers/loaded",list:e})}catch(e){console.warn(`[PilotSwarmUi] worker-registry fetch failed: ${e?.message||e}`),this.dispatch({type:"admin/workers/loadFailed",error:e?.message||String(e)})}}async refreshAdminAgentPackages(){if(typeof this.transport.listAgentPackages!="function"){this.dispatch({type:"admin/packages/loadFailed",error:"Agent packages are not available on this deployment."});return}this.dispatch({type:"admin/packages/loading"});try{const[e,s]=await Promise.all([this.transport.listAgentPackages(),typeof this.transport.listAgentWorkerState=="function"?this.transport.listAgentWorkerState().catch(()=>[]):[]]);this.dispatch({type:"admin/packages/loaded",list:e,workerState:s})}catch(e){this.dispatch({type:"admin/packages/loadFailed",error:e?.message||String(e)})}}async selectAdminPackage(e,s=null){if(this.dispatch({type:"admin/packages/select",name:e,selector:s}),!e)return;const n=this.getState().admin?.packages?.selectionSeq??0;await Promise.all([(async()=>{try{const r=await this.transport.getAgentPackage(e,s);if(!r)throw new Error(`package "${e}" not found`);this.dispatch({type:"admin/packages/detail/loaded",name:e,seq:n,detail:r})}catch(r){this.dispatch({type:"admin/packages/detail/loadFailed",name:e,seq:n,error:r?.message||String(r)})}})(),(async()=>{try{const r=await this.transport.getAgentPackageTree(e,null,s);if((this.getState().admin?.packages?.selectionSeq??0)!==n)return;this.dispatch({type:"admin/packages/tree/loaded",name:e,seq:n,tree:r}),r?.files?.some(l=>l.path==="CHANGELOG.md")&&typeof this.transport.getAgentPackageFile=="function"?(async()=>{try{const l=await this.transport.getAgentPackageFile(e,null,"CHANGELOG.md",s);if((this.getState().admin?.packages?.selectionSeq??0)!==n)return;this.dispatch({type:"admin/packages/changelog/loaded",name:e,seq:n,content:typeof l=="string"?l:l?.content??l?.text??""})}catch{}})():this.dispatch({type:"admin/packages/changelog/loaded",name:e,seq:n,content:null});const o=r?.files?.find(l=>l.path==="plugin.json")??r?.files?.[0];o&&this.selectAdminPackageFile(o.path)}catch(r){this.dispatch({type:"admin/packages/tree/loadFailed",name:e,seq:n,error:r?.message||String(r)})}})()])}async stepAdminPackageSelection(e){const s=this.getState().admin?.packages;if(!s?.list?.length)return;const n=[...s.list.filter(c=>c.scope==="shared"),...s.list.filter(c=>c.scope!=="shared")],r=c=>`${c.name}${c.scope??""}${c.owner?.subject??""}`,i=s.selectedName?`${s.selectedName}${s.selectedSelector?.scope??""}${s.selectedSelector?.owner?.subject??""}`:null;let o=n.findIndex(c=>r(c)===i);o<0&&(o=n.findIndex(c=>c.name===s.selectedName));const l=n[Math.min(n.length-1,Math.max(0,(o<0?e>0?-1:0:o)+e))];l&&(l.name!==s.selectedName||r(l)!==i)&&await this.selectAdminPackage(l.name,Th(l))}toggleAdminPackageDir(e){this.dispatch({type:"admin/packages/toggleDir",dir:e})}async selectAdminPackageFile(e){const s=this.getState().admin?.packages,n=s?.selectedName;if(!n||!e)return;const r=s?.selectionSeq??0,i=s?.selectedSelector??null;this.dispatch({type:"admin/packages/file/loading",path:e});try{const o=await this.transport.getAgentPackageFile(n,null,e,i);this.dispatch({type:"admin/packages/file/loaded",seq:r,file:o})}catch(o){this.dispatch({type:"admin/packages/file/loadFailed",seq:r,path:e,error:o?.message||String(o)})}}async runAdminPackageAction(e,s=null){const n=this.getState().admin?.packages,r=n?.selectedName,i=n?.selectedSelector??null;if(r){this.dispatch({type:"admin/packages/action/pending",action:e});try{switch(e){case"promote":await this.transport.setAgentPackageScope(r,"shared",i);break;case"demote":await this.transport.setAgentPackageScope(r,"user",i);break;case"republish":await this.transport.republishAgentPackageVersion(r,s,i?.scope==="shared"?"user":"shared",i);break;case"pin":await this.transport.pinAgentPackageVersion(r,s,i);break;case"enable":case"disable":await this.transport.setAgentPackageEnabled(r,e==="enable",i);break;case"delete":await this.transport.deleteAgentPackage(r,i);break;default:throw new Error(`unknown package action: ${e}`)}if(this.dispatch({type:"admin/packages/action/done"}),await this.refreshAdminAgentPackages(),e!=="delete"){const o=e==="promote"?{scope:"shared",...i?.owner?{owner:i.owner}:{}}:e==="demote"?{scope:"user",...i?.owner?{owner:i.owner}:{}}:i;await this.selectAdminPackage(r,o)}}catch(o){this.dispatch({type:"admin/packages/action/failed",error:o?.message||String(o)})}}}failAdminAddPackage(e){this.dispatch({type:"admin/packages/addDialog/failed",error:e})}async submitAdminUploadPackage(e,s){const n=this.getState().admin?.packages?.addDialog;if(!(!n?.open||n.submitting)){if(typeof this.transport.uploadAgentPackage!="function"){this.dispatch({type:"admin/packages/addDialog/failed",error:"Folder upload is not available on this deployment."});return}this.dispatch({type:"admin/packages/addDialog/submitting"});try{const r=await this.transport.uploadAgentPackage(e,s==="shared"?"shared":"user");this.dispatch({type:"admin/packages/addDialog/close"}),await this.refreshAdminAgentPackages(),r?.name&&await this.selectAdminPackage(r.name)}catch(r){const i=Array.isArray(r?.validation?.errors)?`
|
|
79
|
-
${r.validation.errors.map(o=>`[${o.code}] ${o.message}`).join(`
|
|
80
|
-
`)}`:"";this.dispatch({type:"admin/packages/addDialog/failed",error:`${r?.message||r}${i}`})}}}openAdminAddPackage(){this.dispatch({type:"admin/packages/addDialog/open"})}openAdminUpdatePackage(e,s="user"){const n=String(e||"").trim();n&&this.dispatch({type:"admin/packages/addDialog/open",updateName:n,scope:s})}closeAdminAddPackage(){this.dispatch({type:"admin/packages/addDialog/close"})}setAdminAddPackageField(e,s){this.dispatch({type:"admin/packages/addDialog/setField",field:e,value:s})}async submitAdminAddPackage(){const e=this.getState().admin?.packages?.addDialog;if(!e?.open||e.submitting)return;if(typeof this.transport.uploadAgentPackage!="function"){this.dispatch({type:"admin/packages/addDialog/failed",error:"Package upload is not available on this deployment."});return}const s=String(e.repoUrl||"").trim(),n=kl(s);if(n.error){this.dispatch({type:"admin/packages/addDialog/failed",error:n.error});return}this.dispatch({type:"admin/packages/addDialog/submitting"});try{let i=String(e.authToken||"").trim()||null,o="pat";!i&&n.kind==="ado"&&(this.dispatch({type:"admin/packages/addDialog/progress",message:"getting an Azure DevOps token for your account…"}),i=typeof this.transport.getRepoAccessToken=="function"?await this.transport.getRepoAccessToken("ado"):null,o="bearer");const{files:l}=await $u(s,{token:i,tokenKind:o,onProgress:d=>this.dispatch({type:"admin/packages/addDialog/progress",message:d})});if(e.updateName){const d=_u(l);if(d&&d!==e.updateName){this.dispatch({type:"admin/packages/addDialog/failed",error:`That folder builds "${d}", not "${e.updateName}". Use Add package to publish it as its own package.`});return}}this.dispatch({type:"admin/packages/addDialog/progress",message:`publishing ${l.length} file(s)…`});const c=await this.transport.uploadAgentPackage(l,e.scope==="shared"?"shared":"user");this.dispatch({type:"admin/packages/addDialog/close"}),await this.refreshAdminAgentPackages(),c?.name&&await this.selectAdminPackage(c.name)}catch(r){const i=Array.isArray(r?.validation?.errors)?`
|
|
81
|
-
${r.validation.errors.map(o=>`[${o.code}] ${o.message}`).join(`
|
|
82
|
-
`)}`:"";this.dispatch({type:"admin/packages/addDialog/failed",error:`${r?.message||r}${i}`})}}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,""),r=mt(s.draft||"",s.cursorIndex||0,n);this.setAdminGhcpKeyDraft(r.prompt,r.cursor)}deleteAdminGhcpKeyChar(){const e=this.getState().admin?.ghcpKey;if(!e?.editing)return;const s=Ct(e.draft||"",e.cursorIndex||0);this.setAdminGhcpKeyDraft(s.prompt,s.cursor)}moveAdminGhcpKeyCursor(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,ke(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 r=await this.transport.setSystemGitHubCopilotKey({key:n});this.dispatch({type:"admin/systemGhcpKey/saved",status:r})}else{const r=await this.transport.setCurrentUserGitHubCopilotKey({key:n});this.dispatch({type:"admin/ghcpKey/saved",profile:r})}}catch(r){this.dispatch({type:"admin/ghcpKey/saveFailed",error:r?.message||String(r)})}}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 openBudget({provider:e=void 0}={}){this.dispatch({type:"ui/budgetOpen",open:!0,...e===void 0?{}:{provider:e}}),await this.loadProviderTable();const s=this.getState().budget||{};s.selectedProvider&&await Promise.all([this.loadProviderSeries(s.selectedProvider,s.selectedScope||"*"),this.loadProviderSystemUsage(s.selectedProvider,s.selectedScope||"*")])}closeBudget(){this.dispatch({type:"ui/budgetOpen",open:!1})}setBudgetOverall(e){const s=this.getState().budget?.overall===!0;this.dispatch({type:"budget/overall",...typeof e=="boolean"?{overall:e}:{}});const n=this.getState().budget||{};if(!(n.overall===s||!n.selectedProvider))return this.loadProviderSeries(n.selectedProvider,n.selectedScope||"*")}async setBudgetRangeDays(e){const s=Number(e);if(!an.includes(s))return;const n=this.getState().budget?.rangeDays??Ee;this.dispatch({type:"budget/rangeDays",rangeDays:s});const r=this.getState().budget||{};s===n||!r.selectedProvider||await Promise.all([this.loadProviderSeries(r.selectedProvider,r.selectedScope||"*"),this.loadProviderSystemUsage(r.selectedProvider,r.selectedScope||"*")])}async selectBudgetProvider(e,s="*"){this.dispatch({type:"budget/selectProvider",provider:e,scope:s});const n=this.getState().budget||{};n.selectedProvider&&await Promise.all([this.loadProviderSeries(n.selectedProvider,n.selectedScope||"*"),this.loadProviderSystemUsage(n.selectedProvider,n.selectedScope||"*")])}async loadProviderTable(){if(!this._budgetReadable())return;this.dispatch({type:"budget/loading"});const[e,s]=await Promise.all([this._readBudgetPart(()=>this.transport.getProviderUsageGrid()),this._readBudgetPart(()=>this.transport.listPausedSessions())]);this._settleBudgetRead([["grid","the provider table",e,n=>n?.rows||[]],["paused","the paused sessions",s,n=>n?.sessions||[]]])}async refreshProviderTable(){await this.loadProviderTable();const e=this.getState().budget||{};e.selectedProvider&&await Promise.all([this.loadProviderSeries(e.selectedProvider,e.selectedScope||"*"),this.loadProviderSystemUsage(e.selectedProvider,e.selectedScope||"*")])}async loadProviderSeries(e,s="*"){const n=String(e??"").trim();if(!n||typeof this.transport.getProviderUsage!="function")return;const r=s&&s!=="*"?s:null,i=this.getState().budget?.overall===!0,o=this.getState().budget?.rangeDays??Ee;this.dispatch({type:"budget/series/loading",provider:n,scope:s,rangeDays:o});try{const l=await this.transport.getProviderUsage({days:o,provider:n,...r?{model:r}:{},chargeClass:"user",...i?{}:{mine:!0},dimension:"provider"});this.dispatch({type:"budget/series/loaded",provider:n,scope:s,rangeDays:o,days:Array.isArray(l?.daily)?l.daily:[]})}catch(l){this.dispatch({type:"budget/series/failed",provider:n,scope:s,rangeDays:o,error:Bs(l)})}}async loadProviderSystemUsage(e,s="*"){const n=this.getState().auth?.authorization?.role,r=n==="admin"||n==="anonymous"||this.getState().admin?.profile?.isAdmin===!0,i=String(e??"").trim();if(!r||!i||typeof this.transport.getProviderUsage!="function")return;const o=s&&s!=="*"?s:null,l=this.getState().budget?.rangeDays??Ee;this.dispatch({type:"budget/systemUsage/loading",provider:i,scope:s,rangeDays:l});try{const c=await this.transport.getProviderUsage({days:l,provider:i,...o?{model:o}:{},chargeClass:"system",dimension:"model",limit:100});this.dispatch({type:"budget/systemUsage/loaded",provider:i,scope:s,rangeDays:l,report:c})}catch(c){this.dispatch({type:"budget/systemUsage/failed",provider:i,scope:s,rangeDays:l,error:Bs(c)})}}async refreshBudgetPausesIfStale(e){if(typeof this.transport.listPausedSessions!="function")return;const s=this.getState();if(s.ui?.budgetOpen||!(Array.isArray(e)?e:[]).some(i=>i&&!i.isGroup&&i.status==="waiting"&&i.cronActive!==!0)&&(s.budget?.paused||[]).length===0)return;const r=Date.now();r-(this.budgetPauseReadAt||0)<6e4||(this.budgetPauseReadAt=r,await this.refreshPausedSessions({quiet:!0}).catch(()=>{}))}async refreshPausedSessions({quiet:e=!1}={}){if(typeof this.transport.listPausedSessions!="function"){if(e)return;this.dispatch({type:"budget/loadFailed",error:"Providers and budgets are not available on this deployment."});return}const s=await this._readBudgetPart(()=>this.transport.listPausedSessions());s.error&&e||this._settleBudgetRead([["paused","the paused sessions",s,n=>n?.sessions||[]]])}_budgetReadable(){return typeof this.transport.getProviderUsageGrid=="function"?!0:(this.dispatch({type:"budget/loadFailed",error:"Providers and budgets are not available on this deployment."}),!1)}async _readBudgetPart(e){try{return{value:await e(),error:null}}catch(s){return{value:null,error:Bs(s)}}}_settleBudgetRead(e){const s={},n=[];for(const[o,l,c,d]of e)c.error?n.push({label:l,error:c.error}):s[o]=d(c.value);if(Object.keys(s).length===0){this.dispatch({type:"budget/loadFailed",error:n[0]?.error||"The read failed."});return}if(this.dispatch({type:"budget/loaded",...s}),n.length===0)return;const r=n.map(o=>`${o.label} could not be read: ${o.error}`).join(" "),i=e.some(([o,,l])=>o==="grid"&&l.error);this.dispatch(i?{type:"budget/loadFailed",error:r}:{type:"budget/pausedFailed",error:r})}async _runBudgetChange(e){try{const s=await e();await this.loadProviderTable();const n=this.getState().budget||{};return n.selectedProvider&&await this.loadProviderSeries(n.selectedProvider,n.selectedScope||"*"),{ok:!0,error:null,code:null,result:s??null}}catch(s){const n=Bs(s);return this.dispatch({type:"ui/status",text:n}),await this.loadProviderTable().catch(()=>{}),{ok:!1,error:n,code:s?.code||null,result:null}}}_refuseBudgetChange(e){return this.dispatch({type:"ui/status",text:e}),{ok:!1,error:e,code:"UNSUPPORTED",result:null}}async createProvider({name:e,type:s,credentials:n,baseUrl:r=null,shared:i=!1}={}){const o=i?"createProvider":"createMyProvider";return typeof this.transport[o]!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport[o]({name:e,type:s,credentials:n,baseUrl:r}))}async deleteProvider(e,{shared:s=null}={}){const n=(this.getState().budget?.grid||[]).find(o=>o?.providerName===e&&o?.rowKind!=="model"),i=(s===null?n?.class==="shared":s===!0)?"deleteProvider":"deleteMyProvider";return typeof this.transport[i]!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport[i](e))}async setProviderLimit({provider:e,period:s,model:n=null,tokens:r}={}){return typeof this.transport.setProviderLimit!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setProviderLimit({name:e,period:s,model:n,tokens:r}))}async removeProviderLimit({provider:e,period:s,model:n=null}={}){return typeof this.transport.removeProviderLimit!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.removeProviderLimit({name:e,period:s,model:n}))}async setProviderAllowance({provider:e,pct:s}={}){return typeof this.transport.setProviderAllowance!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setProviderAllowance({name:e,pct:s}))}async setProviderHold({provider:e,untilUtc:s=null,release:n=!1}={}){return typeof this.transport.setProviderHold!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setProviderHold({name:e,untilUtc:s,release:n}))}async setClusterDefault(e){return typeof this.transport.setClusterDefault!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setClusterDefault(e))}async setMyDefault(e){return typeof this.transport.setMyDefault!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setMyDefault(e))}async ensureExecutionHistory(e,{force:s=!1}={}){if(!e||typeof this.transport.getExecutionHistory!="function")return null;const n=this.getState().executionHistory?.bySessionId?.[e]||null,r=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&r-n.fetchedAt<15e3)return n;this.dispatch({type:"executionHistory/loading",sessionId:e});try{const i=await this.transport.getExecutionHistory(e);this.dispatch({type:"executionHistory/loaded",sessionId:e,events:i||[],fetchedAt:Date.now()})}catch(i){console.error("[executionHistory] fetch error:",i?.message||i),this.dispatch({type:"executionHistory/error",sessionId:e,error:i?.message||String(i),fetchedAt:Date.now()})}return this.getState().executionHistory?.bySessionId?.[e]||null}async ensureFilesForScope(e=Ye(this.getState()),{force:s=!1}={}){const n=pn(this.getState(),e);return n.length===0?e==="allSessions"?[]:null:e==="allSessions"||n.length>1?Promise.allSettled(n.map(r=>this.ensureFilesForSession(r,{force:s}))):this.ensureFilesForSession(n[0],{force:s})}async ensureSelectedFilePreview(){const e=St(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 r=Date.now()-(Number(n?.fetchedAt)||0);if(!s&&n?.loaded&&r<wg)return n.selectedFilename&&await this.ensureFilePreview(e,n.selectedFilename).catch(()=>{}),n;this.dispatch({type:"files/sessionLoading",sessionId:e});try{const i=await this.transport.listArtifacts(e),o=Date.now();this.dispatch({type:"files/sessionLoaded",sessionId:e,entries:i,fetchedAt:o});const l=this.getState().files.bySessionId[e];return l?.selectedFilename&&await this.ensureFilePreview(e,l.selectedFilename).catch(()=>{}),l}catch(i){return this.dispatch({type:"files/sessionError",sessionId:e,error:i?.message||String(i)}),null}}async ensureFilePreview(e,s,{force:n=!1}={}){if(!e||!s||typeof this.transport.downloadArtifact!="function")return null;const r=this.getState().files.bySessionId[e],i=r?.previews?.[s];let o=gp(r?.entries,s);if(!n&&i?.loading||!n&&i&&(i.content!==void 0||i.error))return i;if(!o&&typeof this.transport.getArtifactMetadata=="function")try{o=await this.transport.getArtifactMetadata(e,s)}catch{o=null}this.dispatch({type:"files/previewLoading",sessionId:e,filename:s});try{const l=o?.isBinary===!0?la(s,"",o.contentType||"",o):la(s,await this.transport.downloadArtifact(e,s),o?.contentType||"",o);return this.dispatch({type:"files/previewLoaded",sessionId:e,filename:s,...l}),l}catch(l){return this.dispatch({type:"files/previewError",sessionId:e,filename:s,error:l?.message||String(l)}),null}}buildArtifactPickerItems(e=[],s=[]){const n=(e||[]).map(r=>({id:`${r.sessionId}/${r.filename}`,kind:"artifact",sessionId:r.sessionId,filename:r.filename}));for(const r of s||[]){const i=String(r?.href||"").trim();i&&n.push({id:`url:${i}`,kind:"url",href:i,text:String(r?.text||i).trim()||i})}return(e||[]).length>1&&n.push({id:"__downloadAll__",kind:"downloadAll"}),n}buildArtifactPickerModal({artifactLinks:e,httpLinks:s,previousFocus:n,selectedId:r}={}){const i=this.buildArtifactPickerItems(e,s);if(i.length===0)return null;const o=i.findIndex(l=>l.id===r);return{type:"artifactPicker",title:"Linked Items",previousFocus:n,artifactLinks:e,httpLinks:s,items:i,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 r=this.getState().sessions.activeSessionId;return(e===r||this.getState().ui.inspectorTab==="files")&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),e===r&&(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=St(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||Ye(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:r}=s,i=Ye(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?.[r]?.localPath||null;if(o||(this.dispatch({type:"ui/status",text:`Downloading ${r} to open it...`}),o=(await this.saveArtifactDownload(n,r))?.localPath||null),!o){this.dispatch({type:"ui/status",text:`Open failed: could not save ${r} locally`});return}try{await this.transport.openPathInDefaultApp(o),this.dispatch({type:"ui/status",text:i==="allSessions"?`Opened ${Oe(n)} ${r} in the default app`:`Opened ${r} in the default app`})}catch(l){this.dispatch({type:"ui/status",text:`Open failed: ${l?.message||String(l)}`})}}async downloadSelectedArtifact(){const e=St(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=Mt(this.getState()),n=this.getState().files.markedIds||[],r=n.length>0?n[n.length-1]:this.getState().files.selectedArtifactId,i=s.findIndex(p=>p.id===r),o=s.findIndex(p=>p.id===e.id);if(o<0)return;if(i<0){this.dispatch({type:"files/toggleMark",artifactId:e.id});return}const[l,c]=i<=o?[i,o]:[o,i],d=s.slice(l,c+1).map(p=>p.id);this.dispatch({type:"files/setMarks",artifactIds:[...new Set([...n,...d])]})}clearArtifactMarks(){this.dispatch({type:"files/clearMarks"})}async deleteMarkedArtifacts({confirmed:e=!1}={}){const s=this.getState(),n=s.files.markedIds||[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No artifacts marked"}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifacts",message:`Delete ${n.length} artifact${n.length===1?"":"s"}? This action cannot be undone.`,confirmLabel:`Delete ${n.length}`,action:"deleteMarkedArtifacts",previousFocus:s.ui.focusRegion}}),!1;const r=new Set;let i=0;const o=[];for(const l of n){const c=String(l).indexOf("/");if(c<=0)continue;const d=l.slice(0,c),p=l.slice(c+1);try{await this.transport.deleteArtifact(d,p),this.dispatch({type:"files/deleted",sessionId:d,filename:p}),r.add(d),i+=1}catch(u){o.push(`${p}: ${u?.message||String(u)}`)}}for(const l of r)await this.ensureFilesForSession(l,{force:!0}).catch(()=>null);return this.dispatch({type:"files/clearMarks"}),this.dispatch({type:"ui/status",text:o.length>0?`Deleted ${i}, ${o.length} failed — ${o[0]}`:`Deleted ${i} artifact${i===1?"":"s"}`}),o.length===0}async deleteSelectedArtifact({confirmed:e=!1}={}){const s=this.getState(),n=St(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const r=Ye(s),i=r==="allSessions"?`${Oe(n.sessionId)} ${n.filename}`:n.filename;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifact",message:`Delete artifact "${i}"? 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=St(this.getState());return o?.sessionId&&o?.filename&&await this.ensureFilePreview(o.sessionId,o.filename).catch(()=>null),this.dispatch({type:"ui/status",text:r==="allSessions"?`Deleted ${Oe(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=_f(e),r=Lf(e);if(n.length===0&&r.length===0){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}const i=this.getState().files.bySessionId[s]?.selectedFilename||null,o=i?`${s}/${i}`:null,l=this.buildArtifactPickerModal({artifactLinks:n,httpLinks:r,previousFocus:e.ui.focusRegion,selectedId:o});if(!l){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:l}),this.dispatch({type:"ui/status",text:"Select a linked item and press Enter to open or download it"})}async downloadArtifactModalSelection(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="url"){if(typeof this.transport.openUrlInDefaultBrowser!="function"){this.dispatch({type:"ui/status",text:"Opening URLs is not supported by this transport"});return}this.dispatch({type:"ui/status",text:`Opening ${s.href}...`}),await this.transport.openUrlInDefaultBrowser(s.href),this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Opened ${s.href}`});return}if(s.kind==="downloadAll"){const r=(e.items||[]).filter(o=>o.kind!=="artifact"?!1:!this.getState().files.bySessionId[o.sessionId]?.downloads?.[o.filename]?.localPath);if(r.length===0){this.dispatch({type:"ui/status",text:"All artifacts already downloaded"});return}this.dispatch({type:"ui/status",text:`Downloading ${r.length} artifacts...`});let i=0;for(const o of r)(await this.saveArtifactDownload(o.sessionId,o.filename))?.localPath&&(i+=1);this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${i}/${r.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=Ye(this.getState());await this.ensureFilesForScope(s);const n=Mt(this.getState());if(n.length===0)return;const r=St(this.getState())||n[0],i=Math.max(0,n.findIndex(c=>c.id===r?.id)),o=Math.max(0,Math.min(n.length-1,i+e)),l=n[o];!l?.sessionId||!l?.filename||(s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:l.id}):this.dispatch({type:"files/select",sessionId:l.sessionId,filename:l.filename}),await this.ensureFilePreview(l.sessionId,l.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${Oe(l.sessionId)} ${l.filename}`:`Previewing ${l.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;this.dispatch({type:"files/previewOrigin",origin:"list"});const s=Ye(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 ${Oe(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],r=!!e.files.fullscreen;if(!r&&!n?.selectedFilename){this.dispatch({type:"ui/status",text:"Select a file before entering fullscreen"});return}const i=!r;this.dispatch({type:"files/fullscreen",fullscreen:i}),this.dispatch({type:"ui/status",text:i?`Fullscreen files browser: ${n?.selectedFilename||""}`:"Closed fullscreen files browser"})}toggleFocusedPaneFullscreen(){const e=this.getState(),s=e.ui.focusRegion,n=e.ui.fullscreenPane||null,r=s===$.PROMPT?n:s;if(!Fh.has(r)||r===$.INSPECTOR&&e.ui.inspectorTab==="files")return;const i=n===r?null:r;this.dispatch({type:"ui/fullscreenPane",fullscreenPane:i}),this.dispatch({type:"ui/status",text:i?`Fullscreen ${r} pane`:`Closed fullscreen ${r} pane`}),!i&&s===$.PROMPT&&this.setFocus(r)}openFilesFilter(){const e=Ye(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(r=>{this.dispatch({type:"sessions/navigationIntentFailed",sessionId:s,errorKind:tr(r)})});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(()=>{}),this.dispatch({type:"canvas/snapshotInvalidate",sessionId:e}),this.ensureCanvasSnapshot(e).catch(()=>{})}reconcileOutboxAgainstEvent(e,s){if(!(!e||!s)){if(s.eventType==="user.message"){const n=s?.data?.content,r=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(i=>typeof i=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];if(r.length>0)for(const i of r)this.acknowledgeOutboxPrompt(e,n,i);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(r=>typeof r=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];this.acknowledgeCancelledOutboxPrompt(e,n)}}}maybeRevealPresentedArtifact(e,s){const n=String(s?.data?.filename||"").trim();if(!n||e!==this.getState().sessions.activeSessionId)return!1;const r=s?.createdAt?Date.parse(s.createdAt):Number.NaN;if(Number.isFinite(r)&&Date.now()-r>nr)return!1;const i=s?.data?.fullscreen===!0;return this.revealArtifact(e,n,i?{fullscreen:!0}:{pane:!0}).catch(()=>{}),!0}applyCanvasUpdate(e,s){const n=Number(s?.data?.rev);if(!e||!Number.isFinite(n)||n<=0)return!1;const r=Number(s?.data?.slot),i=Number.isInteger(r)&&r>=1&&r<=5?r:1;this.dispatch({type:"canvas/updated",sessionId:e,slot:i,...typeof s?.data?.name=="string"?{name:s.data.name}:{},rev:n,note:typeof s?.data?.note=="string"?s.data.note:"",sizeBytes:s?.data?.sizeBytes,responseContract:s?.data?.responseContract});const o=this.getState();if(e!==o.sessions.activeSessionId||o.canvas.prefs[Qe(e,i)]?.optedOut)return!0;const l=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(l)&&Date.now()-l>nr||this.dispatch({type:"canvas/flip",sessionId:e,slot:i}),!0}submitCanvasAction(e,s){if(!e)return Promise.resolve({ok:!1,reason:"no session"});const n=this.getState().auth?.principal||null,r=this.getState().sessions.byId[e]?.owner||null;if(n&&r&&(String(r.provider||"")!==String(n.provider||"")||String(r.subject||"")!==String(n.subject||"")))return Promise.resolve({ok:!1,reason:"only the session's creator can use canvas controls"});const i=this.getState().canvas.bySessionId[e]?.responseContract||null,o=Vd(i,s);if(!o.ok)return Promise.resolve(o);this.canvasActionLimiters||(this.canvasActionLimiters=new Map);let l=this.canvasActionLimiters.get(e);if(l||(l=Qd(),this.canvasActionLimiters.set(e,l)),!l())return Promise.resolve({ok:!1,reason:"rate limited"});const c=Yd(o.action,o.data);return this.transport.sendMessage(e,c,{enqueueOnly:!0}).then(()=>(this.syncSessionEvents(e).catch(()=>{}),{ok:!0,action:o.action})).catch(d=>({ok:!1,reason:d?.message||String(d)}))}async ensureCanvasSnapshot(e){if(e&&!this.getState().canvas.bySessionId[e]?.snapshotLoaded){if(typeof this.transport.getSessionEventsBefore!="function"){this.dispatch({type:"canvas/snapshot",sessionId:e,rev:0});return}try{const s=await this.transport.getSessionEventsBefore(e,Number.MAX_SAFE_INTEGER,30,["session.canvas_updated"]),n=new Map;for(const i of Array.isArray(s)?s:[]){const o=Number(i?.data?.slot)||1,l=Number(i?.data?.rev)||0;(!n.has(o)||l>(Number(n.get(o)?.data?.rev)||0))&&n.set(o,i)}n.has(1)||n.set(1,null);let r=!1;for(const[i,o]of n){const l=Number(o?.data?.rev)||0;l>0&&(r=!0),this.dispatch({type:"canvas/snapshot",sessionId:e,slot:i,rev:l,...typeof o?.data?.name=="string"?{name:o.data.name}:{},note:typeof o?.data?.note=="string"?o.data.note:"",sizeBytes:o?.data?.sizeBytes,responseContract:o?.data?.responseContract})}if(r){const i=await this.transport.getSessionEventsBefore(e,Number.MAX_SAFE_INTEGER,30,["session.canvas_data"]).catch(()=>[]),o=new Map;for(const l of Array.isArray(i)?i:[]){const c=Number(l?.data?.slot)||1,d=Number(l?.data?.dataRev)||0;(!o.has(c)||d>(Number(o.get(c)?.data?.dataRev)||0))&&o.set(c,l)}for(const[l,c]of o)c?.data?.dataRev&&this.dispatch({type:"canvas/data",sessionId:e,slot:l,dataRev:Number(c.data.dataRev),payload:c.data.payload,note:typeof c.data.note=="string"?c.data.note:""})}}catch{}}}applyCanvasPresented(e,s){const n=Number(s?.data?.slot),r=Number.isInteger(n)&&n>=1&&n<=5?n:1;if(!e)return!1;const i=this.getState();if(e!==i.sessions.activeSessionId||i.canvas.prefs[Qe(e,r)]?.optedOut)return!1;const o=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(o)&&Date.now()-o>nr?!1:(this.dispatch({type:"canvas/flip",sessionId:e,slot:r}),!0)}applyCanvasDataEvent(e,s){this.dispatch({type:"canvas/data",sessionId:e,slot:Number(s?.data?.slot)||1,dataRev:Number(s?.data?.dataRev),payload:s?.data?.payload,...Number.isFinite(Number(s?.data?.planeSeq))?{planeSeq:Number(s.data.planeSeq)}:{},...s?.data?.patch&&typeof s.data.patch=="object"?{patch:s.data.patch}:{},note:typeof s?.data?.note=="string"?s.data.note:""})}mergeSessionEvent(e,s){if(!e||!s)return!1;if(s.transient===!0)return s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(e,s),s.eventType==="session.canvas_plane_released"&&this.dispatch({type:"canvas/planeReleased",sessionId:e}),!1;const r=this.getState().history.bySessionId.get(e)||{chat:[],activity:[],lastSeq:0};if(s.seq<=(r.lastSeq||0))return!1;this.dispatch({type:"history/set",sessionId:e,history:Zi(r,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}}}),s.eventType==="session.artifact_presented"&&this.maybeRevealPresentedArtifact(e,s),s.eventType==="session.canvas_updated"&&this.applyCanvasUpdate(e,s),s.eventType==="session.canvas_presented"&&this.applyCanvasPresented(e,s),s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(e,s),this.reconcileOutboxAgainstEvent(e,s);const i=Wh(s),o=this.getState().sessions.byId[e]||{sessionId:e},l=Ya(o.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(i||l)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...i||{},...l?{contextUsage:l}:{}}}),this.maybeFlushQueuedOutbox(e,this.getState().sessions.byId[e]||o),this.scheduleSessionDetailSync(e),!0}async syncSessionEvents(e){if(!e||typeof this.transport.getSessionEvents!="function")return;const s=this.getState().history.bySessionId.get(e);if(!s?.events){await this.ensureSessionHistory(e,{force:!0});return}const n=Number(s.lastSeq||0);let r=null;try{r=await this.transport.getSessionEvents(e,n,200)}catch(i){if(bs(i)){this.handleSessionGone(e);return}throw i}if(!(!Array.isArray(r)||r.length===0))for(const i of r)this.mergeSessionEvent(e,i)}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||ys(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||ys(e))return;let s=null;try{s=await this.transport.getSession(e)}catch(i){if(bs(i)){this.handleSessionGone(e);return}throw i}if(!s)return;const n=this.getState().sessions.byId[e]||null,r=Yh(n,s);(r||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:r||{sessionId:e}}),this.maybeFlushQueuedOutbox(e,s)}async createSession(e={}){try{const s=this.applyActiveGroupDefault(e),n=await this.transport.createSession(s);return await this.placeCreatedSessionInGroup(n,s.groupId??null),await this.refreshSessions(),await this.loadSession(n.sessionId),this.revealCreatedSession(),this.dispatch({type:"ui/status",text:`Created session ${n.sessionId.slice(0,8)}`}),n}catch(s){return this.dispatch({type:"ui/status",text:s?.message||String(s)||"Failed to create session"}),null}}async createSessionForAgent(e,s={}){if(typeof this.transport.createSessionForAgent!="function")throw new Error("Named-agent session creation is not supported by this transport");try{const n=this.applyActiveGroupDefault(s),r=await this.transport.createSessionForAgent(e,n);return await this.placeCreatedSessionInGroup(r,n.groupId??null),await this.refreshSessions(),await this.loadSession(r.sessionId),this.revealCreatedSession(),this.dispatch({type:"ui/status",text:`Created ${Jo(e,s.title)} session ${r.sessionId.slice(0,8)}`}),r}catch(n){return this.dispatch({type:"ui/status",text:n?.message||String(n)||"Failed to create session"}),null}}async placeCreatedSessionInGroup(e,s){!s||!e?.sessionId||typeof this.transport.placeSessionsInGroup=="function"&&(e.viewerGroupId??null)!==s&&await this.transport.placeSessionsInGroup([e.sessionId],s).catch(()=>{})}getMovableGroupSessionSelection(){const e=this.getState(),s=e.sessions.activeSessionId&&!e.sessions.listDeselected?[e.sessions.activeSessionId]:[];return(Array.isArray(e.sessions.selectedIds)&&e.sessions.selectedIds.length>0?e.sessions.selectedIds:s).map(r=>e.sessions.byId[r]).filter(r=>r&&!r.isSystem&&!r.isGroup&&!r.parentSessionId)}async openMoveToGroupModal(){const e=this.getState(),s=this.getMovableGroupSessionSelection();if(s.length===0){const c=e.sessions.activeSessionId?e.sessions.byId[e.sessions.activeSessionId]:null;return c?.isGroup&&c.groupId?this.openRenameGroupModal(c):this.openCreateEmptyGroupModal()}if(typeof this.transport.listSessionGroups!="function")return this.dispatch({type:"ui/status",text:"Session groups are not supported by this transport"}),null;const n=await this.transport.listSessionGroups().catch(()=>[]),r=s.map(c=>c.sessionId),i=s.length===1&&s[0].groupId||null,o=[{id:"__no_group__",kind:"noGroup",label:"[No Group]",description:"Remove the selected session(s) from any group.",groupId:null,memberCount:0},{id:"__new_group__",kind:"newGroup",label:"[New Group]",description:"Create a new group, then move the selected session(s) into it.",groupId:null,memberCount:0},...(Array.isArray(n)?n:[]).map(c=>({id:c.groupId,kind:"group",label:c.title||c.groupId,description:c.description||"Move selected session(s) into this group.",groupId:c.groupId,memberCount:c.memberCount??0}))],l=i?Math.max(0,o.findIndex(c=>c.groupId===i)):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:r,sessionLabels:s.map(c=>c.title||c.sessionId.slice(0,8)),selectedIndex:l>=0?l:0,items:o}}),this.dispatch({type:"ui/status",text:"Choose a group, [New Group], or [No Group]"}),o}async createSessionGroupFromSelection(){return this.openMoveToGroupModal()}openRenameGroupModal(e){if(typeof this.transport.updateSessionGroup!="function")return this.dispatch({type:"ui/status",text:"Group rename is not supported by this transport"}),null;const s=this.getState(),n=String(e.title||"").trim();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",mode:"rename",groupId:e.groupId,title:"Rename Group",previousFocus:s.ui.focusRegion,sessionIds:[],value:n,cursorIndex:n.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Edit the group name and press Enter"}),null}async openCreateEmptyGroupModal(){if(typeof this.transport.createSessionGroup!="function")return this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"}),null;const e=this.getState();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.ui.focusRegion,sessionIds:[],value:"",cursorIndex:0,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"}),null}async moveSessionsToGroup(e,s,{statusTitle:n=null}={}){const r=Array.from(new Set((Array.isArray(s)?s:[]).map(u=>String(u||"").trim()).filter(Boolean)));if(r.length===0)return this.dispatch({type:"ui/status",text:"No sessions selected to move"}),null;let i=null;if(typeof this.transport.placeSessionsInGroup=="function")i=await this.transport.placeSessionsInGroup(r,e??null);else if(typeof this.transport.moveSessionsToGroup=="function")await this.transport.moveSessionsToGroup(e??null,r);else if(e&&typeof this.transport.assignSessionsToGroup=="function")await this.transport.assignSessionsToGroup(e,r);else return this.dispatch({type:"ui/status",text:"Moving sessions between groups is not supported by this transport"}),null;const o=Array.isArray(i)?i.filter(Boolean):null,l=o?o.filter(u=>u.placed!==!0):[],c=o?o.filter(u=>u.placed===!0).length:r.length;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&c>0&&await this.loadSession(`group:${e}`).catch(()=>{});const d=e?`group ${n||e}`:"No Group",p=l.length>0?` · skipped ${l.length} (${Bh(l)})`:"";return this.dispatch({type:"ui/status",text:c>0?`Moved ${c} session${c===1?"":"s"} to ${d}${p}`:`No sessions moved to ${d}${p}`}),c>0}async confirmSessionGroupPickerModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="newGroup"){const r=(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:r,cursorIndex:r.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(r){this.dispatch({type:"ui/status",text:`Move failed: ${r?.message||String(r)}`})}}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 r=Ut(e,n.maxLength||80),i=ke(r,s);this.updateSessionGroupNameModal({value:r,cursorIndex:i})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=mt(s.value||"",s.cursorIndex||0,Ut(e,s.maxLength||80));this.setSessionGroupNameValue(n.prompt,n.cursor)}deleteSessionGroupNameChar(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=Ct(e.value||"",e.cursorIndex||0);this.setSessionGroupNameValue(s.prompt,s.cursor)}moveSessionGroupNameCursor(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",ke(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(e.mode==="rename"&&e.groupId){const r=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.updateSessionGroup(e.groupId,{title:s}),this.dispatch({type:"ui/status",text:`Renamed group to "${s}"`}),await this.refreshSessions().catch(()=>{})}catch(i){this.dispatch({type:"ui/status",text:`Rename failed: ${i?.message||String(i)}`})}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 r=await this.transport.createSessionGroup({title:s,description:`${(e.sessionIds||[]).length} grouped session${(e.sessionIds||[]).length===1?"":"s"}`,sessionIds:e.sessionIds||[]}),i=e.sessionIds||[];i.length===0?(this.dispatch({type:"ui/status",text:`Created group "${r.title||s}"`}),await this.refreshSessions().catch(()=>{})):await this.moveSessionsToGroup(r.groupId,i,{statusTitle:r.title||s})}catch(r){this.dispatch({type:"ui/status",text:`Move failed: ${r?.message||String(r)}`})}}applyActiveGroupDefault(e={}){if(e&&Object.prototype.hasOwnProperty.call(e,"groupId"))return e;const s=this.getState(),n=s.sessions?.activeSessionId?s.sessions.byId[s.sessions.activeSessionId]:null;if(!n?.isGroup)return e;const r=n.groupId||Ws(n.sessionId);return r?{...e,groupId:r}:e}getActiveSession(e=this.getState()){const s=e.sessions?.activeSessionId;return s&&e.sessions.byId[s]||null}async openSessionAgentPicker(e={},s=null){const n=s??this.getState().ui.focusRegion,r=()=>{this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n)};let i=[];try{i=typeof this.transport.listCreatableAgents=="function"?await this.transport.listCreatableAgents():[]}catch(m){r(),this.dispatch({type:"ui/status",text:`Could not load agents: ${m?.message||m}`});return}const l=(typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0;if(!Array.isArray(i)||i.length===0){if(r(),!l){this.dispatch({type:"ui/status",text:"No user-creatable agents are available for this app"});return}await this.createSession(e);return}const c=[];for(const m of i){const h=String(m?.name||"").trim();h&&c.push({id:h,kind:"agent",agentName:h,title:Jo(h,m?.title),description:String(m?.description||"").trim(),tools:Array.isArray(m?.tools)?m.tools.filter(Boolean):[],splash:typeof m?.splash=="string"&&m.splash.trim()?m.splash:null,splashMobile:typeof m?.splashMobile=="string"&&m.splashMobile.trim()?m.splashMobile:null,initialPrompt:typeof m?.initialPrompt=="string"&&m.initialPrompt.trim()?m.initialPrompt:null,group:m?.source==="package"&&m?.scope==="user"&&m?.mine!==!1?"mine":"shared",packageName:m?.packageName||null,packageTitle:m?.packageTitle||null,packageSemver:m?.packageSemver||null,packageScope:m?.scope||null,ownerLabel:m?.ownerLabel||null,startedBy:Array.isArray(m?.startedBy)?m.startedBy.filter(Boolean):[],supportsDirectStart:typeof m?.supportsDirectStart=="boolean"?m.supportsDirectStart:void 0,builtin:m?.source!=="package"})}const d=[...c.filter(m=>m.group==="shared"),...c.filter(m=>m.group==="mine")],p=l?{id:"__generic__",kind:"generic",group:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,splashMobile:null,initialPrompt:null,supportsDirectStart:!0}:null,u=[xs,vc,wc,...new Set(d.filter(m=>!m.builtin).map(m=>Ec(m)))],f=ta(d,u,p);this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",catalog:d,genericItem:p,collapsed:u,items:f,selectedIndex:tg(f),previousFocus:n,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select an agent and press Enter"})}async openNewSessionFlow(e={}){if((typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0){await this.createSession(e);return}if(typeof this.transport.listModels=="function"){await this.openModelPicker(e);return}await this.openSessionAgentPicker(e)}async openReasoningEffortPicker(e,s={},n=null){const r=n??this.getState().ui.focusRegion,i=qs(e?.supportedReasoningEfforts),o=s?.reasoningEffort||Vo(e);if(!i.length||!o){await this.openContextTierPicker(e,s,r);return}const l=i.map(d=>({id:d,effort:d,label:d,isDefault:o===d})),c=Math.max(0,l.findIndex(d=>d.id===o));this.dispatch({type:"ui/modal",modal:{type:"reasoningEffortPicker",title:s?.mode==="switchModel"?`Switch reasoning for ${e?.modelName||e?.qualifiedName||"model"}`:`Reasoning effort for ${e?.modelName||e?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:r,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a reasoning effort and press Enter"})}async openContextTierPicker(e,s={},n=null){const r=n??this.getState().ui.focusRegion,i=Ks(e?.supportedContextTiers),o=s?.contextTier||jh(e);if(!i.length||!o){if(s?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r),await this.switchSessionModel({...s,model:e?.id});return}await this.openSessionAgentPicker(s,r);return}const l=i.map(d=>({id:d,tier:d,tokenLimit:e?.contextWindowSizes?.[d]||null,label:zh(d,e?.contextWindowSizes?.[d]),isDefault:o===d})),c=Math.max(0,l.findIndex(d=>d.id===o));this.dispatch({type:"ui/modal",modal:{type:"contextTierPicker",title:`Context window for ${e?.modelName||e?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:r,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=await this._resolveProviderNamespace(),r=n?.error?{refusal:n.error}:n?this._buildProviderPickerGroups(n,s,e):await this._buildCatalogPickerGroups(s,e);if(r.refusal){this.dispatch({type:"ui/status",text:r.refusal});return}const{items:i,groups:o,selectedIndex:l}=r;this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:e?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:i,groups:o,selectedIndex:l,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async _resolveProviderNamespace(){if(typeof this.transport.listProviders!="function")return null;try{const[e,s,n]=await Promise.all([this.transport.listProviders(),typeof this.transport.getProviderStatus=="function"?this.transport.getProviderStatus().catch(()=>null):null,typeof this.transport.getDefaults=="function"?this.transport.getDefaults().catch(()=>null):null]),r=Array.isArray(e?.providers)?e.providers:null;return r?{providers:r,status:Array.isArray(s?.providers)?s.providers:[],statusKnown:Array.isArray(s?.providers),defaults:n||null}:{error:"Runtime provider availability could not be verified. Refresh and try again."}}catch{return{error:"Runtime provider availability could not be verified. Refresh and try again."}}}_buildProviderPickerGroups(e,s,n){const r=e.providers.filter(f=>f.usableByMe!==!1);if(r.length===0)return{refusal:"No provider can pay for a session yet — add one of your own, or ask an admin for a shared one."};const i=new Map;for(const f of s){const m=f?.providerId;m&&(i.has(m)||i.set(m,[]),i.get(m).push(f))}const o=new Map(e.status.map(f=>[f.name,f])),l=Date.now(),c=[...r].sort((f,m)=>{const h=g=>g.isMyDefault===!0?0:g.isClusterDefault===!0?1:g.class==="personal"?2:3;return h(f)-h(m)||String(f.name).localeCompare(String(m.name))}),d=n?.model||e.defaults?.mine?.model||e.defaults?.cluster?.model||(typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0),p=[],u=c.map(f=>{const m=Ig(f,o.get(f.name)||null,l),h=f.hasCredential===!1?`${f.name} has no credential`:null;return{providerId:f.name,providerType:f.typeId,providerClass:f.class,isClusterDefault:f.isClusterDefault===!0,isMyDefault:f.isMyDefault===!0,hasCredential:f.hasCredential!==!1,budgetState:m.state,budgetNote:m.text,models:(i.get(f.name)||i.get(f.typeId)||[]).map(g=>{const b=g.providerId===f.name&&g.qualifiedName?g.qualifiedName:`${f.name}:${g.modelName}`,y=h||(g.credentialAvailable===!1?`${f.name} has no usable credential or endpoint`:null),v={id:b,qualifiedName:b,modelName:g.modelName||b,providerId:f.name,providerType:f.typeId,providerClass:f.class,description:g.description||"",cost:g.cost||null,supportedReasoningEfforts:qs(g.supportedReasoningEfforts),defaultReasoningEffort:g.defaultReasoningEffort||null,supportedContextTiers:Ks(g.supportedContextTiers),defaultContextTier:g.defaultContextTier||null,contextWindowSizes:g.contextWindowSizes||null,isDefault:d===b,budgetState:m.state,budgetNote:m.text,disabledReason:y,disabled:!!y};return p.push(v),v})}}).filter(f=>f.models.length>0);return p.length===0?{refusal:"No provider in your namespace offers a model to run."}:{items:p,groups:u,selectedIndex:Ko(p,d)}}async _buildCatalogPickerGroups(e,s){const n=typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0,r=typeof this.transport.getModelsByProvider=="function"?this.transport.getModelsByProvider():Uh(e),i=await this._resolveGhcpUserKeySet(),o=[],l=r.map(c=>({providerId:c.providerId,providerType:c.type||c.providerType,models:(c.models||[]).map(d=>{const p=d.providerType||c.type||c.providerType,u=p==="github"&&d.credentialAvailable===!1&&i===!1,f={id:d.qualifiedName,qualifiedName:d.qualifiedName,modelName:d.modelName||d.qualifiedName,providerId:d.providerId||c.providerId,providerType:p,description:d.description||"",cost:d.cost||null,supportedReasoningEfforts:qs(d.supportedReasoningEfforts),defaultReasoningEffort:d.defaultReasoningEffort||null,supportedContextTiers:Ks(d.supportedContextTiers),defaultContextTier:d.defaultContextTier||null,contextWindowSizes:d.contextWindowSizes||null,isDefault:n===d.qualifiedName,ghcpKeyMissing:u,disabledReason:u?"needs GitHub key":null,disabled:u};return o.push(f),f})})).filter(c=>c.models.length>0);return{items:o,groups:l,selectedIndex:Ko(o,s?.model||n)}}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,r=n&&s.sessions.byId[n]||null;if(!r||r.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:r.model||void 0,reasoningEffort:r.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 r=e.reasoningEffort?`${n}:${e.reasoningEffort}`:n,i=e.contextTier?` · ${yc[e.contextTier]||e.contextTier}`:"";this.dispatch({type:"ui/status",text:`Next turn will use ${r}${i}`}),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=fp().map(r=>({id:r.id,label:r.label,description:r.description,group:r.group,page:r.page,terminal:r.terminal,tui:r.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(r=>r.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 (${Oe(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 r=String(e||"").replace(/\r?\n/g,""),i=ke(r,s);this.updateArtifactUploadModal({value:r,cursorIndex:i})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=mt(s.value||"",s.cursorIndex||0,String(e||"").replace(/\r?\n/g,""));this.setArtifactUploadValue(n.prompt,n.cursor)}deleteArtifactUploadChar(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=Ct(e.value||"",e.cursorIndex||0);this.setArtifactUploadValue(s.prompt,s.cursor)}moveArtifactUploadCursor(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",ke(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:r=!1,pane:i=!1}={}){const o=e||this.getState().sessions.activeSessionId,l=String(s||"").trim();if(!o||!l)return!1;if(this.dispatch({type:"files/previewOrigin",origin:"chat",restoreArtifactId:this.getState().files.selectedArtifactId||null}),this.getState().sessions.activeSessionId!==o&&await this.loadSession(o).catch(()=>null),i||this.dispatch({type:"ui/inspectorTab",inspectorTab:"files"}),i){const c=!!this.getCurrentLayout()?.rightHidden;c&&this.expandRightColumn(),this.dispatch({type:"files/pane",open:!0,restoresToHidden:c})}else this.setFocus("inspector");return await this.ensureFilesForSession(o,{force:n}).catch(()=>null),this.dispatch({type:"files/select",sessionId:o,filename:l}),await this.ensureFilePreview(o,l,{force:n}).catch(()=>null),r&&this.dispatch({type:"files/fullscreen",fullscreen:!0}),!0}async closeArtifactPane(){const e=this.getState().files.paneRestoresToHidden;return this.dispatch({type:"files/pane",open:!1}),this.dispatch({type:"files/fullscreen",fullscreen:!1}),this.dispatch({type:"files/previewOrigin",origin:null}),e&&this.collapseRightColumn(),this.dispatch({type:"ui/focus",focusRegion:$.CHAT}),{collapsedRightColumn:!!e}}expandRightColumn(){this.dispatch({type:"ui/paneAdjust",paneAdjust:0});const e=this.getCurrentLayout({paneAdjust:0}),s=this.getState().ui.focusRegion,n=nt(s,e);n!==s&&this.setFocus(n)}collapseRightColumn(){const s=(this.getState().ui.layout||{}).viewportWidth??120,n=Math.floor(s*bl),r=s-zs-n;this.dispatch({type:"ui/paneAdjust",paneAdjust:r});const i=this.getCurrentLayout({paneAdjust:r}),o=this.getState().ui.focusRegion,l=nt(o,i);l!==o&&this.setFocus(l)}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($.INSPECTOR);return}const n=e.files.restoreArtifactId;if(n){const r=String(n).indexOf("/");r>0&&this.dispatch({type:"files/select",sessionId:n.slice(0,r),filename:n.slice(r+1)})}else this.dispatch({type:"files/select",sessionId:null,filename:null});this.dispatch({type:"files/previewOrigin",origin:null}),this.dispatch({type:"ui/focus",focusRegion:$.CHAT})}async stepArtifactPreview(e){const s=this.getState();if(s.files.previewOrigin!=="chat"){await this.moveFileSelection(e);return}const n=ko(s);if(n.length===0){await this.moveFileSelection(e);return}const r=n.indexOf(s.files.selectedArtifactId),o=(r>=0?r:e>0?-1:n.length)+(e>0?1:-1);if(o<0||o>=n.length)return;const l=n[o],c=l.indexOf("/");if(c<=0)return;const d=l.slice(0,c),p=l.slice(c+1);this.dispatch({type:"files/select",sessionId:d,filename:p}),await this.ensureFilePreview(d,p).catch(()=>{})}canStepArtifactPreview(e){const s=this.getState(),n=s.files.previewOrigin==="chat"?ko(s):Mt(s).map(i=>i.id);if(n.length===0)return!1;const r=n.indexOf(s.files.selectedArtifactId);return r<0?!0:e>0?r<n.length-1:r>0}async finalizeArtifactUpload(e,{sessionId:s=null,suppressStatus:n=!1}={}){const r=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!r||!e?.filename)throw new Error("Upload did not return a session id and filename");return this.getState().sessions.activeSessionId!==r&&await this.loadSession(r),await this.ensureFilesForSession(r,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:r,filename:e.filename}),await this.ensureFilePreview(r,e.filename,{force:!0}).catch(()=>null),n||this.dispatch({type:"ui/status",text:`Uploaded ${e.filename}`}),{sessionId:r,filename:e.filename}}async applyUploadedPromptAttachment(e,{sessionId:s=null,suppressStatus:n=!1}={}){const r=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!r||!e?.filename)throw new Error("Upload did not return a session id and filename");const i=sa(e.filename),o=this.getState().ui.prompt,l=this.getState().ui.promptCursor,c=this.getPromptAttachments(),d=c.findIndex(u=>u?.sessionId===r&&u?.filename===e.filename);if(this.getState().sessions.activeSessionId!==r&&await this.loadSession(r),d===-1||!o.includes(c[d]?.token||i)){const u=mt(o,l,`${i} `);this.setPrompt(u.prompt,u.cursor)}const p=d>=0?c.map((u,f)=>f===d?{...u,sessionId:r,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:i}:u):[...c,{id:`${r}/${e.filename}`,sessionId:r,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:i}];return this.setPromptAttachments(p),await this.ensureFilesForSession(r,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:r,filename:e.filename}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(r,e.filename,{force:!0}).catch(()=>null),this.setFocus($.PROMPT),n||this.dispatch({type:"ui/status",text:d>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:r,existingAttachmentIndex:d,token:i}}async uploadArtifactFiles(e=[],{sessionId:s=null}={}){const n=Array.isArray(e)?e.filter(c=>c&&typeof c.name=="string"):[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No files selected"}),[];if(typeof this.transport.uploadArtifactFromFile!="function")return this.dispatch({type:"ui/status",text:"Browser file uploads are not supported by this transport"}),[];this.dispatch({type:"ui/status",text:n.length===1?`Uploading ${n[0].name}...`:`Uploading ${n.length} artifact files...`});const r=s||await this.ensurePromptAttachmentSessionId(),i=[];let o=0,l=null;for(const c of n)try{const d=await this.transport.uploadArtifactFromFile(r,c);i.push(d),await this.finalizeArtifactUpload(d,{sessionId:r,suppressStatus:!0})}catch(d){o+=1,l=d}return i.length>0?this.dispatch({type:"ui/status",text:o>0?`Uploaded ${i.length}/${n.length} file(s); last error: ${l?.message||String(l)}`:i.length===1?`Uploaded ${i[0].filename}`:`Uploaded ${i.length} files`}):l&&this.dispatch({type:"ui/status",text:`Upload failed: ${l?.message||String(l)}`}),i}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(),r=await this.transport.uploadArtifactFromPath(n,s),i=await this.finalizeArtifactUpload(r,{sessionId:n,suppressStatus:!0});if(this.dispatch({type:"ui/modal",modal:null}),this.stageUploadedImageAttachment(i,n)){this.dispatch({type:"ui/status",text:`Uploaded ${i.filename} — attached to your next message`});return}this.dispatch({type:"ui/status",text:`Uploaded ${i.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 r=eg(n),i=wi(n),o=Jh(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:n.isGroup?"Rename folder":`Rename (${Oe(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:r,cursorIndex:r.length,agentTitlePrefix:i,currentTitle:String(n.title||"").trim(),maxLength:o,isGroup:!!n.isGroup}}),this.dispatch({type:"ui/status",text:n.isGroup?"Type a new folder name and press Enter to save":i?`Rename title for ${i}; 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 i=this.getBulkSelectedSessionActions(e).eligible;if(i.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:i.length,skippedCount:s.length-i.length,selectedIds:i.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 r=e.sessions.byId[n];if(!r){this.dispatch({type:"ui/status",text:"No session selected"});return}if(r.isSystem){const i=String(r.title||r.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:i,state:String(r.state||"").trim(),systemRestart:!0}}),this.dispatch({type:"ui/status",text:"Choose how to restart the system session"});return}if(r.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; manage sessions individually."});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:`Terminate (${Oe(n)})`,sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:String(r.title||"").trim(),state:String(r.state||"").trim(),canRegenerate:!1}})}async pickTerminateAction(e){const s=this.getState().ui.modal;if(!s||s.type!=="terminatePicker")return;const n=s.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),e==="complete"?await this.completeActiveSession():e==="cancel"?await this.cancelActiveSession():e==="delete"?await this.deleteActiveSession():e==="regenerate"&&await this.regenerateActiveSession()}getBulkSelectedSessionActions(e=this.getState()){const s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[],r=[...new Set(s.map(o=>String(o||"").trim()).filter(Boolean))].map(o=>e.sessions.byId[o]).filter(Boolean),i=r.filter(o=>!o.isSystem&&!o.isGroup);return{selected:r,eligible:i,skippedCount:r.length-i.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 r=Ut(e,n.maxLength),i=ke(r,s);this.updateRenameSessionModal({value:r,cursorIndex:i})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=mt(s.value||"",s.cursorIndex||0,Ut(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=Ct(e.value||"",e.cursorIndex||0);this.setRenameSessionValue(s.prompt,s.cursor)}moveRenameSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",ke(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 r=this.getState().sessions.byId[s],i=r?.isGroup?r.groupId||Ws(s):null;if(i){if(typeof this.transport.updateSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group renaming is not supported by this transport"});return}const l=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),l&&this.setFocus(l),this.dispatch({type:"ui/status",text:`Renaming group ${i.slice(0,8)}...`});try{await this.transport.updateSessionGroup(i,{title:n}),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Renamed group ${n}`})}catch(c){this.dispatch({type:"ui/status",text:`Rename failed: ${c?.message||String(c)}`})}return}if(typeof this.transport.renameSession!="function"){this.dispatch({type:"ui/status",text:"Session renaming is not supported by this transport"});return}const o=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),o&&this.setFocus(o),this.dispatch({type:"ui/status",text:`Renaming ${Oe(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${Oe(s)}`})}catch(l){this.dispatch({type:"ui/status",text:`Rename failed: ${l?.message||String(l)}`})}}async cycleSessionVisibility(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups don't have visibility"});return}if(typeof this.transport.setSessionVisibility!="function"){this.dispatch({type:"ui/status",text:"Not supported by this transport"});return}const r=Bt(["private","shared_read","shared_write"],n.visibility||"private",1);try{await this.transport.setSessionVisibility(s,r),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Visibility → ${r}`})}catch(i){this.dispatch({type:"ui/status",text:i?.message||String(i)})}}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 r;try{r=await this.transport.listSessionShares(s)}catch(i){this.dispatch({type:"ui/status",text:i?.message||String(i)});return}this.dispatch({type:"ui/modal",modal:{type:"shareSession",title:`Share (${Oe(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0,shares:Array.isArray(r)?r:[],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 r=Ut(e,120),i=ke(r,s);this.updateShareSessionModal({value:r,cursorIndex:i})}insertShareSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=mt(s.value||"",s.cursorIndex||0,Ut(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=Ct(e.value||"",e.cursorIndex||0);this.setShareSessionValue(s.prompt,s.cursor)}moveShareSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",ke(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(),r=e.previousFocus;if(!n){this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);return}const i=n.startsWith("-")?n.slice(1).trim():n.toLowerCase().startsWith("revoke ")?n.slice(7).trim():null;if(i!==null){const m=i.toLowerCase(),h=(e.shares||[]).find(g=>g.subject&&String(g.subject).toLowerCase()===m||g.email&&String(g.email).toLowerCase()===m||g.displayName&&String(g.displayName).toLowerCase()===m);if(!h){this.dispatch({type:"ui/status",text:`No grant matching "${i}"`});return}this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.revokeSessionShare(s,{provider:h.provider,subject:h.subject}),this.dispatch({type:"ui/status",text:`Revoked ${i}`})}catch(g){this.dispatch({type:"ui/status",text:g?.message||String(g)})}return}const o=n.split(/\s+/),l={r:"read",read:"read",w:"write",write:"write"},c=o.length>1?o[o.length-1].toLowerCase():null,d=c&&l[c]?l[c]:"read",p=c&&l[c]?o.slice(0,-1).join(" "):n,u=p.toLowerCase();let f=null;if(typeof this.transport.listKnownUsers=="function"){let m=[];try{m=await this.transport.listKnownUsers({limit:500})}catch{m=[]}const h=Array.isArray(m)?m:[];if(f=h.find(g=>g.displayName&&g.displayName.toLowerCase()===u||g.email&&g.email.toLowerCase()===u||g.subject&&g.subject.toLowerCase()===u)||null,!f){const g=h.filter(b=>b.displayName&&b.displayName.toLowerCase().includes(u)||b.email&&b.email.toLowerCase().includes(u)||b.subject&&b.subject.toLowerCase().includes(u));if(g.length===1)f=g[0];else if(g.length>1){this.dispatch({type:"ui/status",text:`"${p}" is ambiguous (${g.length} matches)`});return}}}f||(f={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:p,email:null,displayName:null}),this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.grantSessionShare(s,{provider:f.provider,subject:f.subject,email:f.email??null,displayName:f.displayName??null},d),this.dispatch({type:"ui/status",text:`Granted ${d} to ${p}`})}catch(m){this.dispatch({type:"ui/status",text:m?.message||String(m)})}}closeModal(){const e=this.getState().ui.modal;e&&(this.dispatch({type:"ui/modal",modal:null}),e.type==="themePicker"&&e.currentThemeId&&this.dispatch({type:"ui/theme",themeId:e.currentThemeId}),e.previousFocus&&this.setFocus(e.previousFocus),this.dispatch({type:"ui/status",text:"Connected"}))}toggleAgentPickerSection(e,s=null){const n=this.getState().ui.modal;if(!n||n.type!=="sessionAgentPicker"||!e)return;const r=new Set(n.collapsed||[]),i=s===null?!r.has(e):s;if(i===r.has(e))return;i?r.add(e):r.delete(e);const o=[...r],l=ta(n.catalog||[],o,n.genericItem||null),c=n.items?.[n.selectedIndex||0]?.id;let d=l.findIndex(p=>p.id===c);d<0&&(d=Math.max(0,l.findIndex(p=>p.sectionKey===e))),this.dispatch({type:"ui/modal",modal:{...n,collapsed:o,items:l,selectedIndex:d}})}moveAgentPickerSection(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionAgentPicker")return!1;const n=Array.isArray(s.items)?s.items:[],r=Math.max(0,Math.min(Number(s.selectedIndex)||0,n.length-1)),i=n[r];if(!i)return!1;if(e>0)return i.kind==="section"&&i.collapsed?(this.toggleAgentPickerSection(i.sectionKey,!1),!0):!1;if(i.kind==="section"&&!i.collapsed)return this.toggleAgentPickerSection(i.sectionKey,!0),!0;for(let o=r-1;o>=0;o-=1)if(n[o].kind==="section"&&n[o].depth<i.depth)return this.dispatch({type:"ui/modalSelection",index:o}),!0;return!1}moveModalSelection(e){const s=this.getState().ui.modal;if(!s)return;if(s.type==="help"){const i=Math.max(0,Number(s.selectedIndex)||0);this.dispatch({type:"ui/modalSelection",index:Math.max(0,i+e)});return}if(!Array.isArray(s.items)||s.items.length===0)return;if(s.type==="logFilter"||s.type==="filesFilter"||s.type==="historyFormat"){const i=Math.max(0,Math.min(Number(s.selectedIndex)||0,s.items.length-1)),o=s.items[i];if(!o||!Array.isArray(o.options)||o.options.length===0)return;const l=o.options.map(u=>u.id).filter(Boolean);if(l.length===0)return;const c=s.type==="filesFilter"?this.getState().files.filter?.[o.id]||l[0]:s.type==="historyFormat"?this.getState().executionHistory?.format||l[0]:this.getState().logs.filter?.[o.id]||l[0],d=Bt(l,c,e),p=o.options.find(u=>u.id===d)||o.options[0];this.dispatch({type:s.type==="filesFilter"?"files/filter":s.type==="historyFormat"?"executionHistory/format":"logs/filter",filter:s.type==="historyFormat"?void 0:{[o.id]:d},...s.type==="historyFormat"?{format:d}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(d).catch(()=>{}),this.ensureSelectedFilePreview().catch(()=>{})),this.dispatch({type:"ui/status",text:`${s.type==="filesFilter"?"Files":s.type==="historyFormat"?"History":"Log"} filter updated: ${o.label} = ${p?.label||d}`});return}const n=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(0,Math.min(n+e,s.items.length-1));this.dispatch({type:"ui/modalSelection",index:r})}moveModalPane(e){const s=this.getState().ui.modal;if(s?.type==="sessionAgentPicker"){this.moveAgentPickerSection(e);return}if(!s||s.type!=="logFilter"&&s.type!=="filesFilter"&&s.type!=="historyFormat"||!Array.isArray(s.items)||s.items.length===0)return;const r=(Math.max(0,Number(s.selectedIndex)||0)+e+s.items.length)%s.items.length,i=s.items[r],o=s.type==="filesFilter"?this.getState().files.filter?.[i.id]||i.options?.[0]?.id:s.type==="historyFormat"?this.getState().executionHistory?.format||i.options?.[0]?.id:this.getState().logs.filter?.[i.id]||i.options?.[0]?.id,l=i.options?.find(c=>c.id===o)||i.options?.[0];this.dispatch({type:"ui/modalSelection",index:r}),this.dispatch({type:"ui/status",text:`Editing ${i.label}: ${l?.label||o||""}`})}async confirmModal(){const e=this.getState().ui.modal;if(e){if(e.type==="help"){this.closeModal();return}if(e.type==="confirm"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s),e.action==="cancelSession"?await this.cancelActiveSession({confirmed:!0}):e.action==="completeSession"?await this.completeActiveSession("Completed by user",{confirmed:!0}):e.action==="deleteSession"?await this.deleteActiveSession({confirmed:!0}):e.action==="regenerateSession"?await this.regenerateActiveSession({confirmed:!0,...e.extras||{}}):e.action==="deleteArtifact"?await this.deleteSelectedArtifact({confirmed:!0}):e.action==="deleteMarkedArtifacts"?await this.deleteMarkedArtifacts({confirmed:!0}):e.action==="deleteAdminProvider"&&await this.deleteSelectedAdminProvider();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=pt(s?.id);if(!n){this.dispatch({type:"ui/status",text:"Unable to apply that theme"});return}const r=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r),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 provider — add your own in Admin Console first":"This model is not available"});return}const n=e.previousFocus;if(!s){if(e.sessionOptions?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),this.dispatch({type:"ui/status",text:"No model selected"});return}await this.openSessionAgentPicker({},n);return}const r=Vo(s);if(e.sessionOptions?.mode==="switchModel"){await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,reasoningEffort:r??null},n);return}await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,...r?{reasoningEffort:r}:{}},n);return}if(e.type==="reasoningEffortPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,r=e.sessionOptions||{};await this.openContextTierPicker(e.modelItem,{...r,...s?.id?{reasoningEffort:s.id}:{}},n);return}if(e.type==="contextTierPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,r=e.sessionOptions||{},i={...r,...s?.id?{contextTier:s.id}:{}};if(r?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),await this.switchSessionModel({...i,model:e.modelItem?.id||r.model});return}await this.openSessionAgentPicker(i,n);return}if(e.type==="sessionAgentPicker"){const s=e.items?.[e.selectedIndex||0];if(s?.kind==="section"){this.toggleAgentPickerSection(s.sectionKey);return}if(s&&s.kind!=="generic"&&s.supportsDirectStart===!1){this.dispatch({type:"ui/status",text:`${s.title||s.agentName} is created by another agent and cannot be started on its own`});return}const n=e.previousFocus,r=e.sessionOptions||{};if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s||s.kind==="generic"){await this.createSession(r);return}await this.createSessionForAgent(s.agentName,{...r,...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(),r=n[0]?.sessionId||null,i=og(s,n);let o=e.sessions.activeSessionId;r&&(o=r,e.sessions.activeSessionId!==r&&await this.loadSession(r));let l=o&&e.sessions.byId[o]||null;if(o&&!l&&(l=this.getState().sessions.byId[o]||null),!o){const g=await this.createSession({});if(!g?.sessionId)return;o=g.sessionId,l=this.getState().sessions.byId[o]||null}const c=n.some(g=>g?.kind==="image");if(!i.trim()&&!c){o&&this.getPendingOutboxItems(o).length>0&&await this.dispatchPendingOutbox(o).catch(()=>{});return}const d=l?.pendingQuestion||null,p=!!d?.question,u=this.getPromptEditSessionMatch(o);if(u){const g=this.getSessionOutbox(o).find(b=>b.id===u.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(p&&typeof this.transport.sendAnswer=="function"){const g=Date.now(),b={...d,answer:i,answeredAt:g,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:null,answeredPendingQuestion:b}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(o,i),this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:{...b,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(o,100),this.syncSessionEvents(o).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(y){this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:d}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(i,String(i||"").length),this.dispatch({type:"ui/status",text:y?.message||String(y)})}return}const f=n.filter(g=>g?.kind==="image");let m=null;if(f.length>0){if(f.some(y=>y.file)&&typeof this.transport.uploadArtifactFromFile!="function"){this.dispatch({type:"ui/status",text:"This transport does not support image attachments."});return}const b=this.buildOutboxItem("","pending");this.dispatch({type:"ui/status",text:`Uploading ${f.length} image${f.length>1?"s":""}...`});try{m=await this.uploadPendingImageAttachments(o,f,b.id),this.dispatch({type:"ui/status",text:""})}catch(y){this.dispatch({type:"ui/status",text:`Image upload failed: ${y?.message||y}`});return}}const h=i.trim()?i:m&&m.length>0?"See the attached image(s).":i;this.queuePromptInOutbox(o,h,m?{attachments:m}:null),this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(o).catch(()=>{})}setPrompt(e,s=String(e||"").length){const n=String(e||""),r=Math.max(0,Math.min(Number.isFinite(s)?s:n.length,n.length)),i=this.getState().ui;if(!(i.prompt===n&&i.promptCursor===r)){if(i.promptEdit?.sessionId&&i.promptEdit?.itemId){const l=this.getSessionOutbox(i.promptEdit.sessionId).map(c=>c.id===i.promptEdit.itemId&&c.phase==="pending"&&c.attempted!==!0?{...c,text:n}:c);this.setSessionOutboxItems(i.promptEdit.sessionId,l)}this.dispatch({type:"ui/prompt",prompt:n,promptCursor:r}),this.syncPromptReferenceBrowser()}}setPromptCursor(e){const s=this.getState().ui.prompt||"";this.setPrompt(s,e)}insertPromptText(e){const s=this.getState().ui,n=mt(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=Ct(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=ug(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,ke(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,Ic(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=pg(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,r=e.prompt??n.prompt;return Is({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??Jt(r),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===$.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),r=this.getState().ui.layout||{};(r.viewportWidth!==s||r.viewportHeight!==n)&&this.dispatch({type:"ui/viewport",width:s,height:n});const i=this.getCurrentLayout({width:s,height:n}),o=this.getState().ui.focusRegion,l=nt(o,i);l!==o&&this.setFocus(l)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:nt(e,this.getCurrentLayout()),requestedFocusRegion:e})}focusNext(){const e=this.getCurrentLayout(),s=nt(this.getState().ui.focusRegion,e),n=yr(e);this.setFocus(Bt(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=nt(this.getState().ui.focusRegion,e),n=yr(e);this.setFocus(Bt(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=nt(this.getState().ui.focusRegion,e);this.setFocus(xu(s,e))}focusRight(){const e=this.getCurrentLayout(),s=nt(this.getState().ui.focusRegion,e);this.setFocus(Iu(s,e))}adjustPaneSplit(e){const s=this.getState().ui.layout||{},n=s.viewportWidth??120,r=Math.max(-n,Math.min(n,(s.paneAdjust||0)+e));this.dispatch({type:"ui/paneAdjust",paneAdjust:r});const i=this.getCurrentLayout({paneAdjust:r}),o=this.getState().ui.focusRegion,l=nt(o,i);l!==o&&this.setFocus(l)}adjustSessionPaneSplit(e){const s=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,i=Math.max(-r,Math.min(r,(s.sessionPaneAdjust||0)+e));this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:i});const o=this.getCurrentLayout({sessionPaneAdjust:i}),l=this.getState().ui.focusRegion,c=nt(l,o);c!==l&&this.setFocus(c)}adjustActivityPaneSplit(e){const s=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,i=Math.max(-r,Math.min(r,(s.activityPaneAdjust||0)+e));this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:i});const o=this.getCurrentLayout({activityPaneAdjust:i}),l=this.getState().ui.focusRegion,c=nt(l,o);c!==l&&this.setFocus(c)}resizeFocusedPane(e){const s=this.getState().ui.focusRegion,n=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??n.viewportHeight??40,i=n.viewportHeight??40,o=(l,c,d,p)=>{const u=Math.max(d,p);return Math.max(d,Math.min(u,(l||0)+c))};if(s===$.SESSIONS||s===$.CHAT){const l=wl(r),c=rs+1,d=Math.min(El(i,r),r-wn-1),p=s===$.CHAT?-e:e,u=o(n.sessionPaneAdjust,p,c-l,d-l);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:u})}else if(s===$.INSPECTOR||s===$.ACTIVITY){const l=Math.max(Zt,Math.floor(r*vl)),c=Zt+1,d=r-en-1,p=s===$.INSPECTOR?-e:e,u=o(n.activityPaneAdjust,p,c-l,d-l);this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:u})}}getActiveSequenceCompletedTurns(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return[];const n=e.history.bySessionId?.get?.(s),r=[],i=new Set;for(const o of n?.events||[]){if(o?.eventType!=="session.turn_completed")continue;const l=Number(o?.data?.turnIndex??o?.data?.iteration);!Number.isFinite(l)||i.has(l)||(i.add(l),r.push(l))}return r.sort((o,l)=>o-l),r}moveSequenceSelection(e){const s=this.getActiveSequenceCompletedTurns();if(s.length===0)return;const n=s.indexOf(Number(this.getState().ui.sequenceSelectedTurn)),r=n===-1?s.length-1:Math.max(0,Math.min(s.length-1,n+e));this.dispatch({type:"ui/sequenceSelectedTurn",turn:s[r]})}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):[],r=n.includes(s)?n.filter(i=>i!==s):[...n,s];this.dispatch({type:"ui/sequenceExpandedTurns",turns:r})}nextInspectorTab(){const e=this.getState().ui.inspectorTab,s=Bt(ot,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=Bt(ot,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,r=e[(n+1)%e.length];this.setStatsViewMode(r)}setStatsViewMode(e){this.dispatch({type:"ui/statsViewMode",statsViewMode:e}),this.getState().ui.inspectorTab==="stats"&&this.ensureInspectorData("stats").catch(()=>{})}async selectInspectorTab(e){ot.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=as(s);if(n.length===0)return;const r=s.sessions.activeSessionId||n[0].sessionId,i=Math.max(0,n.findIndex(c=>c.sessionId===r)),o=Math.max(0,Math.min(n.length-1,i+e)),l=n[o].sessionId;this.navigateToSession(l)}navigateToSession(e){e&&(this.getState().sessions.activeSessionId!==e&&(this.dispatch({type:"sessions/selected",sessionId:e}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.sessionNavSettleTimer&&clearTimeout(this.sessionNavSettleTimer),this.sessionNavSettleTimer=setTimeout(()=>{this.sessionNavSettleTimer=null,this.loadSession(e).catch(()=>{})},Eg))}getSessionPageSize(){const e=this.getCurrentLayout(),s=e.fullscreenPane===$.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 fg.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),r=Math.max(0,Math.min(Number(s.ui.scroll?.[e])||0,n));return this.isPaneFollowingBottom(e,s)?Math.max(0,n-r):r}applyPaneVisualScrollOffset(e,s,n={},r=this.getState()){const i=this.getPaneMaxScrollOffset(e,r),o=n.fromViewport?Math.max(0,Number(s)||0):Math.max(0,Math.min(Number(s)||0,i));if(this.paneUsesStickyBottomFollow(e,r)){const l=n.followBottom!==void 0?!!n.followBottom:n.atBottom!==void 0?!!n.atBottom:o>=i;return this.dispatch({type:"ui/followBottom",pane:e,followBottom:l}),this.dispatch({type:"ui/scroll",pane:e,offset:l?0:o}),o}return this.dispatch({type:"ui/scroll",pane:e,offset:o}),o}updatePaneScrollFromViewport(e,s,n={}){const r=this.getState();if(this.paneUsesStickyBottomFollow(e,r)){this.applyPaneVisualScrollOffset(e,s,{...n,fromViewport:!0},r);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(),r=this.getPaneMaxScrollOffset(e,n);if(this.paneUsesStickyBottomFollow(e,n)){const l=this.getPaneVisualScrollOffset(e,n),c=Math.max(0,Math.min(l-s,r));this.applyPaneVisualScrollOffset(e,c,{followBottom:c>=r},n);return}const i=Math.max(0,Math.min(Number(n.ui.scroll?.[e])||0,r)),o=Math.max(0,Math.min(i+s,r));this.dispatch({type:"ui/scroll",pane:e,offset:o}),e==="chat"&&s>0?i>=r?this.handleChatTopHistoryScrollIntent(o).catch(()=>{}):o>=r&&this.armChatTopHistoryLoad():e==="chat"&&s<0&&this.disarmChatTopHistoryLoad()}scrollPaneTo(e,s){const n=this.getState(),r=this.getPaneMaxScrollOffset(e,n),i=Math.max(0,Math.min(Number(s)||0,r));if(this.paneUsesStickyBottomFollow(e,n)){this.applyPaneVisualScrollOffset(e,i,{followBottom:i>=r},n);return}this.dispatch({type:"ui/scroll",pane:e,offset:i}),e==="chat"&&(r>0&&i>=r?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 r=this.getState().sessions.activeSessionId;if(r){if(!s.force&&(!this.chatTopHistoryLoadArmed||this.chatTopHistoryLoadSessionId!==r)){this.armChatTopHistoryLoad();return}await this.maybeAutoExpandActiveHistory(e,{pages:_h,force:!0})}}artifactPreviewOwnsActivitySlot(e=this.getState()){return e.ui.inspectorTab==="files"&&!!e.files?.selectedArtifactId}focusIsArtifactList(e=this.getState()){return e.ui.focusRegion===$.INSPECTOR&&e.ui.inspectorTab==="files"}getScrollablePaneForFocus(){const e=this.getState(),s=e.ui.focusRegion;return s===$.CHAT?"chat":s===$.ACTIVITY?this.artifactPreviewOwnsActivitySlot(e)?"filePreview":"activity":s===$.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(),r=s==="inspector"||s==="filePreview";this.scrollPane(s,r&&!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),r=Math.max(1,s.chatPaneHeight-2),i=oi(e,n),o=[...ci(e,n),...ii(e)],l=Math.min(Math.max(0,Math.floor(r*.34)),jt(o,n)),c=jt(i,n);return{contentWidth:n,contentHeight:Math.max(1,r-l),totalLines:c}}getActivityRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.activityHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.rightWidth-4),r=Math.max(1,s.activityPaneHeight-2),i=e.sessions.activeSessionId,o={sessions:{activeSessionId:i,byId:i?{[i]:e.sessions.byId[i]||null}:{}},history:{bySessionId:i?new Map([[i,e.history.bySessionId.get(i)||null]]):new Map}},l=ui(o);return{contentWidth:n,contentHeight:r,totalLines:jt(l.lines,n)}}getInspectorRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.inspectorHidden)return{contentWidth:20,contentHeight:1,stickyLineCount:0,totalLines:0};const n=Math.max(20,s.rightWidth-4),r=e.sessions.activeSessionId,i=r&&e.orchestration.bySessionId?.[r]||null,o={branding:e.branding,sessions:{activeSessionId:r,byId:e.sessions.byId,flat:e.sessions.flat},history:{bySessionId:e.history.bySessionId},orchestration:{bySessionId:r&&i?{[r]:i}:{}},logs:e.logs,sessionStats:e.sessionStats,fleetStats:e.fleetStats,ui:{inspectorTab:e.ui.inspectorTab,statsViewMode:e.ui.statsViewMode},executionHistory:e.executionHistory},l=kt(o,{width:n}),c=l.tabs.map(f=>({text:f===l.activeTab?`[${f}] `:`${f} `,color:f===l.activeTab?"magenta":"gray",bold:f===l.activeTab})),d=(l.lines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f),p=l.activeTab==="sequence"?[c,...(l.stickyLines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f)]:[],u=l.activeTab==="sequence"?d:[c,...d];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:jt(p,n),totalLines:jt(u,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,r=n?s.totalWidth:s.rightWidth,i=n?Math.max(10,s.bodyHeight):s.inspectorPaneHeight,o=Math.max(20,r-4),l=Math.max(8,o-4),c=e.sessions.activeSessionId,d=c&&e.sessions.byId[c]||null,p={sessions:{activeSessionId:c,byId:c&&d?{[c]:d}:{},flat:e.sessions.flat},files:{bySessionId:e.files.bySessionId,fullscreen:!!e.files.fullscreen,selectedArtifactId:e.files.selectedArtifactId,filter:e.files.filter},ui:{scroll:{filePreview:e.ui.scroll.filePreview}}},u=pi(p,{listWidth:l,previewWidth:l}),f=Math.max(9,i-4),m=Math.max(5,Math.min(10,Math.floor(f*.35)));let h=Math.max(5,Math.min(m,(u.listBodyLines||[]).length+2)),g=Math.max(5,f-h-1);const b=8;if(g<b){const y=b-g;h=Math.max(5,h-y),g=Math.max(5,f-h-1)}return{contentWidth:l,contentHeight:Math.max(1,g-2),totalLines:jt(u.previewLines,l)}}getPaneMaxScrollOffset(e,s=this.getState()){if(!e)return 0;if(e==="chat"){const n=this.getActiveChatRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="activity"){const n=this.getActivityRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="inspector"){const n=this.getInspectorRenderMetrics(s),r=Math.min(n.contentHeight,n.stickyLineCount||0),i=Math.max(0,n.contentHeight-r);return Math.max(0,n.totalLines-i)}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(),r=n.sessions.activeSessionId;if(!r)return;const i=n.history.bySessionId.get(r);if(!i?.hasOlderEvents||this.sessionHistoryExpansionLoads.has(r))return;if(Number(i.loadedEventCount||0)>=Nr){this.dispatch({type:"ui/status",text:"Reached automatic history limit. Press e to load more older CMS events."});return}const o=Array.isArray(i?.chat)&&i.chat.length>0;if(!s.force&&o){const{contentHeight:l,totalLines:c}=this.getActiveChatRenderMetrics(n),d=Math.max(0,c-l);if(e<d)return}await this.expandSessionHistory(r,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages,eventTypes:Jd})}async expandSessionHistory(e,s={}){if(!e)return;if(this.sessionHistoryExpansionLoads.has(e))return this.sessionHistoryExpansionLoads.get(e);const n=this.getState(),r=n.history.bySessionId.get(e),i=Math.max(be,Number(r?.loadedEventLimit??be)||be),o=be,l=Array.isArray(r?.events)&&r.events.length>0?Number(r.events[0]?.seq||0):0;if(!r?.hasOlderEvents||l<=1){this.dispatch({type:"ui/status",text:"Already showing the oldest loaded history"});return}const c=e===n.sessions.activeSessionId,d=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),p=c?this.getActiveChatRenderMetrics(n).totalLines:0,u=(async()=>{let f;const m=Math.max(1,Math.floor(Number(s.pages)||1)),h=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&l>0){f=r||Rs([],{requestedLimit:i});for(let y=0;y<m;y+=1){const v=Array.isArray(f?.events)&&f.events.length>0?Number(f.events[0]?.seq||0):0;if(!f?.hasOlderEvents||v<=1){f={...f,hasOlderEvents:!1};break}if(Number(f.loadedEventCount||0)>=Nr)break;const E=await this.transport.getSessionEventsBefore(e,v,o,h);if(!Array.isArray(E)||E.length===0){f={...f,hasOlderEvents:!1};break}const k=Rs(E,{requestedLimit:o}),x=[...k.events||[],...f?.events||[]];if(f={chat:Xt([...k.chat||[],...f?.chat||[]]),activity:[...k.activity||[],...f?.activity||[]],events:x,lastSeq:f?.lastSeq||f?.events?.[f?.events?.length-1]?.seq||E[E.length-1]?.seq||0,loadedEventLimit:x.length,loadedEventCount:x.length,hasOlderEvents:E.length>=o&&Number(E[0]?.seq||0)>1},!f.hasOlderEvents)break}}else{const y=bu(i);if(y<=i){this.dispatch({type:"ui/status",text:r?.hasOlderEvents?`Already showing a large recent history window (${i} events)`:"Already showing the oldest loaded history"});return}const v=await this.transport.getSessionEvents(e,void 0,y);f={...Rs(v,{requestedLimit:y}),lastSeq:v[v.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:f});for(const y of f?.events||[])this.reconcileOutboxAgainstEvent(e,y);const g=Array.isArray(r?.chat)&&r.chat.length>0;if(c&&!g)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(c&&d>0&&!s.autoTriggered){const y=this.getState(),v=this.getActiveChatRenderMetrics(y).totalLines,E=Math.max(0,v-p);E>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:d+E})}const b=f.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${f.loadedEventCount} events loaded)`:`Loaded older history page (${f.loadedEventCount} events loaded)`:`Loaded full available history (${f.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:b}),f.hasOlderEvents?s.autoTriggered&&c&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,u),u}async cancelActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:o,skippedCount:l}=this.getBulkSelectedSessionActions(s);if(o.length===0){this.dispatch({type:"ui/status",text:"No cancellable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Sessions",message:`Cancel ${o.length} selected session${o.length===1?"":"s"}?${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Cancel Sessions",action:"cancelSession",previousFocus:s.ui.focusRegion}});return}let c=0;const d=[];for(const u of o)try{await this.transport.cancelSession(u.sessionId),c+=1}catch(f){d.push(`${u.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const p=d.length===0?`Cancelled ${c} session${c===1?"":"s"}`:`Cancelled ${c}/${o.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:p}),await this.refreshSessions();return}const r=s.sessions.activeSessionId;if(!r)return;const i=s.sessions.byId[r];if(i?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; cancel sessions individually."});return}if(i?.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=i.title||i.agentId||r.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:r,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(i.agentId||r,{disposition:"terminate",reason:"Terminated by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${i.agentId||r.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const l=i?.title||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Session",message:`Cancel session "${l}"? The session will stop processing.`,confirmLabel:"Cancel Session",action:"cancelSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.cancelSession(r),this.dispatch({type:"ui/status",text:`Cancelled ${r.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:r="",distillerEffort:i="",distillerContextTier:o=""}={}){const l=this.getState(),c=l.sessions.activeSessionId;if(!c)return;if(typeof this.transport.regenerateSession!="function"){this.dispatch({type:"ui/status",text:"Session regeneration is not supported by this deployment"});return}const d=l.sessions.byId[c];if(d?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; regenerate sessions individually."});return}if(d?.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be regenerated."});return}if(d?.serviceKind){this.dispatch({type:"ui/status",text:"Service sessions are runtime machinery and cannot be regenerated."});return}if(!e){const p=d?.title||c.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Regenerate Session",message:`Regenerate context for "${p}"? The transcript is archived and distilled, then the session rebuilds fresh from it at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved. As an operator action this overrides the rate limits (cooldown / minimum age).`,confirmLabel:"Regenerate",action:"regenerateSession",sessionId:c,previousFocus:l.ui.focusRegion,extras:{instructions:"",distillMode:"llm",distillerModel:"",distillerEffort:"",distillerContextTier:"",distillerModelOptions:await this._loadDistillerModelOptions()}}});return}try{const p=String(s||"").trim();await this.transport.regenerateSession(c,{force:!0,...p?{instructions:p.slice(0,4e3)}:{},...n==="deterministic"?{distillMode:"deterministic"}:{},...r?{distillerModel:r}:{},...i?{distillerReasoningEffort:i}:{},...o?{distillerContextTier:o}:{}}),this.dispatch({type:"ui/status",text:`Regeneration requested for ${c.slice(0,8)} — rebuilding at the next boundary`})}catch(p){this.dispatch({type:"ui/status",text:`Regenerate failed: ${p?.message||String(p)}`});return}await this.refreshSessions()}async _loadDistillerModelOptions(){if(typeof this.transport.listModels!="function")return[];try{const e=await this.transport.listModels({groupByProvider:!0});return(Array.isArray(e)?e:Array.isArray(e?.providers)?e.providers:Array.isArray(e?.models)?e.models:[]).flatMap(r=>Array.isArray(r?.models)?r.models.map(i=>({...i,providerId:i.providerId||r.providerId})):[r]).filter(r=>r&&(r.qualifiedName||r.modelName)).map(r=>({qualifiedName:r.qualifiedName||r.modelName,modelName:r.modelName||r.qualifiedName,providerId:r.providerId||"",supportedReasoningEfforts:Array.isArray(r.supportedReasoningEfforts)?r.supportedReasoningEfforts:[],supportedContextTiers:Array.isArray(r.supportedContextTiers)?r.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 i=(await this.transport.stopSessionTurn(s,{reason:"Stopped by user"}))?.outcome||"stopped";i==="no_active_turn"?this.dispatch({type:"ui/status",text:"No active turn to stop"}):i==="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(r){this.dispatch({type:"ui/status",text:`Stop turn failed: ${r?.message||r}`})}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 r=Array.isArray(e.sessions.pinnedIds)&&e.sessions.pinnedIds.includes(s);this.dispatch({type:"sessions/pinToggle",sessionId:s}),this.dispatch({type:"ui/status",text:r?`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(),r=Array.isArray(n.sessions.selectedIds)?n.sessions.selectedIds:[];if(n.sessions.selectMode&&r.length>=1){const{eligible:l,skippedCount:c}=this.getBulkSelectedSessionActions(n);if(l.length===0){this.dispatch({type:"ui/status",text:"No completable sessions in selection (system sessions and groups are skipped)."});return}if(!s){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Sessions",message:`Complete ${l.length} selected session${l.length===1?"":"s"}? This will cascade to their sub-agents.${c>0?` (${c} selected row${c===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Complete Sessions",action:"completeSession",previousFocus:n.ui.focusRegion}});return}let d=0;const p=[];for(const f of l)try{await this.transport.completeSession(f.sessionId,e),d+=1}catch(m){p.push(`${f.sessionId.slice(0,8)}: ${m?.message||String(m)}`)}this.dispatch({type:"sessions/selectClear"});const u=p.length===0?`Completed ${d} session${d===1?"":"s"}`:`Completed ${d}/${l.length}; ${p.length} failed: ${p.slice(0,2).join(", ")}${p.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),await this.refreshSessions();return}const i=this.getState().sessions.activeSessionId;if(!i)return;const o=this.getState().sessions.byId[i];if(o?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; complete sessions individually."});return}if(o?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!s){const l=o.title||o.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete & Restart System Session",message:`Mark system session "${l}" complete and start a fresh one?`,confirmLabel:"Complete & Restart",action:"completeSession",sessionId:i,previousFocus:this.getState().ui.focusRegion}});return}await this.transport.restartSystemSession(o.agentId||i,{disposition:"complete",reason:e}),this.dispatch({type:"ui/status",text:`Restarted system session ${o.agentId||i.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:`${i.slice(0,8)} is already completed`});return}if(!s){const l=o?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Session",message:`Complete session "${l}"? This will cascade to all sub-agents.`,confirmLabel:"Complete",action:"completeSession",sessionId:i,previousFocus:this.getState().ui.focusRegion}});return}this.dispatch({type:"ui/status",text:`Completing ${i.slice(0,8)} (cascading to sub-agents)...`});try{await this.transport.completeSession(i,e),await this.refreshSessions(),this.scheduleSessionDetailSync(i,100),this.scheduleSessionsRefresh(900)}catch(l){await this.loadSession(i).catch(()=>{}),this.dispatch({type:"ui/status",text:`Failed to send /done: ${l?.message||String(l)}`})}}async deleteActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:o,skippedCount:l}=this.getBulkSelectedSessionActions(s);if(o.length===0){this.dispatch({type:"ui/status",text:"No deletable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete Sessions",message:`Hard delete ${o.length} selected session${o.length===1?"":"s"}? This action cannot be undone.${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Hard Delete Sessions",action:"deleteSession",previousFocus:s.ui.focusRegion}});return}let c=0;const d=[];for(const u of o)try{await this.transport.deleteSession(u.sessionId),this.handleSessionGone(u.sessionId),c+=1}catch(f){d.push(`${u.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const p=d.length===0?`Deleted ${c} session${c===1?"":"s"}`:`Deleted ${c}/${o.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:p}),await this.refreshSessions();return}const r=s.sessions.activeSessionId;if(!r)return;const i=s.sessions.byId[r];if(i?.isGroup){const o=i.groupId||Ws(r);if(!o||typeof this.transport.deleteSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group deletion is not supported by this transport"});return}if(Number(i.memberCount||0)>0){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Group Not Empty",message:`Group "${i.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 "${i.title||o}"? This action cannot be undone.`,confirmLabel:"Delete Group",action:"deleteSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSessionGroup(o),this.dispatch({type:"ui/status",text:`Deleted group ${i.title||o}`}),await this.refreshSessions();return}if(i?.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=i.title||i.agentId||r.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:r,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(i.agentId||r,{disposition:"hard_delete",reason:"Hard-deleted by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${i.agentId||r.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const l=i?.title||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Session",message:`Delete session "${l}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteSession",sessionId:r,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSession(r),this.handleSessionGone(r),this.dispatch({type:"ui/status",text:`Deleted ${r.slice(0,8)}`}),await this.refreshSessions()}async handleCommand(e){switch(e){case P.REFRESH:await this.refreshSessions();return;case P.NEW_SESSION:await this.openNewSessionFlow();return;case P.OPEN_MODEL_PICKER:await this.openModelPicker();return;case P.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case P.OPEN_THEME_PICKER:this.openThemePicker();return;case P.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case P.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case P.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case P.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case P.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case P.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case P.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case P.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case P.CLOSE_MODAL:this.closeModal();return;case P.MODAL_PREV:this.moveModalSelection(-1);return;case P.MODAL_NEXT:this.moveModalSelection(1);return;case P.MODAL_PANE_PREV:this.moveModalPane(-1);return;case P.MODAL_PANE_NEXT:this.moveModalPane(1);return;case P.MODAL_CONFIRM:await this.confirmModal();return;case P.SEND_PROMPT:await this.sendPrompt();return;case P.FOCUS_NEXT:this.focusNext();return;case P.FOCUS_PREV:this.focusPrev();return;case P.FOCUS_LEFT:this.focusLeft();return;case P.FOCUS_RIGHT:this.focusRight();return;case P.FOCUS_PROMPT:this.setFocus($.PROMPT);return;case P.FOCUS_SESSIONS:this.setFocus($.SESSIONS);return;case P.MOVE_SESSION_UP:await this.moveSession(-1);return;case P.MOVE_SESSION_DOWN:await this.moveSession(1);return;case P.EXPAND_SESSION:this.expandActiveSession();return;case P.COLLAPSE_SESSION:this.collapseActiveSession();return;case P.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case P.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case P.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case P.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case P.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case P.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case P.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case P.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case P.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case P.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case P.OPEN_HELP:this.openHelpModal();return;case P.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case P.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case P.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case P.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case P.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case P.OPEN_LOG_FILTER:this.openLogFilter();return;case P.OPEN_FILES_FILTER:this.openFilesFilter();return;case P.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case P.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case P.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case P.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case P.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case P.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case P.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case P.SCROLL_UP:this.scrollCurrentPane(1);return;case P.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case P.PAGE_UP:if(this.getState().ui.focusRegion===$.SESSIONS){await this.moveSessionPage(-1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(-10);return}this.scrollCurrentPane(10);return;case P.PAGE_DOWN:if(this.getState().ui.focusRegion===$.SESSIONS){await this.moveSessionPage(1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(10);return}this.scrollCurrentPane(-10);return;case P.EXPAND_HISTORY:await this.expandActiveHistory();return;case P.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case P.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case P.CANCEL_SESSION:await this.cancelActiveSession();return;case P.STOP_TURN:await this.stopActiveSessionTurn();return;case P.DONE_SESSION:await this.completeActiveSession();return;case P.DELETE_SESSION:await this.deleteActiveSession();return;case P.REGENERATE_SESSION:await this.regenerateActiveSession();return;case P.PIN_SESSION:this.togglePinActiveSession();return;case P.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case P.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case P.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case P.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case P.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case P.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case P.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case P.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case P.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case P.ADMIN_SHOW_GHCP:this.setAdminSection("providers");return;case P.ADMIN_SHOW_PACKAGES:this.setAdminSection("packages");return;case P.ADMIN_SHOW_WORKERS:this.setAdminSection("workers");return;case P.ADMIN_WORKERS_REFRESH:await this.refreshAdminWorkers();return;case P.ADMIN_PACKAGES_REFRESH:await this.refreshAdminAgentPackages();return;case P.ADMIN_PACKAGES_NEXT:await this.stepAdminPackageSelection(1);return;case P.ADMIN_PACKAGES_PREV:await this.stepAdminPackageSelection(-1);return;case P.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case P.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case P.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case P.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 In=0;function qe(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 r of s)if(!Object.prototype.hasOwnProperty.call(e,r)||!Object.is(t[r],e[r]))return!1;return!0}function rr(){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 Cg(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 Ng(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 Tg(t,e=null,s=null){const n=[],r=typeof s=="string"?s.trim():"";r&&n.push({text:r,color:"yellow",bold:!0}),Array.isArray(t)&&t.length>0&&(n.length>0&&n.push({text:" ",color:"gray"}),n.push(...t));const i=typeof e=="string"?e.trim():"";return i?(n.length>0&&n.push({text:" ",color:"gray"}),n.push({text:i,color:"cyan",bold:!0}),n):n.length>0?n:null}function Pg(t=2e3){const[e,s]=a.useState(()=>rr());return a.useEffect(()=>{if(rr()==null)return;const n=()=>{const i=rr();i!=null&&s(o=>o===i?o:i)};n();const r=setInterval(n,t);return()=>clearInterval(r)},[t]),a.useMemo(()=>Cg(e),[e])}function us(t,e){return t&&e?{[t]:e}:{}}function ca(t){return typeof t=="string"?{text:t,color:"white"}:t}function Ms(t,e,s,n,r,i){const o=(e.tabs||ot).map(u=>({text:u===e.activeTab?`[${u}] `:`${u} `,color:u===e.activeTab?"magenta":"gray",bold:u===e.activeTab})),l=(e.lines||[]).map(ca),c=(e.stickyLines||[]).map(ca),d=e.activeTab==="sequence"?[o,...c]:[],p=e.activeTab==="sequence"?l:[o,...l];return a.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:r,stickyLines:d,marginBottom:In,lines:p,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="sequence"||e.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:i})}function da(t,e){const s=String(t||"");return e<=0?"":s.length<=e?s:e===1?s.slice(0,1):`${s.slice(0,e-1)}...`}a.memo(function({controller:e,maxRows:s,width:n,height:r,frame:i,versionLabel:o=null}){const l=tt(),c=Pg(),d=ee(e,h=>({sessions:h.sessions,mode:h.connection?.mode||"local",brandingTitle:h.branding?.title||"PilotSwarm",focused:h.ui.focusRegion==="sessions",identityLabel:Ng(h.auth)}),qe),p=a.useMemo(()=>Tg(c,o,d.identityLabel),[c,o,d.identityLabel]),u=a.useMemo(()=>({sessions:d.sessions,connection:{mode:d.mode},branding:{title:d.brandingTitle}}),[d.brandingTitle,d.mode,d.sessions]),f=a.useMemo(()=>xr(u,s),[u,s]),m=a.useMemo(()=>f.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:f.map(h=>h.active?Ll(h.runs,{preserveColors:!0}):h.runs),[f]);return a.createElement(l.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:p,color:"yellow",focused:d.focused,width:n,height:r,marginBottom:In,lines:m,paneId:"sessions",paneLabel:"Sessions",frame:i})});a.memo(function({controller:e,width:s,height:n,frame:r}){const i=tt(),o=ee(e,E=>{const k=E.sessions.activeSessionId;return{activeSessionId:k,activeSession:k&&E.sessions.byId[k]||null,activeHistory:k&&E.history.bySessionId.get(k)||null,activeOutbox:k&&E.outbox?.bySessionId?.[k]||null,authPrincipal:E.auth?.principal||null,branding:E.branding,connectionError:E.connection.error,connectionMode:E.connection.mode,chatScroll:E.ui.scroll.chat,focused:E.ui.focusRegion==="chat"}},qe),l=Math.max(20,s-4),c=a.useMemo(()=>{const E=new Map;return o.activeSessionId&&o.activeHistory&&E.set(o.activeSessionId,o.activeHistory),{branding:o.branding,auth:{principal:o.authPrincipal},connection:{error:o.connectionError,mode:o.connectionMode},ui:{},sessions:{activeSessionId:o.activeSessionId,byId:us(o.activeSessionId,o.activeSession)},history:{bySessionId:E},outbox:{bySessionId:o.activeSessionId&&o.activeOutbox?{[o.activeSessionId]:o.activeOutbox}:{}}}},[o.activeHistory,o.activeSessionId,o.activeSession,o.activeOutbox,o.authPrincipal,o.branding,o.connectionError,o.connectionMode]),d=a.useMemo(()=>tc(c,{width:l}),[l,c]),p=qa(!!d?.animateTitleRight),u=a.useMemo(()=>Ka(d?.titleRight,p),[p,d?.titleRight]),f=!o.activeSessionId&&o.connectionError,m=a.useMemo(()=>f?[{kind:"markup",value:o.branding.splash},{text:"",color:"gray"},{text:"Startup failed",color:"red",bold:!0},{text:o.connectionError,color:"white"},{text:"",color:"gray"},{text:"Check env credentials and model provider config, then relaunch.",color:"yellow"}]:oi(c,l),[o.branding.splash,o.connectionError,l,c,f]),h=String(o.activeSession?.status||"").toLowerCase()==="running",g=Wa(h),b=a.useMemo(()=>f?[]:ii(c,{spinnerFrame:g,maxWidth:l}),[c,f,g,l]),y=a.useMemo(()=>f?[]:ci(c,l),[c,f,l]),v=a.useMemo(()=>y.length>0||b.length>0?[...y,...b]:[],[y,b]);return a.createElement(i.Panel,{title:d.title,titleRight:u,color:d.color,focused:o.focused,width:s,height:n,lines:m,bottomStickyLines:v,scrollOffset:o.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:r})});const Mg=a.memo(function({controller:e,width:s,height:n,shellTitle:r,focused:i=!1,frame:o,showFullscreenTitle:l=!1,embedded:c=!1}){const d=tt(),p=ee(e,_=>({activeSessionId:_.sessions.activeSessionId,activeSession:_.sessions.activeSessionId&&_.sessions.byId[_.sessions.activeSessionId]||null,sessionsFlat:_.sessions.flat,filesBySessionId:_.files.bySessionId,filesFullscreen:!!_.files.fullscreen,selectedArtifactId:_.files.selectedArtifactId,filesFilter:_.files.filter,filePreviewScroll:_.ui.scroll.filePreview}),qe),u=Math.max(20,s-4),f=a.useMemo(()=>({sessions:{activeSessionId:p.activeSessionId,byId:p.activeSessionId&&p.activeSession?{[p.activeSessionId]:p.activeSession}:{},flat:p.sessionsFlat},files:{bySessionId:p.filesBySessionId,fullscreen:p.filesFullscreen,selectedArtifactId:p.selectedArtifactId,filter:p.filesFilter},ui:{scroll:{filePreview:p.filePreviewScroll}}}),[p]),m=a.useMemo(()=>pi(f,{listWidth:Math.max(8,u-4),previewWidth:Math.max(8,u-4)}),[u,f]),h=r||(l?m.fullscreenTitle:m.panelTitle||m.listTitle)||[{text:"Files",color:"magenta",bold:!0}],g=Math.max(9,n-4),b=Math.max(5,Math.min(10,Math.floor(g*.35)));let y=Math.max(5,Math.min(b,(m.listBodyLines||[]).length+2)),v=Math.max(5,g-y-1);const E=8;if(v<E){const _=E-v;y=Math.max(5,y-_),v=Math.max(5,g-y-1)}const k=Math.max(1,y-2),x=Math.max(0,m.selectedIndex-Math.floor(k/2)),w=!c&&o?{x:o.x+2,y:o.y+2,width:u,height:y}:null,S=!c&&o?{x:o.x+2,y:o.y+2+y+1,width:u,height:v}:null,C=ot.map(_=>({text:_==="files"?`[${_}] `:`${_} `,color:_==="files"?"magenta":"gray",bold:_==="files"})),M=a.createElement(d.Column,{width:u},a.createElement(d.Lines,{lines:[C]}),a.createElement(d.Panel,{title:m.listTitle,color:"gray",focused:!1,width:u,height:y,lines:m.listBodyLines||m.listLines.slice(1),scrollOffset:x,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:w}),a.createElement(d.Panel,{title:m.previewTitle,color:"gray",focused:!1,width:u,height:v,lines:m.previewLines,scrollOffset:m.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:S}));return c?M:a.createElement(d.Panel,{title:h,color:"magenta",focused:i,width:s,height:n,marginBottom:In,paneId:"inspector",paneLabel:"Inspector",frame:o},M)}),Rg=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=tt(),l=Math.max(20,s-4),c=ee(e,u=>({activeSessionId:u.sessions.activeSessionId,activeSession:u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]||null}),qe),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:us(c.activeSessionId,c.activeSession)},ui:{inspectorTab:"files"}}),[c.activeSession,c.activeSessionId]),p=a.useMemo(()=>kt(d,{width:l}),[l,d]);return a.createElement(o.Panel,{title:p.title,color:"magenta",focused:i.focused,width:s,height:n,marginBottom:In,paneId:"inspector",paneLabel:"Inspector",frame:r},a.createElement(Mg,{controller:e,width:s,height:n,frame:r,focused:i.focused,embedded:!0}))}),$g=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=tt(),l=Math.max(20,s-4),c=ee(e,u=>({activeSessionId:u.sessions.activeSessionId,activeSession:u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]||null,activeOrchestration:u.sessions.activeSessionId&&u.orchestration.bySessionId?.[u.sessions.activeSessionId]||null,histories:u.history.bySessionId,expandedTurns:u.ui.sequenceExpandedTurns,selectedTurn:u.ui.sequenceSelectedTurn}),qe),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:us(c.activeSessionId,c.activeSession)},history:{bySessionId:c.histories},orchestration:{bySessionId:c.activeSessionId&&c.activeOrchestration?{[c.activeSessionId]:c.activeOrchestration}:{}},ui:{inspectorTab:"sequence"}}),[c.activeOrchestration,c.activeSession,c.activeSessionId,c.histories]),p=a.useMemo(()=>kt(d,{width:l,sequenceExpansion:{expandedTurns:c.expandedTurns||[],selectedTurn:c.selectedTurn??null}}),[l,d,c.expandedTurns,c.selectedTurn]);return Ms(o,p,i,s,n,r)}),_g=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=tt(),l=Math.max(20,s-4),c=ee(e,u=>({activeSessionId:u.sessions.activeSessionId,activeSession:u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]||null,logs:u.logs}),qe),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:us(c.activeSessionId,c.activeSession)},logs:c.logs,ui:{inspectorTab:"logs"}}),[c.activeSession,c.activeSessionId,c.logs]),p=a.useMemo(()=>kt(d,{width:l}),[l,d]);return Ms(o,p,i,s,n,r)}),Lg=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=tt(),l=Math.max(20,s-4),c=ee(e,u=>({activeSessionId:u.sessions.activeSessionId,activeSession:u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]||null,executionHistory:u.executionHistory}),qe),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:us(c.activeSessionId,c.activeSession)},executionHistory:c.executionHistory,ui:{inspectorTab:"history"}}),[c.activeSession,c.activeSessionId,c.executionHistory]),p=a.useMemo(()=>kt(d,{width:l}),[l,d]);return Ms(o,p,i,s,n,r)}),Og=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=tt(),l=Math.max(20,s-4),c=ee(e,u=>({activeSessionId:u.sessions.activeSessionId,sessionsById:u.sessions.byId,sessionsFlat:u.sessions.flat,histories:u.history.bySessionId}),qe),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:c.sessionsById,flat:c.sessionsFlat},history:{bySessionId:c.histories},ui:{inspectorTab:"nodes"}}),[c.activeSessionId,c.histories,c.sessionsById,c.sessionsFlat]),p=a.useMemo(()=>kt(d,{width:l}),[l,d]);return Ms(o,p,i,s,n,r)}),Fg=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=tt(),l=Math.max(20,s-4),c=ee(e,u=>({activeSessionId:u.sessions.activeSessionId,activeSession:u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]||null,sessionStats:u.sessionStats,fleetStats:u.fleetStats,statsViewMode:u.ui.statsViewMode}),qe),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:us(c.activeSessionId,c.activeSession)},sessionStats:c.sessionStats,fleetStats:c.fleetStats,ui:{inspectorTab:"stats",statsViewMode:c.statsViewMode}}),[c.activeSession,c.activeSessionId,c.fleetStats,c.sessionStats,c.statsViewMode]),p=a.useMemo(()=>kt(d,{width:l}),[l,d]);return Ms(o,p,i,s,n,r)});a.memo(function({controller:e,width:s,height:n,frame:r}){const i=ee(e,o=>({inspectorTab:o.ui.inspectorTab,inspectorScroll:o.ui.scroll.inspector,inspectorFollowBottom:o.ui.followBottom?.inspector!==!1,focused:o.ui.focusRegion==="inspector"}),qe);return i.inspectorTab==="files"?a.createElement(Rg,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="sequence"?a.createElement($g,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="logs"?a.createElement(_g,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="history"?a.createElement(Lg,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="stats"?a.createElement(Fg,{controller:e,width:s,height:n,frame:r,meta:i}):a.createElement(Og,{controller:e,width:s,height:n,frame:r,meta:i})});a.memo(function({controller:e,width:s,height:n,maxLines:r,frame:i}){const o=tt(),l=ee(e,u=>{const f=u.sessions.activeSessionId;return{sessionsById:u.sessions.byId,activeSessionId:f,activeSession:f&&u.sessions.byId[f]||null,activeHistory:f&&u.history.bySessionId.get(f)||null,scroll:u.ui.scroll.activity,followBottom:u.ui.followBottom?.activity!==!1,focused:u.ui.focusRegion==="activity",inspectorTab:u.ui.inspectorTab,nodeMapSelectedNode:u.ui.nodeMapSelectedNode,adminWorkers:u.admin?.workers,branding:u.branding,historyBySessionId:u.history.bySessionId,sessionsFlat:u.sessions.flat}},qe),c=l.inspectorTab==="nodes",d=a.useMemo(()=>{const u=new Map;return l.activeSessionId&&l.activeHistory&&u.set(l.activeSessionId,l.activeHistory),{branding:l.branding,admin:{workers:l.adminWorkers},ui:{nodeMapSelectedNode:l.nodeMapSelectedNode},sessions:{activeSessionId:l.activeSessionId,byId:l.sessionsById,flat:l.sessionsFlat},history:{bySessionId:c?l.historyBySessionId:u}}},[l.activeHistory,l.activeSessionId,l.sessionsById,l.adminWorkers,l.branding,l.historyBySessionId,l.nodeMapSelectedNode,l.sessionsFlat,c]),p=a.useMemo(()=>c?sc(d):ui(d,r),[r,c,d]);return a.createElement(o.Panel,{title:p.title,color:"gray",focused:l.focused,width:s,height:n,lines:p.lines,scrollOffset:l.scroll,scrollMode:l.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:i})});a.memo(function({controller:e,rows:s}){const n=tt(),r=ee(e,i=>{const o=i.sessions.activeSessionId,l=o&&i.sessions.byId[o]||null,c=o&&i.outbox?.bySessionId?.[o]?i.outbox.bySessionId[o]:[];return{prompt:i.ui.prompt,promptCursor:i.ui.promptCursor,focused:i.ui.focusRegion==="prompt",answeringQuestion:!!l?.pendingQuestion?.question,editingPending:i.ui.promptEdit?.sessionId===o,hasOutbox:c.length>0,hasPendingOutbox:c.some(d=>d?.phase==="pending")}},qe);return a.createElement(n.Input,{label:r.answeringQuestion?"answer":r.editingPending?"pending":"you",value:r.prompt,cursorIndex:r.promptCursor,focused:r.focused,placeholder:r.answeringQuestion?"Type an answer and press Enter":r.editingPending?"Edit pending prompt, Enter sends batch, Esc cancels":r.hasOutbox?"Type a message and press Enter to queue it":"Type a message and press Enter",rows:s})});a.memo(function({controller:e}){const s=tt(),n=ee(e,p=>({connected:p.connection.connected,workersOnline:p.connection.workersOnline,focusRegion:p.ui.focusRegion,inspectorTab:p.ui.inspectorTab,fullscreenPane:p.ui.fullscreenPane||null,logsAvailable:p.logs.available,logsTailing:p.logs.tailing,filesFullscreen:!!p.files.fullscreen,mode:p.connection.mode,statusText:p.ui.statusText,modal:p.ui.modal,activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,selectedIds:p.sessions.selectedIds,selectMode:p.sessions.selectMode}),qe),r=a.useMemo(()=>({connection:{connected:n.connected,workersOnline:n.workersOnline,mode:n.mode},ui:{focusRegion:n.focusRegion,inspectorTab:n.inspectorTab,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]),i=a.useMemo(()=>sm(r),[r]),o=typeof s.getViewport=="function"?s.getViewport():{width:120},l=Math.max(20,(o.width||120)-4),c=Math.min(Math.max(18,Math.floor(l*.45)),l-8),d=Math.max(8,l-c-3);return a.createElement(s.StatusLine,{left:da(i.left,d),right:da(i.right,c)})});const Dg="modulepreload",Bg=function(t){return"/"+t},ua={},Cc=function(e,s,n){let r=Promise.resolve();if(s&&s.length>0){let c=function(d){return Promise.all(d.map(p=>Promise.resolve(p).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");r=c(s.map(d=>{if(d=Bg(d),d in ua)return;ua[d]=!0;const p=d.endsWith(".css"),u=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":Dg,p||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),p)return new Promise((m,h)=>{f.addEventListener("load",m),f.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return r.then(o=>{for(const l of o||[])l.status==="rejected"&&i(l.reason);return e().catch(i)})},Hg=920,Nc=7,Ug=19,Ei=.24,Tc=16,Pc=8,jg=224,Gg=190,zg=48,ht=16,Mc=.5,Ss=Mc,Wg=24,qg=700,Kg=5e3,Vg=new Set(["low","medium","high","xhigh"]),Yg=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],Xg=["pilotswarm_theme","pilotswarm_session_owner_filter"],Qg={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"Duroxide Event History",files:"Files",stats:"Stats"},pa={sequence:jb,logs:zb,nodes:Wb,history:Yb,files:Xb,stats:Qb};function Zg(t,e,s){const n=Array.isArray(t)?t.filter(Boolean):[];if(n.length===0)return e;const r=n.indexOf(e),o=((r===-1?0:r)+s+n.length)%n.length;return n[o]}function Jg(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function ey(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function ty(t){return typeof t?.transport?.listArtifacts=="function"}function sy(t){return typeof t?.transport?.deleteArtifact=="function"}function ny(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const ry="Session link copied to clipboard",Rc="Artifact link copied to clipboard",iy=140,oy="Only people with access can open this link.";function $c(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function An(t,e,{fullscreen:s=!0}={}){const n=$c(t);return!n||!e?n:`${n}&artifact=${encodeURIComponent(e)}${s?"&view=full":""}`}let Cn=[];function YS(t){Cn=Array.isArray(t)?t:[]}function gn(t){const e=gc(Si(t,Cn));navigator?.clipboard?.writeText&&navigator.clipboard.writeText(e).catch(()=>{})}function _c({url:t,keyPrefix:e,copied:s,onCopy:n}){const r=Si(t,Cn),i=l=>l.currentTarget.select();if(r.length<=1)return a.createElement("div",{className:"ps-link-row"},a.createElement("input",{className:"ps-link-input",readOnly:!0,value:t,onFocus:i}),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>n(e,t)},s===e?"Copied":"Copy"));const o=`${e}:all`;return a.createElement("div",{className:"ps-link-origins"},r.map((l,c)=>{const d=`${e}:${c}`;return a.createElement("div",{className:"ps-link-origin",key:d},a.createElement("div",{className:"ps-link-origin-label"},l.label),a.createElement("div",{className:"ps-link-row"},a.createElement("input",{className:"ps-link-input",readOnly:!0,value:l.url,"aria-label":`${l.label} link`,onFocus:i}),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>n(d,l.url)},s===d?"Copied":"Copy")))}),a.createElement("div",{className:"ps-link-copy-all"},a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>n(o,gc(r))},s===o?"Copied all":"Copy all")))}async function ay(t,e){try{const s=t.transport;if(typeof s?.getSessionAccess=="function"&&((await s.getSessionAccess(e))?.visibility||"private")==="private"){const r=typeof s.listSessionShares=="function"?await s.listSessionShares(e).catch(()=>[]):[];return!Array.isArray(r)||r.length===0}}catch{}return!1}function ly(){if(!(typeof window>"u")){try{for(const t of Yg)window.localStorage.removeItem(t)}catch{}try{for(const t of Xg)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function Lt(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{},s={};if(typeof e.themeId=="string"&&e.themeId.trim()&&(s.themeId=e.themeId.trim()),typeof e.touchScale=="boolean"&&(s.touchScale=e.touchScale),typeof e.touchScaleMobile=="boolean"&&(s.touchScaleMobile=e.touchScaleMobile),xe(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=xe(n,"includeShared")?n:{...n,includeShared:!0}}if(xe(e,"layoutAdjustments")&&(s.layoutAdjustments=Kr(e.layoutAdjustments)),xe(e,"pinnedSessionIds")&&(s.pinnedSessionIds=on(e.pinnedSessionIds)),xe(e,"sessionOrder")&&(s.sessionOrder=Vr(e.sessionOrder)),xe(e,"collapsedSessionIds")&&(s.collapsedSessionIds=cy(e.collapsedSessionIds)),xe(e,"activeSessionId")){const n=e.activeSessionId==null?null:String(e.activeSessionId).trim();s.activeSessionId=n||null}return(e.rightPaneMode==="canvas"||e.rightPaneMode==="panes")&&(s.rightPaneMode=e.rightPaneMode),xe(e,"desktopPanes")&&e.desktopPanes&&typeof e.desktopPanes=="object"&&(s.desktopPanes={canvasOpen:e.desktopPanes.canvasOpen===!0,diagnosticsOpen:e.desktopPanes.diagnosticsOpen===!0,zen:e.desktopPanes.zen===!0}),xe(e,"canvasPrefs")&&(s.canvasPrefs=Yr(e.canvasPrefs)),s}function ps(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches}function yn(){return ps()?"touchScaleMobile":"touchScale"}function bn(){return ps()?"touchScale":"touchScaleMobile"}function cy(t){if(t instanceof Set){const n=[];for(const r of t){const i=String(r||"").trim();i&&n.push(i)}return n.sort(),n}if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const r=String(n||"").trim();!r||e.has(r)||(e.add(r),s.push(r))}return s.sort(),s}function xe(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function ir(t,e=null,s=null,n=null){return Lt({themeId:t.themeId,[yn()]:t.touchScale,sessionOwnerFilter:t.ownerFilter,layoutAdjustments:{paneAdjust:t.paneAdjust,sessionPaneAdjust:t.sessionPaneAdjust,portalSessionColumnAdjust:t.portalSessionColumnAdjust,activityPaneAdjust:t.activityPaneAdjust,canvasPaneAdjust:t.canvasPaneAdjust,diagnosticsPaneAdjust:t.diagnosticsPaneAdjust,diagnosticsSplitAdjust:t.diagnosticsSplitAdjust},pinnedSessionIds:t.pinnedIds,sessionOrder:t.manualOrder,collapsedSessionIds:t.collapsedSessionIds,activeSessionId:t.activeSessionId,...ps()?{...s==="canvas"||s==="panes"?{rightPaneMode:s}:{},...n&&typeof n=="object"?{desktopPanes:n}:{}}:{rightPaneMode:t.canvasOpen?"canvas":"panes",desktopPanes:{canvasOpen:t.canvasOpen===!0,diagnosticsOpen:t.diagnosticsOpen===!0,zen:t.canvasZen===!0}},canvasPrefs:t.canvasPrefs,...typeof e=="boolean"?{[bn()]:e}:{}})}function fa(t,e=null,s=null){return Lt({themeId:t?.ui?.themeId,[yn()]:t?.ui?.touchScale,sessionOwnerFilter:hn(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,sessionOrder:t?.sessions?.manualOrder,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,...ps()?s==="canvas"||s==="panes"?{rightPaneMode:s}:{}:{rightPaneMode:t?.ui?.rightPaneMode,desktopPanes:{canvasOpen:t?.ui?.canvasOpen===!0,diagnosticsOpen:t?.ui?.diagnosticsOpen===!0,zen:t?.ui?.canvasZen===!0}},canvasPrefs:t?.canvas?.prefs,...typeof e=="boolean"?{[bn()]:e}:{}})}function dy(t,e){const s=Lt(t),n=Lt(e);return Lt({themeId:xe(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:xe(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:xe(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:xe(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,sessionOrder:xe(s,"sessionOrder")?s.sessionOrder:n.sessionOrder,...xe(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...xe(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...xe(s,"desktopPanes")?{desktopPanes:s.desktopPanes}:{},...xe(s,"rightPaneMode")?{rightPaneMode:s.rightPaneMode}:{},...xe(s,"canvasPrefs")?{canvasPrefs:s.canvasPrefs}:{},...xe(s,yn())?{touchScale:s[yn()]}:ps()&&xe(s,"touchScale")?{touchScale:s.touchScale}:{}})}async function uy(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:Lt(e)})}function ki(t){return ty(t)?ot:ot.filter(e=>e!=="files")}function _e(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const r of s)if(!Object.prototype.hasOwnProperty.call(e,r)||!Object.is(t[r],e[r]))return!1;return!0}function Tr(t,e,s){return Math.max(e,Math.min(s,t))}const Vs=120,py=1440;function fy(t){return!t||typeof t!="object"?!1:t.desktopPanes&&typeof t.desktopPanes=="object"?!0:t.rightPaneMode==="canvas"||t.rightPaneMode==="panes"}const xi=640,Ii=320;function Pr(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-Tc-Pc*2),n=s*Ei,r=Math.max(0,s-jg);return{minAdjust:-n,maxAdjust:r-n}}function my(t,e){const s=Pr(t),n=Math.max(0,Number(t)||0),i=Math.max(0,n-Tc-Pc*2)*Ei;return Tr(i+(Number(e)||0),0,i+s.maxAdjust)}function hy(t){return t<=zg?"hidden":t<=Gg?"compact":"wrap"}function Lc(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:Jt(t?.ui?.prompt||"")}function Nn(t){return Is({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,Lc(t),t.ui.layout?.sessionPaneAdjust??0)}function gy(t,e,s=!1){return Math.max(20,t-(s?6:4))}function Oc({slack:t=1,debounceMs:e=120}={}){const[s,n]=a.useState(null),r=a.useRef({node:null,observer:null,timer:null,frame:null}),i=a.useCallback(o=>{const l=r.current;if(l.observer&&(l.observer.disconnect(),l.observer=null),l.timer&&(window.clearTimeout(l.timer),l.timer=null),l.frame&&(cancelAnimationFrame(l.frame),l.frame=null),l.node=o,!o||typeof window>"u"||typeof ResizeObserver>"u")return;const c=()=>{if(l.timer=null,l.node!==o||!o.isConnected)return;const p=o.querySelector(".ps-line")||o,u=window.getComputedStyle(p),f=document.createElement("span");f.style.cssText="position:absolute;visibility:hidden;white-space:pre;",f.style.fontFamily=u.fontFamily,f.style.fontSize=u.fontSize,f.style.fontWeight=u.fontWeight,f.style.letterSpacing=u.letterSpacing,f.textContent="0".repeat(100),o.appendChild(f);const m=f.getBoundingClientRect().width/100||0;if(f.remove(),!(m>0))return;const h=window.getComputedStyle(o),g=o.clientWidth-(parseFloat(h.paddingLeft)||0)-(parseFloat(h.paddingRight)||0);if(!(g>50))return;const b=Math.max(20,Math.floor(g/m)-t);n(y=>y===b?y:b)},d=()=>{l.timer&&window.clearTimeout(l.timer),l.timer=window.setTimeout(c,e)};l.frame=requestAnimationFrame(c),l.observer=new ResizeObserver(d);try{l.observer.observe(o,{box:"content-box"})}catch{l.observer.observe(o)}},[t,e]);return[s,i]}function Ue(t){const e=[],s=n=>{const r=String(n||"");return!r.includes("\\n")||r.includes(`
|
|
83
|
-
`)?r:r.replace(/\\n/g,`
|
|
84
|
-
`)};for(const n of t||[]){if(n?.kind==="markup"){const r=n.splashAlt?[{text:n.value,variant:"desktop"},{text:n.splashAlt,variant:"mobile"}]:[{text:n.value,variant:null}];for(const i of r)for(const o of Xa(i.text||""))e.push({kind:"runs",runs:o,preserve:!0,splashVariant:i.variant});continue}if(n?.kind==="markdownTable"||n?.kind==="cardStart"||n?.kind==="cardEnd"||n?.kind==="imageAttachments"){e.push(n);continue}if(n?.kind==="runs"){const r=Array.isArray(n.runs)?n.runs:[];if(r.length===1){const i=r[0]||{},o=s(i.text||"");if(o.includes(`
|
|
85
|
-
`)){const l=o.split(`
|
|
86
|
-
`);for(const c of l)e.push({kind:"runs",runs:[{...i,text:c}]});continue}e.push({kind:"runs",runs:[{...i,text:o}]});continue}e.push({kind:"runs",runs:r.map(i=>({...i,text:s(i?.text||"")}))});continue}if(Array.isArray(n)){e.push({kind:"runs",runs:n});continue}if(n&&typeof n=="object"&&typeof n.text=="string"){const r=s(n.text);if(r.includes(`
|
|
87
|
-
`)){const i=r.split(`
|
|
88
|
-
`);for(const o of i)e.push({kind:"text",...n,text:o});continue}e.push({kind:"text",...n,text:r});continue}e.push({kind:"text",...n})}return e}function et(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function Fc(t=[]){return t.map(e=>String(e?.text||"")).join("")}function ma(t){return Array.isArray(t)?Fc(t):String(t||"")}function ha(t,e=40){if(!Array.isArray(t)){const i=String(t||"");return[{text:i.length>e?`${i.slice(0,e-1)}…`:i,color:"white",bold:!0}]}const s=[],n=i=>/^[\s·—-]+$/.test(String(i?.text||""));let r=Math.max(8,e);for(const i of t){if(r<=0)break;if(i?.color==="gray"&&s.length>0&&!n(i))continue;const l=String(i?.text||"");if(!l)continue;if(n(i)&&r<l.length+2)break;const c=l.length>r&&r>1?`${l.slice(0,r-1)}…`:l.slice(0,r);c&&(s.push({...i,text:c}),r-=c.length)}for(;s.length>0&&n(s[s.length-1]);)s.pop();return s.length>0?s:t}function yy(t){typeof document>"u"||(t?document.documentElement.dataset.psTouch="1":delete document.documentElement.dataset.psTouch)}function by(t){const e=pt(t);if(!e||typeof document>"u")return;const s=document.documentElement;s.style.setProperty("--ps-page-background",e.page.background),s.style.setProperty("--ps-page-foreground",e.page.foreground),s.style.setProperty("--ps-surface",e.tui.surface),s.style.setProperty("--ps-background",e.tui.background),s.style.setProperty("--ps-foreground",e.tui.foreground),s.style.setProperty("--ps-muted",e.tui.gray),s.style.setProperty("--ps-border",e.tui.border||e.tui.gray),s.style.setProperty("--ps-selection-background",e.tui.selectionBackground),s.style.setProperty("--ps-selection-foreground",e.tui.selectionForeground),s.style.setProperty("--ps-highlight-background",e.tui.activeHighlightBackground),s.style.setProperty("--ps-highlight-foreground",e.tui.activeHighlightForeground),s.style.setProperty("--ps-modal-backdrop",e.page.modalBackdrop),s.style.setProperty("--ps-modal-background",e.page.modalBackground),s.style.setProperty("--ps-modal-border",e.page.modalBorder),s.style.setProperty("--ps-modal-foreground",e.page.modalForeground),s.style.setProperty("--ps-modal-muted",e.page.modalMuted),s.style.setProperty("--ps-modal-selected-background",e.page.modalSelectedBackground),s.style.setProperty("--ps-modal-selected-border",e.page.modalSelectedBorder),s.style.setProperty("--ps-modal-selected-foreground",e.page.modalSelectedForeground),s.style.setProperty("--ps-accent",e.tui.cyan),s.style.setProperty("--ps-success",e.tui.green),s.style.setProperty("--ps-warning",e.tui.yellow),s.style.setProperty("--ps-danger",e.tui.red),s.dataset.psTheme=e.id}function ga(t){const[e,s]=a.useState({width:0,height:0});return a.useLayoutEffect(()=>{const n=t.current;if(!n)return;const r=()=>{s({width:n.clientWidth,height:n.clientHeight})};r();const i=new ResizeObserver(r);return i.observe(n),window.addEventListener("resize",r),()=>{i.disconnect(),window.removeEventListener("resize",r)}},[t]),e}function Sy(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/Nc)),height:Math.max(18,Math.floor(s/Ug))}}function vy(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function wy(t){return vy(t)<=Mc}function Ey(t,e,s,n=!1){if(!t)return 0;const r=Math.max(0,t.scrollHeight-t.clientHeight);if(n)return Math.max(0,Math.min(t.scrollTop,r));const i=Math.max(0,Number(e)||0)*ht;return s==="bottom"?Math.max(0,r-i):Math.min(r,i)}function ky(t,e,s,n,r,i,{stickyBottom:o=!1}={}){const l=a.useMemo(()=>Ue(e),[e]),c=a.useRef(null),d=a.useRef({scrollMode:n,scrollOffset:s}),p=a.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),u=a.useRef({width:null,height:null}),[f,m]=a.useState(0);a.useLayoutEffect(()=>{const x=t.current;if(!x||typeof ResizeObserver>"u")return;u.current={width:x.clientWidth,height:x.clientHeight};const w=new ResizeObserver(()=>{const S={width:x.clientWidth,height:x.clientHeight},C=u.current;S.width===C.width&&S.height===C.height||(u.current=S,m(M=>M+1))});return w.observe(x),()=>w.disconnect()},[t]),a.useLayoutEffect(()=>{const x=t.current;if(!x)return;const w=d.current,S=p.current,C=typeof performance<"u"?performance.now():Date.now(),M=S.touching||C-(S.lastUserScrollAt||0)<qg,_=S.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-S.lastDispatchedOffset)<2;if(M&&n===w?.scrollMode&&(s===w?.scrollOffset||_)){d.current={scrollMode:n,scrollOffset:s};return}const O=o&&n==="top"&&w?.scrollMode==="top"&&w?.scrollOffset===s,R=Ey(x,s,n,O);if(Math.abs(x.scrollTop-R)>Ss){const T={target:R};c.current=T,x.scrollTop=R,window.requestAnimationFrame(()=>{c.current===T&&(c.current=null)})}d.current={scrollMode:n,scrollOffset:s}},[l,t,n,s,o,f]);const h=Iy(x=>{i.dispatch({type:"ui/scroll",pane:r,offset:x})}),g=a.useCallback(()=>{const x=t.current;if(!x||!r)return;const w=c.current;if(w){if(Math.abs(x.scrollTop-w.target)<=Ss)return;c.current=null}p.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const S=Math.max(0,x.scrollHeight-x.clientHeight);if(S<=0)return;if(o&&typeof i.updatePaneScrollFromViewport=="function"){const M=Math.max(0,x.scrollTop)/ht;p.current.lastDispatchedOffset=M,i.updatePaneScrollFromViewport(r,M,{atBottom:wy(x)});return}const C=n==="bottom"?Math.max(0,S-x.scrollTop):Math.max(0,x.scrollTop);p.current.lastDispatchedOffset=C/ht,h(C/ht),r==="chat"&&n==="bottom"&&x.scrollTop<=Ss&&i.armChatTopHistoryLoad?.()},[i,h,r,t,n,o]),b=a.useCallback(x=>{const w=t.current;if(!w||r!=="chat"||n!=="bottom"||x.deltaY>=0||w.scrollTop>Ss)return;const S=Math.max(0,w.scrollHeight-w.clientHeight);i.handleChatTopHistoryScrollIntent?.(S/ht)},[i,r,t,n]),y=a.useRef({startY:null,fired:!1}),v=a.useCallback(x=>{p.current.touching=!0,!(r!=="chat"||n!=="bottom")&&(y.current={startY:x.touches?.[0]?.clientY??null,fired:!1})},[r,n]),E=a.useCallback(()=>{p.current.touching=!1,p.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),k=a.useCallback(x=>{const w=t.current,S=y.current;if(!w||r!=="chat"||n!=="bottom"||S.fired||S.startY==null||w.scrollTop>Ss)return;const C=x.touches?.[0]?.clientY;if(C==null||C-S.startY<Wg)return;S.fired=!0;const M=Math.max(0,w.scrollHeight-w.clientHeight);i.handleChatTopHistoryScrollIntent?.(M/ht+1,{force:!0})},[i,r,t,n]);return{normalizedLines:l,onScroll:g,onWheel:b,onTouchStart:v,onTouchMove:k,onTouchEnd:E}}function Ge({runs:t,theme:e}){return a.createElement(a.Fragment,null,(t||[]).map((s,n,r)=>{const i=n>0&&!!Sn(r[n-1]?.href),o={color:et(e,s.color),backgroundColor:et(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"};if(s?.trailingRule)return a.createElement("span",{key:`${n}:rule`,className:"ps-line-trailing-rule",style:o},s.text||"");const l=String(s?.href||"").trim(),c=/^https?:\/\//i.test(l),d=Sn(l);if(d)return a.createElement(Wc,{key:`${n}:${s.text||""}`,artifactRef:d,style:o});const p=i?Uc(s.text||""):s.text||"";return i&&!p?null:c?a.createElement("a",{key:`${n}:${s.text||""}`,className:"ps-md-link",href:l,target:"_blank",rel:"noreferrer",style:o},p):a.createElement("span",{key:`${n}:${s.text||""}`,style:o},p)}))}function xy({line:t,theme:e}){const s=String(t?.body||"").trim();return a.createElement("details",{className:"ps-system-notice"},a.createElement("summary",{className:"ps-system-notice-summary",style:{color:et(e,t?.color)||"var(--ps-muted)"}},a.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),s?a.createElement("div",{className:"ps-system-notice-body"},a.createElement(Mi,{content:s,theme:e})):null)}function Iy(t){const e=a.useRef(0),s=a.useRef(null),n=a.useRef(t);return n.current=t,a.useEffect(()=>()=>{e.current&&cancelAnimationFrame(e.current)},[]),a.useCallback((...r)=>{s.current=r,!e.current&&(e.current=requestAnimationFrame(()=>{e.current=0;const i=s.current;s.current=null,i&&n.current(...i)}))},[])}const je=a.memo(function({line:e,theme:s,className:n=""}){const r=n?`ps-line ${n}`:"ps-line";return e?e.kind==="systemNotice"?a.createElement(xy,{line:e,theme:s}):e.kind==="runs"?a.createElement("div",{className:r},a.createElement(Ge,{runs:e.runs,theme:s})):a.createElement("div",{className:r,style:{color:et(s,e.color),backgroundColor:et(s,e.backgroundColor),fontWeight:e.bold?700:400,textDecoration:e.underline?"underline":"none"}},e.text||" "):a.createElement("div",{className:r}," ")});function Ve(t){return t?t.kind==="runs"?Fc(t.runs):String(t.text||""):""}function Dc(t,e,s,n){const r=a.useRef(!1);return a.useLayoutEffect(()=>{const i=t.current;if(!i||!s)return;const o=Math.max(0,i.scrollHeight-i.clientHeight),l=Math.min(o,Math.max(0,Number(e)||0)*ht);Math.abs(i.scrollTop-l)>2&&(r.current=!0,i.scrollTop=l,window.requestAnimationFrame(()=>{r.current=!1}))},[t,e,s]),a.useCallback(i=>{if(r.current)return;const o=t.current;!o||!s||i&&i.target!==o||o.scrollHeight<=o.clientHeight||n.dispatch({type:"ui/scroll",pane:s,offset:Math.max(0,o.scrollTop)/ht})},[n,s,t])}const Ay={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"},Cy=new Set(["diff","patch","udiff"]),Ny=/\.(patch|diff)$/i,Ai=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,Ci=/\.(png|jpe?g|gif|webp|avif|bmp|svg|ico)$/i,Ty={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",bmp:"image/bmp",svg:"image/svg+xml",ico:"image/x-icon"};function Py(t){const e=/\.([a-z0-9]+)$/i.exec(String(t||""));return e&&Ty[e[1].toLowerCase()]||null}const My={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 Ry(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 $y=/\.(html?|xhtml)$/i;function Bc(t,e){return $y.test(String(t||""))?!0:/^(text\/html|application\/xhtml\+xml)$/i.test(String(e||"").trim().split(";")[0])}const _y=/\.(csv|tsv)$/i;function Hc(t,e){return _y.test(String(t||""))?!0:/^text\/(csv|tab-separated-values)$/i.test(String(e||"").trim())}const or=2e3;function Ly(t){const e=String(t??"");return/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Oy({content:t,filename:e}){const[s,n]=a.useState(null),r=a.useRef(null),i=a.useRef(null),o=a.useRef(null);a.useEffect(()=>{let k=!1;return n(null),Cc(()=>import("./papaparse.min-DWBU_pXS.js").then(x=>x.p),[]).then(x=>{if(k)return;const w=x.default||x,S=/\.tsv$/i.test(String(e||""))?" ":"",C=w.parse(String(t||"").trim(),{delimiter:S,skipEmptyLines:"greedy"});n({rows:C.data||[],errors:C.errors||[]})}).catch(()=>{k||n({rows:null,errors:[{message:"parser unavailable"}]})}),()=>{k=!0}},[t,e]),a.useEffect(()=>{const k=()=>{o.current=null};return window.addEventListener("mouseup",k),()=>window.removeEventListener("mouseup",k)},[]);const l=a.useCallback((k,x)=>{if(!k||!x)return;const w=window.getSelection();if(!w)return;const S=!!(k.compareDocumentPosition(x)&Node.DOCUMENT_POSITION_PRECEDING),C=document.createRange();C.setStartBefore(S?x:k),C.setEndAfter(S?k:x),w.removeAllRanges(),w.addRange(C)},[]),c=k=>k.target?.closest?k.target.closest("td,th"):null,d=a.useCallback(k=>{if(k.button!==0)return;const x=c(k);x&&(k.preventDefault(),r.current?.focus(),o.current=x,l(x,x))},[l]),p=a.useCallback(k=>{if(!o.current||!(k.buttons&1))return;const x=c(k);x&&l(o.current,x)},[l]),u=a.useCallback(k=>{if(!(k.metaKey||k.ctrlKey)||k.altKey||k.key!=="a"&&k.key!=="A")return;const x=i.current,w=window.getSelection();if(!x||!w)return;k.preventDefault(),k.stopPropagation();const S=document.createRange();S.selectNodeContents(x),w.removeAllRanges(),w.addRange(S)},[]),f=a.useCallback(k=>{const x=i.current,w=window.getSelection();if(!x||!w||w.rangeCount===0)return;const S=w.getRangeAt(0),C=new Map;for(const M of x.querySelectorAll("th,td")){if(!S.intersectsNode(M))continue;const _=M.parentElement;C.has(_)||C.set(_,[]),C.get(_).push(Ly(M.textContent))}C.size!==0&&(k.clipboardData.setData("text/plain",Array.from(C.values(),M=>M.join(" ")).join(`
|
|
89
|
-
`)),k.preventDefault())},[]);if(!s)return a.createElement("div",{className:"ps-csv-status"},"Parsing…");if(!s.rows||s.rows.length===0)return a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,String(t||"")));const[m,...h]=s.rows,g=h.reduce((k,x)=>Math.max(k,x.length),m.length),b=Array.from({length:g},(k,x)=>m[x]??""),y=h.length>or,v=y?h.slice(0,or):h,E=[];return y&&E.push(`showing first ${or} of ${h.length} rows`),s.errors.length&&E.push(`${s.errors.length} parse warning${s.errors.length===1?"":"s"}`),a.createElement("div",{className:"ps-csv-wrap",ref:r,tabIndex:0,onMouseDown:d,onMouseMove:p,onKeyDown:u,onCopy:f},a.createElement("table",{className:"ps-csv-table",ref:i},a.createElement("thead",null,a.createElement("tr",null,b.map((k,x)=>a.createElement("th",{key:`h${x}`},String(k??""))))),a.createElement("tbody",null,v.map((k,x)=>a.createElement("tr",{key:`r${x}`},b.map((w,S)=>a.createElement("td",{key:`c${S}`},String(k[S]??""))))))),E.length?a.createElement("div",{className:"ps-csv-status"},E.join(" · ")):null)}function Ni(t){const e=/\.([A-Za-z0-9]+)$/.exec(String(t||""));return e&&My[e[1].toLowerCase()]||null}function Ti(t,e){return Ny.test(String(t||""))?!0:/^text\/x-(patch|diff)$/i.test(String(e||"").trim())}function Uc(t){const e=String(t??"");if(e.startsWith(Us))return e.slice(Us.length);const s=Us.trimStart();return e.startsWith(s)?e.slice(s.length):e}function Sn(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 jc=a.createContext(null);function Gc(t){const e=String(t||""),s=(/\.([A-Za-z0-9]+)$/.exec(e)?.[1]||"").toLowerCase();return Bc(e)?{kind:"page",type:"HTML",noun:"Page"}:Ti(e)?{kind:"diff",type:s.toUpperCase()||"DIFF",noun:"Diff"}:Ci.test(e)?{kind:"image",type:s.toUpperCase(),noun:"Image"}:Hc(e)?{kind:"table",type:s.toUpperCase(),noun:"Table"}:/\.md$/i.test(e)?{kind:"doc",type:"MD",noun:"Document"}:Ni(e)?{kind:"code",type:s.toUpperCase(),noun:"Code"}:{kind:"file",type:s.toUpperCase()||"FILE",noun:"File"}}function zc(t){const e=String(t||"").replace(/\.[A-Za-z0-9]+$/,""),n=(e.replace(/[-_ ]?\d{6,8}$/,"")||e).replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):String(t||"Artifact")}function Fy({kind:t}){const e={fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},s=t==="page"?[a.createElement("rect",{key:"w",x:2.5,y:3.5,width:15,height:13,rx:2,...e}),a.createElement("path",{key:"b",d:"M2.5 7.5h15",...e}),a.createElement("circle",{key:"d",cx:5.2,cy:5.5,r:.7,fill:"currentColor",stroke:"none"})]:t==="image"?[a.createElement("rect",{key:"f",x:2.5,y:3.5,width:15,height:13,rx:2,...e}),a.createElement("path",{key:"m",d:"M2.5 13l4-4 4 3.5 3-2.5 3.5 3",...e})]:t==="table"?[a.createElement("rect",{key:"f",x:2.5,y:3.5,width:15,height:13,rx:2,...e}),a.createElement("path",{key:"g",d:"M2.5 8h15M8 8v8.5M2.5 12.5h15",...e})]:[a.createElement("path",{key:"p",d:"M5 2.5h6.5L16 7v10.5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-14a1 1 0 0 1 1-1z",...e}),a.createElement("path",{key:"c",d:"M11.5 2.5V7H16",...e}),t==="diff"?a.createElement("path",{key:"t",d:"M7 11h6M10 8.5v5",...e}):a.createElement("path",{key:"t",d:"M7 10.5h6M7 13.5h4",...e})];return a.createElement("svg",{className:"ps-artifact-card-glyph",viewBox:"0 0 20 20","aria-hidden":"true"},s)}function Wc({artifactRef:t}){const e=a.useContext(jc),s=Gc(t.filename),n=a.useCallback(r=>{r.preventDefault(),r.stopPropagation(),Dy(e,t.sessionId,t.filename)},[e,t.sessionId,t.filename]);return a.createElement("button",{type:"button",className:`ps-artifact-card is-${s.kind}`,onClick:n,title:`Open ${t.filename}`},a.createElement("span",{className:"ps-artifact-card-thumb","aria-hidden":"true"},a.createElement(Fy,{kind:s.kind})),a.createElement("span",{className:"ps-artifact-card-text"},a.createElement("span",{className:"ps-artifact-card-title"},zc(t.filename)),a.createElement("span",{className:"ps-artifact-card-meta"},`${s.noun} · ${s.type}`)),a.createElement("span",{className:"ps-artifact-card-open"},"Open"))}function Dy(t,e,s){if(!t?.revealArtifact)return;const n=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;Promise.resolve(n?t.revealArtifact(e,s,{fullscreen:!0}):t.revealArtifact(e,s,{pane:!0})).catch(()=>{})}function qc(t){return Cy.has(String(t||"").trim().toLowerCase())}const By=/^(?: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 Hy(t){return By.test(t)?"meta":t.startsWith("@@")?"hunk":t.startsWith("+")?"add":t.startsWith("-")?"del":"context"}const Uy={add:"green",del:"red",hunk:"cyan",meta:"gray"};function Pi(t,e){return String(t||"").replace(/\n$/,"").split(`
|
|
90
|
-
`).map((n,r)=>{const i=Hy(n),o=Uy[i],l=i==="add"||i==="del"||i==="context"&&n.startsWith(" "),c=l?n.slice(0,1):"",d=l?n.slice(1):n;return a.createElement("span",{key:`d:${r}`,className:`ps-diff-line is-${i}`,style:o?{color:et(e,o)||void 0}:void 0},a.createElement("span",{className:"ps-diff-marker","aria-hidden":"true"},c.trim()),a.createElement("span",{className:"ps-diff-text"},d))})}function Kc(t){return String(t||"").trim().toLowerCase()==="mermaid"}const ya={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 jy(t){const e={type:"comment",re:/#[^\n]*/y},s={type:"comment",re:/\/\/[^\n]*|\/\*[\s\S]*?\*\//y},n={type:"comment",re:/--[^\n]*|\/\*[\s\S]*?\*\//y},r={type:"number",re:/\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b0[xX][0-9a-fA-F]+\b/y},i={type:"identifier",re:/[A-Za-z_$][\w$]*/y},o={type:"string",re:/"(?:\\.|[^"\\])*"?/y},l={type:"string",re:/'(?:\\.|[^'\\])*'?/y},c={type:"string",re:/`(?:\\.|[^`\\])*`?/y},d={type:"string",re:/"""[\s\S]*?"""|'''[\s\S]*?'''/y};switch(t){case"python":return[e,d,o,l,r,i];case"shell":return[e,o,l,r,i];case"sql":return[n,l,o,r,i];case"yaml":return[e,o,l,r,i];case"json":return[o,r,i];case"css":return[{type:"comment",re:/\/\*[\s\S]*?\*\//y},o,l,r,i];default:return[s,o,l,c,r,i]}}const Gy={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},zy=2e4,Nt=new Map,Wy=120;function qy(t,e){const s=`${e||""}\0${t}`,n=Nt.get(s);if(n)return Nt.delete(s),Nt.set(s,n),n;const r=Ky(t,e);return Nt.set(s,r),Nt.size>Wy&&Nt.delete(Nt.keys().next().value),r}function Ky(t,e){const s=Ay[String(e||"").trim().toLowerCase()]||"default",n=ya[s]||ya.js,r=jy(s),i=[];let o=0,l=0;const c=d=>{d>l&&i.push({type:"plain",text:t.slice(l,d)})};for(;o<t.length;){let d=null;for(const u of r){u.re.lastIndex=o;const f=u.re.exec(t);if(f&&f.index===o&&f[0].length>0){d={type:u.type,text:f[0]};break}}if(!d){o+=1;continue}let p=d.type;if(p==="identifier")if(n.has(d.text))p="keyword";else{const u=t.slice(o+d.text.length);p=/^\s*\(/.test(u)?"fn":"plain"}if(p==="plain"){o+=d.text.length;continue}c(o),i.push({type:p,text:d.text}),o+=d.text.length,l=o}return c(t.length),i}function ls(t,e,s){const n=String(t||"");if(!n||n.length>zy)return n;let r;try{r=qy(n,e)}catch{return n}return r.map((i,o)=>{const l=Gy[i.type];return l?a.createElement("span",{key:`t:${o}`,className:`ps-code-token is-${i.type}`,style:{color:et(s,l)||void 0}},i.text):a.createElement(a.Fragment,{key:`t:${o}`},i.text)})}let Hs=null;function Vy(){return Hs||(Hs=Cc(()=>import("./mermaid.core-Di8sQC4g.js").then(t=>t.bp),[]).then(t=>t.default||t).catch(t=>{throw Hs=null,t})),Hs}function Yy(t,e){return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"default":"dark",fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"}),t}let ba=0,Sa=Promise.resolve();function Xy(t){const e=Sa.then(t,t);return Sa=e.then(()=>{},()=>{}),e}function Vc({code:t,theme:e,fallback:s}){const[n,r]=a.useState(null),[i,o]=a.useState(!1),[l,c]=a.useState(""),d=a.useMemo(()=>ju(e),[e]);return a.useEffect(()=>{let p=!0;const u=String(t||"").trim();if(u)return o(!1),Vy().then(f=>Xy(async()=>{if(!p)return;Yy(f,d),ba+=1;const m=`ps-mermaid-${ba}`;await f.parse(u);const{svg:h}=await f.render(m,u);p&&r(h)})).catch(f=>{p&&(r(null),o(!0),c(String(f?.message||f)))}),()=>{p=!1}},[t,d]),n&&!i?a.createElement("div",{className:"ps-mermaid",dangerouslySetInnerHTML:{__html:n}}):i&&l?a.createElement("div",{className:"ps-mermaid-failed"},a.createElement("div",{className:"ps-mermaid-error"},`Diagram could not be rendered — ${String(l).split(`
|
|
91
|
-
`)[0]}`),s):s}function ut(t,e,s="md"){const n=Ur(t);return n.map((r,i)=>{const o=`${s}:${i}`;if(i>0&&n[i-1]?.type==="link"&&Sn(n[i-1]?.href)){const l=Uc(r.text||"");if(!l)return null;l!==r.text&&(r={...r,text:l})}if(r.type==="code")return a.createElement("code",{key:o,className:"ps-md-inline-code"},r.text);if(r.type==="strong")return a.createElement("strong",{key:o,className:"ps-md-strong"},ut(r.text,e,`${o}:strong`));if(r.type==="em")return a.createElement("em",{key:o,className:"ps-md-em"},ut(r.text,e,`${o}:em`));if(r.type==="link"){const l=Sn(r.href);return l?a.createElement(Wc,{key:o,artifactRef:l}):/^https?:\/\//i.test(String(r.href||"").trim())?a.createElement("a",{key:o,className:"ps-md-link",href:r.href,target:"_blank",rel:"noreferrer",style:{color:et(e,"cyan")}},r.text):a.createElement("span",{key:o,style:{color:et(e,"cyan")}},r.text)}return a.createElement(a.Fragment,{key:o},r.text)})}function Mr(t=""){return String(t||"").replace(/\s+/g," ").trim()}const Qy=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],Zy=24,Jy=32,eb=6,va=30,tb=56,ar=.4,sb=1.4,nb=2;function Yc(t=[]){const e=Math.max(0,...t.map(h=>h.length));if(e<=0)return null;const s=t[0]||[],n=Math.max(1,t.length-1),r=Array.from({length:e},()=>({max:0,spaceCells:0}));for(let h=0;h<t.length;h+=1){const g=t[h];for(let b=0;b<e;b+=1){const y=Mr(g[b]||"");y.length>r[b].max&&(r[b].max=y.length),h>0&&/\s/.test(y)&&(r[b].spaceCells+=1)}}let i=-1,o=0;for(let h=0;h<e;h+=1){const g=r[h];if(g.max<Zy||g.spaceCells/n<.4)continue;const y=Mr(s[h]||"").toLowerCase(),v=Qy.some(k=>y.includes(k))?60:0,E=g.max+v;E>o&&(o=E,i=h)}if(i<0)return null;const l=r.map((h,g)=>g===i?0:Math.max(eb,Math.min(h.max+2,Jy))),c=l.reduce((h,g)=>h+g,0),d=r[i],p=Math.max(va,Math.min(d.max*.45,tb,Math.max(va,c*sb))),u=l.map((h,g)=>g===i?p:h),f=u.reduce((h,g)=>h+g,0);if(f>0&&u[i]/f<ar){const h=f-u[i];u[i]=h*(ar/(1-ar))}const m=u.reduce((h,g)=>h+g,0);return m>0?{widths:u.map(h=>`${(h/m*100).toFixed(2)}%`),flexIndex:i,minWidth:`${Math.ceil(m+nb)}ch`}:null}function Xc(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(i=>Mr(i?.[n]||"")).filter(Boolean).join(" / ")||null)}function wa(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 Ea(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function rb(t=""){const s=String(t||"").replace(/\r\n?/g,`
|
|
92
|
-
`).split(`
|
|
93
|
-
`),n=[];for(let r=0;r<s.length;){const i=s[r],o=i.trim();if(!o){r+=1;continue}const l=/^```(\S*)\s*$/.exec(o);if(l){const u=l[1]||"",f=[];for(r+=1;r<s.length&&!/^```/.test(s[r].trim());)f.push(s[r]),r+=1;r<s.length&&(r+=1),n.push({type:"code",language:u,content:f.join(`
|
|
94
|
-
`)});continue}const c=/^(#{1,6})\s+(.*)$/.exec(i);if(c){n.push({type:"heading",level:c[1].length,text:c[2].trim()}),r+=1;continue}if(i.includes("|")&&r+1<s.length&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(s[r+1].trim())){const u=Ea(i);r+=2;const f=[];for(;r<s.length&&s[r].includes("|")&&s[r].trim();)f.push(Ea(s[r])),r+=1;n.push({type:"table",header:u,rows:f});continue}if(/^\s*>/.test(i)){const u=[];for(;r<s.length&&/^\s*>/.test(s[r]);)u.push(s[r].replace(/^\s*>\s?/,"")),r+=1;n.push({type:"blockquote",text:u.join(`
|
|
95
|
-
`).trim()});continue}const d=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(i);if(d){const u=/\d+\./.test(d[2]),f=[];for(;r<s.length;){const m=s[r],h=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(m);if(!h||/\d+\./.test(h[2])!==u)break;const g=[h[3].trim()];for(r+=1;r<s.length&&s[r].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[r])&&!wa(s[r],s[r+1]||"");)g.push(s[r].trim()),r+=1;if(f.push(g.join(" ")),!s[r]?.trim())break}n.push({type:"list",ordered:u,items:f});continue}const p=[i.trim()];for(r+=1;r<s.length&&s[r].trim()&&!wa(s[r],s[r+1]||"");)p.push(s[r].trim()),r+=1;n.push({type:"paragraph",text:p.join(" ")})}return n}function Mi({content:t,theme:e}){const s=a.useMemo(()=>rb(t),[t]);return s.length===0?a.createElement("div",{className:"ps-empty-state"},"No preview content."):a.createElement("div",{className:"ps-markdown-preview"},s.map((n,r)=>{if(n.type==="heading")return a.createElement("div",{key:`block:${r}`,className:`ps-md-heading is-h${n.level}`},ut(n.text,e,`heading:${r}`));if(n.type==="code"){const i=qc(n.language),o=a.createElement("section",{key:`block:${r}`,className:`ps-md-code-block${i?" is-diff":""}`},a.createElement("div",{className:"ps-md-code-header"},n.language||"text"),a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,i?Pi(n.content,e):ls(n.content,n.language,e))));return Kc(n.language)?a.createElement(Vc,{key:`block:${r}`,code:n.content,theme:e,fallback:o}):o}if(n.type==="blockquote")return a.createElement("blockquote",{key:`block:${r}`,className:"ps-md-quote"},ut(n.text,e,`quote:${r}`));if(n.type==="list"){const i=n.ordered?"ol":"ul";return a.createElement(i,{key:`block:${r}`,className:`ps-md-list${n.ordered?" is-ordered":""}`},n.items.map((o,l)=>a.createElement("li",{key:`item:${l}`,className:"ps-md-list-item"},ut(o,e,`list:${r}:${l}`))))}if(n.type==="table"){const i=Math.max(n.header.length||0,...n.rows.map(h=>h.length)),o=i>0&&i<=6,l=o?Yc([n.header,...n.rows]):null,c=!!l,d=l?l.flexIndex:-1,p=h=>h===d?"is-flex-column":null,u=Xc([n.header],i),f=`ps-md-table${o?" is-fit-width":""}${c?" has-flex-column":""}`,m=`ps-md-table-wrap${o?" is-fit-width":""}${c?" has-flex-column":""}`;return a.createElement("div",{key:`block:${r}`,className:m},a.createElement("table",{className:f,style:l?.minWidth?{"--ps-table-min-width":l.minWidth}:void 0},l?a.createElement("colgroup",null,l.widths.map((h,g)=>a.createElement("col",{key:`col:${g}`,className:p(g)||void 0,style:{width:h}}))):null,a.createElement("thead",null,a.createElement("tr",null,n.header.map((h,g)=>a.createElement("th",{key:`head:${g}`,className:p(g)||void 0},ut(h,e,`table:${r}:head:${g}`))))),a.createElement("tbody",null,n.rows.map((h,g)=>a.createElement("tr",{key:`row:${g}`},h.map((b,y)=>a.createElement("td",{key:`cell:${g}:${y}`,className:p(y)||void 0,"data-label":u[y]||void 0},a.createElement("span",{className:"ps-table-cell-value"},ut(b,e,`table:${r}:${g}:${y}`)))))))))}return a.createElement("p",{key:`block:${r}`,className:"ps-md-paragraph"},ut(n.text,e,`para:${r}`))}))}function lr({controller:t,title:e,color:s,focused:n,scrollOffset:r=0,paneKey:i,theme:o,className:l="",focusRegion:c=null,children:d}){const p=a.useRef(null),u=Dc(p,r,i,t),f=a.useCallback(()=>{const m=Ri(i,c);m&&t?.setFocus&&t.setFocus(m)},[t,i,c]);return a.createElement(xt,{title:e,color:s,focused:n,theme:o},a.createElement("div",{ref:p,className:`ps-scroll-panel is-preview ${l}`.trim(),onScroll:u,onMouseDown:f},d))}function ib({controller:t,title:e,color:s,focused:n,scrollOffset:r=0,paneKey:i,theme:o,content:l,focusRegion:c=null}){const d=a.useCallback(()=>{const f=Ri(i,c);f&&t?.setFocus&&t.setFocus(f)},[t,i,c]),p=a.useRef(null),u=Dc(p,r,i,t);return a.createElement(xt,{title:e,color:s,focused:n,theme:o},a.createElement("div",{ref:p,className:"ps-scroll-panel ps-markdown-scroll",onScroll:u,onMouseDown:d},a.createElement(Mi,{content:l,theme:o})))}function Qc(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 ka({title:t,color:e,focused:s,theme:n,filename:r,contentType:i,sizeBytes:o,source:l,uploadedAt:c,controller:d=null,sessionId:p=null}){const u=[];i&&u.push(i),o!=null&&u.push(Qc(o)),l&&u.push(l);const f=c?new Date(c).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"",m=Ai.test(String(i||""))||Ci.test(String(r||"")),[h,g]=a.useState(null);return a.useEffect(()=>{if(g(null),!m||!d||!p||!r)return;let b=!1;return nd(d,p,r).then(y=>{b||g(y)}).catch(()=>{b||g("error")}),()=>{b=!0}},[m,d,p,r]),a.createElement(xt,{title:t,color:e,focused:s,theme:n},a.createElement("div",{className:"ps-binary-preview-card"},a.createElement("div",{className:"ps-binary-preview-kicker"},m?"Image artifact":"Binary artifact"),a.createElement("h3",{className:"ps-binary-preview-title"},r||"Artifact"),u.length>0?a.createElement("div",{className:"ps-binary-preview-meta"},u.join(" • ")):null,f?a.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${f}`):null,m&&h&&h!=="error"?a.createElement("img",{className:"ps-binary-preview-image",src:h,alt:r||"artifact image",onClick:()=>{const b=An(p,r);if(b)try{window.open(b,"_blank","noopener")}catch{}}}):a.createElement("p",{className:"ps-binary-preview-copy"},m?h==="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.")))}const ob=260,ab=28;function lb(t,e,s,n){const[r,i]=a.useState(null),[o,l]=a.useState(0),c=a.useRef(null),d=a.useRef(0);a.useEffect(()=>{c.current=null,d.current+=1,i(null),l(d.current)},[s]);const p=a.useRef(!0);a.useEffect(()=>{if(p.current){p.current=!1;return}e&&(c.current=null,d.current+=1,l(d.current))},[n,e]),a.useEffect(()=>{const f=t.current;if(!e||!f||typeof ResizeObserver>"u")return;let m=null;const h=new ResizeObserver(g=>{const b=Math.round(g[0]?.contentRect?.width||0);if(b){if(c.current===null){c.current=b;return}Math.abs(b-c.current)<ab||(m&&clearTimeout(m),m=setTimeout(()=>{m=null,c.current=Math.round(f.getBoundingClientRect().width)||b,d.current+=1,l(d.current)},ob))}});return h.observe(f),()=>{m&&clearTimeout(m),h.disconnect()}},[t,e]);const u=a.useCallback(f=>{const m=()=>{l(h=>h===f?null:h),i(h=>h===f?h:f)};if(typeof requestAnimationFrame!="function"){m();return}requestAnimationFrame(()=>requestAnimationFrame(m))},[]);return{live:r,pending:o,promote:u}}const cr=1024;function Zc({fitWidth:t,setFitWidth:e}){return a.createElement(pe,{icon:t?"1:1":"⤢",label:t?"Actual size":"Fit page to width",active:t,onClick:()=>e(!t)})}const Tt=[.5,.67,.8,.9,1,1.1,1.25,1.5,1.75,2,2.5,3];function vn({zoom:t,setZoom:e}){const s=n=>{const r=Tt.findIndex(l=>Math.abs(l-t)<.005),i=r===-1?Tt.indexOf(1):r,o=Tt[Math.min(Tt.length-1,Math.max(0,i+n))];e(o)};return a.createElement("span",{className:"ps-html-zoom",role:"group","aria-label":"Artifact zoom"},a.createElement("button",{type:"button",className:"ps-html-zoom-btn",onClick:()=>s(-1),disabled:t<=Tt[0]+.001,title:"Zoom out (artifact only)","aria-label":"Zoom out"},"−"),a.createElement("button",{type:"button",className:"ps-html-zoom-level",onClick:()=>e(1),title:"Reset zoom to 100%","aria-label":`Zoom ${Math.round(t*100)} percent, click to reset`},`${Math.round(t*100)}%`),a.createElement("button",{type:"button",className:"ps-html-zoom-btn",onClick:()=>s(1),disabled:t>=Tt[Tt.length-1]-.001,title:"Zoom in (artifact only)","aria-label":"Zoom in"},"+"))}function Jc({mode:t,setMode:e}){return a.createElement("span",{className:"ps-html-preview-modes",role:"group","aria-label":"Preview mode"},["rendered","source"].map(s=>a.createElement("button",{key:s,type:"button",className:`ps-html-preview-mode${t===s?" is-active":""}`,"aria-pressed":t===s,onClick:()=>e(s)},s==="rendered"?"Rendered":"Source")))}function ed(t){const[e,s]=a.useState({width:0,height:0});return a.useLayoutEffect(()=>{const n=t.current;if(!n||typeof ResizeObserver>"u")return;const r=()=>{const o=n.getBoundingClientRect();s(l=>{const c=Math.round(o.width)||0,d=Math.round(o.height)||0;return l.width===c&&l.height===d?l:{width:c,height:d}})};r();const i=new ResizeObserver(r);return i.observe(n),()=>i.disconnect()},[t]),e}function td(t,e,s){const n=t?.transport?.api?.downloadArtifactResponse;return typeof n!="function"?Promise.reject(new Error("artifact download unavailable")):n.call(t.transport.api,e,s).then(async r=>{if(!r?.ok)throw new Error(`download failed (${r?.status})`);const i=await r.arrayBuffer();return URL.createObjectURL(new Blob([i],{type:"text/html;charset=utf-8"}))})}function cb({controller:t,sessionId:e,filename:s,contentType:n,sizeBytes:r,theme:i,color:o="cyan",focused:l=!1,title:c=null,chromeless:d=!1}){const p=ee(t,N=>N.files.htmlViewMode||"rendered"),u=a.useCallback(N=>{t.dispatch({type:"files/htmlViewMode",mode:N})},[t]),[f,m]=a.useState(null),[h,g]=a.useState(null),b=a.useRef(null),y=ee(t,N=>!!N.files.htmlFitWidth),v=a.useCallback(N=>{t.dispatch({type:"files/htmlFitWidth",enabled:N})},[t]),E=ed(b),k=y&&E.width>0&&E.width<cr?E.width/cr:1,x=k<1,w=ee(t,N=>Number(N.files.htmlZoom)||1),S=a.useCallback(N=>{t.dispatch({type:"files/htmlZoom",zoom:N})},[t]),C=x?k*w:w,M=lb(b,p==="rendered"&&!x,`${e}/${s}`,w);a.useEffect(()=>{if(m(null),g(null),p!=="rendered"||!t||!e||!s)return;let N=!1,j=null;return td(t,e,s).then(q=>{if(j=q,N){URL.revokeObjectURL(q);return}m(q)}).catch(q=>{N||g(q?.message||String(q))}),()=>{N=!0,j&&URL.revokeObjectURL(j)}},[t,e,s,p]);const _=An(e,s),O=d?null:a.createElement(a.Fragment,null,a.createElement(Jc,{mode:p,setMode:u}),p==="rendered"?a.createElement(Zc,{fitWidth:y,setFitWidth:v}):null,p==="rendered"?a.createElement(vn,{zoom:w,setZoom:S}):null,_?a.createElement(pe,{icon:"↗",label:"Open in a new tab",onClick:()=>{try{window.open(_,"_blank","noopener")}catch{}}}):null),R=p==="source"?a.createElement(db,{controller:t,sessionId:e,filename:s,theme:i}):h?a.createElement("div",{className:"ps-html-preview-status"},a.createElement("p",null,`Could not load ${s}: ${h}`),a.createElement("p",null,"Use Download to save the file and open it locally.")):f?[M.live,M.pending].filter((N,j,q)=>N!==null&&q.indexOf(N)===j).map(N=>a.createElement("iframe",{key:`frame:${N}`,className:`ps-html-preview-frame${N===M.live?"":" is-staging"}`,style:x?{flex:"none",width:`${cr}px`,height:`${Math.max(1,Math.round(E.height/C))}px`,transform:`scale(${C})`,transformOrigin:"top left"}:w!==1&&E.width>0?{flex:"none",width:`${Math.max(1,Math.round(E.width/w))}px`,height:`${Math.max(1,Math.round(E.height/w))}px`,transform:`scale(${w})`,transformOrigin:"top left"}:void 0,src:f,title:s||"HTML artifact",sandbox:"allow-scripts allow-popups allow-popups-to-escape-sandbox",allow:"autoplay *",referrerPolicy:"no-referrer",onLoad:()=>M.promote(N)})):a.createElement("div",{className:"ps-html-preview-status"},a.createElement("p",null,`Rendering ${s}…`),r!=null?a.createElement("p",{className:"ps-html-preview-meta"},[n,Qc(r)].filter(Boolean).join(" • ")):null),T=p==="rendered"?a.createElement("div",{ref:b,className:`ps-html-preview-host${x||w!==1?" is-fitting":""}`},R):R;return a.createElement(xt,{title:c,color:o,focused:l,theme:i,actions:O,className:"ps-html-preview"},T)}function db({controller:t,sessionId:e,filename:s,theme:n}){const[r,i]=a.useState(null),[o,l]=a.useState(null);return a.useEffect(()=>{i(null),l(null);const c=t?.transport?.api?.downloadArtifactResponse;if(typeof c!="function"||!e||!s){l("artifact download unavailable");return}let d=!1;return c.call(t.transport.api,e,s).then(async p=>{if(!p?.ok)throw new Error(`download failed (${p?.status})`);return p.text()}).then(p=>{d||i(p)}).catch(p=>{d||l(p?.message||String(p))}),()=>{d=!0}},[t,e,s]),o?a.createElement("div",{className:"ps-html-preview-status"},a.createElement("p",null,`Could not load source: ${o}`)):r==null?a.createElement("div",{className:"ps-html-preview-status"},a.createElement("p",null,"Loading source…")):a.createElement("div",{className:"ps-scroll-panel is-preview ps-diff-preview"},a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,ls(r,"html",n))))}function Ys(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function dr(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function ub(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function Cs(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function pb(t){const e=String(Ve(t)||"").trim();return Ys(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function fb(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=Ve(t);return Cs(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function mb(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 xa(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?mb(t.runs.slice(1,-1)):[{text:Ve(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function hb(t){const e=String(t||"").trim();return Cs(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function gb(t="",e=""){const s=String(t||"").trimEnd(),n=String(e||"").trimStart();if(!s||!n)return!1;const r=s.slice(-1),i=n[0];return!!(/^[,.;:!?%)\]}>]/u.test(i)||/^[._/\\-]/u.test(i)||/[([{<._/\\-]$/u.test(r)||/\.[A-Za-z0-9]{0,4}$/u.test(s)&&/^[A-Za-z0-9]/u.test(i))}function yb(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)=>gb(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function Ia(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>yb(t.map(r=>String(r[n]||"").trim()).filter(Boolean)))}function sd(t=[]){const e=[];for(let s=0;s<t.length;){const n=t[s];if(n?.preserve){const i=n.splashVariant||null,o=[];for(;s<t.length&&t[s]?.preserve&&(t[s].splashVariant||null)===i;)o.push(t[s]),s+=1;e.push({type:"preserve",lines:o,splashVariant:i});continue}if(n?.kind==="cardStart"){const i=[];for(s+=1;s<t.length&&t[s]?.kind!=="cardEnd";)i.push(t[s]),s+=1;s<t.length&&(s+=1),s<t.length&&Ve(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:sd(i)});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 r=Ve(n);if(Ys(r)&&r.includes("┬")){const i=[],o=[];let l=[],c=!0;for(s+=1;s<t.length;){const d=t[s],p=Ve(d);if(dr(p)){if(l.length>0){const u=Ia(l);u.length>0&&(c?i.push(u):o.push(u))}s+=1;break}if(ub(p)){if(l.length>0){const u=Ia(l);u.length>0&&(c?i.push(u):o.push(u))}l=[],c=!1,s+=1;continue}if(Cs(p)){const u=hb(p);u.length>0&&l.push(u)}s+=1}e.push({type:"table",headerRows:i,bodyRows:o});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&Ys(r)){const i=pb(n),o=[];for(s+=1;s<t.length;){const l=t[s],c=Ve(l);if(dr(c)){s+=1;break}Cs(c)?o.push(fb(l)):o.push(Ve(l)),s+=1}s<t.length&&Ve(t[s]).trim().length===0&&(s+=1),e.push({type:"code",language:i||"text",content:o.join(`
|
|
96
|
-
`)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&Ys(r)){const i=xa(n),o=n.runs[0]?.color||"gray",l=[];for(s+=1;s<t.length;){const c=t[s],d=Ve(c);if(dr(d)){s+=1;break}Cs(d)?l.push(xa(c)):l.push(c?.kind==="runs"?c.runs:[{text:Ve(c),color:c?.color||null}]),s+=1}s<t.length&&Ve(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:i,bodyLines:l,borderColor:o});continue}e.push({type:"line",line:n}),s+=1}return e}function bb({lines:t,theme:e,controller:s=null}){const n=a.useMemo(()=>sd((t||[]).filter(r=>!r?.canvasUpdate&&!r?.canvasAction)),[t]);return a.createElement(rd,{blocks:n,theme:e,controller:s})}const ft=new Map,Sb=60;function nd(t,e,s){const n=`${e}/${s}`,r=ft.get(n);if(r)return ft.delete(n),ft.set(n,r),r;const i=t?.transport?.api?.downloadArtifactResponse;if(typeof i!="function")return Promise.reject(new Error("artifact download unavailable"));const o=i.call(t.transport.api,e,s).then(async l=>{if(!l?.ok)throw new Error(`download failed (${l?.status})`);const c=await l.blob(),d=Py(s),p=d&&!Ai.test(c.type)?new Blob([c],{type:d}):c;return URL.createObjectURL(p)}).catch(l=>{throw ft.get(n)===o&&ft.delete(n),l});for(ft.set(n,o);ft.size>Sb;){const[l,c]=ft.entries().next().value;ft.delete(l),Promise.resolve(c).then(d=>URL.revokeObjectURL(d)).catch(()=>{})}return o}function vb({controller:t,sessionId:e,attachments:s}){const[n,r]=a.useState({});return a.useEffect(()=>{if(!t||!e)return;let i=!1;for(const o of s){const l=o?.filename;l&&nd(t,e,l).then(c=>{i||r(d=>d[l]===c?d:{...d,[l]:c})}).catch(()=>{i||r(c=>c[l]==="error"?c:{...c,[l]:"error"})})}return()=>{i=!0}},[t,e,s]),a.createElement("div",{className:"ps-chat-image-strip"},s.map((i,o)=>{const l=i?.filename||`image-${o}`,c=n[l];return c&&c!=="error"?a.createElement("img",{key:`thumb:${o}:${l}`,className:"ps-chat-image-thumb",src:c,alt:l,title:`${l} — click to view full size`,onClick:()=>{try{window.open(c,"_blank","noopener")}catch{}}}):a.createElement("div",{key:`thumb:${o}:${l}`,className:`ps-chat-image-thumb is-pending${c==="error"?" is-error":""}`,title:l},c==="error"?"⚠":"🖼")}))}function rd({blocks:t,theme:e,controller:s=null}){return a.createElement(a.Fragment,null,(t||[]).map((n,r)=>{if(n.type==="imageAttachments")return a.createElement(vb,{key:`imageAttachments:${r}`,controller:s,sessionId:n.sessionId,attachments:n.attachments});if(n.type==="preserve"){const i=n.splashVariant?` is-splash-${n.splashVariant}`:"";return a.createElement("div",{key:`preserve:${r}`,className:`ps-chat-preserve-block${i}`},n.lines.map((o,l)=>a.createElement(je,{key:`preserve:${r}:${l}`,line:o,theme:e,className:"ps-line-preserve"})))}if(n.type==="code"){const i=qc(n.language),o=a.createElement("section",{key:`code:${r}`,className:`ps-md-code-block ps-chat-code-block${i?" is-diff":""}`},a.createElement("div",{className:"ps-md-code-header"},n.language||"text"),a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,i?Pi(n.content||"",e):ls(n.content||"",n.language,e))));return Kc(n.language)?a.createElement(Vc,{key:`code:${r}`,code:n.content||"",theme:e,fallback:o}):o}if(n.type==="card")return a.createElement("section",{key:`card:${r}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":et(e,n.borderColor)||"var(--ps-border)"}},a.createElement("header",{className:"ps-chat-card-header"},a.createElement(Ge,{runs:n.headerRuns,theme:e})),a.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?a.createElement(rd,{blocks:n.blocks,theme:e,controller:s}):(n.bodyLines||[]).map((i,o)=>a.createElement("div",{key:`card:${r}:line:${o}`,className:"ps-chat-card-line"},a.createElement(Ge,{runs:i,theme:e})))));if(n.type==="table"){const i=n.headerRows||[],o=n.bodyRows||[],l=Math.max(1,...i.map(b=>b.length),...o.map(b=>b.length)),c=l<=6,d=c?Yc([...i,...o]):null,p=!!d,u=d?d.flexIndex:-1,f=b=>b===u?"is-flex-column":null,m=Xc(i,l),h=`ps-chat-table${c?" is-fit-width":""}${p?" has-flex-column":""}`,g=`ps-chat-table-wrap${c?" is-fit-width":""}${p?" has-flex-column":""}`;return a.createElement("div",{key:`table:${r}`,className:g},a.createElement("table",{className:h,style:d?.minWidth?{"--ps-table-min-width":d.minWidth}:void 0},d?a.createElement("colgroup",null,d.widths.map((b,y)=>a.createElement("col",{key:`col:${y}`,className:f(y)||void 0,style:{width:b}}))):null,i.length>0?a.createElement("thead",null,i.map((b,y)=>a.createElement("tr",{key:`thead:${y}`},Array.from({length:l},(v,E)=>a.createElement("th",{key:`th:${y}:${E}`,className:f(E)||void 0},ut(b[E]||"",e,`chat-table:${r}:head:${y}:${E}`)))))):null,a.createElement("tbody",null,o.map((b,y)=>a.createElement("tr",{key:`tbody:${y}`},Array.from({length:l},(v,E)=>a.createElement("td",{key:`td:${y}:${E}`,className:f(E)||void 0,"data-label":m[E]||void 0},a.createElement("span",{className:"ps-table-cell-value"},ut(b[E]||"",e,`chat-table:${r}:${y}:${E}`)))))))))}return a.createElement(je,{key:`line:${r}`,line:n.line,theme:e})}))}function xt({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:r=null,children:i,theme:o,className:l=""}){const c=et(o,s),d=!!((Array.isArray(t)?t.length>0:String(t??"").trim())||e||r);return a.createElement("section",{className:`ps-panel${n?" is-focused":""}${d?"":" is-chromeless"}${l?` ${l}`:""}`,style:{"--ps-panel-accent":c||"var(--ps-border)"}},d?a.createElement("header",{className:"ps-panel-header"},a.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?a.createElement(Ge,{runs:t,theme:o}):ma(t)),e||r?a.createElement("div",{className:"ps-panel-header-right"},e?a.createElement("div",{className:"ps-panel-title-right"},Array.isArray(e)?a.createElement(Ge,{runs:e,theme:o}):ma(e)):null,r?a.createElement("div",{className:"ps-panel-actions"},r):null):null):null,a.createElement("div",{className:"ps-panel-body"},i))}function wb({lines:t,theme:e,controller:s}){return a.createElement("div",{className:"ps-nodemap"},(t||[]).map((n,r)=>{const i=Array.isArray(n?.runs)?n.runs:Array.isArray(n)?n:[n],o=i.find(d=>d?.nodeSelect)?.nodeSelect||null,l=i.some(d=>d?.nodeSelected),c=a.createElement(Ge,{runs:i,theme:e});return o?a.createElement("button",{key:`line:${r}`,type:"button",className:`ps-nodemap__row${l?" is-selected":""}`,onPointerDown:d=>{d.preventDefault(),d.stopPropagation(),s.selectNodeMapNode(o)}},c):a.createElement("div",{key:`line:${r}`,className:"ps-nodemap__line"},c)}))}function Eb({lines:t,theme:e,completionByTurn:s}){const[n,r]=a.useState(()=>new Set),i=a.useCallback(p=>{r(u=>{const f=new Set(u);return f.has(p)?f.delete(p):f.add(p),f})},[]),o=p=>Number(p||0).toLocaleString("en-US"),l=p=>{const u=Number(p||0);if(!Number.isFinite(u))return"?K";const f=u/1e3,m=Math.abs(f)>=10?1:2;return`${f.toFixed(m)}K`},c=p=>{const u=Number(p||0);return Number.isFinite(u)?`${(u/1e3).toFixed(1)}s`:"?s"},d=p=>{const u=String(p||"").trim();if(!u)return"unknown";const f=u.split(":").filter(Boolean),m=f[f.length-1]||"",h=f.length>1&&Vg.has(m.toLowerCase())?f.length-2:f.length-1;return f[Math.max(0,h)]||f[0]||"unknown"};return a.createElement(a.Fragment,null,t.map((p,u)=>{const f=p?.kind==="runs"&&Array.isArray(p.runs)?p.runs.find(S=>S?.completedTurn!=null)?.completedTurn:null,m=f!=null?s.get(Number(f)):null;if(!m)return a.createElement(je,{key:`line:${u}`,line:p,theme:e});const h=m.data||{},g=String(m.seq??`${h.turnIndex??f}:${m.createdAt??u}`),b=n.has(g),y=h.reasoningEffort?`${h.model||"(unknown)"}:${h.reasoningEffort}`:h.model||"(unknown)",v=d(h.model),E=h.durationMs!=null?c(h.durationMs):"duration n/a",k=h.durationMs!=null?`${o(h.durationMs)} ms`:"duration n/a",x=`${l(h.tokensInput)} / ${l(h.tokensOutput)}`,w=[["model",y],["started",h.startedAt?new Date(h.startedAt).toLocaleString():null],["ended",h.endedAt?new Date(h.endedAt).toLocaleString():null],["duration",k],["tokens",`${o(h.tokensInput)} in / ${o(h.tokensOutput)} out`],["cache",`${o(h.tokensCacheRead)} read / ${o(h.tokensCacheWrite)} write`],["tools",`${o(h.toolCalls)} calls / ${o(h.toolErrors)} errors`],["names",Array.isArray(h.toolNames)&&h.toolNames.length?h.toolNames.join(", "):null],["worker",h.workerNodeId||null],["result",h.resultType||null],["error",h.errorMessage||null]].filter(([,S])=>S!=null&&S!=="");return a.createElement(a.Fragment,{key:`seq:${u}`},a.createElement(je,{line:p,theme:e}),a.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>i(g)},a.createElement("span",{className:"ps-sequence-turn-caret"},b?"v":">"),a.createElement("span",{className:"ps-sequence-turn-rule"},"--- "),a.createElement("span",{className:"ps-sequence-turn-key"},"Mod: "),a.createElement("span",{className:"ps-sequence-turn-model"},v),a.createElement("span",{className:"ps-sequence-turn-rule"}," ("),a.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),a.createElement("span",{className:"ps-sequence-turn-tokens"},x),a.createElement("span",{className:"ps-sequence-turn-rule"},", "),a.createElement("span",{className:"ps-sequence-turn-key"},"dur: "),a.createElement("span",{className:"ps-sequence-turn-duration"},E),a.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),b?a.createElement("div",{className:"ps-sequence-turn-details"},w.map(([S,C])=>a.createElement("div",{key:S},a.createElement("span",{className:"ps-sequence-turn-detail-label"},`${S}: `),a.createElement("span",null,String(C))))):null)}))}const kb={chat:"chat",activity:"activity",inspector:"inspector",filePreview:"inspector"};function Ri(t,e=null){return e||kb[String(t||"")]||null}function Tn({title:t,titleRight:e=null,color:s,focused:n,actions:r,lines:i,stickyLines:o=[],bottomStickyLines:l=[],scrollOffset:c=0,scrollMode:d="top",paneKey:p,controller:u,className:f="",panelClassName:m="",topContent:h=null,bottomContent:g=null,structuredBlocks:b=!1,stickyBottom:y=!1,renderBody:v=null,focusRegion:E=null,panelRef:k=null}){const x=ee(u,V=>V.ui.themeId),w=pt(x),S=a.useRef(null),C=a.useCallback(V=>{S.current=V,typeof k=="function"?k(V):k&&(k.current=V)},[k]),M=a.useRef(null),_=a.useRef(!1),{normalizedLines:O,onScroll:R,onWheel:T,onTouchStart:N,onTouchMove:j,onTouchEnd:q}=ky(S,i,c,d,p,u,{stickyBottom:y}),Z=a.useMemo(()=>Ue(o),[o]),ue=a.useMemo(()=>Ue(l),[l]),oe=f.includes("is-preserve")&&m.includes("has-preserved-sticky"),de=`${p}:${t}`;a.useEffect(()=>{const V=()=>{S.current&&(S.current.scrollLeft=0),M.current&&(M.current.scrollLeft=0)};V();const Y=typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{V()}):null;return()=>{Y!=null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(Y)}},[de]);const A=a.useCallback(()=>{const V=Ri(p,E);V&&u?.setFocus&&u.setFocus(V)},[u,p,E]),D=a.useCallback((V,Y)=>{!V||!Y||Math.abs((Y.scrollLeft||0)-(V.scrollLeft||0))<=1||(_.current=!0,Y.scrollLeft=V.scrollLeft,window.requestAnimationFrame(()=>{_.current=!1}))},[]),[F,K]=a.useState({up:!1,down:!1}),W=a.useCallback(V=>{if(!V)return;const Y=V.scrollHeight-V.scrollTop-V.clientHeight>4,ge=V.scrollTop>4;K(fe=>fe.up===Y&&fe.down===ge?fe:{up:Y,down:ge})},[]),Q=a.useCallback(V=>{R(),W(V.currentTarget),!(!oe||_.current)&&D(V.currentTarget,M.current)},[R,oe,D,W]);a.useEffect(()=>{W(S.current)});const J=a.useCallback(V=>{!oe||_.current||D(V.currentTarget,S.current)},[oe,D]);return a.createElement(xt,{title:t,titleRight:e,color:s,focused:n,actions:r,theme:w,className:m},h,Z.length>0?a.createElement("div",{ref:M,className:`ps-panel-sticky${oe?" is-scroll-sync":""}`,onScroll:J},Z.map((V,Y)=>a.createElement(je,{key:`sticky:${Y}`,line:V,theme:w}))):null,a.createElement("div",{ref:C,className:`ps-scroll-panel ${f}${F.down?" is-scrolled-down":""}${F.up?" is-scrolled-up":""}`.trim(),"data-session-scroll":E==="sessions"?"1":void 0,onScroll:Q,onMouseDown:A,onTouchStart:N,onWheel:T,onTouchMove:j,onTouchEnd:q,onTouchCancel:q},typeof v=="function"?v(O,w):b?a.createElement(bb,{lines:O,theme:w,controller:u}):O.map((V,Y)=>a.createElement(je,{key:`line:${Y}`,line:V,theme:w}))),ue.length>0?a.createElement("div",{className:"ps-panel-bottom-sticky"},ue.map((V,Y)=>a.createElement(je,{key:`bottom-sticky:${Y}`,line:V,theme:w}))):null,g)}const Aa="—";function xb({session:t,childCount:e=0,pause:s=null,controller:n=null}){const r=(b,y,v="")=>{const E=y==null||y===""?Aa:String(y),k=E===Aa;return a.createElement("div",{className:`ps-session-detail-field${v?` ${v}`:""}${k?" is-none":""}`,key:b},a.createElement("span",{className:"ps-session-detail-label"},b),a.createElement("span",{className:"ps-session-detail-value",title:E},E))},i=t?.contextUsage,o=i&&Number.isFinite(i.currentTokens)&&Number.isFinite(i.tokenLimit)&&i.tokenLimit>0,l=o?Math.round(i.currentTokens/i.tokenLimit*100):null,c=o?`${te(i.currentTokens)} / ${te(i.tokenLimit)} · ${l}%`:null;let d=null;t&&!t.isGroup&&(d="off",t.cronActive===!0&&(d=t.cronKind==="wall-clock"?`next ${ln(t.cronNextFireAt)}`:typeof t.cronInterval=="number"?`every ${qt(t.cronInterval)}`:"on"));const p=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,m=Pp(t),h=typeof t?.waitReason=="string"&&t.waitReason.trim()?t.waitReason.trim():null,g=!s&&!h?null:a.createElement("div",{className:`ps-session-detail-pause${s?" is-paused":""}`},a.createElement("span",{className:"ps-session-detail-label"},s?"Paused":"Waiting"),a.createElement("span",{className:"ps-session-detail-why"},s?s.reason:h,s&&s.clears?a.createElement("span",{className:"ps-session-detail-clears"},s.clears):null,s&&n?a.createElement("button",{type:"button",className:"ps-budget-link",title:s.provider?`Open ${s.provider} in Providers & Budgets`:"Open providers and budgets",onClick:()=>n.openBudget(s.provider?{provider:s.provider}:{}).catch(()=>{})},s.provider?`Open ${s.provider}`:"Open providers and budgets"):null));return a.createElement("div",{className:"ps-session-detail-box"},r("Title",t?.title,"is-title"),r("ID",t?.sessionId,"is-id"),r("Owner",t?.owner?hd(t.owner):null),r("Model",p),r("Context",c,l!=null&&l>=85?"is-hot":l!=null&&l>=70?"is-warm":""),r("Cron",d,t?.cronActive===!0?"is-armed":""),r("Agent",t?.agentId),r("Updated",m?`${m.relative} (${m.status})`:null),r("Children",f),r("Access",u),g)}function Ib(){const t="(pointer: coarse)",e=()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(t).matches:!1,[s,n]=a.useState(e);return a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(t),i=o=>n(o.matches);return r.addEventListener?.("change",i),()=>r.removeEventListener?.("change",i)},[]),s}const id=13,od=11,ad=1.5,Ab=7;function Cb(t){return id+(t-1)*od+ad/2-Ab/2}const Nb=a.memo(function({row:e,theme:s,structuredRows:n,mobile:r,onRowClick:i,setRef:o,drag:l}){const c=Math.max(0,e.depth),d=a.useMemo(()=>{if(c<1)return;const v=Array.from({length:c},(E,k)=>k);return{backgroundImage:v.map(()=>"linear-gradient(var(--ps-rail), var(--ps-rail))").join(", "),backgroundSize:v.map(()=>`${ad}px 100%`).join(", "),backgroundPosition:v.map(E=>`${id+E*od}px 0`).join(", "),backgroundRepeat:"no-repeat"}},[c]),p=a.useCallback(v=>o(e.sessionId,v),[o,e.sessionId]),u=a.useCallback(v=>i(v,e),[i,e]),f=e.groupId||null,m=!!(l?.dragging&&l.overGroupId&&f===l.overGroupId),h=m&&!!e.isGroup,g=!!(l?.dragging&&l.insertBeforeId===e.sessionId),b=!!(l?.dragging&&l.insertAfterId&&l.insertAfterId===e.sessionId),y=a.useCallback(v=>{if(l?.onPointerDown&&v.button===0){if(v.currentTarget?.setPointerCapture&&v.pointerId!=null)try{v.currentTarget.setPointerCapture(v.pointerId)}catch{}l.onPointerDown(v,e)}},[l,e]);return a.createElement("button",{type:"button",ref:p,className:`ps-list-button ps-session-list-button${e.active?" is-selected":""}${e.selected?" is-multiselected":""}${e.pinned?" is-pinned":""}${m?" is-drop-zone":""}${h?" is-drop-target":""}${g?" is-insert-before":""}${b?" is-insert-after":""}${e.depth>0?" is-nested":""}`,style:d,tabIndex:e.active?0:-1,"aria-selected":e.active?"true":"false","data-session-id":e.sessionId,"data-group-row":e.isGroup?"1":void 0,"data-group-id":e.isGroup?e.groupId||"":void 0,"data-drop-group":f||void 0,"data-order-container":e.orderContainer??void 0,"data-orderable":e.orderable?"1":void 0,onPointerDown:y,onClick:u,onContextMenu:v=>{v.ctrlKey&&(v.preventDefault(),i(v,e))}},a.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:c>0?`${Cb(c)}px`:"0px"}},a.createElement(Tb,{row:e,theme:s,structured:n,showInlineDetail:r})))});function Ca(t,e){if(!Array.isArray(t))return{statusColor:null,rest:t};let s=null;const n=[];for(const r of t)if(r?.role!=="depth"&&r?.role!=="selection"){if(r?.role==="status"){s=et(e,r.color)||null;continue}n.push(r)}return{statusColor:s,rest:n}}function Na({color:t,node:e=!1}){return a.createElement("span",{className:`ps-session-status-dot${e?" is-node":""}`,style:t?e?{borderColor:t}:{background:t}:void 0})}function Rr({badge:t,size:e="sm"}){return t?a.createElement("span",{className:`ps-owner-avatar is-${e}${t.isMine?" is-mine":""}`,"data-owner-hue":String(t.hue??0),title:t.isMine?`${t.name} (you)`:t.name,"aria-label":t.name},t.initials):null}function Ta(t){return Array.isArray(t)?t.filter(e=>!e?.ownerChip):t}function Tb({row:t,theme:e,structured:s=!1,showInlineDetail:n=!1}){if(!(s&&Array.isArray(t.titleRuns))){if(!Array.isArray(t.runs))return t.text;const p=Ca(Ta(t.runs),e);return a.createElement(a.Fragment,null,p.statusColor?a.createElement(Na,{color:p.statusColor,node:t.depth>0}):null,a.createElement(Rr,{badge:t.ownerBadge}),a.createElement(_a,{mark:t.canvasMark}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(Ge,{runs:p.rest,theme:e})))}const i=Ca(Ta(t.titleRuns),e),o=Array.isArray(t.ctxRuns)?t.ctxRuns:[],l=o.length>0,c=Array.isArray(t.detailRuns)?t.detailRuns:Array.isArray(t.selectedMetaRuns)?t.selectedMetaRuns:[],d=n&&t.active&&c.length>0;return a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-session-row-line"},a.createElement("div",{className:"ps-session-row-title"},i.statusColor?a.createElement(Na,{color:i.statusColor,node:t.depth>0}):null,a.createElement(Rr,{badge:t.ownerBadge}),a.createElement(_a,{mark:t.canvasMark}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(Ge,{runs:i.rest,theme:e}))),l?a.createElement("div",{className:"ps-session-row-ctx"},a.createElement(Ge,{runs:o,theme:e})):null),d?a.createElement("div",{className:"ps-session-row-detail"},a.createElement(Ge,{runs:c,theme:e})):null)}function Pb(t){const e=a.useRef(t),s=a.useRef(null),n=a.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]);return(n===null||s.current!==n)&&(s.current=n,e.current=t),e.current}const Pa=10,Mb=1.6;function Rb(t){a.useEffect(()=>{const e=t.current;if(!e)return;let s=0,n=0,r=0,i=null;const o=d=>{if(d.touches.length!==1){i="y";return}const p=d.touches[0];s=r=p.clientX,n=p.clientY,i=null},l=d=>{if(i==="y"||d.touches.length!==1)return;const p=d.touches[0],u=p.clientX-s,f=p.clientY-n;i===null&&(Math.abs(u)<Pa&&Math.abs(f)<Pa||(i=Math.abs(u)>Math.abs(f)*Mb?"x":"y",r=p.clientX,i==="y"))||(e.scrollLeft-=p.clientX-r,r=p.clientX,d.cancelable&&d.preventDefault())},c=()=>{i=null};return e.addEventListener("touchstart",o,{passive:!0}),e.addEventListener("touchmove",l,{passive:!1}),e.addEventListener("touchend",c,{passive:!0}),e.addEventListener("touchcancel",c,{passive:!0}),()=>{e.removeEventListener("touchstart",o),e.removeEventListener("touchmove",l),e.removeEventListener("touchend",c),e.removeEventListener("touchcancel",c)}},[t])}function $r({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1,showDetailBox:r=null}){const i=String(s).includes("ps-mobile-session-pane"),o=a.useRef(null);Rb(o);const l=i||Ib(),c=ee(t,B=>B.ui.themeId),d=pt(c),p=a.useRef(new Map),u=ee(t,B=>({branding:B.branding,activeSessionId:B.sessions.activeSessionId,sessionsById:B.sessions.byId,sessionsFlat:B.sessions.flat,filterQuery:B.sessions.filterQuery||"",ownerFilter:B.sessions.ownerFilter,pinnedIds:B.sessions.pinnedIds,manualOrder:B.sessions.manualOrder,selectedIds:B.sessions.selectedIds,selectMode:B.sessions.selectMode,auth:B.auth,connectionMode:B.connection?.mode||"local",modalOpen:!!B.ui.modal,focused:B.ui.focusRegion==="sessions",listDeselected:!!B.sessions.listDeselected,canvasBySessionId:B.canvas?.bySessionId,canvasPrefs:B.canvas?.prefs,budgetPaused:B.budget?.paused}),_e),f=a.useMemo(()=>as({sessions:{activeSessionId:u.activeSessionId,byId:u.sessionsById,flat:u.sessionsFlat,filterQuery:u.filterQuery,ownerFilter:u.ownerFilter,pinnedIds:u.pinnedIds,manualOrder:u.manualOrder,selectedIds:u.selectedIds,selectMode:u.selectMode,listDeselected:u.listDeselected},auth:u.auth,connection:{mode:u.connectionMode},branding:u.branding,canvas:{bySessionId:u.canvasBySessionId,prefs:u.canvasPrefs},budget:{paused:u.budgetPaused}}),[u.activeSessionId,u.auth,u.branding,u.budgetPaused,u.canvasBySessionId,u.canvasPrefs,u.connectionMode,u.filterQuery,u.listDeselected,u.ownerFilter,u.pinnedIds,u.manualOrder,u.selectedIds,u.selectMode,u.sessionsById,u.sessionsFlat]),m=Pb(f),h=u.activeSessionId&&u.sessionsById[u.activeSessionId]||null,g=u.activeSessionId&&m.find(B=>B.sessionId===u.activeSessionId)||null,[b,y]=a.useState(!1),[v,E]=a.useState(null),k=a.useRef(!1),x=["modelPicker","reasoningEffortPicker","contextTierPicker"],w=ee(t,B=>x.includes(B.ui.modal?.type));a.useEffect(()=>{!w&&k.current&&(k.current=!1,y(!0))},[w]);const S=()=>{k.current=!0,y(!1),t.openSwitchModelPicker(()=>{k.current=!1}).then(()=>{!x.includes(t.getState().ui.modal?.type)&&k.current&&(k.current=!1,y(!0))}).catch(B=>{k.current=!1,y(!0),t.dispatch({type:"ui/status",text:B?.message||String(B)||"Failed to switch model"})})},C=u.auth?.principal||null,M=u.auth?.authorization?.role,_=M==="admin"||M==="anonymous",O=!!(h?.owner&&C&&String(h.owner.provider)===String(C.provider)&&String(h.owner.subject)===String(C.subject)),R=!!(h&&!h.isGroup&&(h.isSystem?_:_||O)),T=Array.isArray(u.selectedIds)?u.selectedIds.length:0,N=T>1,j=!!(h?.isGroup&&!N),q=!!(h&&!h.isSystem&&(h.isGroup||!h.parentSessionId&&!h.groupId)),Z=!!(h&&Array.isArray(u.pinnedIds)&&u.pinnedIds.includes(h.sessionId)),ue=!!(h?.isGroup&&Number(h.memberCount||0)===0),oe=N?Array.isArray(u.selectedIds)&&u.selectedIds.some(B=>{const z=u.sessionsById[B];return z&&!z.isSystem&&!z.isGroup}):h?.isGroup?!0:!!h,de=T>0,A=!!(h&&!u.listDeselected&&!h.isSystem&&!h.isGroup&&!h.parentSessionId),D=de?u.selectedIds.filter(B=>{const z=u.sessionsById[B];return z&&!z.isSystem&&!z.isGroup&&!z.parentSessionId}):A?[h.sessionId]:[],F=`ps-session-pane${s?` ${s}`:""}`,K=a.useRef(null);K.current={rows:m,viewState:u,controller:t};const[W,Q]=a.useState({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),J=a.useRef(null),V=a.useRef(null),Y=a.useCallback(()=>{V.current!=null&&(cancelAnimationFrame(V.current),V.current=null)},[]),ge=a.useCallback(()=>{let B=o.current;for(;B&&B!==document.body;){const z=window.getComputedStyle(B).overflowY;if(/(auto|scroll|overlay)/.test(z)&&B.scrollHeight-B.clientHeight>1)return B;B=B.parentElement}return null},[]),fe=a.useCallback((B,z)=>{const U=ge();if(!U){Y();return}const H=U.getBoundingClientRect();let X=0;if(z<H.top+48?X=-14*Math.min(1,(H.top+48-z)/48):z>H.bottom-48&&(X=14*Math.min(1,(z-(H.bottom-48))/48)),J.current&&(J.current.autoScrollStep=X),!J.current){Y();return}if(V.current!=null)return;const ae=()=>{const le=J.current;if(!le||!le.autoScrollStep){Y();return}U.scrollTop+=le.autoScrollStep,V.current=requestAnimationFrame(ae)};V.current=requestAnimationFrame(ae)},[ge,Y]),ye=a.useCallback(B=>{const z=J.current;if(J.current=null,Y(),Q({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),!(!B||!z?.started||z.ids.length===0)){if(z.intent==="reorder"){t.dispatch({type:"sessions/reorder",sessionId:z.ids[0],beforeSessionId:z.beforeSessionId});return}z.intent!=="file"&&z.intent!=="unfile"||t.moveSessionsToGroup(z.overGroupId,z.ids).catch(L=>{t.dispatch({type:"ui/status",text:`Move failed: ${L?.message||L}`})})}},[t,Y]),Te=a.useCallback((B,z)=>typeof B!="number"||typeof z!="number"?null:(document.elementFromPoint(B,z)?.closest?.("[data-drop-group]")||null)?.getAttribute("data-drop-group")||null,[]),Re=a.useCallback((B,z,L,I)=>{if(typeof B!="number"||typeof z!="number"||L==null)return;const U=Array.from(document.querySelectorAll(`[data-order-container="${CSS.escape(L)}"][data-orderable="1"]`));if(U.length===0)return;for(const ae of U){const le=ae.getBoundingClientRect();if(z<le.top+le.height/2)return{before:ae.getAttribute("data-session-id")||null,after:null}}const X=U[U.length-1]?.getAttribute("data-session-id")||null;return{before:null,after:X&&X!==I?X:null}},[]),Le=a.useCallback((B,z,L)=>{const I=Te(B,z);if(L?.isGroup){const ae=L.ids.length===1?Re(B,z,L.container,L.ids[0]):void 0;return ae===void 0?{kind:"none",overGroupId:null,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:ae.before,after:ae.after}}const U=L?.ownGroupId||null;if(I&&I!==U)return{kind:"file",overGroupId:I,before:void 0,after:null};if(!I&&U)return{kind:"unfile",overGroupId:null,before:void 0,after:null};const X=L?.orderable&&L.ids.length===1?Re(B,z,L.container,L.ids[0]):void 0;return X===void 0?{kind:I?"file":"none",overGroupId:I,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:X.before,after:X.after}},[Te,Re]);a.useEffect(()=>{if(!W.dragging)return;const B=U=>{const H=J.current;if(!H)return;const X=Le(U.clientX,U.clientY,H);H.intent=X.kind,H.overGroupId=X.overGroupId,H.beforeSessionId=X.before,fe(U.clientX,U.clientY),document.body.classList.toggle("ps-drop-ok",X.kind==="file"),Q(ae=>({...ae,intent:X.kind,overGroupId:X.overGroupId,insertBeforeId:X.before,insertAfterId:X.after,x:U.clientX,y:U.clientY}))},z=U=>{const H=J.current;if(H&&typeof U?.clientX=="number"){const X=Le(U.clientX,U.clientY,H);H.intent=X.kind,H.overGroupId=X.overGroupId,H.beforeSessionId=X.before}ye(!0)},L=()=>ye(!1),I=U=>{U.key==="Escape"&&ye(!1)};return window.addEventListener("pointermove",B),window.addEventListener("pointerup",z),window.addEventListener("pointercancel",L),window.addEventListener("keydown",I),document.body.classList.add("ps-dragging-sessions"),()=>{window.removeEventListener("pointermove",B),window.removeEventListener("pointerup",z),window.removeEventListener("pointercancel",L),window.removeEventListener("keydown",I),document.body.classList.remove("ps-dragging-sessions"),document.body.classList.remove("ps-drop-ok")}},[W.dragging,ye,Le,fe]);const De=a.useMemo(()=>({dragging:W.dragging,overGroupId:W.overGroupId,insertBeforeId:W.insertBeforeId,insertAfterId:W.insertAfterId,onPointerDown:(B,z)=>{if(z.isSystem||!z.orderable&&!z.isGroup&&z.depth>0)return;const L=B.clientX,I=B.clientY,U={row:z,startX:L,startY:I,started:!1,ids:[],overGroupId:null,beforeSessionId:void 0,orderable:!!z.orderable,container:z.orderContainer??null,isGroup:!!z.isGroup,ownGroupId:z.groupId||null,intent:"none",autoScrollStep:0},H=ae=>{if(U.started||Math.hypot(ae.clientX-L,ae.clientY-I)<5)return;U.started=!0;const le=K.current.viewState,Ae=Array.isArray(le.selectedIds)?le.selectedIds:[],ve=Ae.includes(z.sessionId)&&Ae.length>1?Ae:[z.sessionId],Ke=le.sessionsById||{};U.ids=ve,J.current=U,Q({dragging:!0,ids:ve,titles:ve.map(ce=>Ke[ce]?.title||String(ce).slice(0,8)).slice(0,3),overGroupId:null,x:ae.clientX,y:ae.clientY})},X=()=>{window.removeEventListener("pointermove",H),window.removeEventListener("pointerup",X)};window.addEventListener("pointermove",H),window.addEventListener("pointerup",X)}}),[W.dragging,W.overGroupId,W.insertBeforeId,W.insertAfterId]),Be=a.useCallback((B,z)=>{const{rows:L,viewState:I,controller:U}=K.current;if(B.metaKey||B.ctrlKey){B.preventDefault(),I.selectMode||U.dispatch({type:"sessions/selectMode",enabled:!0}),U.dispatch({type:"sessions/selectToggle",sessionId:z.sessionId}),U.setFocus("sessions");return}if(B.shiftKey&&I.activeSessionId){B.preventDefault();const X=L.map(Ae=>Ae.sessionId),ae=X.indexOf(I.activeSessionId),le=X.indexOf(z.sessionId);if(ae>=0&&le>=0){const[Ae,ve]=ae<=le?[ae,le]:[le,ae],Ke=X.slice(Ae,ve+1),ce=Array.from(new Set([...I.selectedIds||[],...Ke]));U.setSessionSelection(ce),U.setFocus("sessions");return}}if(z.hasChildren&&z.active){U.dispatch({type:z.collapsed?"sessions/expand":"sessions/collapse",sessionId:z.sessionId}),U.setFocus("sessions");return}I.selectMode&&U.dispatch({type:"sessions/selectClear"}),U.setFocus("sessions"),z.sessionId===I.activeSessionId?U.dispatch({type:"sessions/listReselect"}):z.active||U.loadSession(z.sessionId).catch(()=>{})},[]),ct=a.useCallback((B,z)=>{B&&(z?p.current.set(B,z):p.current.delete(B))},[]),We=a.useRef(null),G=`${u.activeSessionId||""}${u.focused?1:0}${u.modalOpen?1:0}`;a.useEffect(()=>{if(u.modalOpen||!u.focused||!u.activeSessionId){We.current=null;return}const B=p.current.get(u.activeSessionId);if(!B||We.current===G)return;We.current=G;const z=document.activeElement,L=!!(z&&(z.tagName==="INPUT"||z.tagName==="TEXTAREA"||z.tagName==="SELECT"||z.isContentEditable));z!==B&&!L&&B.focus({preventScroll:!0}),B.scrollIntoView({block:"nearest"})},[G,u.activeSessionId,u.focused,u.modalOpen,u.sessionsFlat]);const ne=a.createElement(a.Fragment,null,N?a.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",fontSize:"12px",opacity:.85},title:"Multiple sessions selected. Move to group or cancel selected sessions; click Clear to exit."},`${T} selected`):null,N?a.createElement(pe,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(P.CLEAR_SESSION_SELECTION).catch(()=>{})}):a.createElement(pe,{className:"ps-mini-button ps-pin-icon",icon:a.createElement(Jb),onClick:()=>t.handleCommand(P.PIN_SESSION).catch(()=>{}),disabled:!q,active:Z,label:q?Z?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"}),a.createElement(pe,{className:"ps-mini-button",icon:D.length>1?a.createElement("span",{className:"ps-icon-badge"},a.createElement(Ra),a.createElement("span",{className:"ps-icon-badge__count"},String(D.length))):a.createElement(Ra),onClick:()=>t.handleCommand(P.OPEN_MOVE_TO_GROUP).catch(()=>{}),label:D.length>1?`Move ${D.length} selected sessions to a group`:D.length===1?"Move this session to a group":"New group"}),a.createElement(pe,{className:"ps-mini-button",icon:a.createElement(ld),onClick:()=>{if(h?.isGroup){t.handleCommand(P.OPEN_RENAME_SESSION).catch(()=>{});return}y(!0)},disabled:!R&&!j||N,label:N?"Disabled while multiple sessions are selected":h?.isSystem?"System sessions are managed by administrators":h?.isGroup?"Rename folder":R?"Manage session — rename, switch model, and sharing":"Only this session's owner or an admin can manage it"}),a.createElement(pe,{className:"ps-mini-button",icon:a.createElement(Zb),onClick:()=>{const B=h?.sessionId;if(!B)return;const z=$c(B);z&&(gn(z),E({url:z,warn:!1}),ay(t,B).then(L=>{E(I=>I&&I.url===z?{...I,warn:L}:I)}).catch(()=>{}))},disabled:!h||h.isGroup||N,label:"Copy link — copy a direct link to this session"}),a.createElement(pe,{className:"ps-mini-button",icon:a.createElement(h?.isSystem?Hb:_r),onClick:()=>t.handleCommand(h?.isGroup?P.DELETE_SESSION:P.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!oe,label:N?`Terminate ${T} selected sessions (Mark Completed, Cancel, or Delete)`:h?.isGroup?ue?"Delete this empty group":"This group cannot be deleted yet":h?.isSystem?"Restart this system session (complete, terminate, or hard delete)":"Terminate — mark completed, cancel, or delete this session"}),e),Se=W.dragging?a.createElement("div",{className:"ps-drag-ghost",style:{left:`${W.x}px`,top:`${W.y}px`}},a.createElement("div",{className:`ps-drag-ghost__stack${W.ids.length>1?" is-collection":""}`},W.ids.length>1?a.createElement("span",{className:"ps-drag-ghost__count"},String(W.ids.length)):null,a.createElement("span",{className:"ps-drag-ghost__title"},W.ids.length>1?`${W.ids.length} sessions`:W.titles[0]||"session")),a.createElement("div",{className:"ps-drag-ghost__hint"},W.intent==="file"?"Release to file here":W.intent==="unfile"?"Release to remove from folder":W.intent==="reorder"?"Release to move here":"Release to cancel")):null;return a.createElement(a.Fragment,null,Se,a.createElement(xt,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:u.focused,theme:d,actions:ne,className:F},a.createElement("div",{ref:o,className:`ps-action-list ps-session-list${W.dragging?" is-dragging":""}`,onClick:B=>{B.target instanceof Element&&B.target.closest(".ps-session-list-button")||t.dispatch({type:"sessions/listDeselect"})}},m.length===0?a.createElement("div",{className:"ps-empty-state"},u.filterQuery?`No sessions matched "@@${u.filterQuery}".`:"No sessions yet."):m.map(B=>a.createElement(Nb,{key:B.sessionId,row:B,theme:d,structuredRows:n,mobile:i,onRowClick:Be,setRef:ct,drag:l?null:De}))),(r===null?!i:r)?a.createElement(xb,{session:h,childCount:g?.childCount||0,pause:g?.pause||null,controller:t}):null),b&&h&&!h.isGroup?a.createElement(sS,{controller:t,sessionId:h.sessionId,initialTitle:h.title||"",currentModel:h.model||"",currentReasoningEffort:h.reasoningEffort||"",principal:u.auth?.principal||null,onClose:()=>y(!1),onSwitchModel:S,onChanged:()=>{}}):null,v?a.createElement($b,{url:v.url,warn:v.warn,onCopyAgain:()=>{gn(v.url),t.dispatch({type:"ui/status",text:ry})},onClose:()=>E(null)}):null)}function $b({url:t,warn:e,onCopyAgain:s,onClose:n}){const[r,i]=a.useState(""),o=Si(t,Cn).length>1,l=a.useCallback((d,p)=>{d==="session"&&!o?s?.():navigator?.clipboard?.writeText&&navigator.clipboard.writeText(p).catch(()=>{}),i(d),window.setTimeout(()=>i(""),1500)},[o,s]),c=d=>d.stopPropagation();return a.createElement("div",{className:"ps-share-overlay",onClick:n},a.createElement("div",{className:"ps-link-modal",onClick:c},a.createElement("div",{className:"ps-share-modal-head"},a.createElement("span",null,o?"Session links copied":"Link copied"),a.createElement("button",{className:"ps-modal-close",onClick:n,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-share-section-sub"},o?"All entry-point links were copied. Copy just the one your recipient's network can reach, or take both.":"Copied to your clipboard — anyone with access can open the session from this link."),a.createElement(_c,{url:t,keyPrefix:"session",copied:r,onCopy:l}),e?a.createElement("div",{className:"ps-link-warn"},oy):null))}const Ma={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function Pe({children:t}){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},t)}function ld(){return a.createElement(Pe,null,a.createElement("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"}))}function $i(){return a.createElement(Pe,null,a.createElement("path",{d:"M21 4H3l7.2 8.5V19l3.6 2v-8.5L21 4z"}))}function _b(){return a.createElement(Pe,null,a.createElement("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),a.createElement("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))}function Lb(){return a.createElement(Pe,null,a.createElement("path",{d:"M3 6h18"}),a.createElement("path",{d:"M8 6V4h8v2"}),a.createElement("path",{d:"M19 6l-1 15H6L5 6"}),a.createElement("path",{d:"M10 11v5"}),a.createElement("path",{d:"M14 11v5"}))}function Ob(){return a.createElement(Pe,null,a.createElement("circle",{cx:"12",cy:"12",r:"9"}),a.createElement("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor"}))}function Fb(){return a.createElement(Pe,null,a.createElement("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),a.createElement("path",{d:"M16 3h3a2 2 0 0 1 2 2v3"}),a.createElement("path",{d:"M21 16v3a2 2 0 0 1-2 2h-3"}),a.createElement("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}))}function Db(){return a.createElement(Pe,null,a.createElement("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),a.createElement("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),a.createElement("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}),a.createElement("path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}))}function cd(){return a.createElement(Pe,null,a.createElement("circle",{cx:"12",cy:"12",r:"3"}),a.createElement("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"}))}function Bb(){return a.createElement(Pe,null,a.createElement("circle",{cx:"12",cy:"12",r:"9"}),a.createElement("path",{d:"M14.5 9.2a2.6 2.6 0 0 0-2.5-1.6c-1.5 0-2.6.8-2.6 2s1 1.7 2.6 2 2.6.8 2.6 2-1.1 2-2.6 2a2.6 2.6 0 0 1-2.5-1.6"}),a.createElement("path",{d:"M12 6v1.6"}),a.createElement("path",{d:"M12 16.4V18"}))}function Hb(){return a.createElement(Pe,null,a.createElement("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"}),a.createElement("path",{d:"M21 3v5h-5"}))}function Ub(){return a.createElement(Pe,null,a.createElement("path",{d:"M12 16V4"}),a.createElement("path",{d:"M7.5 8.5L12 4l4.5 4.5"}),a.createElement("path",{d:"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"}))}function dd(){return a.createElement(Pe,null,a.createElement("path",{d:"M12 4v12"}),a.createElement("path",{d:"M7.5 11.5L12 16l4.5-4.5"}),a.createElement("path",{d:"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"}))}function jb(){return a.createElement(Pe,null,a.createElement("line",{x1:"4.5",y1:"3",x2:"4.5",y2:"21"}),a.createElement("line",{x1:"19.5",y1:"3",x2:"19.5",y2:"21"}),a.createElement("path",{d:"M4.5 8.5h13"}),a.createElement("path",{d:"M15 6l2.5 2.5-2.5 2.5"}),a.createElement("path",{d:"M19.5 15.5h-13"}),a.createElement("path",{d:"M9 13l-2.5 2.5 2.5 2.5"}))}function Gb(){return a.createElement(Pe,null,a.createElement("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),a.createElement("line",{x1:"9.5",y1:"4",x2:"9.5",y2:"20"}),a.createElement("line",{x1:"12.5",y1:"9",x2:"18",y2:"9"}),a.createElement("line",{x1:"12.5",y1:"13",x2:"18",y2:"13"}))}function zb(){return a.createElement(Pe,null,a.createElement("path",{d:"M4 17l6-6-6-6"}),a.createElement("line",{x1:"12",y1:"19",x2:"20",y2:"19"}))}function Wb(){return a.createElement(Pe,null,a.createElement("circle",{cx:"6",cy:"6",r:"2.6"}),a.createElement("circle",{cx:"18",cy:"6",r:"2.6"}),a.createElement("circle",{cx:"12",cy:"18",r:"2.6"}),a.createElement("line",{x1:"8.6",y1:"6",x2:"15.4",y2:"6"}),a.createElement("line",{x1:"7.4",y1:"8.3",x2:"10.6",y2:"15.7"}),a.createElement("line",{x1:"16.6",y1:"8.3",x2:"13.4",y2:"15.7"}))}const qb="M12 2.3 20.4 7.15v9.7L12 21.7 3.6 16.85V7.15Z",Kb="M15.2 10.1A4.2 4.2 0 0 1 15.2 11.9L14.23 11.69A3.2 3.2 0 0 1 13.8 12.73L14.64 13.26A4.2 4.2 0 0 1 13.36 14.54L12.83 13.7A3.2 3.2 0 0 1 11.79 14.13L12 15.1A4.2 4.2 0 0 1 10.2 15.1L10.41 14.13A3.2 3.2 0 0 1 9.37 13.7L8.84 14.54A4.2 4.2 0 0 1 7.56 13.26L8.4 12.73A3.2 3.2 0 0 1 7.97 11.69L7 11.9A4.2 4.2 0 0 1 7 10.1L7.97 10.31A3.2 3.2 0 0 1 8.4 9.27L7.56 8.74A4.2 4.2 0 0 1 8.84 7.46L9.37 8.3A3.2 3.2 0 0 1 10.41 7.87L10.2 6.9A4.2 4.2 0 0 1 12 6.9L11.79 7.87A3.2 3.2 0 0 1 12.83 8.3L13.36 7.46A4.2 4.2 0 0 1 14.64 8.74L13.8 9.27A3.2 3.2 0 0 1 14.23 10.31ZM12.8 11A1.7 1.7 0 0 0 9.4 11A1.7 1.7 0 0 0 12.8 11Z",Vb="M7.23 15.01A5.7 5.7 0 0 1 17.76 14.55L19.11 15.04L15.1 16.57L14.71 13.44L16.06 13.93A3.9 3.9 0 0 0 8.87 14.25Z";function Yb(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":"true"},a.createElement("path",{d:qb,strokeWidth:"1.9",strokeLinejoin:"round"}),a.createElement("path",{d:Kb,fill:"currentColor",stroke:"none",fillRule:"evenodd"}),a.createElement("path",{d:Vb,fill:"currentColor",stroke:"none"}))}function Xb(){return a.createElement(Pe,null,a.createElement("path",{d:"M9 2.8h4.2L17 6.6v8.6a1.8 1.8 0 0 1-1.8 1.8H15"}),a.createElement("path",{d:"M4.5 9.4a1.8 1.8 0 0 1 1.8-1.8h4.2l3.8 3.8v8a1.8 1.8 0 0 1-1.8 1.8H6.3a1.8 1.8 0 0 1-1.8-1.8z"}),a.createElement("path",{d:"M10.5 7.6v3.8h3.8"}))}function Qb(){return a.createElement(Pe,null,a.createElement("rect",{x:"4.2",y:"12",width:"3.6",height:"8",rx:"0.6",fill:"currentColor",stroke:"none"}),a.createElement("rect",{x:"10.2",y:"6.5",width:"3.6",height:"13.5",rx:"0.6",fill:"currentColor",stroke:"none"}),a.createElement("rect",{x:"16.2",y:"9.5",width:"3.6",height:"10.5",rx:"0.6",fill:"currentColor",stroke:"none"}),a.createElement("path",{d:"M3 21h18"}))}function Zb(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.createElement("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),a.createElement("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}))}function _r(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.createElement("path",{d:"M3 6h18"}),a.createElement("path",{d:"M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"}),a.createElement("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),a.createElement("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),a.createElement("line",{x1:"14",y1:"11",x2:"14",y2:"17"}))}function Ra(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.createElement("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V18a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"}))}function Jb(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.createElement("path",{d:"M9 3h6"}),a.createElement("path",{d:"M10 3v6l-3 3v2h10v-2l-3-3V3"}),a.createElement("line",{x1:"12",y1:"14",x2:"12",y2:"21"}))}function eS(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.createElement("path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),a.createElement("path",{d:"M3 3v5h5"}),a.createElement("path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"}),a.createElement("path",{d:"M21 21v-5h-5"}))}function tS(t,e,s){const[n,r]=a.useState({access:null,loading:!1}),i=a.useCallback(()=>{if(!e||s||typeof t.transport.getSessionAccess!="function"){r({access:null,loading:!1});return}let o=!1;return r(l=>({...l,loading:!0})),t.transport.getSessionAccess(e).then(l=>{o||r({access:l,loading:!1})}).catch(()=>{o||r({access:null,loading:!1})}),()=>{o=!0}},[t,e,s]);return a.useEffect(()=>{let o;const l=setTimeout(()=>{o=i()},iy);return()=>{clearTimeout(l),typeof o=="function"&&o()}},[i]),{access:n.access,loading:n.loading,reload:i}}function sS({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:r,principal:i,onClose:o,onSwitchModel:l,onChanged:c}){const[d,p]=a.useState("general"),[u,f]=a.useState(null),[m,h]=a.useState(s||""),[g,b]=a.useState([]),[y,v]=a.useState([]),[E,k]=a.useState("private"),[x,w]=a.useState(""),[S,C]=a.useState("write"),[M,_]=a.useState([]),[O,R]=a.useState(!1),[T,N]=a.useState(null);a.useEffect(()=>{let G=!1;return t.transport.getSessionAccess(e).then(ne=>{!G&&ne&&(f(ne),k(ne.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(ne=>{G||_(Array.isArray(ne)?ne:[])}).catch(()=>{}),()=>{G=!0}},[t,e]);const j=a.useCallback(()=>{t.transport.listSessionShares(e).then(G=>{const ne=Array.isArray(G)?G:[];b(ne),v(ne)}).catch(()=>{b([]),v([])})},[t,e]);a.useEffect(()=>{j()},[j]);const q=async G=>{R(!0),N(null);try{await G(),c?.()}catch(ne){N(ne?.message||String(ne))}finally{R(!1)}},Z=()=>q(async()=>{await t.transport.renameSession(e,m.trim())}),ue=G=>{const ne=G.trim().toLowerCase();if(!ne)return null;const Se=M.find(B=>B.displayName&&B.displayName.toLowerCase()===ne||B.email&&B.email.toLowerCase()===ne||B.subject&&B.subject.toLowerCase()===ne);return Se||{provider:i?.provider||"dev",subject:G.trim(),email:null,displayName:null}},oe=G=>`${G.provider}${G.subject}`,de=G=>{const ne=oe(G);v(Se=>[...Se.filter(B=>oe(B)!==ne),{provider:G.provider,subject:G.subject,email:G.email??null,displayName:G.displayName??null,access:S}]),w("")},A=()=>{const G=ue(x);G&&de(G)},D=G=>{const ne=oe(G);v(Se=>Se.filter(B=>oe(B)!==ne))},F=new Set(y.map(oe)),K=u?.owner?`${u.owner.provider}${u.owner.subject}`:null,W=x.trim().toLowerCase(),Q=W?M.filter(G=>{const ne=oe(G);return ne===K||F.has(ne)?!1:G.displayName&&G.displayName.toLowerCase().includes(W)||G.email&&G.email.toLowerCase().includes(W)||G.subject&&G.subject.toLowerCase().includes(W)}).slice(0,25):[],J=!!u?.canManage,V=u?.visibility||"private",Y=new Set(y.map(G=>`${oe(G)}:${G.access}`)),ge=new Set(g.map(G=>`${oe(G)}:${G.access}`)),fe=Y.size!==ge.size||[...Y].some(G=>!ge.has(G)),ye=J&&(E!==V||fe),Te=()=>q(async()=>{E!==V&&await t.transport.setSessionVisibility(e,E);const G=new Map(g.map(z=>[oe(z),z])),ne=new Map(y.map(z=>[oe(z),z]));for(const[z,L]of ne){const I=G.get(z);(!I||I.access!==L.access)&&await t.transport.grantSessionShare(e,{provider:L.provider,subject:L.subject,email:L.email??null,displayName:L.displayName??null},L.access)}for(const[z,L]of G)ne.has(z)||await t.transport.revokeSessionShare(e,{provider:L.provider,subject:L.subject});const Se=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(Se)&&(b(Se),v(Se));const B=await t.transport.getSessionAccess(e).catch(()=>null);B&&(f(B),k(B.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),Re=l||(()=>{o(),t.openSwitchModelPicker().catch(G=>{t.dispatch({type:"ui/status",text:G?.message||String(G)||"Failed to switch model"})})}),Le=n?r?`${n}:${r}`:n:"—",De=[{id:"general",label:"General"},...J?[{id:"access",label:"Access"}]:[]],Be=De.some(G=>G.id===d)?d:"general",ct=typeof t.transport?.regenerateSession=="function",We=G=>G.stopPropagation();return a.createElement("div",{className:"ps-share-overlay",onClick:o},a.createElement("div",{className:"ps-share-modal",onClick:We},a.createElement("div",{className:"ps-share-modal-head"},a.createElement("span",null,"Manage session"),a.createElement("button",{className:"ps-modal-close",onClick:o,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-manage-tabs",role:"tablist"},De.map(G=>a.createElement("button",{key:G.id,type:"button",role:"tab","aria-selected":Be===G.id?"true":"false",className:`ps-manage-tab${Be===G.id?" is-active":""}`,onClick:()=>p(G.id)},G.label))),a.createElement("div",{className:"ps-share-modal-body"},Be==="general"?a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-share-section-label"},"Name"),a.createElement("div",{className:"ps-share-add-row"},a.createElement("input",{className:"ps-share-add-input",placeholder:"Session title",value:m,disabled:O,onChange:G=>h(G.target.value),onKeyDown:G=>{G.key==="Enter"&&Z()}}),a.createElement("button",{className:"ps-mini-button",disabled:O||!m.trim(),onClick:Z},"Save")),a.createElement("div",{className:"ps-share-section-label"},"Model"),a.createElement("div",{className:"ps-share-section-sub"},"The model this session uses on its next turn."),a.createElement("div",{className:"ps-share-add-row"},a.createElement("span",{className:"ps-manage-model-current"},Le),a.createElement("button",{className:"ps-mini-button",disabled:O,onClick:Re},"Switch model…")),ct?a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-share-section-label"},"Context"),a.createElement("div",{className:"ps-share-section-sub"},"Rebuild this session's working context from its summary. The transcript is archived and the session keeps running — it is not a terminal action."),a.createElement("div",{className:"ps-share-add-row"},a.createElement("button",{className:"ps-mini-button ps-manage-regenerate",disabled:O,onClick:()=>{o(),t.handleCommand(P.REGENERATE_SESSION).catch(()=>{})}},a.createElement(eS),a.createElement("span",null,"Regenerate context…")))):null):null,Be==="access"&&J?a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-share-section-label"},"General access"),a.createElement("div",{className:"ps-share-section-sub"},"The baseline level for everyone signed in to this workspace."),["private","shared_read","shared_write"].map(G=>a.createElement("label",{key:G,className:`ps-share-radio${E===G?" is-active":""}`},a.createElement("input",{type:"radio",name:"visibility",checked:E===G,disabled:O,onChange:()=>k(G)}),a.createElement("span",{className:"ps-share-radio-glyph"},Ma[G].glyph),a.createElement("span",null,Ma[G].label),a.createElement("span",{className:"ps-share-radio-hint"},G==="private"?"only you and admins":G==="shared_read"?"everyone here can view":"everyone here can view and send"))),a.createElement("div",{className:"ps-share-section-label"},"Special access"),a.createElement("div",{className:"ps-share-section-sub"},"Give specific people more than the general level. A person's grant wins over general access."),y.length===0?a.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):y.map(G=>a.createElement("div",{key:`${G.provider}/${G.subject}`,className:"ps-share-grant-row"},a.createElement("span",{className:"ps-share-grant-name"},G.displayName||G.subject),a.createElement("span",{className:"ps-share-grant-access"},`can ${G.access}`),a.createElement("button",{className:"ps-mini-button",disabled:O,onClick:()=>D(G)},"Remove"))),a.createElement("div",{className:"ps-share-add-wrap"},a.createElement("div",{className:"ps-share-add-row"},a.createElement("input",{className:"ps-share-add-input",placeholder:"Name, email, or id",value:x,disabled:O,autoComplete:"off",onChange:G=>w(G.target.value),onKeyDown:G=>{G.key==="Enter"&&A()}}),a.createElement("select",{className:"ps-share-add-select",value:S,disabled:O,onChange:G=>C(G.target.value)},a.createElement("option",{value:"read"},"can read"),a.createElement("option",{value:"write"},"can write")),a.createElement("button",{className:"ps-mini-button",disabled:O||!x.trim(),onClick:A},"Add")),Q.length>0?a.createElement("div",{className:"ps-share-suggestions"},Q.map(G=>a.createElement("button",{key:`${G.provider}/${G.subject}`,type:"button",className:"ps-share-suggestion",disabled:O,onClick:()=>de(G)},a.createElement("span",{className:"ps-share-suggestion-name"},G.displayName||G.subject),G.email?a.createElement("span",{className:"ps-share-suggestion-email"},G.email):null))):null),a.createElement("div",{className:"ps-share-foot-hint"},"Sharing applies to this session and its sub-agents. Suggestions are people who have signed in before — you can also grant by email to someone who hasn't; it takes effect when they first sign in.")):null),Be==="access"&&J?a.createElement("div",{className:"ps-manage-apply-bar is-footer"},a.createElement("span",{className:"ps-share-section-sub"},ye?"Unsaved access changes.":"No changes to apply."),a.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:O||!ye,onClick:Te},"Apply")):null,T?a.createElement("div",{className:"ps-share-error"},T):null))}function Lr({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const r=ee(t,N=>N.ui.themeId),i=pt(r),o=ee(t,N=>{const j=N.sessions.activeSessionId,q=Nn(N),Z=s||e?q.totalWidth:q.leftWidth,ue=Math.max(20,Z-4);return{activeSessionId:j,activeHistory:j&&N.history.bySessionId.get(j)||null,activeOutbox:j&&N.outbox?.bySessionId?.[j]?N.outbox.bySessionId[j]:[],branding:N.branding,connection:N.connection,sessionsById:N.sessions.byId,sessionsFlat:N.sessions.flat,inspectorTab:N.ui.inspectorTab,activeSessionIsGroup:!!(j&&N.sessions.byId[j]?.isGroup),activeSessionStatus:j?String(N.sessions.byId[j]?.status||"").toLowerCase():"",focused:N.ui.focusRegion==="chat",scroll:N.ui.scroll.chat,authPrincipal:N.auth?.principal||null,contentWidth:ue}},_e),l=a.useMemo(()=>({branding:o.branding,connection:o.connection,auth:{principal:o.authPrincipal},sessions:{activeSessionId:o.activeSessionId,byId:o.sessionsById,flat:o.sessionsFlat},history:{bySessionId:o.activeSessionId&&o.activeHistory?new Map([[o.activeSessionId,o.activeHistory]]):new Map},outbox:{bySessionId:o.activeSessionId?{[o.activeSessionId]:o.activeOutbox}:{}},ui:{inspectorTab:o.inspectorTab}}),[o.activeHistory,o.activeSessionId,o.activeOutbox,o.authPrincipal,o.branding,o.connection,o.inspectorTab,o.sessionsById,o.sessionsFlat]),[c,d]=Oc(),p=c??o.contentWidth,u=a.useMemo(()=>tc(l,{width:p}),[l,p]),f=qa(!!u.animateTitleRight),m=a.useMemo(()=>Ka(u.titleRight,u.animateTitleRight?f:""),[f,u.animateTitleRight,u.titleRight]),[h,g]=a.useState(!1),b=!!(o.activeHistory?.hasOlderEvents&&Number(o.activeHistory?.loadedEventCount||0)>=Nr),y=a.useMemo(()=>oi(l,p,{tableMode:"sentinel"}),[l,p]),v=Wa(o.activeSessionStatus==="running"),k=a.useMemo(()=>ii(l,{spinnerFrame:v,maxWidth:p}),[l,v,p]),x=a.useMemo(()=>ci(l,p,{tableMode:"sentinel"}),[l,p]),w=a.useMemo(()=>k.length>0?[...x,...k]:x,[x,k]),{access:S}=tS(t,o.activeSessionId,o.activeSessionIsGroup),C=ee(t,Yp,_e),M=n&&!o.activeSessionIsGroup,_=!!o.sessionsById?.[o.activeSessionId]?.serviceKind,O=_||!!S&&S.canWrite===!1,R=M?a.createElement("div",{className:"ps-chat-composer"},O?a.createElement("div",{className:"ps-composer-readonly"},_?"⚗ Service session — runtime machinery. Its transcript is a read-only trace; it does not accept messages.":`You have view access to this session. Ask ${S.owner?.displayName||S.owner?.email||"the owner"} for write access to participate.`):a.createElement(fS,{controller:t,mobile:e,active:!0})):null,T=!!(o.activeSessionId&&o.sessionsById[o.activeSessionId]);return C&&!T?a.createElement(xt,{title:u.title,color:u.color,focused:o.focused,theme:i,className:"ps-chat-panel"},a.createElement("div",{className:"ps-empty-state ps-nav-error-state"},a.createElement("div",{className:"ps-nav-error-message"},C.message),C.retryable?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(C.sessionId)},"Retry"):null)):a.createElement(Tn,{controller:t,title:e?ha(u.title,28):u.title,titleRight:e&&m?ha(m,18):m,actions:null,color:u.color,focused:o.focused,lines:y,bottomStickyLines:w,scrollOffset:o.scroll,scrollMode:"bottom",paneKey:"chat",className:"is-wrapped",panelClassName:"ps-chat-panel",panelRef:d,bottomContent:R,topContent:b?a.createElement("div",{className:"ps-load-older-bar"},a.createElement("button",{type:"button",className:"ps-load-older-button",disabled:h,onClick:()=>{g(!0),t.handleCommand(P.EXPAND_HISTORY).catch(()=>{}).finally(()=>g(!1))}},h?"Loading older messages…":"↑ Load older messages")):null,structuredBlocks:!0,renderBody:null})}function nS({controller:t,onClose:e}){const s=ee(t,g=>g.ui.themeId),n=pt(s),r=ee(t,g=>{const b=g.files.selectedArtifactId||"",y=b.indexOf("/");return{sessionId:y>0?b.slice(0,y):null,filename:y>0?b.slice(y+1):"",canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},_e),i=Gc(r.filename),o=ee(t,g=>g.files.htmlViewMode||"rendered"),l=ee(t,g=>!!g.files.htmlFitWidth),c=a.useCallback(g=>{t.dispatch({type:"files/htmlFitWidth",enabled:g})},[t]),d=a.useCallback(g=>{t.dispatch({type:"files/htmlViewMode",mode:g})},[t]),p=ee(t,g=>Number(g.files.htmlZoom)||1),u=a.useCallback(g=>{t.dispatch({type:"files/htmlZoom",zoom:g})},[t]),f=a.useCallback(g=>{t.stepArtifactPreview(g).catch(()=>{})},[t]),m=a.useCallback(g=>{if(!(g.metaKey||g.ctrlKey||g.altKey)){if(g.key==="ArrowLeft"||g.key==="["){g.preventDefault(),f(-1);return}if(g.key==="ArrowRight"||g.key==="]"){g.preventDefault(),f(1);return}g.key==="Escape"&&(g.preventDefault(),e())}},[e,f]),h=An(r.sessionId,r.filename);return a.createElement("section",{className:"ps-artifact-pane",onKeyDown:m,tabIndex:-1,role:"region","aria-label":`Artifact: ${r.filename||"none"}`},a.createElement("header",{className:"ps-artifact-pane-bar"},i.kind==="page"?a.createElement(Jc,{mode:o,setMode:d}):null,i.kind==="page"&&o==="rendered"?a.createElement(Zc,{fitWidth:l,setFitWidth:c}):null,i.kind==="page"&&o==="rendered"?a.createElement(vn,{zoom:p,setZoom:u}):null,a.createElement("span",{className:"ps-artifact-pane-heading"},a.createElement("span",{className:"ps-artifact-pane-name",title:r.filename},zc(r.filename)||"Artifact"),a.createElement("span",{className:"ps-artifact-pane-type"},i.type)),a.createElement("span",{className:"ps-artifact-pane-actions"},a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",disabled:!r.canPrev,onClick:()=>f(-1),title:"Previous artifact (←)","aria-label":"Previous artifact"},"‹"),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",disabled:!r.canNext,onClick:()=>f(1),title:"Next artifact (→)","aria-label":"Next artifact"},"›"),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>{h&&(gn(h),t.dispatch({type:"ui/status",text:Rc}))},disabled:!h,title:"Copy a link that reopens this artifact","aria-label":"Copy link"},"🔗"),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>t.handleCommand(P.DOWNLOAD_SELECTED_FILE).catch(()=>{}),title:"Download","aria-label":"Download"},a.createElement(dd)),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn is-close",onClick:e,title:"Close (Esc)","aria-label":"Close artifact"},"✕"))),a.createElement("div",{className:"ps-artifact-pane-body"},a.createElement(Pn,{controller:t,focused:!1,previewOnly:!0,chromeless:!0,theme:n})))}function rS({controller:t,visible:e=!0}){const[s,n]=a.useState(!1),r=a.useCallback(()=>n(i=>!i),[]);return a.useEffect(()=>{e||n(!1)},[e]),a.createElement("div",{className:`ps-mobile-canvas-layer${s?" is-maximized":""}${e?"":" is-hidden"}`,...e?{}:{inert:!0,"aria-hidden":"true"}},a.createElement(pd,{controller:t,mobile:!0,visible:e,focusOnPromote:!0,maximized:s,onToggleMaximized:r}))}function iS({controller:t}){const e=ee(t,o=>{const l=o.files.selectedArtifactId||"";return{filename:l?l.slice(l.indexOf("/")+1):"",origin:o.files.previewOrigin||null,canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},_e),s=!!Ni(e.filename)||Ti(e.filename),[n,r]=a.useState(!1);a.useEffect(()=>{r(!1)},[e.filename]);const i=a.useCallback(o=>{t.stepArtifactPreview(o).catch(()=>{})},[t]);return a.createElement("div",{className:"ps-artifact-overlay"},a.createElement("header",{className:"ps-artifact-overlay-bar"},a.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",onClick:()=>t.closeArtifactPreview().catch(()=>{}),"aria-label":e.origin==="chat"?"Close, back to chat":"Close, back to artifacts"},"✕"),a.createElement("span",{className:"ps-artifact-overlay-title"},e.filename||"Artifact"),s?a.createElement("button",{type:"button",className:`ps-artifact-overlay-btn${n?" is-active":""}`,onClick:()=>r(o=>!o),"aria-label":n?"Wrap lines":"Show full lines",title:n?"Wrap to screen width":"Full line width (scroll horizontally)"},n?"⇥":"↔"):null,a.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canPrev,onClick:()=>i(-1),"aria-label":"Previous artifact"},"‹"),a.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canNext,onClick:()=>i(1),"aria-label":"Next artifact"},"›")),a.createElement("div",{className:`ps-artifact-overlay-body${n?" is-content-width":""}`},a.createElement(Pn,{controller:t,focused:!0,mobile:!0,previewOnly:!0,nativeScroll:!0})))}const oS=140;function aS(t,e,s,n){let r=t;!t||Math.abs(e-t.width)>2?r={width:e,height:s}:s>t.height&&(r={width:t.width,height:s});const i=s<=r.height-oS;return{baseline:r,takeover:i&&n}}function lS(t){const[e,s]=a.useState(!1);return a.useEffect(()=>{if(!t||typeof window>"u"||!window.visualViewport){s(!1);return}const n=window.visualViewport;let r={width:n.width,height:n.height},i=0;const o=()=>{i=0;const c=!!document.activeElement?.classList?.contains("ps-prompt-input"),d=aS(r,n.width,n.height,c);r=d.baseline,s(d.takeover)},l=()=>{i||(i=requestAnimationFrame(o))};return o(),n.addEventListener("resize",l),window.addEventListener("focusin",l),window.addEventListener("focusout",l),()=>{i&&cancelAnimationFrame(i),n.removeEventListener("resize",l),window.removeEventListener("focusin",l),window.removeEventListener("focusout",l)}},[t]),t?e:!1}function cS({controller:t,layout:e="split"}){const s=a.createElement($r,{controller:t,panelClassName:"ps-mobile-session-pane"});return e==="chat"?a.createElement("div",{className:"ps-mobile-workspace is-chat-only"},a.createElement("div",{className:"ps-mobile-chat-pane"},a.createElement(Lr,{controller:t,mobile:!0,fullWidth:!0}))):e==="sessions"?a.createElement("div",{className:"ps-mobile-workspace is-sessions-only"},a.createElement($r,{controller:t,panelClassName:"ps-mobile-session-pane",showDetailBox:!0})):a.createElement("div",{className:"ps-mobile-workspace"},s,a.createElement("div",{className:"ps-mobile-chat-pane"},a.createElement(Lr,{controller:t,mobile:!0,fullWidth:!0})))}function ud(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:16,height:16,"aria-hidden":"true"},a.createElement("rect",{x:2.5,y:3.5,width:15,height:11,rx:1.5,...t}),a.createElement("path",{d:"M5.5 11.5l3-3.5 2.5 2.5 3.5-4",...t}),a.createElement("path",{d:"M7 17.5h6M10 14.5v3",...t}))}function $a(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:20,height:20,"aria-hidden":"true"},a.createElement("path",{d:"M6.2 8.6a3.8 3.8 0 0 1 7.6 0v2.9a3.8 3.8 0 0 1-7.6 0z",...t}),a.createElement("path",{d:"M6.2 10.3h7.6",...t}),a.createElement("path",{d:"M7.6 6.5a2.4 2.4 0 0 1 4.8 0",...t}),a.createElement("path",{d:"M8 4.4 6.9 2.9M12 4.4l1.1-1.5",...t}),a.createElement("path",{d:"M6.3 8.6 3.8 7.4M6.2 10.6H3.6M6.3 12.6 3.8 13.9",...t}),a.createElement("path",{d:"M13.7 8.6 16.2 7.4M13.8 10.6h2.6M13.7 12.6l2.5 1.3",...t}))}function _a({mark:t}){if(t!=="canvas"&&t!=="unseen")return null;const e=t==="unseen",s={fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("span",{className:`ps-session-canvas-mark${e?" is-unseen":""}`,title:e?"Canvas updated since you last viewed it":"This session has a canvas","aria-label":e?"Canvas updated":"Has a canvas",role:"img"},a.createElement("svg",{viewBox:"0 0 16 16",width:12,height:12,"aria-hidden":"true"},a.createElement("rect",{x:1.6,y:2.6,width:12.8,height:9.2,rx:1.4,...s}),a.createElement("path",{d:"M6 14.4h4",...s}),e?a.createElement("circle",{cx:12.4,cy:4.6,r:2.4,fill:"currentColor",stroke:"none"}):null))}function La(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:14,height:14,"aria-hidden":"true"},a.createElement("path",{d:"M8.5 11.5l3-3",...t}),a.createElement("path",{d:"M7 13l-1.8 1.8a2.8 2.8 0 01-4-4l3-3a2.8 2.8 0 014 0",...t}),a.createElement("path",{d:"M13 7l1.8-1.8a2.8 2.8 0 014 4l-3 3a2.8 2.8 0 01-4 0",...t}))}const dS=[{id:"session",label:"Session access"},{id:"public",label:"Anyone with link"}];function uS({controller:t,sessionId:e,slot:s,onClose:n}){const[r,i]=a.useState(null),[o,l]=a.useState(null),[c,d]=a.useState(!1),[p,u]=a.useState(""),[f,m]=a.useState(""),[h,g]=a.useState("session"),b=t.transport,y=`${window.location.origin}/?session=${encodeURIComponent(e)}&view=canvas&slot=${s}&max=1`,v=(S,C)=>a.createElement(_c,{url:S,keyPrefix:C,copied:f,onCopy:k}),E=a.useCallback(()=>{b.getCanvasShareLink?.(e,s).then(S=>i(S||{exists:!1})).catch(S=>{i({exists:!1}),u(S?.message||String(S))})},[b,e,s]);a.useEffect(()=>{E()},[E]);const k=(S,C)=>{navigator.clipboard?.writeText(C).then(()=>{m(S),window.setTimeout(()=>m(""),1500)}).catch(()=>u("Could not reach the clipboard — copy the link manually."))},x=S=>{d(!0),u(""),b.resetCanvasShareLink(e,s).then(({token:C})=>{l(`${window.location.origin}/?canvasShare=${encodeURIComponent(C)}`),i({exists:!0})}).catch(C=>u(C?.message||String(C))).finally(()=>d(!1))},w=()=>{d(!0),u(""),b.removeCanvasShareLink(e,s).then(()=>{l(null),i({exists:!1})}).catch(S=>u(S?.message||String(S))).finally(()=>d(!1))};return a.createElement("div",{className:"ps-canvas-share-overlay",onClick:n},a.createElement("div",{className:"ps-canvas-share-dialog",onClick:S=>S.stopPropagation(),role:"dialog","aria-label":"Share canvas"},a.createElement("div",{className:"ps-canvas-share-title"},"Share this canvas",a.createElement("button",{type:"button",className:"ps-mini-button",onClick:n,"aria-label":"Close"},"✕")),a.createElement("div",{className:"ps-manage-tabs",role:"tablist"},dS.map(S=>a.createElement("button",{key:S.id,type:"button",role:"tab","aria-selected":h===S.id?"true":"false",className:`ps-manage-tab${h===S.id?" is-active":""}`,onClick:()=>g(S.id)},S.label))),a.createElement("div",{className:"ps-canvas-share-panels"},a.createElement("div",{className:`ps-canvas-share-panel${h==="session"?" is-active":""}`,role:"tabpanel","aria-hidden":h==="session"?void 0:"true"},a.createElement("div",{className:"ps-canvas-share-sub"},"Opens the portal signed in, canvas full screen. Session visibility rules apply."),v(y,"session")),a.createElement("div",{className:`ps-canvas-share-panel${h==="public"?" is-active":""}`,role:"tabpanel","aria-hidden":h==="public"?void 0:"true"},a.createElement("div",{className:"ps-canvas-share-sub"},"View only, live, no sign-in. One link at a time — resetting makes the previous link stop working immediately."),r===null?a.createElement("div",{className:"ps-canvas-share-sub"},"Checking…"):o?a.createElement(a.Fragment,null,v(o,"public"),a.createElement("div",{className:"ps-canvas-share-sub is-warn"},"Copy it now — the link is shown only this once.")):r.exists?a.createElement("div",{className:"ps-canvas-share-sub"},`A link exists${r.createdAt?` (created ${new Date(r.createdAt).toLocaleString()})`:""}. For safety it cannot be re-shown — Reset to get a new one.`):a.createElement("div",{className:"ps-canvas-share-sub"},"No public link yet."),a.createElement("div",{className:"ps-canvas-share-actions"},a.createElement("button",{type:"button",className:"ps-mini-button",disabled:c,onClick:()=>x(r?.exists)},r?.exists?"Reset link":"Create link"),r?.exists?a.createElement("button",{type:"button",className:"ps-mini-button",disabled:c,onClick:w},"Remove link"):null))),p?a.createElement("div",{className:"ps-canvas-share-error"},p):null))}function ur({controller:t,view:e,compact:s=!1}){const n=Array.isArray(e.slots)?e.slots:[];if(n.length<=1)return null;const r=n.map(c=>c.slot),i=Math.max(0,r.indexOf(e.slot)),o=c=>{const d=r[(i+c+r.length)%r.length];t.dispatch({type:"ui/canvasSlot",slot:d})},l=c=>(c.name?c.name:`canvas ${c.slot}`)+(c.unseen?" •":"");return a.createElement("span",{className:`ps-canvas-slot-controls${s?" is-compact":""}`},a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>o(-1),title:"Previous canvas","aria-label":"Previous canvas"},"‹"),a.createElement("select",{className:"ps-canvas-slot-select",value:e.slot,onChange:c=>t.dispatch({type:"ui/canvasSlot",slot:Number(c.target.value)}),"aria-label":"Choose canvas",title:"Choose canvas"},n.map(c=>a.createElement("option",{key:c.slot,value:c.slot},l(c)))),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>o(1),title:"Next canvas","aria-label":"Next canvas"},"›"))}function Oa(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:15,height:15,"aria-hidden":"true"},a.createElement("rect",{x:2.2,y:3.4,width:3.6,height:13.2,rx:1,...t}),a.createElement("rect",{x:8.2,y:3.4,width:9.6,height:13.2,rx:1,...t}))}function Fa(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.9,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:13,height:13,"aria-hidden":"true"},a.createElement("path",{d:"M8 3H3v5M12 3h5v5M12 17h5v-5M8 17H3v-5",...t}))}function Da(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.9,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:13,height:13,"aria-hidden":"true"},a.createElement("path",{d:"M3 8h5V3M17 8h-5V3M17 12h-5v5M3 12h5v5",...t}))}function pS({controller:t,sessionId:e,slot:s=1,latestRev:n,zoom:r,visible:i=!0,focusOnPromote:o=!1,dataRev:l=0,dataPayload:c=null,dataPatch:d=null}){const[p,u]=a.useState(null),[f,m]=a.useState(null),[h,g]=a.useState(null),[b,y]=a.useState(0),v=a.useRef({live:null,staging:null}),E=a.useRef({rev:0,used:!1}),k=a.useRef(null),x=a.useRef(null),w=ed(k),S=a.useRef(null),C=a.useRef(r);C.current=r;const M=a.useRef(i);M.current=i,a.useEffect(()=>{if(!t||!e)return;const R=T=>{const N=x.current;if(!N||!T.source||T.source!==N.contentWindow)return;const j=T.data;!j||typeof j!="object"||j.type!=="canvas-action"||t.submitCanvasAction(e,j).then(q=>{q&&q.ok===!1&&typeof console<"u"&&console.warn(`canvas action rejected: ${q.reason}`)}).catch(()=>{})};return window.addEventListener("message",R),()=>window.removeEventListener("message",R)},[t,e]),a.useEffect(()=>{if(!t||!e||!n)return;let R=!1,T=null;return td(t,e,s<=1?"canvas.html":`canvas${s}.html`).then(N=>{if(R){URL.revokeObjectURL(N);return}v.current.staging&&v.current.staging!==v.current.live&&URL.revokeObjectURL(v.current.staging),v.current.staging=N,g(null),m({url:N,rev:n})}).catch(()=>{if(!R){if(E.current.rev!==n&&(E.current={rev:n,used:!1}),!E.current.used){E.current.used=!0,T=setTimeout(()=>{R||y(N=>N+1)},1500);return}g({rev:n})}}),()=>{R=!0,T&&clearTimeout(T)}},[t,e,s,n,b]),a.useEffect(()=>()=>{v.current.staging&&v.current.staging!==v.current.live&&URL.revokeObjectURL(v.current.staging),v.current.live&&URL.revokeObjectURL(v.current.live),v.current={live:null,staging:null},u(null),m(null),g(null)},[e]);const _=a.useCallback(R=>{if(!R||v.current.staging!==R.url)return;const T=v.current.live;v.current.live=R.url,v.current.staging=null,T&&T!==R.url&&URL.revokeObjectURL(T),u(R),m(j=>j&&j.url===R.url?null:j);const N=k.current;if(N){const j=N.getBoundingClientRect(),q=C.current||1;S.current={w:Math.round(j.width/q),h:Math.round(j.height/q)}}if(t&&e&&M.current&&t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,rev:R.rev}),o&&M.current)try{x.current?.focus({preventScroll:!0})}catch{}},[t,e,o]);a.useEffect(()=>{if(!(!p||!l||c===null)){try{x.current?.contentWindow?.postMessage({type:"canvas-data",data:c,dataRev:l},"*"),d&&x.current?.contentWindow?.postMessage({type:"canvas-patch",patch:d,dataRev:l},"*")}catch{}t&&e&&M.current&&t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,dataRev:l})}},[p,l,c,d,t,e]),a.useEffect(()=>{if(i&&p&&t&&e&&(t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,rev:p.rev,...l?{dataRev:l}:{}}),o))try{x.current?.focus({preventScroll:!0})}catch{}},[i,p,t,e,o,l]),a.useEffect(()=>{if(!p||!i)return;const R=r||1,T=Math.round((w.width||0)/R),N=Math.round((w.height||0)/R);if(!T||!N)return;const j=S.current;if(j){if(!(j.w<220||j.h<170))return;const ue=Math.abs(j.w-T),oe=Math.abs(j.h-N);if(ue<=2&&oe<=2||ue<=2&&oe/Math.max(1,j.h)<.15)return}const q=setTimeout(()=>{S.current={w:T,h:N},y(Z=>Z+1)},350);return()=>clearTimeout(q)},[w.width,w.height,r,p,i]);const O=r!==1&&w.width>0?{flex:"none",width:`${Math.max(1,Math.round(w.width/r))}px`,height:`${Math.max(1,Math.round(w.height/r))}px`,transform:`scale(${r})`,transformOrigin:"top left"}:void 0;return a.createElement("div",{ref:k,className:"ps-html-preview-host is-fitting"},[p,f].filter(Boolean).map(R=>a.createElement("iframe",{key:`canvas:${R.rev}:${R.url}`,ref:R===p?(T=>{x.current=T}):void 0,className:`ps-html-preview-frame${R===p?"":" is-staging"}`,style:O,src:R.url,title:"Session canvas",sandbox:"allow-scripts allow-popups allow-popups-to-escape-sandbox",allow:"autoplay *",referrerPolicy:"no-referrer",onLoad:R===f?()=>_(R):void 0})),h?a.createElement("div",{className:"ps-canvas-load-error"},a.createElement("span",null,p?`Couldn't load rev ${h.rev} — showing rev ${p.rev}.`:`Couldn't load rev ${h.rev}.`),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>{E.current={rev:0,used:!1},g(null),y(R=>R+1)}},"Retry")):null)}function pd({controller:t,mobile:e=!1,visible:s=!0,focusOnPromote:n=!1,maximized:r=!1,onToggleMaximized:i=null}){const o=ee(t,ai,_e),l=ee(t,b=>Number(b.files.htmlZoom)||1),c=a.useCallback(b=>{t.dispatch({type:"files/htmlZoom",zoom:b})},[t]);a.useEffect(()=>{o.sessionId&&t.ensureCanvasSnapshot(o.sessionId).catch(()=>{})},[t,o.sessionId]);const d=ee(t,b=>b?.ui?.canvasZen===!0),[p,u]=a.useState(!1),[f,m]=a.useState(null);a.useEffect(()=>{if(!r){m(null);return}let b=0;const y=()=>{const v=document.getElementById("ps-toolbar-canvas-slot");v?m(v):b=requestAnimationFrame(y)};return y(),()=>cancelAnimationFrame(b)},[r]),a.useCallback(()=>{t.dispatch({type:"ui/canvasOpen",open:!1,sessionId:o.sessionId,manual:!0})},[t,o.sessionId]);const h=e&&(o.exists||r),g=e?h?a.createElement("header",{className:"ps-artifact-pane-bar is-rev-strip"},a.createElement("span",{className:"ps-artifact-pane-type",title:o.note||void 0},o.exists?`${o.name?`${o.name} · `:""}rev ${o.latestRev}`:""),a.createElement(ur,{controller:t,view:o,compact:!0}),o.exists?a.createElement("button",{type:"button",className:"ps-canvas-max-btn",onClick:()=>u(!0),title:"Share this canvas — copy a view link","aria-label":"Share canvas"},a.createElement(La)):null,i?a.createElement("button",{type:"button",className:"ps-canvas-max-btn",onClick:i,title:r?"Back to the inset canvas":"Maximize — cover the whole screen","aria-label":r?"Restore canvas":"Maximize canvas"},a.createElement(r?Da:Fa)):null):null:r?f?Dr.createPortal(a.createElement(a.Fragment,null,o.exists?a.createElement("span",{className:"ps-toolbar-canvas-rev"},`${o.name?`${o.name} · `:""}rev ${o.latestRev}`):null,a.createElement(ur,{controller:t,view:o,compact:!0}),o.exists?a.createElement(vn,{zoom:l,setZoom:c}):null,a.createElement("button",{type:"button",className:`ps-artifact-pane-btn${d?" is-active":""}`,onClick:()=>{t.dispatch({type:"ui/canvasMaximized",on:!1}),t.dispatch({type:"ui/canvasZen",on:!d})},title:d?"Leave zen — bring back sessions and panels":"Zen — chat rail + canvas only","aria-label":d?"Leave zen mode":"Zen mode"},a.createElement(Oa)),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn ps-toolbar-canvas-restore",onClick:()=>t.dispatch({type:"ui/canvasMaximized",on:!1}),title:"Back to the workspace","aria-label":"Restore canvas"},a.createElement(Da))),f):null:a.createElement("header",{className:"ps-artifact-pane-bar"},a.createElement("span",{className:"ps-artifact-pane-heading"},a.createElement("span",{className:"ps-artifact-pane-name ps-canvas-pane-glyph",title:o.note||"Canvas"},a.createElement(ud)),o.exists?a.createElement("span",{className:"ps-artifact-pane-type",title:o.note||void 0},`${o.name?`${o.name} · `:""}rev ${o.latestRev}`):null,a.createElement(ur,{controller:t,view:o})),a.createElement("span",{className:"ps-artifact-pane-actions"},o.exists?a.createElement(vn,{zoom:l,setZoom:c}):null,o.exists?a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>u(!0),title:"Share this canvas — copy a view link","aria-label":"Share canvas"},a.createElement(La)):null,a.createElement("button",{type:"button",className:`ps-artifact-pane-btn${d?" is-active":""}`,onClick:()=>t.dispatch({type:"ui/canvasZen"}),title:d?"Leave zen — bring back sessions and panels":"Zen — chat rail + canvas only","aria-label":d?"Leave zen mode":"Zen mode"},a.createElement(Oa)),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>t.dispatch({type:"ui/canvasMaximized",on:!0}),title:"Full screen — hide chat and sessions","aria-label":"Full screen canvas"},a.createElement(Fa))));return a.createElement("section",{className:"ps-artifact-pane ps-canvas-pane",role:"region","aria-label":"Session canvas"},g,a.createElement("div",{className:"ps-artifact-pane-body"},o.exists?a.createElement(pS,{key:`slot:${o.slot}`,controller:t,sessionId:o.sessionId,slot:o.slot,latestRev:o.latestRev,zoom:l,visible:s,focusOnPromote:n,dataRev:o.latestDataRev,dataPayload:o.dataPayload,dataPatch:o.dataPatch}):a.createElement("div",{className:"ps-canvas-blank"},a.createElement("p",{className:"ps-canvas-blank-title"},"Nothing on the canvas yet."),a.createElement("p",null,"Ask the agent to draw — a dashboard, a chart, a diagram — or it will draw when it has something worth showing."))),p&&o.exists?a.createElement(uS,{controller:t,sessionId:o.sessionId,slot:o.slot,onClose:()=>u(!1)}):null)}function fd({activeTab:t,controller:e}){const s=a.useMemo(()=>ki(e),[e]);return a.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>a.createElement(pe,{key:n,icon:pa[n]?a.createElement(pa[n]):"•",label:Qg[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function Pn({controller:t,focused:e,mobile:s=!1,previewOnly:n=!1,nativeScroll:r=!1,chromeless:i=!1}){const o=ee(t,N=>N.ui.themeId),l=pt(o),c=a.useRef(null),d=ee(t,N=>{const j=N.sessions.activeSessionId,q=Nn(N),Z=s||N.files.fullscreen?N.ui.layout?.viewportWidth??120:q.rightWidth;return{activeSessionId:j,sessionsById:N.sessions.byId,sessionsFlat:N.sessions.flat,filesBySessionId:N.files.bySessionId,filesFilter:N.files.filter,selectedArtifactId:N.files.selectedArtifactId,markedIds:N.files.markedIds||[],previewOrigin:N.files.previewOrigin||null,focused:e,previewScroll:N.ui.scroll.filePreview,fullscreen:!!N.files.fullscreen,contentWidth:Math.max(20,Z-4),canBrowserUpload:Jg(t),canPathUpload:ey(t),canDeleteArtifacts:sy(t),canOpenLocally:ny(t)}},_e),p=a.useMemo(()=>({sessions:{activeSessionId:d.activeSessionId,byId:d.sessionsById,flat:d.sessionsFlat},files:{bySessionId:d.filesBySessionId,selectedArtifactId:d.selectedArtifactId,filter:d.filesFilter,fullscreen:d.fullscreen},ui:{scroll:{filePreview:d.previewScroll}}}),[d.activeSessionId,d.filesBySessionId,d.filesFilter,d.fullscreen,d.previewScroll,d.selectedArtifactId,d.sessionsById,d.sessionsFlat]),u=a.useMemo(()=>pi(p,{listWidth:Math.max(18,d.contentWidth-4),previewWidth:Math.max(18,d.contentWidth-4),showHints:!1}),[p,d.contentWidth]),f=a.useMemo(()=>Mt(p),[p]),m=f.length>0,h=a.useCallback(N=>{const j=Array.isArray(N)?N.filter(Boolean):[];j.length!==0&&t.uploadArtifactFiles(j).catch(()=>{})},[t]),g=a.useCallback(()=>{if(d.canBrowserUpload&&c.current){c.current.click();return}d.canPathUpload&&t.handleCommand(P.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,d.canBrowserUpload,d.canPathUpload]),b=a.useMemo(()=>new Set(d.markedIds||[]),[d.markedIds]),y=a.createElement(a.Fragment,null,b.size>0?a.createElement(a.Fragment,null,a.createElement("span",{className:"ps-mini-button-label",style:{padding:"0 6px",opacity:.85},title:"Cmd/Ctrl-click to mark, Shift-click for a range"},`${b.size} marked`),d.canDeleteArtifacts?a.createElement(pe,{icon:a.createElement(_r),label:`Delete ${b.size} marked`,onClick:()=>t.deleteMarkedArtifacts().catch(()=>{})}):null,a.createElement(pe,{icon:"✕",label:"Clear marks",onClick:()=>t.clearArtifactMarks()})):null,a.createElement("input",{ref:c,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:N=>{h(Array.from(N.currentTarget.files||[])),N.currentTarget.value=""}}),a.createElement(pe,{icon:a.createElement(Ub),label:"Upload",onClick:g,disabled:!d.canBrowserUpload&&!d.canPathUpload}),a.createElement(pe,{icon:a.createElement(dd),label:"Download",onClick:()=>t.handleCommand(P.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!m}),a.createElement(pe,{icon:"🔗",label:"Copy link to this artifact",onClick:()=>{const N=An(u.selectedSessionId,u.selectedFilename);N&&(gn(N),t.dispatch({type:"ui/status",text:Rc}))},disabled:!m||!u.selectedFilename}),d.canDeleteArtifacts?a.createElement(pe,{icon:a.createElement(_r),label:"Delete",onClick:()=>t.handleCommand(P.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!m}):null,d.canOpenLocally?a.createElement(pe,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(P.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!m}):null,a.createElement(pe,{icon:a.createElement($i),label:"Filter",onClick:()=>t.handleCommand(P.OPEN_FILES_FILTER).catch(()=>{})}),a.createElement(pe,{icon:a.createElement(d.fullscreen?Db:Fb),label:d.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(P.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),v=a.useRef(null);a.useEffect(()=>{const N=v.current;N&&typeof N.scrollIntoView=="function"&&N.scrollIntoView({block:"nearest"})},[u.selectedIndex,d.selectedArtifactId]);const E=f.length===0?Ue(u.listBodyLines||[]).map((N,j)=>a.createElement(je,{key:`empty:${j}`,line:N,theme:l})):f.map((N,j)=>a.createElement("button",{key:N.id,type:"button",ref:j===u.selectedIndex?v:null,className:`ps-list-button${j===u.selectedIndex?" is-selected":""}`+(b.has(N.id)?" is-marked":""),onClick:q=>{if(t.setFocus("inspector"),q.metaKey||q.ctrlKey){t.toggleArtifactMark(N);return}if(q.shiftKey){t.markArtifactRange(N);return}t.clearArtifactMarks(),t.selectFileBrowserItem(N).then(()=>{s&&t.handleCommand(P.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})}).catch(()=>{})}},a.createElement(je,{line:Ue([u.listBodyLines?.[j]])[0],theme:l}))),k=!u.previewLoading&&!u.previewError,x=k&&Ti(u.selectedFilename,u.previewContentType)&&!u.previewIsBinary&&!!u.previewContent,w=k&&(Ai.test(String(u.previewContentType||""))||Ci.test(String(u.selectedFilename||""))),S=k&&!u.previewIsBinary&&!x&&u.previewRenderMode!=="markdown"&&u.previewContent?Ni(u.selectedFilename):null,C=n?"activity":null,M=r?null:"filePreview",_=k&&!u.previewIsBinary&&Hc(u.selectedFilename,u.previewContentType)&&!!u.previewContent,R=k&&!u.previewIsBinary&&Bc(u.selectedFilename,u.previewContentType)?a.createElement(cb,{controller:t,sessionId:u.selectedSessionId,filename:u.selectedFilename,contentType:u.previewContentType,sizeBytes:u.previewSizeBytes,theme:l,color:"cyan",focused:!1,title:null,chromeless:i}):_?a.createElement(lr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:M,scrollOffset:d.previewScroll,className:"ps-csv-preview",focusRegion:C},a.createElement(Oy,{content:u.previewContent,filename:u.selectedFilename})):w?a.createElement(ka,{title:null,color:"cyan",focused:!1,theme:l,filename:u.selectedFilename,contentType:u.previewContentType,sizeBytes:u.previewSizeBytes,source:u.previewSource,uploadedAt:u.previewUploadedAt,controller:t,sessionId:u.selectedSessionId}):S?a.createElement(lr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:M,scrollOffset:d.previewScroll,className:"ps-diff-preview",focusRegion:C},a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,ls(u.previewContent,S,l)))):x?a.createElement(lr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:M,scrollOffset:d.previewScroll,className:"ps-diff-preview",focusRegion:C},a.createElement("pre",{className:"ps-md-code-pre is-diff"},a.createElement("code",null,Pi(u.previewContent,l)))):u.previewRenderMode==="markdown"&&!u.previewLoading&&!u.previewError?a.createElement(ib,{controller:t,title:null,color:"cyan",focused:!1,scrollOffset:d.previewScroll,paneKey:M,theme:l,focusRegion:C,content:Ry(u.previewContent||"")}):u.previewIsBinary&&!u.previewLoading&&!u.previewError?a.createElement(ka,{title:null,color:"cyan",focused:!1,theme:l,filename:u.selectedFilename,contentType:u.previewContentType,sizeBytes:u.previewSizeBytes,source:u.previewSource,uploadedAt:u.previewUploadedAt,controller:t,sessionId:u.selectedSessionId}):a.createElement(Tn,{controller:t,title:null,color:"cyan",focused:!1,lines:u.previewLines,scrollOffset:d.previewScroll,scrollMode:"top",paneKey:M,focusRegion:C,className:"is-preview is-wrapped"}),T=d;return n?R:a.createElement(xt,{title:T.fullscreen?u.fullscreenTitle:s&&u.panelTitleMobile?u.panelTitleMobile:u.panelTitle,color:"magenta",focused:T.focused,actions:y,theme:l},a.createElement(fd,{activeTab:"files",controller:t}),T.fullscreen?R:a.createElement("div",{className:"ps-files-grid is-list-only"},a.createElement("div",{className:"ps-action-list ps-files-list"},E)))}function vs({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const r=ee(t,b=>{const y=Nn(b),v=b.ui.inspectorTab,E=e?b.ui.layout?.viewportWidth??120:y.rightWidth;return{inspectorTab:v,statsViewMode:b.ui.statsViewMode,adminWorkers:b.admin?.workers,nodeMapSelectedNode:b.ui.nodeMapSelectedNode,activeSessionId:b.sessions.activeSessionId,sessionsById:b.sessions.byId,sessionsFlat:b.sessions.flat,historyBySessionId:b.history.bySessionId,sessionStats:b.sessionStats,fleetStats:b.fleetStats,connection:b.connection,orchestrationBySessionId:b.orchestration.bySessionId,executionHistoryBySessionId:b.executionHistory?.bySessionId||{},executionHistoryFormat:b.executionHistory?.format||"pretty",logs:b.logs,files:b.files,focused:b.ui.focusRegion==="inspector",scroll:b.ui.scroll.inspector,followBottom:b.ui.followBottom?.inspector!==!1,logsTailing:b.logs.tailing,filesFullscreen:!!b.files.fullscreen,contentWidth:gy(E,v,e)}},_e),i=a.useMemo(()=>({sessions:{activeSessionId:r.activeSessionId,byId:r.sessionsById,flat:r.sessionsFlat},history:{bySessionId:r.historyBySessionId},sessionStats:r.sessionStats,fleetStats:r.fleetStats,connection:r.connection,admin:{workers:r.adminWorkers},ui:{inspectorTab:r.inspectorTab,statsViewMode:r.statsViewMode,nodeMapSelectedNode:r.nodeMapSelectedNode,scroll:{inspector:r.scroll}},logs:r.logs,files:r.files,orchestration:{bySessionId:r.orchestrationBySessionId},executionHistory:{bySessionId:r.executionHistoryBySessionId,format:r.executionHistoryFormat}}),[r.activeSessionId,r.adminWorkers,r.connection,r.executionHistoryBySessionId,r.executionHistoryFormat,r.fleetStats,r.nodeMapSelectedNode,r.files,r.historyBySessionId,r.inspectorTab,r.sessionStats,r.statsViewMode,r.logs,r.orchestrationBySessionId,r.scroll,r.sessionsById,r.sessionsFlat]),[o,l]=Oc(),c=o??r.contentWidth,d=a.useMemo(()=>kt(i,{width:c}),[i,c]),p=a.useMemo(()=>{const b=r.activeSessionId&&r.historyBySessionId?.get(r.activeSessionId)||null,y=new Map;for(const v of b?.events||[]){if(v?.eventType!=="session.turn_completed")continue;const E=Number(v?.data?.turnIndex??v?.data?.iteration);Number.isFinite(E)&&y.set(E,v)}return y},[r.activeSessionId,r.historyBySessionId]),u=a.useCallback((b,y)=>a.createElement(Eb,{lines:b,theme:y,completionByTurn:p}),[p]),f=a.useCallback((b,y)=>a.createElement(wb,{lines:b,theme:y,controller:t}),[t]);a.useEffect(()=>{if(r.inspectorTab!=="nodes")return;t.ensureInspectorData("nodes");const b=window.setInterval(()=>{t.ensureInspectorData("nodes")},1e4);return()=>window.clearInterval(b)},[t,r.inspectorTab]);const m=a.useRef(null);if(a.useEffect(()=>{if(e)return m.current=requestAnimationFrame(()=>{try{const b=document.querySelector(".ps-mobile-pane-fill .ps-inspector-pane .ps-scroll-panel"),y=b?b.querySelector(".ps-line"):null;if(!b||!y)return;const v=window.getComputedStyle(y),E=document.createElement("span");E.style.cssText="position:absolute;visibility:hidden;white-space:pre;",E.style.fontFamily=v.fontFamily,E.style.fontSize=v.fontSize,E.style.fontWeight=v.fontWeight,E.style.letterSpacing=v.letterSpacing,E.textContent="0".repeat(100),y.parentElement.appendChild(E);const k=E.getBoundingClientRect().width/100||8;E.remove();const x=window.getComputedStyle(b),w=b.clientWidth-(parseFloat(x.paddingLeft)||0)-(parseFloat(x.paddingRight)||0);if(!(w>50))return;const C=Math.floor(w/k)+6,M=t.getState().ui.layout?.viewportWidth??120;if(Math.abs(C-M)<=2)return;t.dispatch({type:"ui/viewport",width:C,height:null})}catch{}}),()=>{m.current&&cancelAnimationFrame(m.current)}},[t,e,r.inspectorTab,r.activeSessionId]),r.inspectorTab==="files"&&!d.disabled)return a.createElement(Pn,{controller:t,focused:r.focused,mobile:e});const h=[];if(r.inspectorTab==="logs")h.push(a.createElement(pe,{key:"tail",icon:r.logsTailing?"■":"⇣",label:r.logsTailing?"Stop tailing":"Tail (follow)",active:r.logsTailing,onClick:()=>t.handleCommand(P.TOGGLE_LOG_TAIL).catch(()=>{})})),h.push(a.createElement(pe,{key:"filter",icon:a.createElement($i),label:"Filter",onClick:()=>t.handleCommand(P.OPEN_LOG_FILTER).catch(()=>{})}));else if(r.inspectorTab==="history")h.push(a.createElement(pe,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(P.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),h.push(a.createElement(pe,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(P.EXPORT_EXECUTION_HISTORY).catch(()=>{})}));else if(r.inspectorTab==="stats"){const b={session:"◉",fleet:"⬢",users:"⚇"};for(const y of["session","fleet","users"])h.push(a.createElement(pe,{key:`stats-view:${y}`,icon:b[y],label:`${y.replace(/^./u,v=>v.toUpperCase())} stats`,active:r.statsViewMode===y,onClick:()=>t.setStatsViewMode(y)}))}const g=n?h.concat(n):h;return a.createElement(Tn,{controller:t,title:d.title,color:"magenta",focused:r.focused,actions:g,topContent:a.createElement(fd,{activeTab:d.activeTab,controller:t}),stickyLines:d.stickyLines||[],lines:d.lines,renderBody:d.activeTab==="sequence"?u:d.activeTab==="nodes"?f:null,scrollOffset:r.scroll,scrollMode:d.activeTab==="sequence"||d.activeTab==="logs"&&r.followBottom?"bottom":"top",stickyBottom:d.activeTab==="logs",paneKey:"inspector",panelRef:l,className:d.activeTab==="history"||d.activeTab==="logs"?"is-wrapped":"is-preserve",panelClassName:`ps-inspector-pane${d.activeTab==="sequence"?" has-preserved-sticky":""}${s?` ${s}`:""}`.trim()})}function pr({controller:t,panelClassName:e="",extraActions:s=null}){const n=ee(t,l=>{const c=l.sessions.activeSessionId,d=Nn(l),p=Math.max(3,d.activityPaneHeight-2);return{activeSessionId:c,activeSession:c&&l.sessions.byId[c]||null,activeHistory:c&&l.history.bySessionId.get(c)||null,focused:l.ui.focusRegion==="activity",scroll:l.ui.scroll.activity,followBottom:l.ui.followBottom?.activity!==!1,maxLines:p,nodeMapSelectedNode:l.ui.nodeMapSelectedNode,adminWorkers:l.admin?.workers,branding:l.branding,sessionsById:l.sessions.byId,sessionsFlat:l.sessions.flat,historyBySessionId:l.history.bySessionId,inspectorTab:l.ui.inspectorTab}},_e),r=n.inspectorTab==="nodes",i=a.useMemo(()=>({branding:n.branding,admin:{workers:n.adminWorkers},ui:{nodeMapSelectedNode:n.nodeMapSelectedNode},sessions:{activeSessionId:n.activeSessionId,byId:r?n.sessionsById:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{},flat:n.sessionsFlat},history:{bySessionId:r?n.historyBySessionId:n.activeSessionId&&n.activeHistory?new Map([[n.activeSessionId,n.activeHistory]]):new Map}}),[r,n.activeHistory,n.activeSession,n.activeSessionId,n.adminWorkers,n.branding,n.historyBySessionId,n.nodeMapSelectedNode,n.sessionsById,n.sessionsFlat]),o=a.useMemo(()=>r?sc(i):ui(i,n.maxLines),[r,i,n.maxLines]);return a.createElement(Tn,{controller:t,title:o.title,color:"gray",focused:n.focused,actions:s,lines:o.lines,scrollOffset:n.scroll,scrollMode:n.followBottom?"bottom":"top",stickyBottom:!0,paneKey:"activity",className:"is-wrapped",panelClassName:`ps-activity-pane${e?` ${e}`:""}`})}const Ba=Object.freeze([]);function Ha(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 fS({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const r=ee(t,S=>{const C=S.sessions.activeSessionId,M=C&&S.sessions.byId[C]||null,_=C&&S.outbox?.bySessionId?.[C]?S.outbox.bySessionId[C]:[];return{value:S.ui.prompt,cursor:S.ui.promptCursor,focused:S.ui.focusRegion==="prompt",modalOpen:!!S.ui.modal,answerMode:!!M?.pendingQuestion?.question,canStopTurn:Xl(M),hasOutbox:_.length>0,hasPendingOutbox:_.some(O=>O?.phase==="pending"),pendingCount:_.filter(O=>O?.phase==="pending").length,editingPending:S.ui.promptEdit?.sessionId===C,selectedOutboxPhase:S.ui.promptEdit?.sessionId===C&&S.ui.promptEdit?.phase||null,promptAttachments:S.ui.promptAttachments||Ba}},_e),i=a.useRef(null),o=a.useRef(null),[l,c]=a.useState(!1),d=a.useCallback(()=>{const S=i.current;S&&(S.style.height="0px",S.style.height=`${S.scrollHeight+2}px`)},[]);a.useLayoutEffect(()=>{d()},[d,r.value]),a.useEffect(()=>(window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)),[d]);const p=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",u=p?r.promptAttachments.filter(S=>S?.kind==="image"):Ba,f=a.useRef(new Map);a.useEffect(()=>{const S=f.current,C=new Set(u.map(M=>M.file));for(const[M,_]of S)C.has(M)||(URL.revokeObjectURL(_),S.delete(M));for(const M of u)if(M.file&&!S.has(M.file))try{S.set(M.file,URL.createObjectURL(M.file))}catch{}},[u]),a.useEffect(()=>()=>{for(const S of f.current.values())URL.revokeObjectURL(S);f.current.clear()},[]);const m=a.useCallback(S=>{if(!p)return 0;const C=Array.from(S||[]).filter(_=>_&&typeof _.type=="string"&&_.type.startsWith("image/"));return C.length===0?0:t.addPendingImageFiles(C)?.accepted||0},[t,p]);a.useEffect(()=>{const S=i.current;if(!(!s||r.modalOpen||!r.focused||!S)){if(document.activeElement!==S){if(e)return;try{S.focus({preventScroll:!0})}catch{S.focus()}}S.value===r.value&&S.selectionStart!==r.cursor&&S.setSelectionRange(r.cursor,r.cursor)}},[s,e,r.cursor,r.value,r.focused,r.modalOpen]);const h=a.useCallback(()=>{t.handleCommand(P.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[g,b]=a.useState(!1),y=a.useCallback(()=>{b(!0),t.handleCommand(P.STOP_TURN).catch(()=>{}).finally(()=>b(!1))},[t]),v=a.useCallback(()=>{if(t.getState().ui.promptEdit){typeof t.cancelSelectedOutboxPrompt=="function"?t.cancelSelectedOutboxPrompt().catch(()=>{}):t.cancelSelectedPendingPrompt();return}typeof t.cancelLatestQueuedOutbox=="function"&&t.cancelLatestQueuedOutbox().catch(()=>{})},[t]),E=r.editingPending||r.hasPendingOutbox&&!r.value.trim()?"⇪":r.hasOutbox?"+":"❯",k=r.selectedOutboxPhase==="queued",x=r.selectedOutboxPhase==="cancelling",w=k||x;return a.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}${l?" is-drag-over":""}`,...p?{onDragOver:S=>{S.dataTransfer?.types?.includes?.("Files")&&(S.preventDefault(),c(!0))},onDragLeave:S=>{S.currentTarget.contains(S.relatedTarget)||c(!1)},onDrop:S=>{c(!1),S.dataTransfer?.files?.length&&(S.preventDefault(),m(S.dataTransfer.files))}}:{}},u.length>0?a.createElement("div",{className:"ps-prompt-attachments"},u.map((S,C)=>{const M=S.file?f.current.get(S.file):null;return a.createElement("div",{key:`attach:${C}:${S.filename}`,className:"ps-attach-chip",title:`${S.filename} · ${Ha(S.sizeBytes)}`},M?a.createElement("img",{className:"ps-attach-thumb",src:M,alt:S.filename}):a.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),a.createElement("div",{className:"ps-attach-size"},Ha(S.sizeBytes)),a.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${S.filename}`,"aria-label":`Remove attachment ${S.filename}`,onClick:()=>t.removePendingImageAttachment(C)},"✕"))})):null,(()=>{const S=r.answerMode?"answer":x?"cancelling":k?"queued":r.editingPending?"pending":"you";return a.createElement("label",{className:`ps-prompt-label${S==="you"?" is-default":""}`},S)})(),a.createElement("textarea",{ref:i,className:"ps-prompt-input",rows:1,value:r.value,readOnly:w,placeholder:r.answerMode?"Type an answer and press Enter":r.editingPending?x?"Cancellation requested":k?"Queued message selected":"Edit the pending message, then send or cancel it":r.hasOutbox?"Type a message and press Enter to queue it behind the pending batch":"Type a message and press Enter",enterKeyHint:e?"enter":"send",onFocus:()=>t.setFocus("prompt"),onSelect:S=>t.setPromptCursor(S.currentTarget.selectionStart||0),onChange:S=>t.setPrompt(S.currentTarget.value,S.currentTarget.selectionStart||S.currentTarget.value.length),onPaste:p?S=>{const M=Array.from(S.clipboardData?.items||[]).filter(_=>_.kind==="file"&&_.type.startsWith("image/")).map(_=>_.getAsFile()).filter(Boolean);M.length>0&&m(M)>0&&S.preventDefault()}:void 0,onKeyDown:S=>{if(S.key==="Tab"&&!S.shiftKey&&t.acceptPromptReferenceAutocomplete()){S.preventDefault();return}if(S.key==="Escape"&&r.editingPending){if(S.preventDefault(),w){t.exitPendingPromptEdit({restoreDraft:!0});return}v();return}S.key==="Enter"&&!S.shiftKey&&!S.metaKey&&!e&&(S.preventDefault(),h())}}),a.createElement("div",{className:"ps-prompt-actions"},p?a.createElement(a.Fragment,null,a.createElement("input",{ref:o,type:"file",accept:"image/*",multiple:!0,className:"ps-hidden-file-input","aria-hidden":!0,tabIndex:-1,onChange:S=>{m(S.currentTarget.files),S.currentTarget.value=""}}),a.createElement("button",{type:"button",className:"ps-mini-button ps-attach-button",title:"Attach images (or paste / drop them into the composer)","aria-label":"Attach images",onPointerDown:S=>S.preventDefault(),onClick:()=>o.current?.click()},"📎")):null,r.editingPending&&!x?a.createElement("button",{type:"button",className:"ps-mini-button",title:k?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":k?"Delete selected queued prompt":"Cancel selected pending prompt",onPointerDown:S=>S.preventDefault(),onClick:v},k?"Delete":"Cancel"):null,r.canStopTurn||g?a.createElement("button",{type:"button",className:`ps-stop-button${g?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:g,onPointerDown:S=>S.preventDefault(),onClick:y},"■"):null,a.createElement("button",{type:"button",className:`ps-send-button${e?" is-inline":""}`,title:r.editingPending||r.hasPendingOutbox&&!r.value.trim()?"Send all queued prompts":r.hasOutbox?"Queue prompt behind the pending batch":"Send prompt","aria-label":r.editingPending||r.hasPendingOutbox&&!r.value.trim()?"Send queued prompts":r.hasOutbox?"Queue prompt":"Send prompt",onPointerDown:S=>S.preventDefault(),onClick:h},E)))}const mS=1e3;function pe({icon:t,label:e,onClick:s,disabled:n=!1,active:r=!1,className:i="ps-toolbar-button"}){const[o,l]=a.useState(null),c=a.useRef(null),d=a.useRef(null),p=a.useRef(null),u=a.useRef(!1);a.useLayoutEffect(()=>{if(!o||!d.current||typeof window>"u")return;const S=d.current.offsetWidth/2,C=6,M=Math.max(S+C,Math.min(o.x,window.innerWidth-S-C));d.current.style.left=`${M}px`},[o]);const f=(S=!1)=>{const C=c.current;if(!C||typeof window>"u")return;const M=C.getBoundingClientRect(),_=S?M.top-44<0:M.bottom+44<window.innerHeight;l({x:M.left+M.width/2,y:_?M.bottom+6:M.top-6,placement:_?"below":"above"})},m=a.useRef(null),h=a.useRef(null),g=S=>{S.pointerType==="mouse"&&(clearTimeout(p.current),clearTimeout(m.current),p.current=setTimeout(f,mS))},b=S=>{S.pointerType==="mouse"&&(clearTimeout(p.current),clearTimeout(m.current),l(null))},y=S=>{S.pointerType!=="mouse"&&(u.current=!1,h.current={x:S.clientX,y:S.clientY},clearTimeout(p.current),clearTimeout(m.current),p.current=setTimeout(()=>{u.current=!0,f(!0)},450))},v=S=>{if(S.pointerType==="mouse"||!h.current)return;const C=S.clientX-h.current.x,M=S.clientY-h.current.y;C*C+M*M>100&&(h.current=null,clearTimeout(p.current),l(null))},E=S=>{S.pointerType!=="mouse"&&(h.current=null,clearTimeout(p.current),u.current?(clearTimeout(m.current),m.current=setTimeout(()=>l(null),3e3),setTimeout(()=>{u.current=!1},250)):l(null))};a.useEffect(()=>()=>{clearTimeout(p.current),clearTimeout(m.current)},[]);const k=S=>{if(u.current){u.current=!1,S.preventDefault?.();return}n||s?.(S)},x=S=>{S.preventDefault?.()},w=o&&typeof document<"u"&&document.body?Dr.createPortal(a.createElement("span",{ref:d,className:`ps-icon-tooltip is-${o.placement}`,role:"tooltip",style:{left:`${o.x}px`,top:`${o.y}px`}},e),document.body):null;return a.createElement("button",{ref:c,type:"button",className:`${i} ps-icon-button${r?" is-active":""}`,onClick:k,disabled:n,"aria-label":e,onPointerEnter:g,onPointerLeave:b,onPointerDown:y,onPointerMove:v,onPointerUp:E,onPointerCancel:E,onContextMenu:x},a.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),w)}function hS({controller:t,mobile:e,canvasPaneOpen:s=!1,onToggleCanvasPane:n=null,mobilePane:r="workspace",onSelectMobilePane:i=null,mobileMainLayout:o="split"}){const[l,c]=a.useState(null);a.useEffect(()=>{typeof document>"u"||c(e?null:document.getElementById("ps-header-toolbar-slot"))},[e]);const d=ee(t,w=>!!w.admin?.visible),p=ee(t,w=>!!w.ui?.budgetOpen),u=ee(t,ai,_e),f=ee(t,w=>w?.ui?.diagnosticsOpen===!0),m=ee(t,w=>w?.ui?.canvasMaximized===!0),h=ee(t,w=>!!(w?.files?.paneOpen&&w?.files?.selectedArtifactId)),g=[{key:"new",icon:a.createElement(_b),label:"New session — choose model and agent",onClick:()=>t.handleCommand(P.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:a.createElement($i),label:"Filter sessions",onClick:()=>t.handleCommand(P.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:a.createElement(Ob),label:"Theme",onClick:()=>t.handleCommand(P.OPEN_THEME_PICKER).catch(()=>{})},{key:"canvas",icon:a.createElement(ud),label:(e?s:u.mode==="canvas"&&!h)?"Hide the canvas":"Show canvas",onClick:()=>{if(e){n&&n();return}t.dispatch({type:"ui/canvasOpen",open:u.mode!=="canvas",sessionId:u.sessionId,manual:!0})},active:e?s:u.mode==="canvas"&&!h,badge:e?u.exists&&(u.latestRev>(u.lastViewedRev||0)||(u.latestDataRev||0)>(u.lastViewedDataRev||0))&&!s:u.unseen,loadedDot:u.exists},{key:"budget",icon:a.createElement(Bb),label:p?"Close budget":"Budget — providers, limits and usage",onClick:()=>{p?t.closeBudget():t.openBudget().catch(()=>{})},active:p},...e?[]:[{key:"diagnostics",icon:a.createElement($a),label:f?"Hide diagnostics":"Show diagnostics (inspector and activity)",onClick:()=>t.dispatch({type:"ui/diagnosticsOpen"}),active:f}],...e?[]:[{key:"admin",icon:a.createElement(cd),label:d?"Close admin console":"Admin console",onClick:()=>t.handleCommand(d?P.CLOSE_ADMIN_CONSOLE:P.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:d}]],b=w=>{const S=a.createElement(pe,{key:w.badge?void 0:w.key,icon:w.icon,label:w.label,onClick:w.onClick,disabled:!!w.disabled,active:!!w.active});return w.badge||w.loadedDot?a.createElement("span",{key:w.key,className:"ps-canvas-toggle"},S,w.loadedDot?a.createElement("span",{className:"ps-canvas-loaded-dot","aria-hidden":"true"}):null,w.badge?a.createElement("span",{className:"ps-canvas-badge","aria-hidden":"true"}):null):S};if(e){const w={split:"Main — sessions and chat (tap for chat only)",chat:"Main — chat only (tap for sessions only)",sessions:"Main — sessions only (tap for both)"},S=r==="inspector"||r==="activity",C=r==="inspector"?"activity":"inspector",M=[{id:"workspace",icon:Gb,label:w[o]||w.split,focus:"chat"},{id:C,icon:$a,active:S,label:S?r==="inspector"?"Diagnostics — inspector (tap for activity)":"Diagnostics — activity (tap for inspector)":"Diagnostics — inspector and activity",focus:C}];return a.createElement("div",{className:"ps-toolbar is-mobile"},a.createElement("div",{className:"ps-toolbar-row ps-toolbar-row-primary"},a.createElement("div",{className:"ps-toolbar-row-actions"},g.map(b)),a.createElement("div",{className:"ps-toolbar-row-actions is-panes"},M.map(_=>a.createElement(pe,{key:_.id==="workspace"?"workspace":"diagnostics",icon:a.createElement(_.icon),label:_.label,active:_.active??r===_.id,onClick:()=>{i&&i(_.id,_.focus)}})))))}const y=new Set(["budget","diagnostics","admin"]),v=w=>!m||w.key==="canvas"?w:{...w,onClick:(...S)=>(t.dispatch({type:"ui/canvasMaximized",on:!1}),w.onClick?.(...S))},E=g.filter(w=>!y.has(w.key)).map(v),k=g.filter(w=>y.has(w.key)).map(v),x=a.createElement("div",{className:"ps-toolbar"},a.createElement("div",{className:"ps-toolbar-side is-left"},m?E.map(b):null),a.createElement("div",{className:"ps-toolbar-actions"},m?null:E.map(b)),a.createElement("div",{className:"ps-toolbar-side is-right"},a.createElement("span",{className:"ps-toolbar-meta-slot",id:"ps-toolbar-meta-slot"}),m?a.createElement("span",{className:"ps-toolbar-canvas-slot",id:"ps-toolbar-canvas-slot"}):null,m?a.createElement("span",{className:"ps-toolbar-divider","aria-hidden":"true"}):null,k.length?a.createElement("div",{className:"ps-toolbar-actions is-tools"},k.map(b)):null,a.createElement("span",{className:"ps-toolbar-signout-slot",id:"ps-toolbar-signout-slot"})));return l?Dr.createPortal(x,l):x}function fs(t){try{t.currentTarget?.setPointerCapture?.(t.pointerId)}catch{}}function gS({controller:t,paneAdjust:e=0}){const s=a.useRef(null),[n,r]=a.useState(!1);return a.useEffect(()=>{if(!n)return;const i=()=>{s.current=null,r(!1),document.body.classList.remove("is-resizing-pane-x")};let o=0,l=0;const c=()=>{o=0;const p=s.current;if(!p)return;const u=Math.round((l-p.startX)/Nc),f=u-p.appliedCells;f&&(t.adjustPaneSplit(f),p.appliedCells=u)},d=p=>{s.current&&(l=p.clientX,!o&&(o=requestAnimationFrame(c)))};return window.addEventListener("pointermove",d),window.addEventListener("pointerup",i),window.addEventListener("pointercancel",i),()=>{o&&(cancelAnimationFrame(o),o=0),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",i),window.removeEventListener("pointercancel",i),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),a.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector column. Double-click to reset.","aria-label":"Resize inspector column",onPointerDown:i=>{i.button===0&&(i.preventDefault(),fs(i),s.current={startX:i.clientX,appliedCells:0},r(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{e&&t.adjustPaneSplit(-e)},onKeyDown:i=>{if(i.key==="ArrowLeft"){i.preventDefault(),t.handleCommand(P.GROW_RIGHT_PANE).catch(()=>{});return}i.key==="ArrowRight"&&(i.preventDefault(),t.handleCommand(P.GROW_LEFT_PANE).catch(()=>{}))}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function yS({controller:t,portalSessionColumnAdjust:e=0}){const s=a.useRef(null),[n,r]=a.useState(!1);return a.useEffect(()=>{if(!n)return;const i=()=>{s.current=null,r(!1),document.body.classList.remove("is-resizing-pane-x")},o=l=>{const c=s.current;if(!c)return;const d=Tr(c.startAdjust+(l.clientX-c.startX),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:d})};return window.addEventListener("pointermove",o),window.addEventListener("pointerup",i),window.addEventListener("pointercancel",i),()=>{window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",i),window.removeEventListener("pointercancel",i),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),a.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the sessions and chat columns. Double-click to reset.","aria-label":"Resize sessions and chat columns",onPointerDown:i=>{if(i.button!==0)return;i.preventDefault(),fs(i);const o=i.currentTarget.closest(".ps-workspace-main-grid"),l=Pr(o?.getBoundingClientRect?.().width);s.current={startX:i.clientX,startAdjust:Number(e)||0,minAdjust:l.minAdjust,maxAdjust:l.maxAdjust},r(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>{t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:0})},onKeyDown:i=>{const o=i.currentTarget.closest(".ps-workspace-main-grid"),l=Pr(o?.getBoundingClientRect?.().width),c=d=>{const p=Tr((Number(e)||0)+d,l.minAdjust,l.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:p})};if(i.key==="ArrowLeft"){i.preventDefault(),c(-24);return}i.key==="ArrowRight"&&(i.preventDefault(),c(24))}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function bS({controller:t,canvasPaneAdjust:e=0,diagnosticsPaneAdjust:s=0}){const n=a.useRef(null),[r,i]=a.useState(!1),o=(c,d)=>({canvas:xi+(Number(c)||0),diag:Ii+(Number(d)||0)}),l=(c,d)=>{const p=o(c,d);if(p.canvas<Vs||p.diag<Vs){t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:0}),t.dispatch(p.canvas<Vs?{type:"ui/canvasOpen",open:!1,manual:!0}:{type:"ui/diagnosticsOpen",open:!1});return}t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:c}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:d})};return a.useEffect(()=>{if(!r)return;const c=p=>{const u=n.current;if(!u)return;const f=p.clientX-u.startX;t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:u.startCanvas+f}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:u.startDiag-f})},d=()=>{const p=n.current;if(n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x"),p){const u=t.getState()?.ui?.layout||{};l(u.canvasPaneAdjust??0,u.diagnosticsPaneAdjust??0)}};return window.addEventListener("pointermove",c),window.addEventListener("pointerup",d),window.addEventListener("pointercancel",d),()=>{window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",d)}},[t,r]),a.createElement("button",{type:"button",className:`ps-column-resizer${r?" is-dragging":""}`,title:"Drag to trade width between the canvas and diagnostics. Drag one away to close it. Double-click to reset.","aria-label":"Resize canvas and diagnostics columns",onPointerDown:c=>{c.button===0&&(c.preventDefault(),fs(c),n.current={startX:c.clientX,startCanvas:Number(e)||0,startDiag:Number(s)||0},i(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:0})},onKeyDown:c=>{if(c.key!=="ArrowLeft"&&c.key!=="ArrowRight")return;c.preventDefault();const d=c.key==="ArrowRight"?24:-24;l((Number(e)||0)+d,(Number(s)||0)-d)}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function SS({controller:t,sessionId:e,railPx:s=380}){const n=a.useRef(null),[r,i]=a.useState(!1);return a.useEffect(()=>{if(!r)return;const o=c=>{const d=n.current;d&&t.dispatch({type:"canvas/zenRail",sessionId:e,px:d.start+(c.clientX-d.startX)})},l=()=>{n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")};return window.addEventListener("pointermove",o),window.addEventListener("pointerup",l),window.addEventListener("pointercancel",l),()=>{window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",l),window.removeEventListener("pointercancel",l)}},[t,r,e]),a.createElement("button",{type:"button",className:`ps-column-resizer${r?" is-dragging":""}`,title:"Drag to resize chat against the canvas (remembered for this session)","aria-label":"Resize the zen chat rail",onPointerDown:o=>{o.button===0&&(o.preventDefault(),fs(o),n.current={startX:o.clientX,start:s},i(!0),document.body.classList.add("is-resizing-pane-x"))},onKeyDown:o=>{o.key!=="ArrowLeft"&&o.key!=="ArrowRight"||(o.preventDefault(),t.dispatch({type:"canvas/zenRail",sessionId:e,px:s+(o.key==="ArrowRight"?24:-24)}))}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function vS({controller:t,target:e,adjust:s=0}){const n=a.useRef(null),[r,i]=a.useState(!1),o=e==="canvas"?"ui/canvasPaneAdjust":"ui/diagnosticsPaneAdjust",l=e==="canvas"?"canvasPaneAdjust":"diagnosticsPaneAdjust",c=e==="canvas"?xi:Ii,d=p=>{if(c+p<Vs){t.dispatch({type:o,[l]:0}),t.dispatch(e==="canvas"?{type:"ui/canvasOpen",open:!1,manual:!0}:{type:"ui/diagnosticsOpen",open:!1});return}t.dispatch({type:o,[l]:p})};return a.useEffect(()=>{if(!r)return;const p=f=>{const m=n.current;m&&t.dispatch({type:o,[l]:m.startAdjust-(f.clientX-m.startX)})},u=()=>{const f=n.current;n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x"),f&&d((t.getState()?.ui?.layout||{})[l]??0)};return window.addEventListener("pointermove",p),window.addEventListener("pointerup",u),window.addEventListener("pointercancel",u),()=>{window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",u)}},[t,r,o,l]),a.createElement("button",{type:"button",className:`ps-column-resizer${r?" is-dragging":""}`,title:"Drag to resize. Drag the column away to close it. Double-click to reset.","aria-label":"Resize the right column",onPointerDown:p=>{p.button===0&&(p.preventDefault(),fs(p),n.current={startX:p.clientX,startAdjust:Number(s)||0},i(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>t.dispatch({type:o,[l]:0}),onKeyDown:p=>{p.key!=="ArrowLeft"&&p.key!=="ArrowRight"||(p.preventDefault(),d((Number(s)||0)-(p.key==="ArrowRight"?24:-24)))}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function wS({controller:t,splitAdjust:e=0}){const s=a.useRef(null),[n,r]=a.useState(!1);return a.useEffect(()=>{if(!n)return;const i=l=>{const c=s.current;if(!c)return;const d=clamp(c.start+(l.clientY-c.startY),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:d})},o=()=>{s.current=null,r(!1),document.body.classList.remove("is-resizing-pane-y")};return window.addEventListener("pointermove",i),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o),()=>{window.removeEventListener("pointermove",i),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),document.body.classList.remove("is-resizing-pane-y")}},[t,n]),a.createElement("button",{type:"button",className:`ps-row-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector and activity panes. Double-click to reset.","aria-label":"Resize the inspector and activity panes",onPointerDown:i=>{if(i.button!==0)return;i.preventDefault(),fs(i);const o=i.currentTarget.closest(".ps-workspace-column"),l=Math.max(0,o?.getBoundingClientRect?.().height||0),c=Math.max(0,i.currentTarget.getBoundingClientRect().height||0),{minAdjust:d,maxAdjust:p}=eo(l,c);s.current={startY:i.clientY,start:clamp(Number(e)||0,d,p),minAdjust:d,maxAdjust:p},r(!0),document.body.classList.add("is-resizing-pane-y")},onDoubleClick:()=>t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:0}),onKeyDown:i=>{if(i.key!=="ArrowUp"&&i.key!=="ArrowDown")return;i.preventDefault();const o=i.currentTarget.closest(".ps-workspace-column"),l=Math.max(0,o?.getBoundingClientRect?.().height||0),c=Math.max(0,i.currentTarget.getBoundingClientRect().height||0),{minAdjust:d,maxAdjust:p}=eo(l,c);t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:clamp((Number(e)||0)+(i.key==="ArrowDown"?c:-c),d,p)})}},a.createElement("span",{className:"ps-row-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}const ES=[{value:"day",label:"Daily"},{value:"week",label:"Weekly"},{value:"month",label:"Monthly"}],Ua={day:"Daily",week:"Weekly",month:"Monthly"},kS={plain:"",amber:" warn",red:" over",idle:""};function xS(t){const e=Math.abs(Number(t)||0),[s,n]=e>=1e9?["B",1e9]:e>=1e6?["M",1e6]:e>=1e3?["K",1e3]:["",1],r=e/n,i=s===""||r>=100?0:r>=10?1:2;return o=>{const l=Number(o);return Number.isFinite(l)?l===0?"0":`${(l/n).toFixed(i)}${s}`:"—"}}function IS(t){const e=String(t??"").trim().replace(/[,_\s]/g,"").toUpperCase();if(!e)return null;const s=/^(\d+(?:\.\d+)?)([KMB])?$/.exec(e);if(!s)return null;const n=s[2]==="K"?1e3:s[2]==="M"?1e6:s[2]==="B"?1e9:1;if(!s[2]&&/\./.test(s[1]))return null;const r=Math.round(Number(s[1])*n);return Number.isSafeInteger(r)&&Number.isFinite(r)&&r>0?r:null}function Or(t){return t?`resets ${t}`:"no reset recorded"}function Fr(t,e,s){return`${t} ${t===1?e:s}`}function AS(t,e){return e?.typeId?t.filter(s=>s.providerId===e.typeId).map(s=>({qualifiedName:`${e.name}:${s.modelName}`,modelName:s.modelName})):[]}function CS(t){return(Array.isArray(t)?t:Array.isArray(t?.providers)?t.providers:Array.isArray(t?.models)?t.models:[]).flatMap(n=>Array.isArray(n?.models)?n.models.map(r=>({...r,providerId:r.providerId||n.providerId})):[n]).filter(n=>n&&(n.modelName||n.qualifiedName)).map(n=>({modelName:n.modelName||String(n.qualifiedName).split(":").pop(),providerId:n.providerId||"",providerType:n.providerType||n.providerId||""}))}function md({title:t,subtitle:e,children:s,footNote:n,confirmLabel:r,danger:i=!1,busy:o=!1,disabled:l=!1,error:c=null,onCancel:d,onConfirm:p=null,cancelLabel:u="Cancel"}){const f=a.useRef(null);return a.useEffect(()=>{const m=f.current;if(!m)return;const h=()=>[...m.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')];m.contains(document.activeElement)||(h()[0]||m).focus();const g=b=>{if(b.key!=="Tab")return;const y=h();if(!y.length)return;const v=y[0],E=y[y.length-1];b.shiftKey&&document.activeElement===v?(b.preventDefault(),E.focus()):!b.shiftKey&&document.activeElement===E&&(b.preventDefault(),v.focus())};return m.addEventListener("keydown",g),()=>m.removeEventListener("keydown",g)},[]),a.useEffect(()=>{const m=h=>{h.key==="Escape"&&(h.preventDefault(),h.stopPropagation(),d())};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[d]),a.createElement("div",{className:"ps-budget-sheet-backdrop",onMouseDown:m=>{m.target===m.currentTarget&&(m.preventDefault(),d())}},a.createElement("div",{className:"ps-budget-sheet",role:"dialog","aria-modal":"true","aria-label":t,ref:f,tabIndex:-1},a.createElement("div",{className:"ps-budget-sheet-top"},a.createElement("div",{className:"ps-budget-sheet-title"},t),e?a.createElement("div",{className:"ps-budget-sheet-sub"},e):null),a.createElement("div",{className:"ps-budget-sheet-body"},s,c?a.createElement("div",{className:"ps-budget-sheet-error",role:"alert"},c):null),a.createElement("div",{className:"ps-budget-sheet-foot"},a.createElement("span",{className:"ps-budget-sheet-note"},n||""),a.createElement("div",{className:"ps-budget-sheet-actions"},a.createElement("button",{type:"button",className:"ps-mini-button",onClick:d,disabled:o},u),p?a.createElement("button",{type:"button",className:`ps-mini-button ${i?"is-danger":"is-primary"}`,onClick:p,disabled:o||l},o?"…":r):null))))}function Xe({label:t,hint:e,children:s}){return a.createElement("div",{className:"ps-budget-field",role:"group","aria-label":t},a.createElement("span",{className:"ps-budget-label"},t),s,e?a.createElement("span",{className:"ps-budget-field-hint"},e):null)}function Rt({value:t,options:e,onChange:s,label:n=null}){return a.createElement("div",{className:"ps-budget-seg",role:"group","aria-label":n||void 0},e.map(r=>a.createElement("button",{key:r.value,type:"button","aria-pressed":t===r.value?"true":"false",className:`ps-budget-seg-btn${t===r.value?" is-on":""}`,onClick:()=>s(r.value)},r.label)))}function NS(t){const e=t.known?kS[t.tone]||"":" idle";return a.createElement(a.Fragment,null,a.createElement("span",{className:`ps-budget-pct${e}`},t.usedLabel),t.providerExhausted?a.createElement("span",{className:"ps-budget-blocked",title:"The provider's own limit is spent."}," ⏻"):null," ",a.createElement("span",{className:`ps-budget-q ps-budget-sub${t.uncapped?" is-inf":""}`},`/ ${t.quotaLabel}`))}function TS(t,e,s){const n=t.kind==="model"?`${t.providerName} · ${t.label}`:t.providerName,r=s.uncapped?"no limit for this period":`${s.usedLabel} of ${s.quotaLabel}${s.pct==null?"":` (${s.pct}%)`}`,i=s.providerExhausted?" The provider's own limit for this period is spent, so nothing runs against it whatever your share says.":"";return`${n} · ${e.label} — ${r}. It ${Or(s.resetsLabel)}.${i}`}function PS({controller:t,view:e,defaults:s=null}){const n=a.useCallback((o,l="*")=>{t.selectBudgetProvider(o,l).catch(()=>{})},[t]),r=o=>o.kind==="model"?a.createElement("td",{className:"ps-budget-grid-name is-model"},a.createElement("button",{type:"button",className:"ps-budget-grid-pick","aria-pressed":o.selected?"true":"false",onClick:()=>n(o.providerName,o.scope)},a.createElement("span",{className:"ps-budget-grid-mname"},o.label),a.createElement("span",{className:"ps-budget-sub"}," · model"))):a.createElement("td",{className:"ps-budget-grid-name"},a.createElement("button",{type:"button",className:"ps-budget-grid-pick","aria-pressed":o.selected?"true":"false","aria-expanded":o.modelRowCount>0?o.expanded?"true":"false":void 0,onClick:()=>n(o.providerName)},a.createElement("span",{className:"ps-budget-grid-pname"},o.label),o.ownerLabel?a.createElement("span",{className:"ps-budget-grid-owner"},`(${o.ownerLabel})`):null,o.classLabel?a.createElement("span",{className:`ps-budget-chip is-${o.class}`,title:o.class==="shared"?"Shared: anyone may spend from it. An administrator manages its limits.":o.ownedByMe===!1?"A user provider belonging to another user.":"Your own provider. Only you see it or spend from it."},o.classLabel):null,s?.mine?.provider===o.providerName?a.createElement("span",{className:"ps-budget-chip"},"my default"):null,s?.cluster?.provider===o.providerName?a.createElement("span",{className:"ps-budget-chip"},"cluster default"):null,s?.system?.provider===o.providerName?a.createElement("span",{className:"ps-budget-chip"},"system default"):null,o.hold?a.createElement("span",{className:"ps-budget-chip is-hold",title:`It ${o.hold.label}.`},"on hold"):null,o.allowanceLabel?a.createElement("span",{className:"ps-budget-grid-allow"},o.allowanceLabel):null,o.expandLabel?a.createElement("span",{className:"ps-budget-grid-teaser"},o.expandLabel):null)),i=o=>a.createElement("tr",{key:o.key,className:`ps-budget-grid-row${o.kind==="model"?" is-model":""}${o.selected?" is-on":""}`,onClick:l=>{l.target?.closest?.("button")||n(o.providerName,o.kind==="model"?o.scope:"*")}},r(o),e.columns.map(l=>a.createElement("td",{key:l.id,className:"ps-budget-grid-num","data-period":l.label,title:TS(o,l,o.cells[l.id])},NS(o.cells[l.id]))));return a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-budget-table-head"},a.createElement("span",{className:"ps-budget-label"},`Providers${e.providerCount>0?` · ${e.providerCount}`:""}`),a.createElement("label",{className:"ps-budget-toggle"},a.createElement("input",{type:"checkbox",checked:e.overall,onChange:()=>t.setBudgetOverall()}),a.createElement("span",null,e.overallLabel))),e.empty?a.createElement("div",{className:"ps-budget-empty"},"No provider exists yet. Add one in Admin Console → Model Providers to start spending."):a.createElement("table",{className:"ps-budget-grid"},a.createElement("thead",null,a.createElement("tr",null,a.createElement("th",{className:"ps-budget-grid-h is-name",rowSpan:2,scope:"col"},"Provider"),a.createElement("th",{className:"ps-budget-grid-h is-span",colSpan:3,scope:"colgroup"},e.usageHeading)),a.createElement("tr",null,e.columns.map(o=>a.createElement("th",{key:o.id,className:"ps-budget-grid-h is-num",scope:"col"},o.label)))),a.createElement("tbody",null,e.rows.map(i))))}function MS({controller:t,view:e}){const s=e.series,n=e.selected,r={className:"ps-budget-chart-pane","data-range-days":String(e.rangeDays)},[i,o]=a.useState(null),[l,c]=a.useState(0);a.useEffect(()=>{if(!i||typeof ResizeObserver>"u")return;const E=()=>{const x=Math.round(i.getBoundingClientRect().width);c(w=>Math.abs(x-w)<1?w:x)},k=new ResizeObserver(E);return k.observe(i),E(),()=>k.disconnect()},[i]);const d=s.days,p=d.length,u=a.useMemo(()=>{const x=l-(p-1)*5,w=l>0?Math.floor(x/30):7,S=Math.max(1,Math.min(7,w)),C=Math.max(1,Math.ceil(p/S)),M=new Set;for(let _=p-1;_>=0;_-=C)M.add(_);return M},[l,p]),f=a.createElement("div",{className:"ps-budget-chart-head"},a.createElement("span",{className:"ps-budget-chart-title"},a.createElement("strong",null,n.subject),a.createElement("span",{className:"ps-budget-sub"},` · ${e.usageHeading.toLowerCase()}, by day`)),a.createElement("div",{className:"ps-budget-chart-range"},a.createElement(Rt,{value:e.rangeDays,options:e.rangeOptions,label:"Chart range",onChange:E=>t.setBudgetRangeDays(E).catch(()=>{})}),a.createElement("span",{className:"ps-budget-sub"},s.rangeLabel)));if(s.failed)return a.createElement("div",r,f,a.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},a.createElement("div",null,`The daily usage for ${n.subject} could not be read.`),a.createElement("div",{className:"ps-budget-sub"},s.error)));if(s.loading&&!s.loaded)return a.createElement("div",r,f,a.createElement("div",{className:"ps-budget-empty"},"Reading the daily usage…"));const m=s.scaleMax,h=[1,.75,.5,.25,0],g=xS(m),b=d.filter(E=>E.tokens>0).length,y=s.quotaPct==null?null:Math.max(0,Math.min(96,100-s.quotaPct)),v=a.createElement("div",{className:"ps-budget-xaxis"},a.createElement("div",{className:"ps-budget-xaxis-spacer"}),a.createElement("div",{className:"ps-budget-tl-x",ref:o},d.map((E,k)=>a.createElement("span",{key:E.dayUtc,className:u.has(k)?"is-tick":void 0},u.has(k)?E.label:""))));return a.createElement("div",r,f,s.mixedScope?a.createElement("div",{className:"ps-budget-note is-warn"},"The bars are what the whole fleet spent on this provider each day. The dashed line is YOUR share of the daily limit, not the limit itself. Tick “Show overall usage” to read both as the provider's."):null,s.stale?a.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},a.createElement("div",null,"These figures are from an earlier read. The most recent read failed."),a.createElement("div",{className:"ps-budget-sub"},s.error)):null,a.createElement("div",{className:"ps-budget-chart"},a.createElement("div",{className:"ps-budget-yaxis-title"},"tokens"),a.createElement("div",{className:"ps-budget-plotwrap"},a.createElement("div",{className:"ps-budget-yaxis"},m>0?h.map(E=>a.createElement("div",{key:`t${E}`,className:"ps-budget-ytick",style:{top:`${(1-E)*100}%`}},g(m*E))):null),a.createElement("div",{className:"ps-budget-plot"},m>0?h.map(E=>a.createElement("div",{key:`g${E}`,className:"ps-budget-gridline",style:{top:`${(1-E)*100}%`}})):null,y==null?null:a.createElement("div",{className:"ps-budget-tl-median",style:{top:`${y}%`}},a.createElement("span",null,`the Day limit · ${s.quotaLabel} a day`)),a.createElement("div",{className:"ps-budget-bars"},d.map(E=>a.createElement("div",{key:E.dayUtc,className:`ps-budget-tl-col${E.tokens===0?" is-idle":""}${s.quotaTokens!=null&&E.tokens>s.quotaTokens?" is-over":""}`,title:`${E.label} · ${E.tokens?`${E.tokens.toLocaleString("en-US")} tokens · ${Fr(E.turns,"turn","turns")}`:"no usage"}`},a.createElement("div",{className:"ps-budget-tl-bar",style:{height:E.tokens===0?"2px":`${Math.max(1,E.pct)}%`}})))),s.empty?a.createElement("div",{className:"ps-budget-noaxis"},`No token usage on ${n.subject} in this range.`):null)),v,a.createElement("div",{className:"ps-budget-xaxis-title"},`Daily totals · UTC · ${s.rangeLabel.toLowerCase()}`),a.createElement("div",{className:"ps-budget-legend"},a.createElement("span",null,`Peak ${s.peakLabel} tokens/day`),a.createElement("span",null,`${b} of ${p} days used`),s.quotaTokens!=null?a.createElement("span",null,`Dashed line: ${s.quotaLabel} a day`):a.createElement("span",null,"No daily limit, so no line"))))}function RS({view:t}){const e=t.systemSpend;if(!e)return null;const s=n=>String(n||"").startsWith(`${t.selectedProvider}:`)?String(n).slice(t.selectedProvider.length+1):String(n||"Unknown model");return a.createElement("section",{className:"ps-budget-system-spend","aria-label":"System spend"},a.createElement("div",{className:"ps-budget-chart-head"},a.createElement("span",{className:"ps-budget-chart-title"},a.createElement("strong",null,"System spend")),a.createElement("span",{className:"ps-budget-sub"},e.rangeLabel)),e.loading&&!e.loaded?a.createElement("div",{className:"ps-budget-empty"},"Reading system spend…"):null,e.error?a.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},e.error):null,e.loaded?a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-budget-system-total"},a.createElement("strong",null,`${e.tokensLabel} tokens`),a.createElement("span",{className:"ps-budget-sub"},` · ${Fr(e.turns,"turn","turns")}`)),e.models.length?a.createElement("div",{className:"ps-budget-system-models"},e.models.map(n=>a.createElement("div",{key:n.key,className:"ps-budget-system-model"},a.createElement("span",null,s(n.label)),a.createElement("strong",null,`${n.tokensLabel} · ${Fr(n.turns,"turn","turns")}`)))):a.createElement("div",{className:"ps-budget-sub"},"No system spend in this range.")):null)}function $S({row:t,rawRows:e,models:s,isAdmin:n,busy:r,error:i,onCancel:o,onRun:l,initialPeriod:c="day",initialScope:d="*"}){const p=t.class==="shared",u=t.manageable===!0,f=[...u?[{value:"limit",label:"Limits"}]:[],...u&&n&&p?[{value:"allowance",label:"Allowance"}]:[],...u&&n?[{value:"hold",label:"Hold"}]:[]],[m,h]=a.useState("limit"),[g,b]=a.useState(c),[y,v]=a.useState(d==="*"?"all":"model"),[E,k]=a.useState(d==="*"?"":d),[x,w]=a.useState("");a.useEffect(()=>{!E&&s[0]&&k(s[0].qualifiedName)},[s,E]);const S=e.find(H=>H.providerName===t.providerName&&H.rowKind!=="model")||null,C=y==="model"?E||s[0]?.qualifiedName||"":null,M=y==="model"?e.find(H=>H.providerName===t.providerName&&H.rowKind==="model"&&H.scope===C)||null:S,_=M?.periods?.[g]||null,O=_?.quotaTokens??null,R=M?Number(_?.usedTokens)||0:null,T=R!=null,N=t.cells[g]?.resetsLabel||null,j=Ua[g]||g,q=C||"all models";a.useEffect(()=>{w(O==null?"":Number(O).toLocaleString("en-US"))},[O,g,C]);const Z=IS(x),ue=!!Z&&(y!=="model"||!!C),oe=O!=null,de=Number.isFinite(t.allowancePct)?t.allowancePct:100,A=Z==null||de>=100?Z:Math.max(1,Math.floor(Z*de/100)),D=Number(_?.yourUsedTokens),F=T&&Z!==null&&R>=Z,K=!F&&Z!==null&&A!==Z&&Number.isFinite(D)&&D>=A,W=Number.isFinite(t.allowancePct)?t.allowancePct:100,[Q,J]=a.useState(String(W)),V=Number(String(Q).trim()),Y=Number.isFinite(V)&&V>=1&&V<=100&&Math.floor(V)===V,ge=["day","week","month"].map(H=>({id:H,label:Ua[H],tokens:S?.periods?.[H]?.quotaTokens??null})).filter(H=>H.tokens!=null),fe=!!t.hold,[ye,Te]=a.useState(fe?"release":"forever"),[Re,Le]=a.useState(""),De=(()=>{if(ye!=="until"||!Re)return null;const H=new Date(Re);return Number.isNaN(H.getTime())?null:H.toISOString()})(),Be=!!De&&Date.parse(De)<=Date.now(),ct=ye!=="until"||!!De&&!Be,We=ye!=="until"?null:Be?"That time has already passed. A hold has to end in the future.":Re&&!De?"That is not a time this can read.":null,G={limit:"Limits",allowance:"Allowance",hold:"Hold"},ne={limit:oe?"Replace limit":"Save limit",allowance:"Save allowance",hold:ye==="release"?"Release hold":"Place hold"},Se={limit:"Limits are enforced.",allowance:"Applies to everyone.",hold:"Stops new turns."},B=m==="limit"?ue:m==="allowance"?Y:m==="hold"?ct:!0,z=()=>{m==="limit"?ue&&l("limit",{period:g,model:C,tokens:Z}):m==="allowance"?Y&&l("allowance",{pct:V}):m==="hold"&&l("hold",ye==="release"?{release:!0,untilUtc:null}:{release:!1,untilUtc:De})},L=a.createElement(a.Fragment,null,a.createElement(Xe,{label:"Time period",hint:"One limit per period and scope."},a.createElement(Rt,{value:g,onChange:b,options:ES,label:"Time period"})),a.createElement(Xe,{label:"Applies to"},a.createElement(Rt,{value:y,onChange:v,label:"Applies to",options:[{value:"all",label:"all models"},{value:"model",label:"one model"}]}),y==="model"?a.createElement("select",{className:"ps-budget-input","aria-label":"Model this limit applies to",value:E,onChange:H=>k(H.target.value)},s.length===0?a.createElement("option",{value:""},"No models are listed for this provider's type"):s.map(H=>a.createElement("option",{key:H.qualifiedName,value:H.qualifiedName},H.qualifiedName))):null),a.createElement(Xe,{label:"Tokens",hint:Z?`= ${Z.toLocaleString("en-US")} tokens.`:x.trim()?"A whole number of tokens: 20,000,000 or 20M.":"Remove the limit to uncap."},a.createElement("input",{className:`ps-budget-input${x&&!Z?" is-invalid":""}`,value:x,"aria-label":"Tokens",placeholder:"20,000,000 or 20M",onChange:H=>w(H.target.value),onKeyDown:H=>{H.key==="Enter"&&z()}})),a.createElement("div",{className:"ps-budget-consequences"},a.createElement("div",null,`${j} · ${q} — `,T?a.createElement(a.Fragment,null,a.createElement("strong",null,`${R.toLocaleString("en-US")} tokens`),p?" spent by users this period.":" spent this period."):a.createElement(a.Fragment,null,a.createElement("strong",null,"not measured yet"),". Current spend will count.")),N?a.createElement("div",{className:"ps-budget-sub"},`Resets ${N}.`):null),oe?a.createElement("div",{className:"ps-budget-note is-warn"},`Replaces the existing ${te(O)} token limit.`):null,a.createElement("div",{className:`ps-budget-note${F||K?" is-warn":""}`},"Current spend counts. Saving does not reset usage.",F?` ${R.toLocaleString("en-US")} already meets ${Z.toLocaleString("en-US")}, so sessions on ${t.providerName} pause on their next turn${N?` — until this period ${Or(N)}`:""}.`:K?` At ${de}% each that is ${A.toLocaleString("en-US")} per person, which you have already spent — so sessions pause on their next turn${N?` — until this period ${Or(N)}`:""}.`:""),oe?a.createElement("div",null,a.createElement("button",{type:"button",className:"ps-mini-button is-danger",disabled:r,onClick:()=>l("removeLimit",{period:g,model:C})},`Remove the ${j} · ${q} limit`),a.createElement("div",{className:"ps-budget-note"},"Usage history is kept.")):null),I=a.createElement(a.Fragment,null,a.createElement(Xe,{label:"Share per person",hint:Y?V>=100?"100% removes the per-person ceiling.":`Each person may use up to ${V}% of each limit, per period.`:"A whole number from 1 to 100."},a.createElement("input",{className:`ps-budget-input${Q&&!Y?" is-invalid":""}`,value:Q,"aria-label":"Share per person, as a percentage",inputMode:"numeric",placeholder:"20",onChange:H=>J(H.target.value),onKeyDown:H=>{H.key==="Enter"&&Y&&z()}})),a.createElement("div",{className:"ps-budget-consequences"},ge.length===0?a.createElement("div",{className:"ps-budget-note is-warn"},"No limits yet. The allowance applies when one is added."):a.createElement(a.Fragment,null,ge.map(H=>a.createElement("div",{key:H.id},`${H.label} · ${te(H.tokens)} → `,a.createElement("strong",null,Y?`${te(Math.floor(H.tokens*V/100))} per person`:"—"))),a.createElement("div",{className:"ps-budget-note"},"The provider limit still caps total spend.")),Y&&V<W?a.createElement("div",{className:"ps-budget-note is-warn"},"Users already past the new ceiling pause on their next turn."):null)),U=a.createElement(a.Fragment,null,a.createElement(Xe,{label:"What to do"},a.createElement(Rt,{value:ye,onChange:Te,label:"What to do",options:[...fe?[{value:"release",label:"release it"}]:[],{value:"forever",label:"hold until released"},{value:"until",label:"hold until a time"}]})),ye==="until"?a.createElement(Xe,{label:"Ends at",hint:We||"Sessions resume at this time."},a.createElement("input",{className:`ps-budget-input${Re&&!ct?" is-invalid":""}`,"aria-label":"The hold ends at",type:"datetime-local",value:Re,onChange:H=>Le(H.target.value)})):null,fe?a.createElement("div",{className:"ps-budget-consequences"},a.createElement("div",null,`This provider is on hold: it ${t.hold.label}.`)):null,a.createElement("div",{className:`ps-budget-note${ye==="release"?"":" is-warn"}`},ye==="release"?`Releasing wakes every session waiting on ${t.providerName}. A session still over a limit stays paused for that reason instead.`:`Every session on ${t.providerName} pauses on its next turn. Messages sent to them are kept and answered when the hold lifts.`));return a.createElement(md,{title:G[m],subtitle:`${t.providerName}${p?" · shared":""}`,confirmLabel:ne[m]||"",danger:m==="hold"&&ye==="release",busy:r,disabled:!B,error:i,onCancel:o,onConfirm:ne[m]?z:null,cancelLabel:ne[m]?"Cancel":"Done",footNote:Se[m]},f.length>1?a.createElement(Xe,{label:"What to change"},a.createElement(Rt,{value:m,onChange:h,options:f,label:"What to change"})):null,m==="limit"?L:null,m==="allowance"?I:null,m==="hold"?U:null)}function _S({types:t,existingNames:e,isAdmin:s,busy:n,error:r,onCancel:i,onConfirm:o,initialName:l="",initialShared:c=!1,initialType:d=""}){const[p,u]=a.useState(l),[f,m]=a.useState(d||t[0]?.id||""),[h,g]=a.useState(""),[b,y]=a.useState(""),[v,E]=a.useState(s&&c),k=a.useRef(null);a.useEffect(()=>{k.current?.focus()},[]),a.useEffect(()=>{!f&&t[0]&&m(t[0].id)},[t,f]);const x=p.trim(),w=e.some(T=>T.toLowerCase()===x.toLowerCase()),S=x!==""&&!/^[A-Za-z0-9._-]+$/.test(x),C=x.length>64,M=!!x&&!w&&!S&&!C&&!!f&&!!h.trim(),_=/github/i.test(f),O=()=>{if(!M)return;const T={name:x,type:f,shared:v,credentials:_?{githubToken:h.trim()}:{apiKey:h.trim()},baseUrl:b.trim()||null};g(""),o(T)},R=()=>{g(""),i()};return a.createElement(md,{title:_?"Add GitHub Copilot provider":"Add model provider",subtitle:v?"Shared":"Personal",confirmLabel:"Add provider",busy:n,disabled:!M,error:r,onCancel:R,onConfirm:O,footNote:""},a.createElement(Xe,{label:"Name",hint:w?"A provider with that name already exists, and names are unique across the cluster.":C?`Too long: ${x.length} characters, and a name may be at most 64.`:S?'Letters, numbers, dot, dash and underscore only — no colon, no spaces, no accents: a session refers to it as "<provider>:<model>".':"Permanent. Used in provider:model."},a.createElement("input",{ref:k,className:`ps-budget-input${(w||S||C)&&x?" is-invalid":""}`,"aria-label":"Provider name",value:p,placeholder:"azure-prod",onChange:T=>u(T.target.value),onKeyDown:T=>{T.key==="Enter"&&M&&O()}})),a.createElement(Xe,{label:"Type",hint:"Backend and model catalog."},a.createElement("select",{className:"ps-budget-input","aria-label":"Provider type",value:f,onChange:T=>m(T.target.value)},t.length===0?a.createElement("option",{value:""},"No provider types are listed on this deployment"):t.map(T=>a.createElement("option",{key:T.id,value:T.id},T.id)))),a.createElement(Xe,{label:_?"GitHub Copilot token":"API key",hint:"Paste the token value."},a.createElement("input",{className:"ps-budget-input",type:"password",autoComplete:"off","aria-label":_?"GitHub Copilot token":"API key",value:h,placeholder:"Paste token",onChange:T=>g(T.target.value)})),a.createElement(Xe,{label:"Base URL",hint:"Optional."},a.createElement("input",{className:"ps-budget-input",value:b,placeholder:"https://…","aria-label":"Base URL",onChange:T=>y(T.target.value)})),s?a.createElement(Xe,{label:"Access"},a.createElement(Rt,{value:v?"shared":"mine",onChange:T=>E(T==="shared"),label:"Access",options:[{value:"shared",label:"Shared"},{value:"mine",label:"Only me"}]})):null)}function LS(t){const e=t.budget||{};return[!!t.ui?.budgetOpen,e.loading,e.refreshing,e.loaded,e.error,e.grid,e.paused,e.overall,e.selectedProvider,e.selectedScope,e.missingProvider,e.series,t.auth?.authorization?.role,t.admin?.profile]}function OS({controller:t}){const e=ee(t,LS,_e),s=a.useMemo(()=>tm(t.getState()),[t,e]),n=a.useMemo(()=>t.getState().budget?.grid||[],[t,e]),[r,i]=a.useState([]),[o,l]=a.useState(new Map),[c,d]=a.useState(null),p=a.useCallback(()=>{typeof t.transport.getDefaults=="function"&&Promise.resolve(t.transport.getDefaults()).then(R=>d(R||null)).catch(()=>{})},[t]);a.useEffect(()=>{let R=!0;return typeof t.transport.listModels=="function"&&Promise.resolve(t.transport.listModels()).then(T=>{R&&i(CS(T))}).catch(()=>{}),typeof t.transport.listProviders=="function"&&Promise.resolve(t.transport.listProviders()).then(T=>{if(!R)return;const N=new Map;for(const j of T?.providers||[])N.set(j.name,j.typeId||"");l(N)}).catch(()=>{}),p(),()=>{R=!1}},[t,p]),a.useEffect(()=>{const R=t.getState().budget||{};!R.loaded&&!R.loading&&!R.error&&t.loadProviderTable().catch(()=>{})},[t]),a.useEffect(()=>{const R=setInterval(()=>{t.refreshProviderTable().catch(()=>{})},6e4);return()=>clearInterval(R)},[t]),a.useEffect(()=>{const R=T=>{if(T.key!=="Escape")return;const N=T.target,j=N&&N.tagName;j==="SELECT"||j==="INPUT"||j==="TEXTAREA"||t.getState().ui.modal||document.querySelector(".ps-budget-sheet")||(T.preventDefault(),T.stopPropagation(),t.closeBudget())};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[t]);const[u,f]=a.useState(null),[m,h]=a.useState(!1),[g,b]=a.useState(null),y=a.useRef(null),v=R=>{y.current=typeof document<"u"?document.activeElement:null,b(null),h(!1),f(R)},E=a.useCallback(()=>{f(null),b(null),h(!1);const R=y.current;y.current=null,R&&typeof R.focus=="function"&&document.contains(R)&&R.focus()},[]),k=async(R,{keepOpen:T=!1,onDone:N=null}={})=>{h(!0),b(null);const j=await R();if(h(!1),!j||j.ok!==!0){b(j?.error||"The change was refused.");return}T||E(),N&&N(j.result||null)},x=R=>t.dispatch({type:"ui/status",text:R}),w=s.selected,S=s.selectedProviderRow,C=w?AS(r,{name:w.providerName,typeId:o.get(w.providerName)||""}):[];let M=null;u?.kind==="edit"&&S&&(M=a.createElement($S,{row:S,rawRows:n,models:C,isAdmin:s.isAdmin,initialPeriod:u.period||"day",initialScope:u.scope||"*",busy:m,error:g,onCancel:E,onRun:(R,T)=>{const N=w.providerName;if(R==="limit")return k(()=>t.setProviderLimit({provider:N,...T}),{onDone:j=>{const q=Number(j?.seededTokens)||0;x(q>0?`Limit saved. This period had already spent ${te(q)} tokens, and they count against it.`:"Limit saved. This period has spent nothing against it yet.")}});if(R==="removeLimit")return k(()=>t.removeProviderLimit({provider:N,...T}),{onDone:()=>x(`That period no longer caps ${N}.`)});if(R==="allowance")return k(()=>t.setProviderAllowance({provider:N,pct:T.pct}),{onDone:()=>x(T.pct>=100?`Everyone shares the whole of ${N} again.`:`Each person may now use up to ${T.pct}% of each of ${N}'s limits.`)});if(R==="hold")return k(()=>t.setProviderHold({provider:N,...T}),{onDone:()=>{if(T.release){x(`The hold on ${N} is released. Sessions waiting on it wake up.`);return}const j=(t.getState().budget?.grid||[]).find(Z=>Z.providerName===N&&Z.rowKind!=="model"),q=j?.holdIndefinite===!0||(j?.holdUntilUtc?Date.parse(j.holdUntilUtc)>Date.now():!1);x(q?`${N} is on hold. No new turn runs against it until it is released.`:`${N} is NOT on hold: the time given has already passed.`)}})}}));const _=a.createElement("div",{className:"ps-budget-head"},a.createElement("div",{className:"ps-budget-headline"},a.createElement("span",{className:"ps-budget-coin","aria-hidden":"true"},"◎"),a.createElement("h2",{className:"ps-budget-h"},"Providers & Budgets"),a.createElement("span",{className:"ps-budget-sub"},"Usage and limits")),a.createElement("div",{className:"ps-budget-head-actions"},a.createElement(pe,{icon:a.createElement(cd),label:"Model providers",className:"ps-mini-button",onClick:()=>{t.closeBudget(),t.openAdminConsole()}}),a.createElement(pe,{icon:"↻",label:"Refresh providers and budgets",className:"ps-mini-button",disabled:s.loading||s.refreshing,onClick:()=>t.refreshProviderTable().catch(()=>{})}),a.createElement("button",{type:"button",className:"ps-budget-close",onClick:()=>t.closeBudget(),"aria-label":"Close providers and budgets",title:"Close (Esc)"},"✕")));let O;return s.failed?O=a.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},a.createElement("div",null,"Providers and budgets could not be read. ",a.createElement("button",{type:"button",className:"ps-budget-link",onClick:()=>t.loadProviderTable().catch(()=>{})},"Try again")),a.createElement("div",{className:"ps-budget-sub"},s.error)):s.loading&&!s.loaded?O=a.createElement("div",{className:"ps-budget-empty"},"Reading providers and budgets…"):O=a.createElement(a.Fragment,null,s.stale?a.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},a.createElement("div",null,"These figures are from an earlier read. The most recent read failed."),a.createElement("div",{className:"ps-budget-sub"},s.error)):null,s.paused.count>0?a.createElement("div",{className:`ps-budget-waiting${s.paused.stale?" is-stale":""}`,role:"status"},s.paused.sentence," ",s.paused.provider?a.createElement("button",{type:"button",className:"ps-budget-link",onClick:()=>{s.selectedProvider!==s.paused.provider&&t.selectBudgetProvider(s.paused.provider).catch(()=>{})}},`Open ${s.paused.provider}`):null,s.paused.stale?a.createElement("span",{className:"ps-budget-sub"}," This line is from an earlier read — the last one failed."):null):null,s.paused.count===0&&s.paused.error?a.createElement("div",{className:"ps-budget-waiting is-stale",role:"status"},"The list of waiting sessions could not be read. The figures below were read successfully."):null,s.missing?a.createElement("div",{className:"ps-budget-waiting is-missing",role:"status"},s.missing.sentence," ",a.createElement("button",{type:"button",className:"ps-budget-link",onClick:()=>{t.closeBudget(),t.openAdminConsole()}},"Open Model Providers")):null,a.createElement("div",{className:`ps-budget-body${s.refreshing?" is-refreshing":""}`},a.createElement(PS,{controller:t,view:s,defaults:c}),a.createElement("div",{className:"ps-budget-actions"},a.createElement(pe,{icon:a.createElement(ld),label:"Edit usage policy",className:"ps-mini-button",disabled:!S||!S.manageable,onClick:()=>v({kind:"edit",scope:w?.kind==="model"?w.scope:"*"})}),a.createElement("span",{className:"ps-budget-sub"},w?w.providerName:"No provider selected")),a.createElement("div",{className:"ps-budget-foot ps-budget-sub"},"Manage providers and defaults in Admin Console."),w?a.createElement(MS,{controller:t,view:s}):null,w?a.createElement(RS,{view:s}):null)),a.createElement("div",{className:"ps-budget-surface"},_,a.createElement("div",{className:"ps-budget"},O),M)}function FS({controller:t}){const e=ee(t,y=>y.ui.themeId),s=ee(t,y=>!!y.ui.touchScale),n=pt(e),r=ee(t,y=>({rawModal:y.ui.modal,themePicker:oh(y),modelPicker:Rm(y),reasoningEffortPicker:_m(y),contextTierPicker:Lm(y),sessionAgentPicker:$m(y),sessionGroupPicker:Om(y),sessionGroupName:Dm(y),artifactPicker:Gm(y),logFilter:Um(y),filesFilter:jm(y),historyFormat:ih(y),renameSession:Fm(y),sessionOwnerFilter:Hm(y),artifactUpload:Bm(y),confirm:ah(y),logsFilter:y.logs.filter,filesFilterState:y.files.filter,historyFormatState:y.executionHistory?.format||"pretty"}),_e),i=r.rawModal,o=a.useRef(null),l=a.useRef(null),c=a.useRef(null),[d,p]=a.useState(""),u=i?.type==="sessionOwnerFilter";if(a.useEffect(()=>{u||p("")},[u]),a.useEffect(()=>{if(i?.type!=="renameSession"||!r.renameSession)return;const y=o.current;if(y){if(document.activeElement!==y)try{y.focus({preventScroll:!0})}catch{y.focus()}y.setSelectionRange(r.renameSession.cursorIndex,r.renameSession.cursorIndex)}},[i?.type,r.renameSession?.cursorIndex,r.renameSession?.value]),a.useEffect(()=>{if(i?.type!=="sessionGroupName"||!r.sessionGroupName)return;const y=l.current;if(y){if(document.activeElement!==y)try{y.focus({preventScroll:!0})}catch{y.focus()}y.setSelectionRange(r.sessionGroupName.cursorIndex,r.sessionGroupName.cursorIndex)}},[i?.type,r.sessionGroupName?.cursorIndex,r.sessionGroupName?.value]),a.useEffect(()=>{if(!i||!["themePicker","modelPicker","reasoningEffortPicker","contextTierPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(i.type))return;const y=c.current;if(!y)return;const v=y.querySelector(".ps-list-button.is-selected");v&&typeof v.scrollIntoView=="function"&&v.scrollIntoView({block:"nearest"})},[i?.type,i?.selectedIndex,r.themePicker?.selectedRowIndex,r.modelPicker?.selectedRowIndex,r.reasoningEffortPicker?.selectedRowIndex,r.contextTierPicker?.selectedRowIndex,r.sessionAgentPicker?.selectedRowIndex,r.sessionGroupPicker?.selectedRowIndex,r.artifactPicker?.selectedRowIndex,r.sessionOwnerFilter?.selectedRowIndex,r.logFilter?.selectedRowIndex,r.filesFilter?.selectedRowIndex,r.historyFormat?.selectedRowIndex]),!i)return null;const f=()=>t.handleCommand(P.CLOSE_MODAL).catch(()=>{}),m=()=>a.createElement("label",{className:"ps-modal-toggle",title:"Larger type and bigger hit targets, for phones and touch screens."},a.createElement("input",{type:"checkbox",checked:s,onChange:y=>t.dispatch({type:"ui/touchScale",enabled:y.target.checked})}),a.createElement("span",null,"Mobile")),h=(y,v="Apply",E=null)=>{const k=Array.isArray(y.rows)?y.rows:[],x=Array.isArray(y.rowItemIndexes)?y.rowItemIndexes:null,w=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",S=x&&x.length===k.length?k.map((C,M)=>{const _=x[M],O=Array.isArray(C)?C:Ue([C])[0]?.runs||[{text:C?.text||"",color:C?.color}];if(_==null||_<0)return a.createElement("div",{key:`row:${M}`,className:"ps-line ps-modal-list-heading-line"},a.createElement(Ge,{runs:O,theme:n}));const R=i.items?.[_];return a.createElement("button",{key:R?.id||`row:${M}`,type:"button",className:`ps-list-button ps-modal-list-button${_===i.selectedIndex?" is-selected":""}${w?" is-hanging":""}${R?.disabled?" is-disabled":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:_}),R?.kind==="section"&&t.toggleAgentPickerSection(R.sectionKey)}},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Ge,{runs:O,theme:n})))}):(i.items||[]).flatMap((C,M,_)=>{const O=a.createElement("button",{key:C.id||M,type:"button",className:`ps-list-button ps-modal-list-button${M===i.selectedIndex?" is-selected":""}${w?" is-hanging":""}${C?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:M})},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Ge,{runs:Array.isArray(k?.[M])?k[M]:Ue([k?.[M]])[0]?.runs||[{text:k?.[M]?.text||"",color:k?.[M]?.color}],theme:n})));return C?.group&&C.group!==_[M-1]?.group?[a.createElement("div",{key:`group:${C.group}`,className:"ps-modal-list-group","aria-hidden":"true"},C.group),O]:[O]});return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:`ps-modal is-list${i.type==="themePicker"?" is-theme-picker":""}`,onClick:C=>C.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},y.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:c,className:"ps-modal-list"},S),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),Ue(y.detailsLines||[]).map((C,M)=>a.createElement(je,{key:`detail:${M}`,line:C,theme:n,className:"ps-modal-detail-line"})))),a.createElement("div",{className:"ps-modal-footer"},E,a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(P.MODAL_CONFIRM).catch(()=>{})},v))))};if(i.type==="confirm"&&r.confirm){const y=!!i.alert,v=!y&&i.action==="deleteSession",E=i.action==="regenerateSession",k=i.extras||{};return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:x=>x.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},r.confirm.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},a.createElement("p",{style:{color:"#94a3b8",margin:0}},r.confirm.message)),E?a.createElement("div",{className:"ps-modal-body",style:{padding:"0 20px 12px",display:"flex",flexDirection:"column",gap:10}},a.createElement("label",{style:{color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8}},"Distillation",a.createElement("select",{className:"ps-modal-input",style:{flex:"1",padding:"4px 8px"},value:k.distillMode||"llm",onChange:x=>t.updateConfirmExtras({distillMode:x.currentTarget.value})},a.createElement("option",{value:"llm"},"Intelligent (LLM reads the whole transcript)"),a.createElement("option",{value:"deterministic"},"Fast (no LLM — tail + pointers)"))),(k.distillMode||"llm")==="llm"?a.createElement(DS,{controller:t,extras:k}):null,(k.distillMode||"llm")==="llm"?a.createElement("textarea",{className:"ps-modal-input",style:{width:"100%",minHeight:"64px",resize:"vertical",fontFamily:"inherit",fontSize:"13px"},placeholder:'Distilling instructions (optional) — e.g. "preserve every SQL snippet verbatim"',value:k.instructions||"",maxLength:4e3,onChange:x=>t.updateConfirmExtras({instructions:x.currentTarget.value})}):null):null,a.createElement("div",{className:"ps-modal-footer"},y?null:a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:`ps-modal-button ${v?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(P.MODAL_CONFIRM).catch(()=>{})},r.confirm.confirmLabel))))}if(i.type==="themePicker"&&r.themePicker)return h(r.themePicker,"Apply Theme",m());const g=i.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(i.type==="modelPicker"&&r.modelPicker)return h(r.modelPicker,g);if(i.type==="reasoningEffortPicker"&&r.reasoningEffortPicker)return h(r.reasoningEffortPicker,g);if(i.type==="contextTierPicker"&&r.contextTierPicker)return h(r.contextTierPicker,g);if(i.type==="sessionAgentPicker"&&r.sessionAgentPicker){const y=i.items?.[i.selectedIndex||0],v=y?.kind==="section"?y.collapsed?"Open":"Close":"Create Session";return h(r.sessionAgentPicker,v)}if(i.type==="sessionGroupPicker"&&r.sessionGroupPicker)return h(r.sessionGroupPicker,"Move");if(i.type==="artifactPicker"&&r.artifactPicker)return h(r.artifactPicker,r.artifactPicker.confirmLabel||"Open / Download");if(i.type==="sessionOwnerFilter"&&r.sessionOwnerFilter){const y=r.sessionOwnerFilter,v=Array.isArray(y.rows)?y.rows:[],E=d.trim().toLowerCase(),k=w=>{const S=v?.[w];return(Array.isArray(S)?S:Ue([S])[0]?.runs||[]).map(M=>M?.text||"").join("")||String(S?.text||"")},x=(i.items||[]).map((w,S)=>S).filter(w=>{if(!E)return!0;const S=(i.items||[])[w]||{};return`${k(w)} ${S.label||""} ${S.description||""}`.toLowerCase().includes(E)});return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-list",onClick:w=>w.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},y.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{className:"ps-modal-input ps-modal-search",value:d,placeholder:"Search people…",autoFocus:!0,onChange:w=>p(w.currentTarget.value),onKeyDown:w=>{w.key==="Escape"&&d&&(w.stopPropagation(),p(""))}}),a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:c,className:"ps-modal-list"},x.length===0?a.createElement("div",{className:"ps-empty-state"},`No one matches "${d}".`):null,x.map(w=>(S=>a.createElement("button",{key:S.id||w,type:"button",className:`ps-list-button ps-modal-list-button${w===i.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(w)},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Ge,{runs:Array.isArray(v?.[w])?v[w]:Ue([v?.[w]])[0]?.runs||[{text:v?.[w]?.text||"",color:v?.[w]?.color}],theme:n}))))((i.items||[])[w]||{}))),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),Ue(y.detailsLines||[]).map((w,S)=>a.createElement(je,{key:`detail:${S}`,line:w,theme:n,className:"ps-modal-detail-line"})))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:f},"Done"))))}if(i.type==="renameSession"&&r.renameSession)return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},r.renameSession.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{ref:o,className:"ps-modal-input",value:r.renameSession.value,placeholder:r.renameSession.placeholder,onChange:y=>t.setRenameSessionValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),t.handleCommand(P.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Ue(r.renameSession.helpLines||[]).map((y,v)=>a.createElement(je,{key:`help:${v}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(P.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(i.type==="sessionGroupName"&&r.sessionGroupName)return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},r.sessionGroupName.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{ref:l,className:"ps-modal-input",value:r.sessionGroupName.value,placeholder:r.sessionGroupName.placeholder,onChange:y=>t.setSessionGroupNameValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),t.handleCommand(P.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Ue(r.sessionGroupName.helpLines||[]).map((y,v)=>a.createElement(je,{key:`help:${v}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(P.MODAL_CONFIRM).catch(()=>{})},r.sessionGroupName.mode==="rename"?"Rename":"Create and Move"))));if(i.type==="terminatePicker"){const y=Number(i.bulkCount)>1,v=!!i.systemRestart,E=String(i.sessionTitle||"").trim()||"this session",k=Number(i.bulkCount)||0,x=y?`What should happen to the ${k} selected sessions? Choose an action; you'll be asked to confirm.`:v?`How should "${E}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${E}"? Choose an action; you'll be asked to confirm.`,w=S=>()=>{t.pickTerminateAction(S).catch(()=>{})};return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:S=>S.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},i.title||"Session Lifecycle"),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},a.createElement("p",{style:{color:"#94a3b8",margin:0}},x)),a.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},i.canRegenerate?a.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},title:"Archive and distill the transcript, then rebuild context fresh at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved.",onClick:w("regenerate")},"Regenerate Context"):null,a.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:w("complete")},y?`Mark ${k} Completed`:v?"Complete & Restart":"Mark Completed"),a.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:w("cancel")},y?`Cancel ${k} Sessions`:v?"Terminate & Restart":"Cancel Session"),a.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:w("delete")},y?`Hard Delete ${k} Sessions`:v?"Hard Delete & Restart":"Delete Session")),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Close"))))}if(i.type==="artifactUpload"&&r.artifactUpload)return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},r.artifactUpload.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{className:"ps-modal-input",value:r.artifactUpload.value,placeholder:r.artifactUpload.placeholder,onChange:y=>t.setArtifactUploadValue(y.currentTarget.value,y.currentTarget.selectionStart||y.currentTarget.value.length),autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Ue(r.artifactUpload.helpLines||[]).map((y,v)=>a.createElement(je,{key:`help:${v}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(P.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const b=i.type==="logFilter"?r.logFilter:i.type==="filesFilter"?r.filesFilter:i.type==="historyFormat"?r.historyFormat:null;return b?a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-wide",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},b.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-filter-grid"},(i.items||[]).map((y,v)=>{const E=i.type==="filesFilter"?r.filesFilterState?.[y.id]||y.options?.[0]?.id:i.type==="historyFormat"?r.historyFormatState:r.logsFilter?.[y.id]||y.options?.[0]?.id;return a.createElement("div",{key:y.id||v,className:"ps-filter-column"},a.createElement("div",{className:"ps-filter-title"},y.label),(y.options||[]).map(k=>a.createElement("button",{key:k.id,type:"button",className:`ps-filter-option${k.id===E?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:v}),i.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:k.id}):i.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[y.id]:k.id}}),t.ensureFilesForScope(k.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[y.id]:k.id}})}},k.label)))})),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:f},"Done")))):null}function DS({controller:t,extras:e}){const s=Array.isArray(e.distillerModelOptions)?e.distillerModelOptions:[],n=s.find(d=>d.qualifiedName===e.distillerModel)||null,r=n?.supportedReasoningEfforts||[],i=n?.supportedContextTiers||[],o={color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8},l={flex:"1",padding:"4px 8px"},c=d=>t.updateConfirmExtras(d);return a.createElement(a.Fragment,null,a.createElement("label",{style:o},"Distiller model",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerModel||"",onChange:d=>c({distillerModel:d.currentTarget.value,distillerEffort:"",distillerContextTier:""})},a.createElement("option",{value:""},"Deployment default"),s.map(d=>a.createElement("option",{key:d.qualifiedName,value:d.qualifiedName},d.qualifiedName)))),r.length>0?a.createElement("label",{style:o},"Reasoning",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerEffort||"",onChange:d=>c({distillerEffort:d.currentTarget.value})},a.createElement("option",{value:""},"Model default"),r.map(d=>a.createElement("option",{key:d,value:d},d)))):null,i.length>0?a.createElement("label",{style:o},"Context",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerContextTier||"",onChange:d=>c({distillerContextTier:d.currentTarget.value})},a.createElement("option",{value:""},"Model default"),i.map(d=>a.createElement("option",{key:d,value:d},d==="long_context"?"long context (fits a larger transcript)":d)))):null)}function BS(t,e){a.useEffect(()=>{const s=n=>{const r=n.target,i=r instanceof HTMLElement&&(r.tagName==="TEXTAREA"||r.tagName==="INPUT"||r.tagName==="SELECT"||r.isContentEditable),o=t.getState().ui.modal,l=ki(t),c=t.getState().ui.inspectorTab,d=t.getState().ui.focusRegion,p=!n.metaKey&&!n.ctrlKey&&!n.altKey,u=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="T"&&n.shiftKey,f=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="N"&&n.shiftKey,m=h=>{const g=Zg(l,c,h);t.selectInspectorTab(g).catch(()=>{})};if(!i&&u){n.preventDefault(),t.handleCommand(P.OPEN_THEME_PICKER).catch(()=>{});return}if(!i&&f){n.preventDefault(),t.handleCommand(P.OPEN_MODEL_PICKER).catch(()=>{});return}if(o&&!i){if(n.key==="Escape"||o.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(P.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||o.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(P.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(P.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(P.MODAL_PANE_NEXT).catch(()=>{});return}if(o.type==="sessionAgentPicker"&&(n.key==="ArrowRight"||n.key==="ArrowLeft")){n.preventDefault(),t.handleCommand(n.key==="ArrowRight"?P.MODAL_PANE_NEXT:P.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(P.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(P.MODAL_NEXT).catch(()=>{}));return}if(!i){if(n.key==="r"&&p&&d!=="prompt"){n.preventDefault(),t.handleCommand(P.REFRESH).catch(()=>{});return}if(n.key==="n"&&p){n.preventDefault(),t.handleCommand(P.NEW_SESSION).catch(()=>{});return}if(d==="inspector"&&c==="files"&&(n.key==="u"&&p||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(P.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="a"&&p){n.preventDefault(),t.handleCommand(P.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="x"&&p){n.preventDefault(),t.handleCommand(P.DELETE_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="o"&&p){n.preventDefault(),t.handleCommand(P.OPEN_SELECTED_FILE).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(P.OPEN_FILES_FILTER).catch(()=>{});return}if(d==="inspector"&&c==="stats"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(P.TOGGLE_STATS_VIEW).catch(()=>{});return}if(d==="inspector"&&c==="files"&&n.key==="v"&&p){n.preventDefault(),t.handleCommand(P.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(d==="inspector"&&c==="logs"&&n.key==="t"&&p){n.preventDefault(),t.handleCommand(P.TOGGLE_LOG_TAIL).catch(()=>{});return}if(d==="inspector"&&c==="logs"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(P.OPEN_LOG_FILTER).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(P.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="r"&&p){n.preventDefault(),t.handleCommand(P.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(d==="inspector"&&c==="history"&&n.key==="a"&&p){n.preventDefault(),t.handleCommand(P.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&p){n.preventDefault(),t.handleCommand(P.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&p){n.preventDefault(),t.handleCommand(P.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&p){n.preventDefault(),t.handleCommand(P.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&p){n.preventDefault(),t.handleCommand(P.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(P.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&p&&d==="inspector"){n.preventDefault(),m(1);return}if(n.key==="["&&p){n.preventDefault(),t.handleCommand(P.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&p){n.preventDefault(),t.handleCommand(P.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&p){n.preventDefault(),t.handleCommand(P.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&p){n.preventDefault(),t.handleCommand(P.GROW_SESSION_PANE).catch(()=>{});return}if(d==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),m(-1);return}if(d==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),m(1);return}if(d==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(P.MOVE_SESSION_UP).catch(()=>{});return}if(d==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(P.MOVE_SESSION_DOWN).catch(()=>{});return}if(d==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(P.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(d==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(P.PAGE_UP).catch(()=>{});return}if(d==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(P.PAGE_DOWN).catch(()=>{});return}if(d==="sessions"&&n.key==="t"&&p){n.preventDefault(),t.handleCommand(P.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(P.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(P.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&p){n.preventDefault(),t.handleCommand(P.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(P.SCROLL_BOTTOM).catch(()=>{});return}if(d!=="prompt"&&n.key==="h"&&p){n.preventDefault(),t.handleCommand(P.FOCUS_LEFT).catch(()=>{});return}if(d!=="prompt"&&n.key==="l"&&p){n.preventDefault(),t.handleCommand(P.FOCUS_RIGHT).catch(()=>{});return}if(!e&&d==="inspector"&&c==="files"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(P.MOVE_FILE_UP).catch(()=>{});return}if(!e&&d==="inspector"&&c==="files"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(P.MOVE_FILE_DOWN).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(P.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(P.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(P.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function hd(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(),r=String(t.subject||"").trim();return[n,r].filter(Boolean).join(":")||"user"}function HS({controller:t,mobile:e=!1}){const s=ee(t,vt,_e),n=s.packages||{},r=s.section==="packages",i=s.section==="workers",[o,l]=a.useState(null),[c,d]=a.useState(!1),[p,u]=a.useState(null),[f,m]=a.useState(()=>{const O={wsWidth:440,treePct:44,navWidth:240};try{return{...O,...JSON.parse(window.localStorage.getItem("ps-admin-ws-layout")||"{}")}}catch{return O}}),h=a.useCallback(O=>{m(R=>{const T={...R,...O};T.wsWidth=Math.min(900,Math.max(300,Math.round(T.wsWidth))),T.treePct=Math.min(85,Math.max(15,T.treePct)),T.navWidth=Math.min(420,Math.max(170,Math.round(T.navWidth??240)));try{window.localStorage.setItem("ps-admin-ws-layout",JSON.stringify(T))}catch{}return T})},[]),g=a.useCallback(O=>{O.preventDefault(),document.body.style.cursor="col-resize";const R=O.clientX,T=f.navWidth??240,N=q=>h({navWidth:T+(q.clientX-R)}),j=()=>{window.removeEventListener("pointermove",N),window.removeEventListener("pointerup",j),window.removeEventListener("pointercancel",j),document.body.style.cursor=""};window.addEventListener("pointermove",N),window.addEventListener("pointerup",j),window.addEventListener("pointercancel",j)},[f.navWidth,h]),b=a.useCallback(()=>{t.closeAdminConsole()},[t]),y=a.useCallback(()=>{l(null),d(!1),u(null)},[]),v=a.useCallback(async O=>{d(!0),u(null);const R=await t.createAdminProvider(O);if(d(!1),!R?.ok){u(R?.error||"The provider could not be created.");return}y()},[y,t]),E=hd(s.principal),k=a.createElement("header",{className:"ps-admin-console__header"},a.createElement("h2",null,"Admin Console"),a.createElement("span",{className:"ps-admin-console__who"},E),a.createElement("button",{type:"button",className:"ps-mini-button is-icon",onClick:b,title:"Close the admin console","aria-label":"Close the admin console"},"✕")),x=a.createElement(KS,{controller:t,view:s,onAddPersonal:()=>l({shared:!1,github:!0}),onAddShared:()=>l({shared:!0,github:!1})}),w=a.createElement(US,{controller:t,view:s}),S=a.createElement(jS,{controller:t,view:s}),C=r&&n.selectedName?a.createElement(GS,{controller:t,view:s,layout:f,onLayout:h}):null,M=n.addDialog?.open?a.createElement(qS,{controller:t,dialog:n.addDialog}):null,_=o?a.createElement(_S,{types:s.modelProviders?.providerTypes||[],existingNames:[...s.modelProviders?.sharedProviders||[],...s.modelProviders?.myProviders||[]].map(O=>O.name),isAdmin:s.isAdmin,initialShared:o.shared,initialType:o.github&&(s.modelProviders?.providerTypes||[]).find(O=>/github/i.test(O.id))?.id||"",busy:c,error:p,onCancel:y,onConfirm:v}):null;if(e){let O;return r&&n.selectedName?O=a.createElement("div",{className:"ps-admin-mobile-stack"},a.createElement("button",{type:"button",className:"ps-mini-button ps-admin-back",onClick:()=>t.selectAdminPackage(null)},"← All packages"),S,C):r?O=w:i?O=a.createElement("div",{className:"ps-admin-mobile-stack"},w,a.createElement(ja,{controller:t,view:s})):O=a.createElement("div",{className:"ps-admin-mobile-stack"},w,x),a.createElement("div",{className:"ps-admin-console is-mobile"},k,s.loadError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,O,M,_)}return a.createElement("div",{className:"ps-admin-console is-workspace"},k,s.loadError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,a.createElement("div",{className:"ps-admin-workspace",style:C?{gridTemplateColumns:`${f.navWidth}px minmax(0, 1fr) minmax(0, ${f.wsWidth}px)`}:{gridTemplateColumns:`${f.navWidth}px minmax(0, 1fr)`}},a.createElement("div",{className:"ps-admin-nav"},w,a.createElement("div",{className:"ps-admin-nav__resize",onPointerDown:g,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings column"})),a.createElement("div",{className:"ps-admin-main"},r?S:i?a.createElement(ja,{controller:t,view:s}):x),C),M,_)}function ja({controller:t,view:e}){const s=e.workers||{},n=s.rows||[],r=s.counts||{};return a.useEffect(()=>{const i=window.setInterval(()=>{t.refreshAdminWorkers()},25e3);return()=>window.clearInterval(i)},[t]),a.createElement("div",{className:"ps-admin-detail ps-admin-workers"},a.createElement("div",{className:"ps-admin-workers__head"},a.createElement("h3",null,"Workers"),s.summaryText?a.createElement("span",{className:"ps-admin-workers__summary"},`${s.summaryText}${r.pools>1?` · ${r.pools} pools`:""}${r.draining?` · ${r.draining} draining`:""}`):null,a.createElement("button",{type:"button",className:"ps-mini-button is-icon",onClick:()=>t.refreshAdminWorkers(),disabled:!!s.loading,title:s.loading?"Refreshing…":"Refresh the worker list","aria-label":"Refresh the worker list"},a.createElement("svg",{viewBox:"0 0 20 20",width:15,height:15,fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.createElement("path",{d:"M16.2 8.2A6.4 6.4 0 0 0 4.6 6.4M3.8 11.8a6.4 6.4 0 0 0 11.6 1.8"}),a.createElement("path",{d:"M16.4 3.6v4.6h-4.6M3.6 16.4v-4.6h4.6"})))),s.error?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.error):null,s.empty?a.createElement("p",{className:"ps-admin-console__hint"},"No workers registered. Workers appear here on their first heartbeat and self-prune after an hour of silence."):a.createElement("div",{className:"ps-admin-workers__scroll"},a.createElement("table",{className:"ps-admin-workers__table"},a.createElement("thead",null,a.createElement("tr",null,["Worker","Pool","Phase","Heartbeat","Uptime","RSS","Sessions","Loop p99","Packages","SDK"].map(i=>a.createElement("th",{key:i},i)))),a.createElement("tbody",null,n.map(i=>a.createElement("tr",{key:i.id,className:i.live?"is-live":"is-stale"},a.createElement("td",{className:"ps-admin-workers__id",title:i.owner?`owner: ${i.owner}`:void 0},a.createElement("span",{className:`ps-worker-dot${i.live?" is-live":""}`}),i.id,i.substrate&&i.substrate!=="kubernetes"?a.createElement("span",{className:"ps-admin-workers__substrate"},i.substrate):null),a.createElement("td",null,i.pool),a.createElement("td",null,a.createElement("span",{className:`ps-worker-phase is-${i.phase}`},i.phase)),a.createElement("td",null,i.agoText),a.createElement("td",null,i.uptimeText??"—"),a.createElement("td",null,i.rssText??"—"),a.createElement("td",null,i.sessions??"—"),a.createElement("td",null,i.eventLoopText??"—"),a.createElement("td",{title:i.pkgEpoch!=null?`epoch ${i.pkgEpoch}`:void 0},i.pkgText??"—"),a.createElement("td",null,i.sdkVersion??"—")))))))}function US({controller:t,view:e}){const s=e.packages||{};return a.createElement("nav",{className:"ps-admin-tree"},a.createElement("div",{className:"ps-admin-tree__label"},"Settings"),(e.settingsTree||[]).map(n=>{if(n.kind==="group")return a.createElement("div",{key:n.id,className:"ps-admin-tree__group"},`${n.label}`,a.createElement("span",{className:"ps-admin-tree__count"},String(n.count??0)));const r=n.kind==="package"?()=>t.selectAdminPackage(n.name,{scope:n.scope==="shared"?"shared":"user",...n.scope!=="shared"&&n.owner?.provider&&n.owner?.subject?{owner:{provider:n.owner.provider,subject:n.owner.subject}}:{}}):()=>{n.id==="providers"||n.id==="myProviders"?(t.setAdminSection("providers"),t.setAdminModelProviderPage("mine")):n.id==="sharedProviders"?(t.setAdminSection("providers"),t.setAdminModelProviderPage("shared")):t.setAdminSection(n.id==="agents"?"packages":"workers")};return a.createElement("button",{key:n.id,type:"button",className:`ps-admin-tree__row depth-${n.depth}${n.selected?" is-selected":""}${n.kind==="package"&&!n.enabled?" is-disabled":""}`,onClick:r},n.kind==="package"?n.ownerBadge?a.createElement(Rr,{badge:n.ownerBadge}):a.createElement("span",{className:"ps-scope-badge is-shared",title:"shared with the whole deployment"},"S"):null,a.createElement("span",{className:"ps-admin-tree__name"},n.label),n.kind==="package"&&n.semver?a.createElement("span",{className:"ps-admin-tree__ver"},n.semver):null)}),s.loading?a.createElement("div",{className:"ps-admin-tree__hint"},"Loading packages…"):null,s.error?a.createElement("div",{className:"ps-admin-tree__hint is-error"},s.error):null,e.section==="packages"?a.createElement("button",{type:"button",className:"ps-admin-tree__add",onClick:()=>t.openAdminAddPackage()},"+ Add package"):null)}function jS({controller:t,view:e}){const s=e.packages||{},n=s.detail;if(!s.selectedName)return a.createElement("div",{className:"ps-admin-detail is-empty"},a.createElement("h3",null,"Agents"),a.createElement("p",{className:"ps-admin-console__hint"},s.empty?"No agent packages yet. Add one from a GitHub/ADO repo, a tarball URL, or upload a folder — or push from a terminal with `pilotswarm agents push ./my-agents`.":"Select a package from the tree to see its detail, versions, and files."));const r=()=>{window.confirm(`Delete ${n.name}? Every version and its artifacts are removed. Live sessions using its agents will fail on their next turn.`)&&t.runAdminPackageAction("delete")},i=(l,c)=>()=>t.runAdminPackageAction(l,c),o=n.actionPending;return a.createElement("div",{className:"ps-admin-detail"},n.error?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},`Package load failed: ${n.error}`):null,n.loading?a.createElement("p",{className:"ps-admin-console__hint"},"Loading package…"):null,a.createElement("div",{className:"ps-admin-detail__head"},a.createElement("h3",null,n.name),a.createElement("span",{className:`ps-scope-badge is-${n.scope}`},n.scope),n.enabled?null:a.createElement("span",{className:"ps-scope-badge is-off"},"disabled")),n.description?a.createElement("p",{className:"ps-admin-detail__desc"},n.description):null,a.createElement("dl",{className:"ps-admin-detail__meta"},a.createElement("dt",null,"Version"),a.createElement("dd",null,n.activeSemver?`${n.activeSemver} · sha ${n.activeSha12||"?"} · ${n.sizeText}`:"no active version"),n.fleet?[a.createElement("dt",{key:"fk"},"Fleet"),a.createElement("dd",{key:"fv",className:"is-ok"},n.fleet.text)]:null,a.createElement("dt",null,"Created"),a.createElement("dd",null,`${n.createdBy||"unknown"} · ${n.createdAtText}`)),n.agents.length?a.createElement("div",null,a.createElement("div",{className:"ps-admin-detail__label"},"Agents in this package"),a.createElement("div",{className:"ps-admin-detail__chips"},n.agents.map(l=>a.createElement("span",{key:l.name,className:"ps-agent-chip",title:l.description},l.name,l.toolCount?a.createElement("i",null,` · ${l.toolCount} tools`):null)))):null,n.versions.length?a.createElement("div",null,a.createElement("div",{className:"ps-admin-detail__label"},"Versions"),a.createElement("div",{className:"ps-admin-versions"},n.versions.map(l=>a.createElement("div",{key:l.semver,className:`ps-admin-version${l.active?" is-active":""}`},a.createElement("b",null,l.semver),a.createElement("span",null,l.sha12),a.createElement("span",null,l.dateText),l.active?a.createElement("span",{className:"is-ok"},"● active"):n.canManage?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:i("pin",l.semver),disabled:!!o},"Pin"):null)))):null,n.canManage?a.createElement("div",{className:"ps-admin-detail__actions"},n.source?a.createElement("button",{type:"button",className:"ps-primary-button",onClick:i("sync"),disabled:!!o},o==="sync"?"Syncing…":"Sync now"):null,a.createElement("button",{type:"button",className:"ps-primary-button",onClick:()=>t.openAdminUpdatePackage(n.name,n.scope),disabled:!!o,title:`Publish a new version of ${n.name} from a repo folder`},"Update"),n.scope==="user"&&n.hasSharedCounterpart?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:i("republish",n.activeSemver),disabled:!!o||!n.activeSemver,title:`Publish ${n.name}@${n.activeSemver??"?"} into the existing shared package`},o==="republish"?"Publishing…":`Publish ${n.activeSemver??""} to shared`):a.createElement("button",{type:"button",className:"ps-mini-button",onClick:i(n.scope==="shared"?"demote":"promote"),disabled:!!o},n.scope==="shared"?"Demote to user":"Promote to shared"),n.scope==="shared"&&!n.hasOwnUserCounterpart?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:i("republish",n.activeSemver),disabled:!!o||!n.activeSemver,title:"Copy the active version into your user scope as a private test bench"},o==="republish"?"Copying…":"Copy to my user scope"):null,a.createElement("button",{type:"button",className:"ps-mini-button",onClick:i(n.enabled?"disable":"enable"),disabled:!!o},n.enabled?"Disable":"Enable"),a.createElement("button",{type:"button",className:"ps-mini-button is-danger",onClick:r,disabled:!!o},"Delete")):a.createElement("p",{className:"ps-admin-console__hint"},"Read-only: only the package creator or an admin can modify it."),n.actionError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},n.actionError):null)}function GS({controller:t,view:e,layout:s=null,onLayout:n=null}){const r=ee(t,u=>u.ui.themeId),i=pt(r),o=e.packages?.workspace,l=a.useRef(null),c=a.useCallback((u,f)=>{if(!n)return;u.preventDefault();const m=u.clientX,h=u.clientY,g={...s},b=v=>f(g,v.clientX-m,v.clientY-h),y=()=>{window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),document.body.style.cursor=""};window.addEventListener("pointermove",b),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)},[s,n]),d=a.useCallback(u=>{document.body.style.cursor="col-resize",c(u,(f,m)=>n({wsWidth:f.wsWidth-m}))},[c,n]),p=a.useCallback(u=>{document.body.style.cursor="row-resize";const f=l.current?.getBoundingClientRect().height||600;c(u,(m,h,g)=>n({treePct:m.treePct+g/f*100}))},[c,n]);return o?a.createElement("div",{className:"ps-admin-ws",ref:l,style:s?{gridTemplateRows:`auto minmax(80px, ${s.treePct}%) auto minmax(0, 1fr)`}:void 0},n?a.createElement("div",{className:"ps-admin-ws__vdivider",title:"Drag to resize the workspace",onPointerDown:d}):null,a.createElement("div",{className:"ps-admin-ws__head"},`Package workspace${o.semver?` · ${e.packages.selectedName}@${o.semver}`:""}`),a.createElement("div",{className:"ps-admin-ws__tree"},o.loading?a.createElement("div",{className:"ps-admin-tree__hint"},"Loading files…"):null,o.error?a.createElement("div",{className:"ps-admin-tree__hint is-error"},o.error):null,o.treeRows.map(u=>a.createElement("button",{key:`${u.type}:${u.path}`,type:"button",style:{paddingLeft:`${8+(u.depth||0)*16}px`},className:`ps-admin-ws__row is-${u.type}${u.selected?" is-selected":""}`,onClick:u.type==="dir"?()=>t.toggleAdminPackageDir(u.path):()=>t.selectAdminPackageFile(u.path)},a.createElement("span",{className:"ps-admin-ws__caret"},u.type==="dir"?u.expanded?"▾":"▸":""),a.createElement("span",{className:"ps-admin-ws__name"},u.label),u.sizeText?a.createElement("span",{className:"ps-admin-ws__size"},u.sizeText):null))),a.createElement("div",{className:`ps-admin-ws__preview-head${n?" is-resizable":""}`,title:n?"Drag to resize file list vs preview":void 0,onPointerDown:n?p:void 0},o.selectedPath?`Preview · ${o.selectedPath}`:"Preview"),a.createElement("div",{className:"ps-admin-ws__preview"},o.fileLoading?a.createElement("div",{className:"ps-admin-tree__hint"},"Loading…"):null,o.fileError?a.createElement("div",{className:"ps-admin-tree__hint is-error"},o.fileError):null,o.file?o.file.isBinary?a.createElement("div",{className:"ps-admin-tree__hint"},`Binary file · ${o.file.sizeText}`):a.createElement(WS,{file:o.file,theme:i}):null)):null}function zS(t){const e=/^---\n([\s\S]*?)\n---\n?/.exec(t||"");if(!e)return{meta:null,body:t||""};const s=e[1].split(`
|
|
97
|
-
`).map(n=>/^([A-Za-z0-9_-]+):\s*(.*)$/.exec(n)).filter(Boolean).map(([,n,r])=>({key:n,value:r}));return s.length===0?{meta:null,body:t||""}:{meta:s,body:(t||"").slice(e[0].length)}}function WS({file:t,theme:e}){const s=t.language||"text",n=t.truncated?a.createElement("div",{className:"ps-admin-tree__hint"},"… truncated preview"):null;if(s==="markdown"){const{meta:r,body:i}=zS(t.text||"");return a.createElement("div",{className:"ps-admin-ws__doc"},r?a.createElement("div",{className:"ps-admin-ws__frontmatter"},r.map(o=>a.createElement("div",{key:o.key,className:"ps-admin-ws__fm-row"},a.createElement("span",{className:"ps-admin-ws__fm-key"},o.key),a.createElement("span",{className:"ps-admin-ws__fm-val"},o.value)))):null,a.createElement(Mi,{content:i,theme:e}),n)}if(s==="json"){let r=t.text||"";if(!t.truncated)try{r=JSON.stringify(JSON.parse(r),null,2)}catch{}return a.createElement("div",{className:"ps-admin-ws__doc"},a.createElement("pre",{className:"ps-admin-ws__code lang-json"},a.createElement("code",null,ls(r,"json",e))),n)}return a.createElement("div",{className:"ps-admin-ws__doc"},a.createElement("pre",{className:`ps-admin-ws__code lang-${s}`},a.createElement("code",null,ls(t.text||"",s,e))),n)}function qS({controller:t,dialog:e}){const s=ee(t,u=>u.docs?.agentPackageGuideUrl||null),n=u=>f=>t.setAdminAddPackageField(u,f.target.value),r=[["repo","GitHub / Azure DevOps"],["upload","Upload folder"]],i=e.kind==="repo"||e.kind==="github"||e.kind==="ado",o=a.useRef(null),[l,c]=a.useState(!1),d=2*1024*1024,p=u=>{if(u.preventDefault(),!(l||e.submitting)){if(e.kind==="upload"){const f=o.current;if(!f?.files?.length){t.failAdminAddPackage("Choose a package folder first.");return}const m=[...f.files].map(g=>({file:g,path:g.webkitRelativePath.split("/").slice(1).join("/")||g.name})).filter(({path:g})=>g&&!g.split("/").includes("node_modules")&&!g.split("/").includes(".git")),h=m.reduce((g,{file:b})=>g+b.size,0);if(m.length===0){t.failAdminAddPackage("The chosen folder has no uploadable files.");return}if(h>d){t.failAdminAddPackage(`Folder is ${(h/(1024*1024)).toFixed(1)} MB after filtering — the upload envelope is 2 MB. Use a repo/URL source or 'pilotswarm agents push' for larger packages.`);return}c(!0),Promise.all(m.map(({file:g,path:b})=>new Promise((y,v)=>{const E=new FileReader;E.onerror=()=>v(new Error(`could not read ${b}`)),E.onload=()=>y({path:b,contentBase64:String(E.result).split(",",2)[1]||""}),E.readAsDataURL(g)}))).then(g=>t.submitAdminUploadPackage(g,e.scope)).catch(g=>t.failAdminAddPackage(g?.message||"Could not read the chosen folder.")).finally(()=>c(!1));return}t.submitAdminAddPackage().catch(()=>{})}};return a.createElement("div",{className:"ps-modal-backdrop",onClick:()=>t.closeAdminAddPackage()},a.createElement("form",{className:"ps-modal ps-admin-add",onClick:u=>u.stopPropagation(),autoComplete:"off",onSubmit:p},a.createElement("div",{className:"ps-modal-header"},a.createElement("span",null,e.updateName?`Update ${e.updateName}`:"Add agent package"),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage()},"✕")),a.createElement("div",{className:"ps-admin-add__body"},a.createElement("div",{className:"ps-admin-add__tabs"},r.map(([u,f])=>a.createElement("button",{key:u,type:"button",className:`ps-admin-add__tab${e.kind===u?" is-on":""}`,onClick:()=>t.setAdminAddPackageField("kind",u)},f))),i?[a.createElement("label",{key:"u",className:"ps-admin-add__field"},"Link to plugin.json (or the folder containing it)",a.createElement("input",{value:e.repoUrl,onChange:n("repoUrl"),placeholder:"https://github.com/org/repo/blob/main/my-agents/plugin.json",autoFocus:!0,type:"url",name:"agent-package-link",autoComplete:"off",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true"})),a.createElement("div",{key:"h",className:"ps-admin-add__hint"},"Paste the browser URL — branch and path are read from the link. The files are read by THIS BROWSER with your access (public GitHub needs nothing; Azure DevOps uses your signed-in account) and uploaded as a package artifact."),a.createElement("label",{key:"t",className:"ps-admin-add__field"},"PAT (only for private GitHub repos, or to override — used here, never stored)",a.createElement("input",{type:"password",value:e.authToken,onChange:n("authToken"),name:"agent-package-pat",autoComplete:"new-password","data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true"}))]:a.createElement("label",{className:"ps-admin-add__field"},"Package folder with plugin.json — the manifest (≤ 2 MB; node_modules skipped)",a.createElement("input",{ref:o,type:"file",webkitdirectory:"",directory:"",multiple:!0})),a.createElement("div",{className:"ps-admin-add__scope"},a.createElement("label",null,a.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="shared",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","shared")})," Shared — everyone can use it"),a.createElement("label",null,a.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="user",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","user")})," User — only you see it")),e.updateName?a.createElement("p",{className:"ps-admin-console__hint"},`Publishes a new version of ${e.updateName}. Its scope is unchanged — use Demote/Promote on the package to move it.`):null,s?a.createElement("p",{className:"ps-admin-console__hint"},"New to this? ",a.createElement("a",{href:s,target:"_blank",rel:"noreferrer noopener"},"How to build an agent package")," — a complete guide you can also hand straight to Claude or Copilot."):null,a.createElement("p",{className:"ps-admin-console__hint"},"Same thing from a terminal: pilotswarm agents push ./my-agents --shared"),e.progress&&!e.error?a.createElement("p",{className:"ps-admin-add__progress"},e.progress):null,e.error?a.createElement("pre",{className:"ps-admin-add__error",role:"alert"},e.error):null),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage(),disabled:e.submitting},"Cancel"),a.createElement("button",{type:"submit",className:"ps-primary-button",disabled:e.submitting||l},l?"Reading folder…":e.submitting?"Importing…":e.updateName?"Import & update":"Import & publish"))))}function fr(t){return t?.configured?.model||""}function mr({label:t,hint:e,value:s,choices:n,disabled:r,emptyLabel:i,onChange:o}){return a.createElement("label",{className:"ps-admin-provider-default"},a.createElement("span",{className:"ps-admin-detail__label"},t),a.createElement("select",{className:"ps-budget-input",value:s,disabled:r,"aria-label":t,onChange:l=>o(l.target.value)},a.createElement("option",{value:""},i),s&&!n.some(l=>l.qualifiedName===s)?a.createElement("option",{value:s},`${s} (currently configured)`):null,n.map(l=>a.createElement("option",{key:l.qualifiedName,value:l.qualifiedName},`${l.provider} · ${l.model}`))),e?a.createElement("span",{className:"ps-admin-console__hint"},e):null)}function Ga({providers:t,isAdmin:e,personal:s,busy:n,onSystemUse:r,onDelete:i}){return t.length?a.createElement("div",{className:"ps-admin-provider-list"},t.map(o=>a.createElement("div",{key:o.name,className:"ps-admin-provider-row"},a.createElement("div",{className:"ps-admin-provider-row__identity"},a.createElement("strong",null,o.name),a.createElement("span",{className:`ps-scope-badge is-${o.class==="shared"?"shared":"user"}`},o.class),o.isMyDefault?a.createElement("span",{className:"ps-scope-badge is-off"},"my default"):null,o.isClusterDefault?a.createElement("span",{className:"ps-scope-badge is-off"},"cluster default"):null,o.isSystemDefault?a.createElement("span",{className:"ps-scope-badge is-off"},"system default"):null),a.createElement("div",{className:"ps-admin-provider-row__actions"},s&&e?a.createElement("label",{className:"ps-admin-console__system-toggle"},a.createElement("input",{type:"checkbox",checked:o.systemUseEnabled,disabled:n,onChange:l=>r(o.name,l.target.checked)}),"Allow system sessions"):null,a.createElement(pe,{icon:a.createElement(Lb),label:`Delete ${o.name}`,className:"ps-mini-button is-danger",disabled:n,onClick:()=>i(o)}))))):a.createElement("p",{className:"ps-admin-console__hint"},s?"No personal providers yet.":"No shared providers are configured.")}function KS({controller:t,view:e,onAddPersonal:s,onAddShared:n}){const r=e.modelProviders||{},i=!!r.mutation?.pending,o=fr(r.systemSessionDefault),[l,c]=a.useState(o),[d,p]=a.useState(""),[u,f]=a.useState(null);a.useEffect(()=>{c(o)},[o]);const m=(w,S)=>w.find(C=>C.qualifiedName===S)||null,h=(w,S,C)=>{t.setAdminModelDefault(w,m(S,C))},g=w=>{window.confirm(`Delete ${w.name}? Sessions using it will wait until that provider name exists again.`)&&t.deleteAdminProvider(w.name,{shared:w.class==="shared"})},b=async()=>{f(null);const w=await t.setAdminSystemModelDefault(m(r.systemChoices||[],l),{restartDisposition:d||null});w?.ok&&f(w.result?.restart||{requested:!1})},y=(r.systemAgentRoutes||[]).filter(w=>!w.override),v=r.page==="shared"&&e.isAdmin,E=a.createElement("div",{className:"ps-admin-provider-heading"},a.createElement("h3",null,"Model Providers"),a.createElement(pe,{icon:"↻",label:"Refresh model providers",className:"ps-mini-button",disabled:r.loading,onClick:()=>t.refreshAdminModelProviders()})),k=a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-admin-provider-block"},a.createElement("div",{className:"ps-admin-provider-block__head"},a.createElement("h4",null,"My Providers"),a.createElement("button",{type:"button",className:"ps-primary-button",onClick:s,disabled:i},"Add provider")),a.createElement(Ga,{providers:r.myProviders||[],isAdmin:e.isAdmin,personal:!0,busy:i,onSystemUse:(w,S)=>t.setAdminProviderSystemUse(w,S),onDelete:g})),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement(mr,{label:"My Session Default",hint:`Effective: ${r.mySessionDefault?.effective?.model||"none"}.`,value:fr(r.mySessionDefault),choices:r.userChoices||[],disabled:i,emptyLabel:"Use cluster default",onChange:w=>h("user",r.userChoices||[],w)}))),x=a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-admin-provider-block"},a.createElement("div",{className:"ps-admin-provider-block__head"},a.createElement("h4",null,"Shared Providers"),a.createElement("button",{type:"button",className:"ps-primary-button",onClick:n,disabled:i},"Add provider")),a.createElement(Ga,{providers:r.sharedProviders||[],isAdmin:!0,personal:!1,busy:i,onSystemUse:()=>{},onDelete:g})),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement(mr,{label:"Cluster Session Default",hint:`Effective: ${r.clusterSessionDefault?.effective?.model||"none"}.`,value:fr(r.clusterSessionDefault),choices:r.clusterChoices||[],disabled:i,emptyLabel:"Use first shared provider",onChange:w=>h("cluster",r.clusterChoices||[],w)})),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement("h4",null,"System Session Default"),a.createElement(mr,{label:"Model",hint:"Shared and system-enabled personal providers.",value:l,choices:r.systemChoices||[],disabled:i,emptyLabel:"Use first eligible provider",onChange:c}),a.createElement("div",{className:"ps-admin-detail__label"},"Existing system sessions"),a.createElement(Rt,{value:d,onChange:p,label:"Existing system sessions",options:[{value:"",label:"Future only"},{value:"complete",label:"Complete & restart"},{value:"terminate",label:"Terminate & restart"},{value:"hard_delete",label:"Hard delete & restart"}]}),a.createElement("div",{className:"ps-admin-provider-apply"},a.createElement("p",{className:"ps-admin-console__hint"},`${y.length} agent${y.length===1?"":"s"} inherit this default.`),a.createElement("button",{type:"button",className:"ps-primary-button",disabled:i,onClick:b},i&&r.mutation?.pending==="systemDefault"?"Applying…":"Apply")),u?.requested?a.createElement("p",{className:"ps-admin-console__status"},`${u.restarted}/${u.affected} restarted${u.failures?.length?` · ${u.failures.length} failed`:""}.`):null),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement("h4",null,"System Agent Overrides"),(r.systemAgentRoutes||[]).length===0?a.createElement("p",{className:"ps-admin-console__hint"},"No system agents."):a.createElement("div",{className:"ps-admin-override-table"},(r.systemAgentRoutes||[]).map(w=>a.createElement("div",{key:w.agentId,className:"ps-admin-override-row"},a.createElement("div",{className:"ps-admin-override-row__agent"},a.createElement("strong",null,w.title),a.createElement("span",null,w.effectiveModel||"blocked"),a.createElement("small",null,w.override?"override":"system default")),a.createElement("select",{className:"ps-budget-input",value:w.override?.model||"",disabled:i,"aria-label":`Model override for ${w.title}`,onChange:S=>{const C=m(r.systemChoices||[],S.target.value);C?t.setAdminSystemAgentModel(w.agentId,C):t.clearAdminSystemAgentModel(w.agentId)}},a.createElement("option",{value:""},"Inherit system default"),(r.systemChoices||[]).map(S=>a.createElement("option",{key:S.qualifiedName,value:S.qualifiedName},`${S.provider} · ${S.model}`))))))));return a.createElement("section",{className:"ps-admin-detail ps-admin-model-providers"},E,r.error||r.mutation?.error?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},r.mutation?.error||r.error):null,v?x:k)}function XS({transport:t,mode:e="remote",branding:s=null,docs:n=null}={}){ly(),typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;const r=Nh(Ch,vr({mode:e,branding:s,docs:n}));return new Ag({store:r,transport:t})}function QS({controller:t}){const e=a.useRef(null),s=a.useRef(null),n=ga(e),r=ga(s),i=Sy(n);a.useEffect(()=>{const L=()=>{try{const H=document.createElement("span");H.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const X=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");if(X){const ve=window.getComputedStyle(X);H.style.fontFamily=ve.fontFamily,H.style.fontSize=ve.fontSize,H.style.fontWeight=ve.fontWeight,H.style.letterSpacing=ve.letterSpacing}H.textContent="0".repeat(100),(X?.parentElement||document.body).appendChild(H);const ae=H.getBoundingClientRect().width/100||8;H.remove();const le=document.documentElement.clientWidth||window.innerWidth,Ae=document.documentElement.clientHeight||window.innerHeight;t.dispatch({type:"ui/viewport",width:Math.floor(le/ae),height:Math.floor(Ae/ht)})}catch{}};L();let I;const U=()=>{clearTimeout(I),I=setTimeout(L,150)};return window.addEventListener("resize",U),window.addEventListener("orientationchange",U),()=>{clearTimeout(I),window.removeEventListener("resize",U),window.removeEventListener("orientationchange",U)}},[t]);const[o,l]=a.useState("split"),c=ee(t,L=>({themeId:L.ui.themeId,touchScale:!!L.ui.touchScale,ownerFilter:L.sessions.ownerFilter,pinnedIds:L.sessions.pinnedIds,manualOrder:L.sessions.manualOrder,collapsedSessionIds:L.sessions.collapsedIds,activeSessionId:L.sessions.activeSessionId||null,promptRows:Lc(L),rightPaneMode:L.ui.rightPaneMode||"panes",canvasOpen:L.ui.canvasOpen===!0,diagnosticsOpen:L.ui.diagnosticsOpen===!0,canvasMaximized:L.ui.canvasMaximized===!0,canvasZen:L.ui.canvasZen===!0,canvasPrefs:L.canvas?.prefs,activeSessionIsGroup:!!(L.sessions.activeSessionId&&L.sessions.byId[L.sessions.activeSessionId]?.isGroup),paneAdjust:L.ui.layout?.paneAdjust??0,sessionPaneAdjust:L.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:L.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:L.ui.layout?.activityPaneAdjust??0,canvasPaneAdjust:L.ui.layout?.canvasPaneAdjust??0,diagnosticsPaneAdjust:L.ui.layout?.diagnosticsPaneAdjust??0,diagnosticsSplitAdjust:L.ui.layout?.diagnosticsSplitAdjust??0,focusRegion:L.ui.focusRegion,requestedFocusRegion:L.ui.requestedFocusRegion,inspectorTab:L.ui.inspectorTab,filesFullscreen:!!L.files.fullscreen,selectedArtifactId:L.files.selectedArtifactId||null,artifactPaneOpen:!!L.files.paneOpen,adminVisible:!!L.admin?.visible,budgetOpen:!!L.ui?.budgetOpen}),_e),d=a.useRef(!1),p=a.useRef(null),u=a.useRef(null),f=a.useRef(null),m=a.useRef(null),h=a.useRef(null),g=a.useRef(null),b=a.useRef(!1),y=a.useRef(!1),v=a.useRef(null),E=a.useRef(null),[k,x]=a.useState("workspace"),w=(n.width||window.innerWidth||0)<Hg,C=c.activeSessionIsGroup?0:c.promptRows;BS(t,w);const M=lS(w&&k==="workspace"&&!c.adminVisible);a.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-kb-takeover",M),()=>document.body.classList.remove("ps-kb-takeover")},[M]),a.useEffect(()=>{M&&t.applyPaneVisualScrollOffset?.("chat",0,{followBottom:!0})},[M,t]);const _=ee(t,ai,_e),O=k==="canvas",R=a.useRef("workspace"),[T,N]=a.useState(!1),[j,q]=a.useState(!1);a.useEffect(()=>{x(L=>L==="canvas"?R.current||"workspace":L),N(!1),q(!1)},[_.sessionId]),a.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-canvas-lock",!!(w&&O)),()=>document.body.classList.remove("ps-canvas-lock")},[w,O]);const Z=a.useCallback(()=>{k!=="canvas"&&(R.current=k),x("canvas"),N(!0),t.dispatch({type:"ui/rightPaneMode",mode:"canvas",sessionId:_.sessionId})},[t,k,_.sessionId]),ue=a.useCallback(()=>{x(R.current||"workspace"),t.dispatch({type:"ui/rightPaneMode",mode:"panes",sessionId:_.sessionId,manual:!0})},[t,_.sessionId]),oe=a.useRef(_.flipSeq);a.useEffect(()=>{_.flipSeq!==oe.current&&(oe.current=_.flipSeq,w&&Z())},[_.flipSeq,w,Z]);const de=a.useCallback(()=>{if(O){ue();return}Z()},[O,ue,Z]);a.useEffect(()=>{let L=!0;d.current=!1,p.current=null,v.current=null,E.current=fa(t.getState()),h.current&&(clearTimeout(h.current),h.current=null),g.current&&(clearInterval(g.current),g.current=null),b.current=!1,y.current=!1;const I=t.transport;if(typeof I?.getCurrentUserProfile!="function"||typeof I?.setCurrentUserProfileSettings!="function")return d.current=!0,()=>{L=!1};const U=async()=>{if(!(!L||b.current)){b.current=!0;try{const H=await I.getCurrentUserProfile();if(!L)return;const X=Lt(H?.profileSettings);typeof X[bn()]=="boolean"&&(u.current=X[bn()]),(X.rightPaneMode==="canvas"||X.rightPaneMode==="panes")&&(f.current=X.rightPaneMode),X.desktopPanes&&(m.current=X.desktopPanes),E.current=fa(t.getState(),u.current,f.current,m.current);const ae=!fy(X)&&!ps()&&window.innerWidth>=py,le=dy(H?.profileSettings,E.current);ae&&(le.desktopPanes={canvasOpen:!0,diagnosticsOpen:!1});const Ae=JSON.stringify(le),ve=ir(t.getState(),u.current,f.current,m.current),Ke=JSON.stringify(ve),ce=d.current&&p.current!=null&&Ke!==p.current,st=!!h.current||y.current||ce;if(!st&&v.current!==Ae&&(t.dispatch({type:"profileSettings/apply",settings:le}),v.current=Ae),!d.current||!st){const re=ir(t.getState(),u.current,f.current,m.current);p.current=JSON.stringify(re)}d.current=!0}catch{if(!L)return;d.current=!0}finally{b.current=!1}}};return U().catch(()=>{}),g.current=setInterval(()=>{U().catch(()=>{})},Kg),()=>{L=!1,h.current&&(clearTimeout(h.current),h.current=null),g.current&&(clearInterval(g.current),g.current=null),b.current=!1}},[t]),a.useEffect(()=>{if(!d.current)return;const L=ir(c,u.current,f.current,m.current),I=JSON.stringify(L);p.current!==I&&(p.current=I,h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{h.current=null,y.current=!0,uy(t,L).catch(()=>{}).finally(()=>{y.current=!1})},400))},[t,c.activeSessionId,c.activityPaneAdjust,c.canvasPrefs,c.collapsedSessionIds,c.ownerFilter,c.paneAdjust,c.manualOrder,c.pinnedIds,c.portalSessionColumnAdjust,c.rightPaneMode,c.sessionPaneAdjust,c.themeId,c.touchScale]),a.useEffect(()=>{by(c.themeId),yy(c.touchScale)},[c.themeId,c.touchScale]);const A=a.useRef(null);a.useEffect(()=>{const L=A.current;if(A.current=c.focusRegion,L===null||L===c.focusRegion)return;const I=c.requestedFocusRegion;w&&(c.focusRegion==="inspector"||c.focusRegion==="activity")&&(I==="inspector"||I==="activity")&&x(c.focusRegion)},[w,c.focusRegion,c.requestedFocusRegion]),a.useEffect(()=>{const L=ki(t);!L.includes(c.inspectorTab)&&L.length>0&&t.selectInspectorTab(L[0]).catch(()=>{})},[t,c.inspectorTab]);const D=a.useMemo(()=>Is(i,c.paneAdjust,C,c.sessionPaneAdjust,c.activityPaneAdjust),[i,c.activityPaneAdjust,c.paneAdjust,C,c.sessionPaneAdjust]),F=c.filesFullscreen&&c.inspectorTab==="files",K=c.inspectorTab==="files"&&!!c.selectedArtifactId&&!F,W=!w&&c.artifactPaneOpen&&!!c.selectedArtifactId&&!F,Q=!w&&c.canvasOpen&&!F;a.useEffect(()=>{Q&&q(!0)},[Q,_.sessionId]);const J=!w&&c.diagnosticsOpen&&!F&&!W&&!(c.canvasZen&&c.canvasOpen),V=W||Q||J,Y=c.canvasMaximized&&Q,ge=c.canvasZen&&Q&&!W,fe=Math.max(260,Math.min(720,Number(c.canvasPrefs?.[c.activeSessionId]?.zenRailPx)||380));a.useEffect(()=>{if(!Y&&!ge)return;const L=I=>{I.key==="Escape"&&t.dispatch(Y?{type:"ui/canvasMaximized",on:!1}:{type:"ui/canvasZen",on:!1})};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[t,Y,ge]);const ye=Math.max(0,xi+(Number(c.canvasPaneAdjust)||0)),Te=Math.max(0,Ii+(Number(c.diagnosticsPaneAdjust)||0)),Re=(Q?ye:0)+(Q&&J?1:0)+(J?Te:0),Le=a.useCallback(()=>{t.closeArtifactPane().catch(()=>{})},[t]),De=Math.max(0,(n.width||0)*.68),Be=r.width||De,ct=my(Be,c.portalSessionColumnAdjust),We=ge?"hidden":hy(ct),G=We==="hidden"?"0px":`clamp(0px, calc(${Ei*100}% + ${Number(c.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,ne=a.createElement("div",{className:`ps-workspace-grid${V?"":" is-right-hidden"}`,style:{gridTemplateColumns:W?`minmax(0, ${D.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${D.rightWidth}fr)`:ge?`${fe}px var(--ps-resizer-track, 16px) minmax(0, 1fr)`:V?`minmax(0, 1fr) var(--ps-resizer-track, 16px) min(${Re}px, 60%)`:"minmax(0, 1fr)"}},a.createElement("div",{ref:s,className:`ps-workspace-main-grid is-session-${We}`,style:{gridTemplateColumns:`${G} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},We!=="hidden"?a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},a.createElement($r,{controller:t,structuredRows:!0})):null,a.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},a.createElement(yS,{controller:t,portalSessionColumnAdjust:c.portalSessionColumnAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},a.createElement(Lr,{controller:t}))),V?W?a.createElement(gS,{controller:t,paneAdjust:c.paneAdjust}):ge?a.createElement(SS,{controller:t,sessionId:c.activeSessionId,railPx:fe}):a.createElement(vS,{controller:t,target:Q?"canvas":"diagnostics",adjust:Q?c.canvasPaneAdjust:c.diagnosticsPaneAdjust}):null,a.createElement("div",{className:`ps-workspace-column-host is-split${Y?" has-maximized":""}`},W?a.createElement("div",{className:"ps-workspace-column is-artifact"},a.createElement(nS,{controller:t,onClose:Le})):null,j?a.createElement("div",{key:`canvas:${c.activeSessionId||""}`,className:`ps-workspace-column is-artifact ps-canvas-layer${Q&&!W?"":" is-hidden"}${Y&&Q&&!W?" is-maximized":""}`,style:Q&&!W&&J&&!Y?{flex:`0 0 ${ye}px`,minWidth:0}:void 0,...Q&&!W?{}:{inert:!0,"aria-hidden":"true"}},a.createElement(pd,{controller:t,visible:Q&&!W,maximized:Y})):null,Q&&J?a.createElement(bS,{controller:t,canvasPaneAdjust:c.canvasPaneAdjust,diagnosticsPaneAdjust:c.diagnosticsPaneAdjust}):null,J?a.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`minmax(0px, calc(50% + ${Math.round(Number(c.diagnosticsSplitAdjust)||0)}px)) var(--ps-resizer-track, 16px) minmax(0px, 1fr)`,...Q?{flex:"1 1 0%",minWidth:0}:null}},a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},a.createElement(vs,{controller:t,mobile:!1})),a.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},a.createElement(wS,{controller:t,splitAdjust:c.diagnosticsSplitAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},K?a.createElement(Pn,{controller:t,focused:!1,previewOnly:!0}):a.createElement(pr,{controller:t}))):null)),Se=a.createElement("div",{className:"ps-workspace-full"},a.createElement(vs,{controller:t,mobile:!1}));let B=null;F&&!w?B=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(vs,{controller:t,mobile:!0})):k==="inspector"?B=c.inspectorTab==="nodes"?a.createElement("div",{className:"ps-mobile-pane-fill ps-mobile-node-split"},a.createElement(vs,{controller:t,mobile:!0}),a.createElement(pr,{controller:t,panelClassName:"ps-mobile-node-detail"})):a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(vs,{controller:t,mobile:!0})):k==="activity"?B=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(pr,{controller:t})):k==="canvas"?B=null:B=a.createElement(cS,{controller:t,layout:o});const z=w&&T?a.createElement(rS,{key:`canvas:${_.sessionId||""}`,controller:t,visible:O}):null;return a.createElement(jc.Provider,{value:t},a.createElement("div",{ref:e,className:"ps-web-shell"},a.createElement(hS,{controller:t,mobile:w,canvasPaneOpen:O,onToggleCanvasPane:de,mobilePane:k,mobileMainLayout:o,onSelectMobilePane:(L,I)=>{L==="workspace"&&k==="workspace"&&l(U=>U==="split"?"chat":U==="chat"?"sessions":"split"),t.closeBudget(),x(L),I&&t.setFocus(I)}}),a.createElement("div",{className:"ps-workspace"},c.adminVisible?a.createElement(HS,{controller:t,mobile:w}):c.budgetOpen?a.createElement(OS,{controller:t}):F?Se:w?B:ne,z),w&&F?a.createElement(iS,{controller:t}):null,a.createElement(FS,{controller:t})))}export{QS as P,a as R,Cc as _,Ed as a,pt as b,XS as c,Dr as d,VS as e,sm as f,bd as g,za as r,YS as s};
|