pilotswarm 0.5.69 → 0.5.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/ui/core/src/controller.js +3 -1
- package/ui/core/src/history.js +3 -1
- package/ui/core/src/moa.js +2 -2
- package/ui/core/src/native-tasks.js +46 -2
- package/ui/core/src/reducer.js +14 -2
- package/ui/core/src/selectors.js +41 -16
- package/ui/core/src/session-sort.js +45 -0
- package/ui/core/src/state.js +3 -0
- package/ui/react/src/chat-call-line.js +17 -0
- package/ui/react/src/native-task-card.js +53 -23
- package/ui/react/src/web-app.js +100 -48
- package/web/dist/assets/{abnfDiagram-VRR7QNED-DCEEpIGf.js → abnfDiagram-VRR7QNED-C1caNr4U.js} +1 -1
- package/web/dist/assets/{arc-_RJw0dJ3.js → arc-BufdFJYK.js} +1 -1
- package/web/dist/assets/{architectureDiagram-ZJ3FMSHR-Bze_PsYG.js → architectureDiagram-ZJ3FMSHR-C0vQblUK.js} +1 -1
- package/web/dist/assets/{blockDiagram-677ZJIJ3-CZaMO9H-.js → blockDiagram-677ZJIJ3-B6PYWI9u.js} +1 -1
- package/web/dist/assets/{c4Diagram-LMCZKHZV-Dzr58V1d.js → c4Diagram-LMCZKHZV-DFoaVeMm.js} +1 -1
- package/web/dist/assets/channel-CDzPwSI9.js +1 -0
- package/web/dist/assets/{chunk-2Q5K7J3B-1IO7uTFx.js → chunk-2Q5K7J3B-CxFBb-8y.js} +1 -1
- package/web/dist/assets/{chunk-32BRIVSS-DKdpRP0l.js → chunk-32BRIVSS-DO1G8AVc.js} +1 -1
- package/web/dist/assets/{chunk-5VM5RSS4-CxyhZOh5.js → chunk-5VM5RSS4-spE4bKSd.js} +1 -1
- package/web/dist/assets/{chunk-EX3LRPZG-DWY7moCs.js → chunk-EX3LRPZG-Bc_eUP5F.js} +1 -1
- package/web/dist/assets/{chunk-JWPE2WC7-By7oiTbd.js → chunk-JWPE2WC7-CGM2GAMX.js} +1 -1
- package/web/dist/assets/{chunk-MOJQB5TN-CS-m-Pv3.js → chunk-MOJQB5TN-CHdrVT1z.js} +1 -1
- package/web/dist/assets/{chunk-RYQCIY6F-Cxykz4-E.js → chunk-RYQCIY6F-BWJK7-AW.js} +1 -1
- package/web/dist/assets/{chunk-V7JOEXUC-Dwl0aU9m.js → chunk-V7JOEXUC-D8tgpQwK.js} +1 -1
- package/web/dist/assets/{chunk-VR4S4FIN-BERWiLR7.js → chunk-VR4S4FIN-BP86JfVu.js} +1 -1
- package/web/dist/assets/{chunk-XXDRQBXY-CZ0e721z.js → chunk-XXDRQBXY-Ctq_LUrs.js} +1 -1
- package/web/dist/assets/classDiagram-OUVF2IWQ-DdcABn-U.js +1 -0
- package/web/dist/assets/classDiagram-v2-EOCWNBFH-DdcABn-U.js +1 -0
- package/web/dist/assets/{cose-bilkent-JH36ORCC-RLgoKX1J.js → cose-bilkent-JH36ORCC-DNvC4thT.js} +1 -1
- package/web/dist/assets/{cynefin-VYW2F7L2-CUvcvCFo.js → cynefin-VYW2F7L2-3zVj2GvI.js} +1 -1
- package/web/dist/assets/{cynefinDiagram-TSTJHNR4-D2ML_npa.js → cynefinDiagram-TSTJHNR4-DQbITfsJ.js} +1 -1
- package/web/dist/assets/{dagre-VKFMJZFB-BHG6-avE.js → dagre-VKFMJZFB-BkGAcDyj.js} +1 -1
- package/web/dist/assets/{diagram-FQU43EPY-ynOb8q0h.js → diagram-FQU43EPY-D3lsgelm.js} +1 -1
- package/web/dist/assets/{diagram-G47NLZAW-BLHAADd0.js → diagram-G47NLZAW-C2rO9e3d.js} +1 -1
- package/web/dist/assets/{diagram-NH7WQ7WH-DwOMd4DW.js → diagram-NH7WQ7WH-DJBwtT8q.js} +1 -1
- package/web/dist/assets/{diagram-OA4YK3LP-DZWnpqT9.js → diagram-OA4YK3LP-C-SAwEHZ.js} +1 -1
- package/web/dist/assets/{diagram-WEI45ONY-BMcvO3Pf.js → diagram-WEI45ONY-BpXMlmKz.js} +1 -1
- package/web/dist/assets/{ebnfDiagram-CCIWWBDH-CRX9h0gP.js → ebnfDiagram-CCIWWBDH-DwxUgEmE.js} +1 -1
- package/web/dist/assets/{erDiagram-Q63AITRT-Con2S52S.js → erDiagram-Q63AITRT-DNZMCmYz.js} +1 -1
- package/web/dist/assets/{flowDiagram-23GEKE2U-wg4unvdR.js → flowDiagram-23GEKE2U-CUlGtnWV.js} +1 -1
- package/web/dist/assets/{ganttDiagram-NO4QXBWP-CAg65Xfj.js → ganttDiagram-NO4QXBWP-DCj6zkyt.js} +1 -1
- package/web/dist/assets/{gitGraphDiagram-IHSO6WYX-5u02gmfN.js → gitGraphDiagram-IHSO6WYX-Q6UP_dgi.js} +1 -1
- package/web/dist/assets/index-23y0f1it.js +24 -0
- package/web/dist/assets/index-BXR-II2L.css +1 -0
- package/web/dist/assets/{infoDiagram-FWYZ7A6U-DW830L4J.js → infoDiagram-FWYZ7A6U-Cwn8XNQT.js} +1 -1
- package/web/dist/assets/{ishikawaDiagram-FXEZZL3T-6Qr30UBj.js → ishikawaDiagram-FXEZZL3T-BaMvGBAo.js} +1 -1
- package/web/dist/assets/{journeyDiagram-5HDEW3XC-BHCjdAv1.js → journeyDiagram-5HDEW3XC-DK95FJ0t.js} +1 -1
- package/web/dist/assets/{kanban-definition-HUTT4EX6-PGpXvhY7.js → kanban-definition-HUTT4EX6-C6W6RJLm.js} +1 -1
- package/web/dist/assets/{linear-CuN5Qi_I.js → linear-Un37Oyxr.js} +1 -1
- package/web/dist/assets/{mermaid.core-BEG_GOf7.js → mermaid.core-i8uqvLPa.js} +4 -4
- package/web/dist/assets/{mindmap-definition-LN4V7U3C-Bbi2gb0f.js → mindmap-definition-LN4V7U3C-d_cgq1KW.js} +1 -1
- package/web/dist/assets/{papaparse.min-LDhOsJ62.js → papaparse.min-BiJEkQ8f.js} +1 -1
- package/web/dist/assets/{pegDiagram-2B236MQR-IZ3AowOt.js → pegDiagram-2B236MQR-5QRWM5AP.js} +1 -1
- package/web/dist/assets/{pieDiagram-ENE6RG2P-QnG3Rlhe.js → pieDiagram-ENE6RG2P-VIZXsjFV.js} +1 -1
- package/web/dist/assets/pilotswarm-D7Q48waO.js +109 -0
- package/web/dist/assets/{quadrantDiagram-ABIIQ3AL-BIB7xhGf.js → quadrantDiagram-ABIIQ3AL-DMOx841b.js} +1 -1
- package/web/dist/assets/{railroadDiagram-RFXS5EU6-CHbggWfd.js → railroadDiagram-RFXS5EU6-lTWzjdcd.js} +1 -1
- package/web/dist/assets/{requirementDiagram-TGXJPOKE-CgNGJVBn.js → requirementDiagram-TGXJPOKE-BE5SpiNy.js} +1 -1
- package/web/dist/assets/{sankeyDiagram-HTMAVEWB-B1GfGCwn.js → sankeyDiagram-HTMAVEWB-C3LYWQTA.js} +1 -1
- package/web/dist/assets/{sequenceDiagram-DBY2YBRQ-D-Bfj-RU.js → sequenceDiagram-DBY2YBRQ-BTCp88tQ.js} +1 -1
- package/web/dist/assets/{sizeCapture-X5ZJPWSS-Ca-mVfMN.js → sizeCapture-X5ZJPWSS-Ppzj8n5l.js} +1 -1
- package/web/dist/assets/{stateDiagram-2N3HPSRC-5gIoJ_8A.js → stateDiagram-2N3HPSRC-Ch_iZ_cQ.js} +1 -1
- package/web/dist/assets/stateDiagram-v2-6OUMAXLB-BbJN7t8_.js +1 -0
- package/web/dist/assets/{swimlanes-5IMT3BWC-HxN6_3nA.js → swimlanes-5IMT3BWC-BX4-Oeby.js} +2 -2
- package/web/dist/assets/swimlanesDiagram-G3AALYLV-0UA1VebA.js +8 -0
- package/web/dist/assets/{timeline-definition-FHXFAJF6-CSkNwYwY.js → timeline-definition-FHXFAJF6-B1l-6l6u.js} +1 -1
- package/web/dist/assets/{vennDiagram-L72KCM5P-o6qvAiNl.js → vennDiagram-L72KCM5P-Grpa6wFZ.js} +1 -1
- package/web/dist/assets/{wardleyDiagram-EHGQE667-HcUO3YZZ.js → wardleyDiagram-EHGQE667-B5bXnFlL.js} +1 -1
- package/web/dist/assets/{xychartDiagram-FW5EYKEG-DmNJJPi3.js → xychartDiagram-FW5EYKEG-BkELQtgc.js} +1 -1
- package/web/dist/index.html +3 -3
- package/web/dist/assets/channel-CHAZ3LVB.js +0 -1
- package/web/dist/assets/classDiagram-OUVF2IWQ-CXv3ioyD.js +0 -1
- package/web/dist/assets/classDiagram-v2-EOCWNBFH-CXv3ioyD.js +0 -1
- package/web/dist/assets/index-BT3MiUPE.css +0 -1
- package/web/dist/assets/index-DzjecAo8.js +0 -24
- package/web/dist/assets/pilotswarm-BNTnbu9f.js +0 -109
- package/web/dist/assets/stateDiagram-v2-6OUMAXLB-C_IKdqOV.js +0 -1
- package/web/dist/assets/swimlanesDiagram-G3AALYLV-B8jNOz1z.js +0 -8
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
function rp(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var gr={exports:{}},ue={};var Ua;function ip(){if(Ua)return ue;Ua=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"),u=Symbol.for("react.lazy"),p=Symbol.for("react.activity"),m=Symbol.iterator;function f(C){return C===null||typeof C!="object"?null:(C=m&&C[m]||C["@@iterator"],typeof C=="function"?C:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,b={};function y(C,U,H){this.props=C,this.context=U,this.refs=b,this.updater=H||h}y.prototype.isReactComponent={},y.prototype.setState=function(C,U){if(typeof C!="object"&&typeof C!="function"&&C!=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,C,U,"setState")},y.prototype.forceUpdate=function(C){this.updater.enqueueForceUpdate(this,C,"forceUpdate")};function S(){}S.prototype=y.prototype;function v(C,U,H){this.props=C,this.context=U,this.refs=b,this.updater=H||h}var w=v.prototype=new S;w.constructor=v,g(w,y.prototype),w.isPureReactComponent=!0;var E=Array.isArray;function k(){}var x={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function A(C,U,H){var Y=H.ref;return{$$typeof:t,type:C,key:U,ref:Y!==void 0?Y:null,props:H}}function R(C,U){return A(C.type,U,C.props)}function N(C){return typeof C=="object"&&C!==null&&C.$$typeof===t}function $(C){var U={"=":"=0",":":"=2"};return"$"+C.replace(/[=:]/g,function(H){return U[H]})}var F=/\/+/g;function I(C,U){return typeof C=="object"&&C!==null&&C.key!=null?$(""+C.key):U.toString(36)}function O(C){switch(C.status){case"fulfilled":return C.value;case"rejected":throw C.reason;default:switch(typeof C.status=="string"?C.then(k,k):(C.status="pending",C.then(function(U){C.status==="pending"&&(C.status="fulfilled",C.value=U)},function(U){C.status==="pending"&&(C.status="rejected",C.reason=U)})),C.status){case"fulfilled":return C.value;case"rejected":throw C.reason}}throw C}function M(C,U,H,Y,te){var ee=typeof C;(ee==="undefined"||ee==="boolean")&&(C=null);var J=!1;if(C===null)J=!0;else switch(ee){case"bigint":case"string":case"number":J=!0;break;case"object":switch(C.$$typeof){case t:case e:J=!0;break;case u:return J=C._init,M(J(C._payload),U,H,Y,te)}}if(J)return te=te(C),J=Y===""?"."+I(C,0):Y,E(te)?(H="",J!=null&&(H=J.replace(F,"$&/")+"/"),M(te,U,H,"",function(Z){return Z})):te!=null&&(N(te)&&(te=R(te,H+(te.key==null||C&&C.key===te.key?"":(""+te.key).replace(F,"$&/")+"/")+J)),U.push(te)),1;J=0;var ae=Y===""?".":Y+":";if(E(C))for(var de=0;de<C.length;de++)Y=C[de],ee=ae+I(Y,de),J+=M(Y,U,H,ee,te);else if(de=f(C),typeof de=="function")for(C=de.call(C),de=0;!(Y=C.next()).done;)Y=Y.value,ee=ae+I(Y,de++),J+=M(Y,U,H,ee,te);else if(ee==="object"){if(typeof C.then=="function")return M(O(C),U,H,Y,te);throw U=String(C),Error("Objects are not valid as a React child (found: "+(U==="[object Object]"?"object with keys {"+Object.keys(C).join(", ")+"}":U)+"). If you meant to render a collection of children, use an array instead.")}return J}function B(C,U,H){if(C==null)return C;var Y=[],te=0;return M(C,Y,"","",function(ee){return U.call(H,ee,te++)}),Y}function D(C){if(C._status===-1){var U=C._result;U=U(),U.then(function(H){(C._status===0||C._status===-1)&&(C._status=1,C._result=H)},function(H){(C._status===0||C._status===-1)&&(C._status=2,C._result=H)}),C._status===-1&&(C._status=0,C._result=U)}if(C._status===1)return C._result.default;throw C._result}var j=typeof reportError=="function"?reportError:function(C){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var U=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof C=="object"&&C!==null&&typeof C.message=="string"?String(C.message):String(C),error:C});if(!window.dispatchEvent(U))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",C);return}console.error(C)},V={map:B,forEach:function(C,U,H){B(C,function(){U.apply(this,arguments)},H)},count:function(C){var U=0;return B(C,function(){U++}),U},toArray:function(C){return B(C,function(U){return U})||[]},only:function(C){if(!N(C))throw Error("React.Children.only expected to receive a single React element child.");return C}};return ue.Activity=p,ue.Children=V,ue.Component=y,ue.Fragment=s,ue.Profiler=r,ue.PureComponent=v,ue.StrictMode=n,ue.Suspense=c,ue.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=x,ue.__COMPILER_RUNTIME={__proto__:null,c:function(C){return x.H.useMemoCache(C)}},ue.cache=function(C){return function(){return C.apply(null,arguments)}},ue.cacheSignal=function(){return null},ue.cloneElement=function(C,U,H){if(C==null)throw Error("The argument must be a React element, but you passed "+C+".");var Y=g({},C.props),te=C.key;if(U!=null)for(ee in U.key!==void 0&&(te=""+U.key),U)!T.call(U,ee)||ee==="key"||ee==="__self"||ee==="__source"||ee==="ref"&&U.ref===void 0||(Y[ee]=U[ee]);var ee=arguments.length-2;if(ee===1)Y.children=H;else if(1<ee){for(var J=Array(ee),ae=0;ae<ee;ae++)J[ae]=arguments[ae+2];Y.children=J}return A(C.type,te,Y)},ue.createContext=function(C){return C={$$typeof:o,_currentValue:C,_currentValue2:C,_threadCount:0,Provider:null,Consumer:null},C.Provider=C,C.Consumer={$$typeof:i,_context:C},C},ue.createElement=function(C,U,H){var Y,te={},ee=null;if(U!=null)for(Y in U.key!==void 0&&(ee=""+U.key),U)T.call(U,Y)&&Y!=="key"&&Y!=="__self"&&Y!=="__source"&&(te[Y]=U[Y]);var J=arguments.length-2;if(J===1)te.children=H;else if(1<J){for(var ae=Array(J),de=0;de<J;de++)ae[de]=arguments[de+2];te.children=ae}if(C&&C.defaultProps)for(Y in J=C.defaultProps,J)te[Y]===void 0&&(te[Y]=J[Y]);return A(C,ee,te)},ue.createRef=function(){return{current:null}},ue.forwardRef=function(C){return{$$typeof:l,render:C}},ue.isValidElement=N,ue.lazy=function(C){return{$$typeof:u,_payload:{_status:-1,_result:C},_init:D}},ue.memo=function(C,U){return{$$typeof:d,type:C,compare:U===void 0?null:U}},ue.startTransition=function(C){var U=x.T,H={};x.T=H;try{var Y=C(),te=x.S;te!==null&&te(H,Y),typeof Y=="object"&&Y!==null&&typeof Y.then=="function"&&Y.then(k,j)}catch(ee){j(ee)}finally{U!==null&&H.types!==null&&(U.types=H.types),x.T=U}},ue.unstable_useCacheRefresh=function(){return x.H.useCacheRefresh()},ue.use=function(C){return x.H.use(C)},ue.useActionState=function(C,U,H){return x.H.useActionState(C,U,H)},ue.useCallback=function(C,U){return x.H.useCallback(C,U)},ue.useContext=function(C){return x.H.useContext(C)},ue.useDebugValue=function(){},ue.useDeferredValue=function(C,U){return x.H.useDeferredValue(C,U)},ue.useEffect=function(C,U){return x.H.useEffect(C,U)},ue.useEffectEvent=function(C){return x.H.useEffectEvent(C)},ue.useId=function(){return x.H.useId()},ue.useImperativeHandle=function(C,U,H){return x.H.useImperativeHandle(C,U,H)},ue.useInsertionEffect=function(C,U){return x.H.useInsertionEffect(C,U)},ue.useLayoutEffect=function(C,U){return x.H.useLayoutEffect(C,U)},ue.useMemo=function(C,U){return x.H.useMemo(C,U)},ue.useOptimistic=function(C,U){return x.H.useOptimistic(C,U)},ue.useReducer=function(C,U,H){return x.H.useReducer(C,U,H)},ue.useRef=function(C){return x.H.useRef(C)},ue.useState=function(C){return x.H.useState(C)},ue.useSyncExternalStore=function(C,U,H){return x.H.useSyncExternalStore(C,U,H)},ue.useTransition=function(){return x.H.useTransition()},ue.version="19.2.4",ue}var ja;function fc(){return ja||(ja=1,gr.exports=ip()),gr.exports}var ap=fc();const a=rp(ap);var yr={exports:{}},Ve={};var Ga;function op(){if(Ga)return Ve;Ga=1;var t=fc();function e(c){var d="https://react.dev/errors/"+c;if(1<arguments.length){d+="?args[]="+encodeURIComponent(arguments[1]);for(var u=2;u<arguments.length;u++)d+="&args[]="+encodeURIComponent(arguments[u])}return"Minified React error #"+c+"; visit "+d+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(){}var n={d:{f:s,r:function(){throw Error(e(522))},D:s,C:s,L:s,m:s,X:s,S:s,M:s},p:0,findDOMNode:null},r=Symbol.for("react.portal");function i(c,d,u){var p=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:r,key:p==null?null:""+p,children:c,containerInfo:d,implementation:u}}var o=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,d){if(c==="font")return"";if(typeof d=="string")return d==="use-credentials"?d:""}return Ve.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,Ve.createPortal=function(c,d){var u=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!d||d.nodeType!==1&&d.nodeType!==9&&d.nodeType!==11)throw Error(e(299));return i(c,d,null,u)},Ve.flushSync=function(c){var d=o.T,u=n.p;try{if(o.T=null,n.p=2,c)return c()}finally{o.T=d,n.p=u,n.d.f()}},Ve.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))},Ve.prefetchDNS=function(c){typeof c=="string"&&n.d.D(c)},Ve.preinit=function(c,d){if(typeof c=="string"&&d&&typeof d.as=="string"){var u=d.as,p=l(u,d.crossOrigin),m=typeof d.integrity=="string"?d.integrity:void 0,f=typeof d.fetchPriority=="string"?d.fetchPriority:void 0;u==="style"?n.d.S(c,typeof d.precedence=="string"?d.precedence:void 0,{crossOrigin:p,integrity:m,fetchPriority:f}):u==="script"&&n.d.X(c,{crossOrigin:p,integrity:m,fetchPriority:f,nonce:typeof d.nonce=="string"?d.nonce:void 0})}},Ve.preinitModule=function(c,d){if(typeof c=="string")if(typeof d=="object"&&d!==null){if(d.as==null||d.as==="script"){var u=l(d.as,d.crossOrigin);n.d.M(c,{crossOrigin:u,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0})}}else d==null&&n.d.M(c)},Ve.preload=function(c,d){if(typeof c=="string"&&typeof d=="object"&&d!==null&&typeof d.as=="string"){var u=d.as,p=l(u,d.crossOrigin);n.d.L(c,u,{crossOrigin:p,integrity:typeof d.integrity=="string"?d.integrity:void 0,nonce:typeof d.nonce=="string"?d.nonce:void 0,type:typeof d.type=="string"?d.type:void 0,fetchPriority:typeof d.fetchPriority=="string"?d.fetchPriority:void 0,referrerPolicy:typeof d.referrerPolicy=="string"?d.referrerPolicy:void 0,imageSrcSet:typeof d.imageSrcSet=="string"?d.imageSrcSet:void 0,imageSizes:typeof d.imageSizes=="string"?d.imageSizes:void 0,media:typeof d.media=="string"?d.media:void 0})}},Ve.preloadModule=function(c,d){if(typeof c=="string")if(d){var u=l(d.as,d.crossOrigin);n.d.m(c,{as:typeof d.as=="string"&&d.as!=="script"?d.as:void 0,crossOrigin:u,integrity:typeof d.integrity=="string"?d.integrity:void 0})}else n.d.m(c)},Ve.requestFormReset=function(c){n.d.r(c)},Ve.unstable_batchedUpdates=function(c,d){return c(d)},Ve.useFormState=function(c,d,u){return o.H.useFormState(c,d,u)},Ve.useFormStatus=function(){return o.H.useHostTransitionStatus()},Ve.version="19.2.4",Ve}var Wa;function lp(){if(Wa)return yr.exports;Wa=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(),yr.exports=op(),yr.exports}var Rs=lp();const cp=a.createContext(null);function pt(){const t=a.useContext(cp);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function se(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 qa=[". ",".. ","..."],za=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function ji(t,e=120){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!t){n(0);return}const r=setInterval(()=>{n(i=>(i+1)%za.length)},e);return()=>clearInterval(r)},[t,e]),t?za[s]:""}function hc(t,e=360){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!t){n(0);return}const r=setInterval(()=>{n(i=>(i+1)%qa.length)},e);return()=>clearInterval(r)},[t,e]),t?qa[s]:""}function gc(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 L={SESSIONS:"sessions",CHAT:"chat",INSPECTOR:"inspector",ACTIVITY:"activity",PROMPT:"prompt",ADMIN:"admin"},gt=["sequence","logs","nodes","history","files","stats"],_={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",OPEN_WORKSPACE:"openWorkspace",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 cs(t,e,s){const n=t.indexOf(e),i=((n===-1?0:n)+s+t.length)%t.length;return t[i]}function Gi(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 ai(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 dp(t){const e=Gi(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function up(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=Gi(t);return e==null?null:{text:`ctx ${ai(t.currentTokens)}/${ai(t.tokenLimit)} ${e}%`,color:dp(t)}}function pp(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 yc(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function mp(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function bc(t,e,s={},n={}){if(!e)return null;const r=yc(t)||{},i=mp(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 fp(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 ${ai(s.tokensRemoved)}`,color:"gray"}]:[]]}const oi=/\{(\/?)([a-z-]+)\}/g,hp={color:null,bold:!1,underline:!1},_n=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,Ka=/session:\/\/([A-Za-z0-9-]+)/g,wn=" (press a to download)",gp={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function En(t){return{color:t.color,bold:t.bold,underline:t.underline}}function yp(t,e,s){const n=En(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:gp[r]||null,n}return n}function Wi(t){return String(t||"").replace(oi,"")}function Sc(t){const e=[],n=String(t||"").split(`
|
|
2
|
-
`);for(const r of n){const i=[];let o=En(hp),l=0,c;for(;(c=oi.exec(r))!==null;){const[d,u,p]=c;c.index>l&&i.push({text:r.slice(l,c.index),...En(o)}),o=yp(o,p,u==="/"),l=c.index+d.length}(l<r.length||i.length===0)&&i.push({text:r.slice(l),...En(o)}),e.push(i),oi.lastIndex=0}return e}function _e(t){return String(t||"").slice(0,8)}function Cs(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}let br=null,Sr=null,vr=null,wr=null;function bp(){return br||(br=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})),br}function vc(){return Sr||(Sr=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})),Sr}function Sp(){return vr||(vr=new Intl.DateTimeFormat("en-GB",{month:"short"})),vr}function vp(){return wr||(wr=new Intl.DateTimeFormat("en-GB",{month:"short",day:"numeric"})),wr}function wc(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 vc().format(s);const r=bp().format(s),i=String(s.getDate()),o=Sp().format(s),l=s.getFullYear()===e.getFullYear()?"":String(s.getFullYear()).slice(-2);return`${i}${o}${l} ${r}`}catch{return""}}function We(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t),n=vc().format(s);if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return n;const i=vp().format(s),o=s.getFullYear()===e.getFullYear()?"":` ${s.getFullYear()}`;return`${i}${o} ${n}`}catch{return""}}function Zt(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 Ec(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function wp(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function $n(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function Va(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!($n(r)&&$n(n))}function Ep(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!($n(n)&&$n(r))}function Ya(t,e,s){let n=s;for(;n<t.length;){const r=t.indexOf(e,n);if(r<0)return-1;if(Ep(t,r,e))return r;n=r+e.length}return-1}function kp(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 Ip(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function ln(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 _t(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 kc(t){return(t||[]).map(e=>e?.text||"").join("")}function kn(t){return dt(kc(t))}function xp(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=tn(o,r);l&&(n.push({...i,text:l}),r-=dt(l))}return n}function Ic(t,e){const s=Math.max(0,Number(e)||0),n=xp(t,s),r=kn(n),i=Math.max(0,s-r);return i>0&&n.push({text:" ".repeat(i),color:null,bold:!1,underline:!1}),n}function xc(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),u=tn(c,d);if(!u)break;if(u.length===c.length||dt(u)<d){r.push({...l,text:u}),i+=dt(u),c=c.slice(u.length),i>=s&&o();continue}const p=u.lastIndexOf(" ");if(p>0&&(i>0||p>0)){const m=u.slice(0,p+1);r.push({...l,text:m}),i+=dt(m),c=c.slice(m.length),o()}else r.push({...l,text:u}),i+=dt(u),c=c.slice(u.length),i>=s&&o()}}return(r.length>0||n.length===0)&&o(),n}function Xa(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function Ac(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 Ap(t){const e=String(t||"");return _n.lastIndex=0,[...e.matchAll(_n)].map(s=>{const n=s[1],r=Ac(s[2]);return!n||!r?null:{sessionId:n,filename:r,uri:`artifact://${n}/${r}`}}).filter(Boolean)}function Vt(t){const e=String(t||"");if(!e)return e;_n.lastIndex=0;const s=e.replace(_n,(n,r,i,o,l)=>{if(l.slice(Math.max(0,o-2),o)==="](")return n;const c=Ac(i);return!r||!c?n:`[artifact: ${c}](artifact://${r}/${c})${wn}`});return Ka.lastIndex=0,s.replace(Ka,(n,r)=>r?`[session: ${_e(r)}](session://${r})`:n)}function qi(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const i=Ip(e,"`",n),o="`".repeat(i),l=wp(e,o,n+i);if(l>n+i-1){_t(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=Va(e,n,i)?Ya(e,i,n+2):-1;if(o>n+2){_t(s,{type:"strong",text:e.slice(n+2,o)}),n=o+2;continue}}if(e[n]==="["){const i=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(i){_t(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);_t(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}=kp(e.slice(n,i));if(o){_t(s,{type:"link",text:o,href:o}),l&&_t(s,{type:"text",text:l}),n=i;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&Va(e,n,e[n])){const i=e[n],o=Ya(e,i,n+1);if(o>n+1){_t(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)}_t(s,{type:"text",text:e.slice(n,r)}),n=r}return s.length>0?s:[{type:"text",text:""}]}function Np(t=""){return qi(t).filter(e=>e?.type==="link"&&/^https?:\/\//i.test(String(e?.href||""))).map(e=>({href:String(e.href||"").trim(),text:String(e.text||e.href||"").trim()})).filter(e=>e.href)}function Kt(t,e=0){if(e>=32)return[{text:String(t||""),color:null,bold:!1,underline:!1}];const s=qi(t),n=[];for(const r of s){if(r.type==="code"){ln(n,r.text,{color:"cyan"});continue}if(r.type==="strong"||r.type==="em"){for(const i of Kt(r.text,e+1))ln(n,i.text,{...i,...r.type==="strong"?{bold:!0}:{underline:!0}});continue}if(r.type==="link"){ln(n,r.text,{color:"cyan",underline:!0,href:r.href});continue}ln(n,r.text)}return n.length>0?n:[{text:"",color:null,bold:!1,underline:!1}]}function ys(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function bs(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 Rn(t){return t.length>0&&t.every(e=>/^:?-+:?$/.test(String(e||"").replace(/\s+/g,"")))}function dt(t){return Array.from(String(t||"")).length}function tn(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 Nc(t,e){const s=String(t||""),n=Math.max(0,e-dt(s));return s+" ".repeat(n)}function Cc(t){return kc(Kt(t))}function Cp(t,e){const s=Cc(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),r=[];let i="";const o=l=>{let c=l;for(;dt(c)>e;){const d=tn(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}`;dt(d)<=e?i=d:(r.push(i),i=c)}return i&&r.push(i),r.length>0?r:[""]}function Tp(t,e){const s=Math.max(1,...t.map(u=>u.length)),n=Math.max(s*3,e-(s*3+1)),r=Array.from({length:s},(u,p)=>Math.max(3,...t.map(m=>dt(m[p]||"")))),i=Array.from({length:s},(u,p)=>Math.max(3,...t.map(m=>Math.max(0,...String(m[p]||"").split(/\s+/).filter(Boolean).map(f=>dt(f)))))),o=Array.from({length:s},(u,p)=>Math.max(3,Math.min(Math.max(dt(t[0]?.[p]||"")||3,i[p]),24)));if(r.reduce((u,p)=>u+p,0)<=n)return r;const c=o.slice();let d=n-c.reduce((u,p)=>u+p,0);if(d<0){const u=Math.max(3,Math.floor(n/s));return c.map((p,m)=>m===s-1?Math.max(3,n-u*(s-1)):u)}for(;d>0;){let u=0,p=-1/0;for(let m=0;m<s;m++){const f=r[m]-c[m];f>p&&(p=f,u=m)}if(p<=0){c[s-1]+=d;break}c[u]+=1,d-=1}return c}function Pp(t,e){if(!t||t.length===0)return"";const s=Math.max(1,...t.map(m=>m.length)),r=t.map(m=>Array.from({length:s},(f,h)=>m[h]||"")).map(m=>m.map(f=>Cc(f))),i=Tp(r,e),o=[],l=`┌${i.map(m=>"─".repeat(m+2)).join("┬")}┐`,c=`├${i.map(m=>"─".repeat(m+2)).join("┼")}┤`,d=`└${i.map(m=>"─".repeat(m+2)).join("┴")}┘`,u=m=>{const f=m.map((g,b)=>Cp(g,i[b])),h=Math.max(...f.map(g=>g.length));for(let g=0;g<h;g++){const b=f.map((y,S)=>Nc(y[g]||"",i[S]));o.push(`│ ${b.join(" │ ")} │`)}};o.push(l),u(r[0]),o.push(c);const p=r.slice(1);for(const m of p)u(m);return o.push(d),o.join(`
|
|
3
|
-
`)}function Mp(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(!ys(o)||!ys(c)){n.push(o);continue}const d=bs(o),u=bs(c);if(!Rn(u)||d.length!==u.length){n.push(o);continue}const p=[d];for(i+=1;i+1<s.length&&ys(s[i+1]);){i+=1;const m=bs(s[i]);Rn(m)||p.push(m)}n.push(Pp(p,e))}return n.join(`
|
|
5
|
-
`)}function _p(t,e){const s=String(t||"");if(!s)return[""];const n=[];let r=s;for(;r.length>0;){const i=tn(r,e);if(!i)break;n.push(i),r=r.slice(i.length)}return n.length>0?n:[""]}function Qa(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",r=tn(n,Math.max(1,s-4)),i=Math.max(0,s-r.length-2);return[{text:`┌${r}${"─".repeat(i)}┐`,color:"gray"}]}function Za(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function Ja(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),r=[];for(const i of t){const o=_p(i,n);for(const l of o)r.push([{text:"│",color:"gray"},{text:Nc(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 ss(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),r=e.tableMode==="sentinel"?"sentinel":"boxArt",o=(r==="boxArt"?Mp(String(t||""),n):String(t||"")).split(`
|
|
6
|
-
`);let l=!1,c="",d=[];for(let u=0;u<o.length;u+=1){const p=o[u],m=p.trim();if(m.startsWith("```")){l?(s.push(Qa(c,Math.max(8,n))),s.push(...Ja(d,Math.max(8,n))),s.push(Za(Math.max(8,n))),l=!1,c="",d=[]):(l=!0,c=m.slice(3).trim(),d=[]);continue}if(l){d.push(p);continue}if(r==="sentinel"&&p&&ys(p)){const y=o[u+1]||"";if(ys(y)){const S=bs(p),v=bs(y);if(Rn(v)&&S.length===v.length){const w=[];let E=u+2;for(;E<o.length&&ys(o[E]);){const k=bs(o[E]);Rn(k)||w.push(k),E+=1}s.push({kind:"markdownTable",header:S,rows:w}),u=E-1;continue}}}if(!p){s.push([{text:"",color:null}]);continue}const f=/^(#{1,6})\s+(.*)$/.exec(p);if(f){s.push(Kt(f[2]).map(y=>({...y,color:y.color||"white",bold:!0})));continue}const h=/^>\s?(.*)$/.exec(p);if(h){s.push([{text:"> ",color:"gray"},...Kt(h[1]).map(y=>({...y,color:y.color||"gray"}))]);continue}const g=/^\s*[-*]\s+(.*)$/.exec(p);if(g){s.push([{text:"• ",color:"gray"},...Kt(g[1])]);continue}const b=/^\s*(\d+)\.\s+(.*)$/.exec(p);if(b){s.push([{text:`${b[1]}. `,color:"gray"},...Kt(b[2])]);continue}s.push(Kt(p))}return l&&(s.push(Qa(c,Math.max(8,n))),s.push(...Ja(d,Math.max(8,n))),s.push(Za(Math.max(8,n)))),s}function He({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,cardKey:d=null}={}){const u=Math.max(l?12:20,Number(n)||(l?12:20)),p=Math.max(1,u-4),m=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:r,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]];if(c==="sentinel"){const w=ss(String(s||""),{width:p,tableMode:c}),E=o?w.map(k=>Array.isArray(k)?Xa(k,o):k):w;return[{kind:"cardStart",runs:m,borderColor:i,...d?{cardKey:d}:{}},...E,{kind:"cardEnd"},[{text:"",color:null}]]}const f=ss(String(s||""),{width:p}),h=f.length>0?f.flatMap(w=>xc(w,p)):[[{text:"",color:null}]],g=o?h.map(w=>Xa(w,o)):h,b=g.reduce((w,E)=>Math.max(w,kn(E)),0),y=l?Math.min(u,Math.max(12,kn(m)+3,b+4)):u,S=Math.max(1,y-4),v=Math.max(0,y-kn(m)-3);return[[{text:"┌─",color:i},...m,{text:`${"─".repeat(v)}┐`,color:i}],...g.map(w=>[{text:"│ ",color:i},...Ic(w,S),{text:" │",color:i}]),[{text:`└${"─".repeat(Math.max(1,y-2))}┘`,color:i}],[{text:"",color:null}]]}const zi="[canvas-action] ",eo=2048,to=8192;function $p(t){let e;try{e=JSON.stringify(t)||""}catch{return 1/0}return typeof TextEncoder<"u"?new TextEncoder().encode(e).length:e.length}function Rp(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||""),u=d.endsWith("?"),p=u?d.slice(0,-1):d,m=i[l];if(m==null){if(u)continue;return{ok:!1,reason:`required field ${JSON.stringify(l)} is missing`}}if(p==="json"){if(typeof m!="object")return{ok:!1,reason:`field ${JSON.stringify(l)} must be a JSON object or array`};o[l]=m;continue}if(typeof m!==p)return{ok:!1,reason:`field ${JSON.stringify(l)} must be a ${p}`};if(p==="string"&&m.length>eo)return{ok:!1,reason:`field ${JSON.stringify(l)} exceeds ${eo} characters`};if(p==="number"&&!Number.isFinite(m))return{ok:!1,reason:`field ${JSON.stringify(l)} must be a finite number`};o[l]=m}return $p(o)>to?{ok:!1,reason:`action payload exceeds ${to} bytes`}:{ok:!0,action:n,data:o}}function Lp(t,e){return`${zi}${JSON.stringify({action:t,data:e})}`}function Tc(t){return typeof t=="string"&&t.startsWith(zi)}function Op(t){if(!Tc(t))return null;try{const e=JSON.parse(t.slice(zi.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 Fp({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 rs(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";if(n==="agent-manager")return"Agent Smith";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":/^agent manager$/i.test(r)?"Agent Smith":r||"System Agent"}function Pc(t){const e=rs(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}function so(t){return String(t||"").trim().replace(/^Execution failed:\s*/,"")}function sr(t,e){const s=so(t),n=so(e);return!!s&&(n===s||n.startsWith(`${s} (`))}const Ot=new Set(["completed","failed","cancelled","interrupted"]),Tt=(t,e=240)=>typeof t=="string"?t.trim().slice(0,e):"",Lt=t=>{const e=typeof t=="number"?t:new Date(t).getTime();return Number.isFinite(e)&&e>0?e:null},Er=t=>typeof t=="string"?t:t?.detailedContent||t?.content||t?.textResultForLlm||t?.message||t?.error?.message||"",Ln={starting:"Starting",running:"Running",waiting:"Waiting",completed:"Done",failed:"Failed",cancelled:"Cancelled",interrupted:"Interrupted"};function Mc(t,e){for(let s=t.length-1;s>=0;s--){const n=t[s];if(n.kind!=="native-task-group")continue;const r=n.tasks.findLastIndex(i=>e.toolCallId&&i.toolCallId===e.toolCallId||e.agentId&&i.agentId===e.agentId&&(!e.toolCallId||!i.toolCallId)||e.id&&i.id===e.id);if(r>=0)return{groupIndex:s,taskIndex:r}}return null}function li(t,e,s,{authoritative:n=!1}={}){const r=Mc(t,e),i=r?t[r.groupIndex].tasks[r.taskIndex]:null;if(i?.ownerId&&e.ownerId&&i.ownerId!==e.ownerId||e.revision!=null&&i?.revision!=null&&e.revision<i.revision)return;const o={id:e.toolCallId||e.agentId||e.id,title:"Native task",status:"starting",toolCalls:0,startedAt:Lt(e.startedAt)||Lt(s.createdAt),...i,...Object.fromEntries(Object.entries(e).filter(([,u])=>u!==void 0)),telemetryStale:!1};if(!o.id)return;if(o.id=i?.id||o.id,o.startedAt=i?.startedAt||Lt(e.startedAt)||Lt(s.createdAt),o.completedAt=Lt(o.completedAt),i&&Ot.has(i.status)&&(!i.inferredTerminal||!Ot.has(e.status))?(o.status=i.status,o.error=i.error,o.completedAt=i.completedAt,o.durationMs=i.durationMs,(!Ot.has(e.status)||e.status==="cancelled")&&(o.toolCalls=i.toolCalls),!e.result&&!e.error&&(o.preview=i.preview)):Ot.has(e.status)&&!e.inferredTerminal&&(o.inferredTerminal=!1,i?.inferredTerminal&&(o.error=e.error||"")),o.title=Tt(o.title,160)||"Native task",o.preview=Tt(o.preview),o.result=Tt(o.result,4e3),o.error=Tt(o.error,1e3),o.toolCalls=Math.max(Number(i?.toolCalls)||0,Number(o.toolCalls)||0),o.recentActivity=Array.isArray(o.recentActivity)?o.recentActivity.slice(-5).map(u=>({message:Tt(u.message),timestamp:u.timestamp})):[],r){const u=t[r.groupIndex],p=[...u.tasks];p[r.taskIndex]=o,t[r.groupIndex]={...u,tasks:p};return}const l=o.startedAt?t.findIndex(u=>Number(u.createdAt)>o.startedAt):-1,c=l<0?t.length:l,d=t[c-1];d?.kind==="native-task-group"&&d.tasks.length<32?t[c-1]={...d,tasks:[...d.tasks,o]}:t.splice(c,0,{id:`native-tasks:${s.sessionId}:${o.id}`,kind:"native-task-group",role:"system",createdAt:o.startedAt,tasks:[o]})}function _c(t,e){const s=e?.eventType||"",n=e?.data||{};if(s==="native.task_updated"){n.id&&Ln[n.status]&&li(t,n,e,{authoritative:!0});return}if(s==="session.turn_completed"||s==="session.turn_stopped"){for(let f=0;f<t.length;f++)t[f].kind==="native-task-group"&&(t[f]={...t[f],tasks:t[f].tasks.map(h=>Ot.has(h.status)?h:{...h,status:"interrupted",inferredTerminal:!0,completedAt:Lt(e.createdAt),error:s==="session.turn_stopped"?"The parent turn was stopped.":"The parent turn ended before a task result was confirmed."})});return}const r=s.startsWith("subagent."),i=s.startsWith("native."),o=!i&&!n.nativeAgentId&&(n.toolName||n.name)==="task"&&["tool.execution_start","tool.execution_complete"].includes(s);if(!r&&!i&&!o)return;const l=n.arguments||n.args||{},c=i?n.parentToolCallId:n.toolCallId,d=n.nativeAgentId||n.agentId,u={toolCallId:c,agentId:d},p=Mc(t,u),m=p?t[p.groupIndex].tasks[p.taskIndex]:null;if(!(!m&&!r&&!o)){if((!m||o||s==="subagent.started")&&Object.assign(u,{title:l.description||n.agentDisplayName||l.name||n.agentName||"Native task",profile:l.agent_type||n.agentName||n.agentType,model:n.model}),s==="subagent.configured")Object.assign(u,{model:n.model,reasoningEffort:n.reasoningEffort});else if(s==="subagent.started")u.status="running";else if(s==="subagent.completed"||s==="subagent.failed")Object.assign(u,{status:n.cancelled?"cancelled":s==="subagent.failed"?"failed":"completed",completedAt:e.createdAt,durationMs:n.durationMs,toolCalls:n.totalToolCalls,...n.cancelled?{error:"Task was cancelled before returning a result."}:s==="subagent.failed"?{error:Tt(Er(n.error)||n.message||"Native task failed.",1e3)}:{}});else if(s==="tool.execution_start")u.status="starting";else if(s==="tool.execution_complete"){const f=n.success===!1||n.result?.success===!1||!!n.error||["failure","failed","rejected","denied"].includes(n.result?.resultType??n.resultType),h=Er(n.result)||Er(n.error);Object.assign(u,{status:f?"failed":"completed",completedAt:e.createdAt,...f?{error:Tt(h,1e3)||"Native task request failed."}:{result:Tt(h,4e3)}})}else if(s==="native.tool.execution_start"){const f=m.toolCallIds||[];u.toolCallIds=n.toolCallId&&!f.includes(n.toolCallId)?[...f,n.toolCallId].slice(-500):f,u.toolCalls=(m.toolCalls||0)+(u.toolCallIds!==f?1:0),u.preview=l.description||(n.toolName?`Using ${n.toolName}`:"Working")}else if(s==="native.assistant.message")u.preview=Tt(n.content);else return;li(t,u,e)}}function $c(t,e,s={}){if(e?.phase==="unavailable"&&t)return{...t,nativeTaskSnapshot:t.nativeTaskSnapshot?{...t.nativeTaskSnapshot,liveSeq:void 0}:void 0,chat:t.chat.map(l=>l.kind!=="native-task-group"?l:{...l,tasks:l.tasks.map(c=>Ot.has(c.status)?c:{...c,telemetryStale:!0})})};if(e?.version!==1||!Array.isArray(e.tasks)||!e.ownerId)return t;const n=t||{chat:[],activity:[],events:[],lastSeq:0},r=n.nativeTaskSnapshot,i=Math.max(0,...n.chat.filter(l=>l.kind==="native-task-group").flatMap(l=>l.tasks.map(c=>Number(c.ownerStartedAt)||0)));if(Number.isFinite(e.ownerStartedAt)&&e.ownerStartedAt<i)return r?.ownerStartedAt>=i?n:{...n,chat:n.chat.map(l=>l.kind!=="native-task-group"?l:{...l,tasks:l.tasks.map(c=>!Ot.has(c.status)&&c.ownerStartedAt===i?{...c,telemetryStale:!0}:c)})};if(Number.isFinite(r?.ownerStartedAt)&&Number.isFinite(e.ownerStartedAt)&&e.ownerStartedAt<r.ownerStartedAt||r?.ownerId===e.ownerId&&r.revision>=e.revision||r?.ownerId===e.ownerId&&Number.isFinite(s.seq)&&Number.isFinite(r?.liveSeq)&&s.seq<=r.liveSeq)return n;const o=[...n.chat];for(const l of e.tasks.slice(0,32)){if(!l?.id||!Ln[l.status])continue;const c=n.events?.some(u=>["session.turn_completed","session.turn_stopped"].includes(u.eventType)&&Lt(u.createdAt)>Lt(l.startedAt)),d={...l,ownerId:e.ownerId,ownerStartedAt:e.ownerStartedAt,revision:e.revision};c&&!Ot.has(d.status)&&(d.status="interrupted",d.inferredTerminal=!0,d.error="The parent turn ended before a task result was confirmed."),li(o,d,{sessionId:s.sessionId,createdAt:l.startedAt},{authoritative:!0})}return{...n,chat:o,nativeTaskSnapshot:{ownerId:e.ownerId,ownerStartedAt:e.ownerStartedAt,revision:e.revision,liveSeq:s.seq}}}function On(t){return/^(?:Execution failed:\s*)?No response was returned\. Send your message again to retry\.(?: \(retry \d+\/\d+ in \d+s\))?$/.test(String(t||"").trim())}function Dp(t,e){if(!String(t?.error||"").trim()||e?.error!==void 0||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||""))||["completed","failed","cancelled","terminated"].includes(t?.status))return!1;const s=String(e?.status||"");if(["running","error"].includes(s))return!0;if(!["idle","waiting","unknown","pending",""].includes(s))return!1;const n=Number(t?.statusVersion),r=Number(e?.statusVersion);if(n>0&&r>0)return r<=n;const i=c=>typeof c=="number"?c:Date.parse(c||""),o=i(t?.updatedAt),l=i(e?.updatedAt);return o>0&&l>0&&l<=o}const Ft=t=>t instanceof Date?t.getTime():typeof t=="number"?t:Date.parse(t||""),ci=t=>t?.eventType==="session.error"||t?.eventType==="session.turn_completed"&&t.data?.resultType==="error",Ki=t=>t?.eventType==="session.turn_completed"?String(t.data?.resultType==="error"&&t.data.errorMessage||"").trim():typeof t?.data=="string"?t.data:String(t?.data?.message||t?.data?.error||t?.data?.text||"").trim(),di=(t,e)=>sr(e,t);function Bp(t){const e=Ki(t);if(!e||On(e))return null;const s=t?.data?.fatal===!0;return{id:`${t.sessionId}:${t.seq}:warning`,kind:"session-warning",role:"system",text:e,warningSeq:Number(t.seq),createdAt:Ft(t.createdAt)||null,cardTitle:s?"Error":"Warning",cardTitleColor:s?"red":"yellow",cardBorderColor:s?"red":"yellow"}}function no(t,e,s=[],n=Date.now()){const r=t?.chatWarnings||[],i=r.at(-1),o=String(e?.error||"").trim(),l=e?.status==="failed"||e?.orchestrationStatus==="Failed";if(!(!!o&&(l||!["completed","cancelled","terminated","input_required"].includes(e?.status))&&!["Completed","Terminated"].includes(e?.orchestrationStatus)))return i?.active?{...e,chatWarnings:[...r.slice(0,-1),{...i,active:!1}]}:e;const d=i?.createdAt||0,u=s.findLast(h=>ci(h)&&Ft(h.createdAt)>d&&di(o,Ki(h)));if(i&&!i.active&&o===i.text&&o===String(t?.error||"").trim()&&!u)return e;const p=i&&o!==i.text&&s.some(h=>Number(h.seq)>i.afterSeq&&Ft(h.createdAt)>i.createdAt&&["user.message","assistant.message"].includes(h.eventType));if(i?.active&&!p)return i.text===o&&i.failed===l?e:{...e,chatWarnings:[...r.slice(0,-1),{...i,text:o,failed:l}]};const m=(i?.ordinal||0)+1,f=i?.active?[...r.slice(0,-1),{...i,active:!1}]:r;return{...e,chatWarnings:[...f,{id:`session-error:${e.sessionId}:${m}`,ordinal:m,text:o,failed:l,active:!0,eventSeq:u?Number(u.seq):null,afterSeq:Number(s.at(-1)?.seq)||0,since:d,createdAt:Ft(u?.createdAt)||Ft(e.updatedAt)||n}].slice(-300)}}function Hp(t,e,s=[]){const n=t.filter(r=>r.kind!=="session-warning"||!On(r.text));for(const r of e?.chatWarnings||[]){if(On(r.text))continue;const o=s.filter(p=>Number(p.seq)>r.afterSeq).find(p=>ci(p)||["user.message","assistant.message"].includes(p.eventType)),l=t.findLast(p=>p.kind==="session-warning"&&Ft(p.createdAt)>(r.since||0)&&Ft(p.createdAt)<=r.createdAt&&di(r.text,p.text)),c=r.eventSeq??l?.warningSeq??(ci(o)&&di(r.text,Ki(o))?Number(o.seq):null),d=n.findIndex(p=>p.kind==="session-warning"&&(p.warningSeq===c||c!=null&&p.turnCompletedSeq===c)),u={id:r.id,kind:"session-warning",role:"system",text:r.text,createdAt:r.createdAt,cardTitle:r.failed?"Error":"Warning",cardTitleColor:r.failed?"red":"yellow",cardBorderColor:r.failed?"red":"yellow"};if(d>=0)n[d]={...n[d],...u,createdAt:n[d].createdAt};else{const p=n.findIndex(m=>Ft(m.createdAt)>r.createdAt);n.splice(p<0?n.length:p,0,u)}}return n}const Vi=["tool.execution_start","tool.execution_complete","tool.execution_partial_result","tool.execution_progress","external_tool.requested","external_tool.completed","session.agent_spawned"],Up=new Set(Vi),jp=/(?:^|[.:/])(?:spawn_agent|message_agent|send_message|send_session_message|reply_session_message|wait_for_agents|check_agents|complete_agent|cancel_agent|delete_agent|list_agents)$/;function In(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t,null,2)}catch{return String(t)}}function Ts(t){return In(t).split(/\r?\n/).find(e=>e.trim())?.trim()||""}function Gp(t){if(!t||typeof t!="object")return Ts(t);for(const e of["command","cmd","task","message","prompt","subject","body","query","path","reason","agent_ids","agent_id"])if(t[e]!=null)return Ts(typeof t[e]=="object"?JSON.stringify(t[e]):t[e]);return Object.entries(t).map(([e,s])=>`${e}: ${typeof s=="object"?JSON.stringify(s):s}`).join(" · ").split(/\r?\n/)[0]}function Wp(t,e){if(!Up.has(e?.eventType))return!1;const s=e.data||{},n=`${e.sessionId}:${s.durableSessionId||""}`,r=[s.toolCallId&&`call:${s.toolCallId}`,s.requestId&&`request:${s.requestId}`].filter(Boolean),i=e.eventType==="session.agent_spawned";i&&r.push(`spawn:${e.seq}`);const o=r.length?t.findIndex(f=>f.kind==="chat-call"&&f.namespace===n&&f.callKeys.some(h=>r.includes(h))):-1,l=o>=0?t[o]:null;if(!l&&e.eventType==="external_tool.completed")return!0;const c=i?"Agent started":s.toolName||s.name||l?.name||"Tool call",d=s.arguments??s.args??l?.arguments,u=e.eventType==="tool.execution_complete",p=u&&(s.success===!1||!!s.error),m={...l,id:l?.id||`${n}:tool:${r[0]||`event:${e.seq}`}`,kind:"chat-call",role:"tool",namespace:n,callKeys:[...new Set([...l?.callKeys||[],...r])],name:c,arguments:d,category:i||jp.test(c)?"Agent":"Tool",text:i?Ts(s.task):Gp(d)||l?.text||"",time:l?.time||We(e.createdAt),createdAt:l?.createdAt||new Date(e.createdAt).getTime(),status:u?p?"Failed":"Done":l?.status||(i?"Started":"Called")};return u?(m.result=s.result??s.output,m.error=s.error,m.partial="",m.progress=""):m.status==="Called"&&(e.eventType==="tool.execution_partial_result"&&l?.lastPartialSeq!==e.seq&&(m.partial=`${l?.partial||""}${s.partialOutput||""}`,m.lastPartialSeq=e.seq),s.progressMessage&&(m.progress=s.progressMessage)),i&&(m.result={childSessionId:s.childSessionId,agentId:s.agentId,task:s.task}),o>=0?t[o]=m:t.push(m),!0}function qp(t){const e=[t.arguments!==void 0?`Arguments
|
|
7
|
-
${In(t.arguments)}`:"",t.progress?`Progress
|
|
8
|
-
${t.progress}`:"",t.partial?`Output
|
|
9
|
-
${t.partial}`:"",t.result!==void 0?`Result
|
|
10
|
-
${In(t.result)}`:"",t.error?`Error
|
|
11
|
-
${In(t.error)}`:""].filter(Boolean);return{kind:"chatCall",callKey:t.id,category:t.category,text:`${t.name}${t.text?` — ${t.text}`:""}`,body:e.join(`
|
|
12
|
-
|
|
13
|
-
`)||"Call recorded; no output has been recorded yet.",status:t.status,time:t.time}}const ke=300,zp=[ke,1e3,3e3,1e4],Kp=[...Vi,"user.message","assistant.message","session.turn_completed","session.turn_stopped","session.error","subagent.started","subagent.configured","subagent.completed","subagent.failed","native.task_updated","system.message","session.epoch_committed","session.regenerate_refused","session.regenerate_failed","session.canvas_updated"];function Rc(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:We(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Lc(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:We(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Oc(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:We(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Vp(t){const e=t.eventType==="session.turn_completed"&&t.data?.resultType==="error";if(t.eventType!=="session.error"&&!e)return null;const s=Bp(t);return s?{...s,errorText:s.text,sourceEventType:t.eventType,...e?{turnCompletedSeq:t.seq}:{},time:We(t.createdAt)}:null}function Fc(t,e){const s=Vp(e);if(!s||t.some(i=>i.id===s.id||i.turnCompletedSeq!=null&&i.turnCompletedSeq===e.seq))return;const n=t.findLastIndex(i=>i.kind!=="chat-call"&&i.kind!=="native-task-group"),r=t[n];if(r?.kind==="session-warning"&&r.sourceEventType==="session.error"&&r.turnCompletedSeq==null&&e.eventType==="session.turn_completed"&&sr(r.errorText,s.errorText)){t[n]={...r,turnCompletedSeq:e.seq};return}t.push(s)}const Yp=new Set(Vi);function Dc(t,e){if(!Yp.has(e?.eventType))return;const s=e?.data||{},n=s.toolName||s.name,r=`${e.sessionId}:${s.durableSessionId||""}`,i=[s.toolCallId&&`call:${s.toolCallId}`,s.requestId&&`request:${s.requestId}`].filter(Boolean),o=n||s.arguments!=null||s.args!=null||s.result!=null||s.output!=null||s.error||s.partialOutput||s.progressMessage||s.childSessionId||s.agentId||s.task;if(!i.length&&!o)return;const l=!n&&t.some(d=>d.kind==="chat-call"&&d.namespace===r&&d.callKeys.some(u=>i.includes(u)));n==="task"||!n&&!l&&s.toolCallId&&t.some(d=>d.kind==="native-task-group"&&d.tasks.some(u=>u.toolCallId===s.toolCallId))||Wp(t,e)}function Qe(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(ke,Number(e)||ke);return s.length>n?s.slice(-n):s}function Pt(t){return String(t||"").replace(/\r\n/g,`
|
|
14
|
-
`).trim()}function ro(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 Bc=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,Xp=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function Yi(t){return Bc.test(Pt(t))}function Dt(t){const e=String(t||"").replace(/\r\n/g,`
|
|
15
|
-
`).trim();if(!e)return"";const s=e.replace(Xp,"").trimStart();return s!==e?s.trim():Yi(e)?e.replace(Bc,"").trim():e}const Xi="[\\u200b-\\u200f\\u2060-\\u2064\\ufeff]*",Hc=new RegExp(`^\\s*\\[${Xi}SYSTEM:`,"i"),Qp=new RegExp(`^\\s*\\[${Xi}SYSTEM:\\s*(.*?)\\]\\s*$`,"i"),Zp=new RegExp(`^\\s*\\[${Xi}SYSTEM:\\s*`,"i");function Uc(t){const e=String(t||"").replace(/\r\n/g,`
|
|
16
|
-
`).split(`
|
|
17
|
-
`),s=[];let n=[];function r(){n.length!==0&&(s.push({kind:"text",text:n.join(`
|
|
18
|
-
`)}),n=[])}for(let i=0;i<e.length;){const o=e[i];if(!Hc.test(o)){n.push(o),i+=1;continue}const l=Qp.exec(o);if(l){r(),s.push({kind:"system",text:l[1].trim()}),i+=1;continue}const c=[o.replace(Zp,"")];let d=-1;for(let u=i+1;u<e.length;u+=1){const p=e[u];if(p.trim()==="]"){d=u;break}if(/\]\s*$/.test(p.trim())){const m=p.replace(/\]\s*$/,"");m.trim()&&c.push(m),d=u;break}c.push(p)}if(d===-1){n.push(o),i+=1;continue}r(),s.push({kind:"system",text:c.join(`
|
|
19
|
-
`).trim()}),i=d+1}return r(),s}function jc(t,e){const s=String(t||"").replace(/\r\n/g,`
|
|
20
|
-
`);return e==="user"||e==="assistant"?Uc(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
|
|
21
|
-
`).trim():s.trim()}function Jp(t,e){return e!=="user"&&e!=="assistant"?[]:Uc(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function io(t){const e=Pt(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=jc(e,t.role);if(s)return s}return Dt(e)}function nr(t){const e=String(t||"").replace(/\r\n/g,`
|
|
22
|
-
`).trim(),s='The user was asked: "';if(!e.startsWith(s)||!e.endsWith('"'))return null;const n=/"\nThe user responded(?: \(answered by [^\r\n]+?\))?: "/g;n.lastIndex=s.length;const r=n.exec(e);if(!r)return null;const i=e.slice(s.length,r.index),o=e.slice(n.lastIndex,-1);return!i.trim()||!o.trim()?null:{question:i,answer:o}}function em(t){return Pt(Wi(t)).length>0}function tm(t){const e=Pt(t);return e?Hc.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 sm(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(Pt(t))}function ds(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 nm(t,e){const s=Pt(e);if(!s)return null;const n=/^\[SESSION_MESSAGE\s+([^\]]+)\]\n?/i.exec(s);if(n){const i=n[1],o=`
|
|
23
|
-
Request body:
|
|
24
|
-
`,l=s.indexOf(o),c=l>=0?s.slice(l+o.length).trim():s.slice(n[0].length).trim(),d=ds(i,"request_id"),u=ds(i,"from"),p=ds(i,"subject"),m=/\bexpects_response=true\b/i.test(i),f=[u?`From: session-${_e(u)}`:"",d?`Request ID: ${d}`:"",p?`Subject: ${p}`:"",m?"Response: required":"Response: not required","",c].filter((h,g)=>g===4||String(h||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:f.join(`
|
|
25
|
-
`),time:We(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:m?"Session Request":"Session Message",agentCallPreview:c,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=ds(i,"request_id"),d=ds(i,"from"),u=ds(i,"verdict")||"answered",p=[d?`From: session-${_e(d)}`:"",c?`Request ID: ${c}`:"",`Verdict: ${u}`,"",l].filter((m,f)=>f===3||String(m||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:p.join(`
|
|
26
|
-
`),time:We(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:"Session Reply",agentCallPreview:l,cardTitleColor:"green",cardBorderColor:"green"}}return null}function rm(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&tm(s)?"system":e}function ao(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 im(t,e){if(!t||!e||t.role!==e.role)return!1;if(t.sender?.kind==="agent"||e.sender?.kind==="agent")return t.sender?.kind===e.sender?.kind&&t.sender?.sessionId===e.sender?.sessionId&&(t.id===e.id||ao(t,e)===!0);if(t.role==="assistant"&&t.messageId&&e.messageId)return t.messageId===e.messageId;if(t.kind==="canvas-update"||e.kind==="canvas-update"||t.kind==="chat-call"||e.kind==="chat-call"||t.kind==="session-warning"||e.kind==="session-warning")return t.kind===e.kind&&t.id===e.id;const s=io(t),n=io(e);if(!s||!n||s!==n)return!1;const r=ao(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 Ss(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!im(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 am(t){return typeof t=="string"?t.replace(/^\[FROM:[^\]\n]*\]\n?/,""):t}function vs(t,e){const s=Ls(t),n=nm(t,s);if(n)return n;const r=am(jc(s,e));if(e==="user"&&Tc(r)){const p=Op(r);if(p)return{id:`${t.sessionId}:${t.seq}`,kind:"canvas-action",role:"user",action:p.action,data:p.data,text:r,time:We(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 i=r;if(!em(i))return null;const o=Array.isArray(t?.data?.clientMessageIds)?t.data.clientMessageIds.filter(p=>typeof p=="string"&&p):[],l=t?.data?.sender&&typeof t.data.sender=="object"?t.data.sender:null,c=Array.isArray(t?.data?.attachments)?t.data.attachments.filter(p=>p&&typeof p.filename=="string"&&p.filename):[],d=typeof t?.data?.messageId=="string"&&t.data.messageId?t.data.messageId:null,u=rm(t,e,i);return{id:`${t.sessionId}:${t.seq}`,role:u,text:i,time:We(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...o.length>0?{clientMessageIds:o}:{},...l?{sender:l}:{},...c.length>0?{attachments:c}:{},...d?{messageId:d}:{},...u==="assistant"?{assistantPreview:!0,responsePending:!0,responseFinal:!1,responseCanFinalize:!t?.data?.parentToolCallId&&!t?.data?.toolRequests?.length,...typeof t?.data?.reasoningText=="string"&&t.data.reasoningText?{liveReasoningText:t.data.reasoningText}:{}}:{}}}function Gc(t,e){const s=e?.data?.resultType||e?.data?.result,n=e?.eventType==="session.turn_completed"&&(!s||s==="completed");let r=-1;for(let i=t.length-1;i>=0;i-=1)if(t[i]?.responsePending){n&&t[i].responseCanFinalize&&(r=i);break}for(let i=0;i<t.length;i+=1)t[i]?.responsePending&&(t[i]={...t[i],responsePending:!1,responseFinal:i===r})}function om(t,e,s={}){if(!e)return t;if(e.phase==="idle")return zs(t,null,e.streamId||null);if(e.phase!=="live")return t;const n=typeof e.messageId=="string"&&e.messageId?e.messageId:null,r=typeof e.reasoningId=="string"&&e.reasoningId?e.reasoningId:null,i=n||(r?`reasoning:${r}`:"active-turn"),o=Number(s.createdAt)||Date.now(),l=t||{chat:[],activity:[],events:[],lastSeq:0},c=l.chat||[];if(n&&c.some(y=>!y.liveTurn&&y.messageId===n)||(l.closedLiveKeys||[]).includes(i)||e.streamId&&(l.closedLiveStreams||[]).includes(e.streamId))return l;const d=y=>y?.liveTurn===!0&&(y?.liveKey===i||n&&y?.messageId===n||r&&y?.reasoningId===r&&(!y.messageId||!n)),u=c.findIndex(d),p=u>=0?c[u]:null,m=c.filter(y=>!d(y)),f=typeof e.reasoningText=="string"?e.reasoningText:"",h=typeof e.text=="string"?e.text:"",g=Number(p?.liveStartedAt||p?.createdAt)||o,b=f||h?[{id:p?.id||`live:${s.sessionId||""}:${i}`,role:"assistant",...n?{messageId:n}:{},...r?{reasoningId:r}:{},liveKey:p?.liveKey||i,liveTurn:!0,streamId:e.streamId||p?.streamId||null,streaming:!0,truncated:e.truncated===!0,text:h,reasoningText:f,liveStartedAt:g,createdAt:g,time:""}]:[];return m.splice(u<0?m.length:Math.min(u,m.length),0,...b),{...l,chat:m}}function zs(t,e=null,s=null){if(!t?.chat)return t;const n=t.chat.filter(l=>!(l?.liveTurn===!0&&(!e||l?.messageId===e)&&(!s||l?.streamId===s))),r=t.chat.filter(l=>l.liveTurn&&(!e||l.messageId===e)&&(!s||l.streamId===s)),i=[...new Set([...t.closedLiveKeys||[],...r.flatMap(l=>[l.liveKey,l.messageId,l.reasoningId&&`reasoning:${l.reasoningId}`].filter(Boolean))])].slice(-256),o=[...new Set([...t.closedLiveStreams||[],...e?[]:r.map(l=>l.streamId).filter(Boolean),...s?[s]:[]])].slice(-256);return n.length===t.chat.length&&!s?t:{...t,chat:n,closedLiveKeys:i,closedLiveStreams:o}}function Wc(t){return t?.eventType!=="system.message"?!1:!sm(Ls(t))}function Fn(t,e){return Jp(Ls(t),e).map((s,n)=>Jt({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function lm(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=Pt(e.text),n=nr(e.text),r=n?Pt(n.answer):"";let i=!1;return t.filter(o=>{if(i||!o?.optimistic||o.role!==e.role)return!0;const l=Pt(o.text);return l!==s&&l!==r?!0:(i=!0,!1)})}function Ls(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 Ec(e)}function qc(t){return(t||[]).map(e=>e?.text||"").join("")}function cm(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function Qi(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 dm(t,e=""){return Qi([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function um(t,e=""){return Qi([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function pm(t,e=""){const s=Ls(t),n=Dt(e);return Qi([Dt(s),n,t?.data?.detail,t?.data?.message])}function mm(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 fm(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}=${mm(i)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function Zi(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function we(t,e,s,n="",r="white"){return[...Zi(t),{text:e,color:s},...n?[{text:` ${n}`,color:r}]:[]]}function hm(t,e=96){return cm(Wi(Ls(t)),e)||""}function kr(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=fm(i,o),d=s==="start"?"▶":s==="partial"?"…":"✓",u=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...Zi(t),{text:`${d} ${i}${c}`,color:u},...l?[{text:` [sess ${_e(l)}]`,color:"gray"}]:[]]}function Jt(t){const e=We(t.createdAt),s=hm(t);let n=null;if(t.eventType?.startsWith("native.")||t.eventType==="session.background_tasks_changed")return null;switch(t.eventType){case"subagent.started":case"subagent.completed":case"subagent.failed":{const r=t.eventType.slice(9),i=t.data?.agentDisplayName||t.data?.agentName||"agent",o=Number.isFinite(t.data?.durationMs)?` (${Zt(t.data.durationMs/1e3)})`:"";n=we(e,"[native agent]","cyan",`${i} ${r}${o}`,r==="failed"?"red":"white");break}case"subagent.configured":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"model.call_start":{const r=String(t?.data?.model||t?.data?.modelId||"model").split(":").pop();n=we(e,"[model]","cyan",`calling ${r}`,"white");break}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=we(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=we(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=we(e,"[canvas]","cyan",`data tick ${i}${o}${l}`,"white");break}case"tool.execution_start":n=kr(e,t,"start");break;case"tool.execution_complete":n=kr(e,t,"complete");break;case"tool.execution_partial_result":n=kr(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=we(e,"[tool]","cyan",`${i} ${o}`,"white");break}case"assistant.reasoning":n=we(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=we(e,"[intent]","gray",i||"…","white");break}case"assistant.turn_start":n=we(e,"[turn start]","gray",s);break;case"session.turn_completed":n=we(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=we(e,"[lossy handoff]","yellow",um(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=we(e,"[dehydrated]","cyan",dm(t,s));break;case"session.hydrated":case"session.rehydrated":n=we(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=we(e,"[wait]","yellow",`${r}${o}${i}`.trim());break}case"session.input_required_started":n=we(e,"[input]","yellow",s);break;case"session.agent_spawned":n=we(e,"[spawn]","cyan",t?.data?.agentId||_e(t?.data?.childSessionId),"white");break;case"session.cron_started":n=we(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=we(e,"[cron]","magenta",`scheduled${t?.data?.nextFireAt?` ${ro(t.data.nextFireAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_fired":n=we(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=we(e,"[cron]","magenta",`fired${t?.data?.scheduledAt?` ${ro(t.data.scheduledAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_cancelled":case"session.cron_at_cancelled":n=we(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=we(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=we(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=we(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.model_changed":{const r=Cs(t?.data?.oldModel)||"default",i=Cs(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",u=[...l?[`effort ${o}`]:[],...d?[`context ${c}`]:[]];n=we(e,"[model]","cyan",`${r} → ${i}${u.length?` (${u.join(", ")})`:""}`);break}case"session.compaction_start":case"session.compaction_complete":n=fp(e,t.eventType,t.data||{});break;case"session.error":n=we(e,"[error]","red",s||"session error","white");break;case"system.message":Yi(Ls(t))?n=we(e,"[rehydrated]","green",pm(t,s)||"conversation preserved"):n=we(e,"[system]","gray",s||"system message");break;default:n=[...Zi(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:qc(n),line:n}}function gm(t=ke){const e=Math.max(ke,Number(t)||ke);return zp.find(n=>n>e)||Math.min(1e5,e*2)}function zc(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 Kc(t,e){const s=We(t.createdAt),n=`action ${e.action}${Object.keys(e.data||{}).length?" "+Ec(e.data):""}`,r=we(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:qc(r),line:r}}function Bs(t=[],e={}){const s=Math.max(ke,Number(e.requestedLimit??e.eventLimit??ke)||ke),n=[],r=[],i=[];for(const o of t){if(i.push(o),_c(n,o),Dc(n,o),Fc(n,o),["user.message","session.turn_completed","session.turn_stopped","session.epoch_committed"].includes(o.eventType)&&Gc(n,o),o.eventType==="user.message"){r.push(...Fn(o,"user"));const c=vs(o,"user");if(c&&n.push(c),c?.kind==="canvas-action"){const d=Kc(o,c);d&&r.push(d)}continue}if(o.eventType==="session.canvas_updated"){n.push(zc(o));const c=Jt(o);c&&r.push(c);continue}if(o.eventType==="assistant.message"){r.push(...Fn(o,"assistant"));const c=vs(o,"assistant");c&&n.push(c);continue}if(o.eventType==="system.message"){if(Wc(o)){const c=Jt(o);c&&r.push(c)}else{const c=vs(o,"system");c&&n.push(c)}continue}if(o.eventType==="session.epoch_committed"){n.push(Rc(o));continue}if(o.eventType==="session.regenerate_refused"){n.push(Lc(o));continue}if(o.eventType==="session.regenerate_failed"){n.push(Oc(o));continue}const l=Jt(o);l&&r.push(l)}return{chat:Ss(n),activity:r,events:i.slice(-s),loadedEventLimit:s,loadedEventCount:i.length,hasOlderEvents:i.length>=s}}function Ir(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max(ke,Number(t?.loadedEventLimit??ke)||ke),r=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),i={nativeTaskSnapshot:t?.nativeTaskSnapshot,closedLiveKeys:t?.closedLiveKeys||[],closedLiveStreams:t?.closedLiveStreams||[],chat:Qe(t?.chat||[],n),activity:Qe(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(_c(i.chat,e),Dc(i.chat,e),Fc(i.chat,e),i.chat=Qe(i.chat,n),["user.message","session.turn_completed","session.turn_stopped","session.epoch_committed"].includes(e.eventType)&&Gc(i.chat,e),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(u=>c.has(u))?{...d,stopped:!0}:d)}return Object.assign(i,zs(i)),i}if(e.eventType==="user.message"){i.activity.push(...Fn(e,"user"));const l=vs(e,"user");if(l?.kind==="canvas-action"){const c=Kc(e,l);c&&i.activity.push(c)}return i.activity=Qe(i.activity,n),l&&(Array.isArray(l.clientMessageIds)&&l.clientMessageIds.some(c=>i.stoppedMessageIds.includes(c))&&(l.stopped=!0),i.chat=lm(i.chat,l),i.chat.push(l),i.chat=Qe(Ss(i.chat),n)),i}if(e.eventType==="session.canvas_updated"){i.chat.push(zc(e)),i.chat=Qe(i.chat,n);const l=Jt(e);return l&&(i.activity.push(l),i.activity=Qe(i.activity,n)),i}if(e.eventType==="assistant.message"){i.activity.push(...Fn(e,"assistant")),i.activity=Qe(i.activity,n);const l=vs(e,"assistant");if(!l)return i;const c=l.messageId?i.chat.findIndex(u=>u?.liveTurn===!0&&u?.messageId===l.messageId):-1,d=c>=0?i.chat[c]:null;if(Object.assign(i,zs(i,l.messageId||null)),c>=0){const u=Date.now(),p=Number(d?.liveStartedAt||d?.createdAt)||u;Object.assign(l,{streamSettling:!0,liveKey:d?.liveKey||l.messageId,liveStartedAt:p,liveReasoningText:l.liveReasoningText||d?.reasoningText||""}),i.chat.splice(Math.min(c,i.chat.length),0,l)}else i.chat.push(l);return i.chat=Qe(Ss(i.chat),n),i}if((e.eventType==="session.turn_completed"||e.eventType==="session.turn_stopped")&&Object.assign(i,zs(i)),e.eventType==="system.message"){if(Wc(e)){const l=Jt(e);l&&(i.activity.push(l),i.activity=Qe(i.activity,n))}else{const l=vs(e,"system");if(!l)return i;i.chat.push(l),i.chat=Qe(Ss(i.chat),n)}return i}if(e.eventType==="session.epoch_committed")return i.chat.push(Rc(e)),i.chat=Qe(i.chat,n),i;if(e.eventType==="session.regenerate_refused")return i.chat.push(Lc(e)),i.chat=Qe(i.chat,n),i;if(e.eventType==="session.regenerate_failed")return i.chat.push(Oc(e)),i.chat=Qe(i.chat,n),i;const o=Jt(e);return o&&(i.activity.push(o),i.activity=Qe(i.activity,n)),i}function cn(t,e=null,{loading:s=!1}={}){const n=typeof e?.splash=="string"&&e.splash.trim()?e.splash:null,r=n||t?.splash;if(!r)return[];const i=n?e?.splashMobile:t?.splashMobile,o=typeof i=="string"&&i.trim()?i:null,l=e?.isSystem?rs(e,t?.title||"PilotSwarm"):e?.title||t?.title||"PilotSwarm",c=s?"{gray-fg}Loading conversation…{/gray-fg}":"{gray-fg}Start interacting with this session to replace the splash screen.{/gray-fg}";return[{id:`splash:${l}`,role:"system",text:`${r}
|
|
27
|
-
|
|
28
|
-
${c}`,...o?{mobileText:`${o}
|
|
29
|
-
|
|
30
|
-
${c}`}:{},time:"",splash:!0}]}const Vc=.7,ym=30,oo=36,xr=18,xn=18,Ar=0,Yc=3,Ps=6,rr=10,bm=.25,Sm=.5,ws=6,Dn=10,Xc=.336,Nr=ws,Cr=Dn,Tr=Ps,Pr=rr;function hs(t,e,s){return Math.max(e,Math.min(s,t))}function vm(t){return[L.SESSIONS,L.CHAT,L.INSPECTOR,L.ACTIVITY].includes(t)?t:null}function wm(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function Es(t=""){const e=String(t||"").split(`
|
|
31
|
-
`).length;return hs(e,1,Yc)}function Qc(t){return Math.max(Ps,Math.floor(t*bm))}function Zc(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*Sm),n=Math.max(Ps,e-rr);return Math.max(Ps,Math.min(n,s))}function lo(t,e){const s=Math.max(0,Number(t)||0),n=hs(Math.max(0,Number(e)||0),0,s),r=-(s/2);return{minAdjust:r,maxAdjust:Math.max(r,s/2-n)}}function Ks(t,e=0,s=1,n=0,r=0,i=null){const o=wm(t),l=o.width,c=o.height,d=hs(Number(s)||1,1,Yc),u=vm(i),p=5+d,m=Math.max(18,c-p),h=Math.floor(l*Vc)+(Number(e)||0),g=l-h-Ar;let b=!1,y=!1;h<=xr&&g>xn?b=!0:g<=xn&&h>xr?y=!0:h<=xr&&g<=xn&&(y=e>=0,b=!y);let S,v;b?(S=0,v=l):y?(S=l,v=0):(S=hs(h,ym,l-oo-Ar),v=Math.max(oo,l-S-Ar));const E=Qc(m)+(Number(n)||0),k=m-E;let x=!1,T=!1;k<=Pr&&E>Tr?T=!0:E<=Tr&&k>Pr?x=!0:k<=Pr&&E<=Tr&&(T=(Number(n)||0)>=0,x=!T);let A,R;if(x)A=0,R=m;else if(T)A=m,R=0;else{const D=Zc(c,m);A=hs(E,Ps,D),R=Math.max(rr,m-A)}const $=Math.max(ws,Math.floor(m*Xc))+(Number(r)||0),F=m-$;let I=!1,O=!1;F<=Cr&&$>Nr?I=!0:$<=Nr&&F>Cr?O=!0:F<=Cr&&$<=Nr&&(I=(Number(r)||0)>=0,O=!I);let M,B;return I?(M=m,B=0):O?(B=m,M=0):(M=hs($,ws,Math.max(ws,m-Dn)),B=Math.max(Dn,m-M)),{viewport:o,totalWidth:l,totalHeight:c,reservedRows:p,bodyHeight:m,promptRows:d,fullscreenPane:u,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(r)||0,leftHidden:b,rightHidden:y,inspectorHidden:I,activityHidden:O,sessionHidden:x,chatHidden:T,leftWidth:S,rightWidth:v,sessionPaneHeight:A,chatPaneHeight:R,activityPaneHeight:M,inspectorPaneHeight:B}}function ui(t){if(t?.fullscreenPane)return[t.fullscreenPane,L.PROMPT];if(t?.leftHidden)return[L.INSPECTOR,L.ACTIVITY,L.PROMPT];if(t?.rightHidden)return[...t?.sessionHidden?[L.CHAT]:t?.chatHidden?[L.SESSIONS]:[L.SESSIONS,L.CHAT],L.PROMPT];if(t?.sessionHidden){const e=t?.inspectorHidden?[L.ACTIVITY]:t?.activityHidden?[L.INSPECTOR]:[L.INSPECTOR,L.ACTIVITY];return[L.CHAT,...e,L.PROMPT]}if(t?.chatHidden){const e=t?.inspectorHidden?[L.ACTIVITY]:t?.activityHidden?[L.INSPECTOR]:[L.INSPECTOR,L.ACTIVITY];return[L.SESSIONS,...e,L.PROMPT]}return t?.inspectorHidden?[L.SESSIONS,L.CHAT,L.ACTIVITY,L.PROMPT]:t?.activityHidden?[L.SESSIONS,L.CHAT,L.INSPECTOR,L.PROMPT]:[L.SESSIONS,L.CHAT,L.INSPECTOR,L.ACTIVITY,L.PROMPT]}function mt(t,e){const s=ui(e);return s.includes(t)?t:s[0]||L.PROMPT}function Em(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[L.PROMPT]:L.PROMPT,[L.ACTIVITY]:L.INSPECTOR,[L.INSPECTOR]:L.INSPECTOR}[t]||L.INSPECTOR:e?.rightHidden?{[L.PROMPT]:L.PROMPT,[L.CHAT]:e?.sessionHidden?L.CHAT:L.SESSIONS,[L.SESSIONS]:L.SESSIONS}[t]||(e?.sessionHidden?L.CHAT:L.SESSIONS):{[L.PROMPT]:e?.sessionHidden?L.CHAT:L.SESSIONS,[L.ACTIVITY]:e?.chatHidden?L.SESSIONS:L.CHAT,[L.INSPECTOR]:e?.chatHidden?L.SESSIONS:L.CHAT,[L.CHAT]:e?.sessionHidden?L.CHAT:L.SESSIONS,[L.SESSIONS]:L.SESSIONS}[t]||(e?.sessionHidden?L.CHAT:L.SESSIONS)}function km(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[L.PROMPT]:L.PROMPT,[L.INSPECTOR]:L.ACTIVITY,[L.ACTIVITY]:L.ACTIVITY}[t]||L.INSPECTOR:e?.rightHidden?{[L.PROMPT]:L.PROMPT,[L.SESSIONS]:e?.chatHidden?L.SESSIONS:L.CHAT,[L.CHAT]:L.CHAT}[t]||(e?.chatHidden?L.SESSIONS:L.CHAT):e?.inspectorHidden?{[L.PROMPT]:L.PROMPT,[L.SESSIONS]:L.CHAT,[L.CHAT]:L.ACTIVITY,[L.ACTIVITY]:L.ACTIVITY}[t]||L.CHAT:e?.activityHidden?{[L.PROMPT]:L.PROMPT,[L.SESSIONS]:L.CHAT,[L.CHAT]:L.INSPECTOR,[L.INSPECTOR]:L.INSPECTOR}[t]||L.CHAT:{[L.PROMPT]:L.PROMPT,[L.SESSIONS]:L.CHAT,[L.CHAT]:L.INSPECTOR,[L.INSPECTOR]:L.ACTIVITY,[L.ACTIVITY]:L.ACTIVITY}[t]||L.CHAT}function Jc(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,...u]=i,p=l.replace(/\.git$/u,""),m=`https://github.com/${o}/${p}`;return c?c!=="blob"&&c!=="tree"?{error:`Unrecognized GitHub link shape (…/${c}/…) — use a /blob/ or /tree/ link, or the bare repo URL.`}:d?{kind:"github",repoUrl:m,ref:d,path:u.length?`/${u.join("/")}`:null}:{error:"That GitHub link is missing the branch segment."}:{kind:"github",repoUrl:m,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 Bn=2*1024*1024,Im=new Set(["node_modules",".git"]);function pi(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 ed(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 td(t){return t.split("/").some(e=>Im.has(e))}function sd(t){const e=String(t||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.endsWith("/plugin.json")?e.slice(0,-12):e==="plugin.json"?"":e:""}function xm(t,e){return t?`${t}/${e}`:e}function nd(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 Hn(t,e,s,n){let r;try{r=await t(e,{headers:{accept:"application/json",...s}})}catch(i){throw nd(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 rd(t,e,s,n){let r;try{r=await t(e,{headers:s})}catch(o){throw nd(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 Am(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 Nm({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:r,onProgress:i}){const{owner:o,repo:l}=Am(t),c="https://api.github.com",d={"x-github-api-version":"2022-11-28",...r?{authorization:`Bearer ${r}`}:{}};let u=e;u||(i("resolving the default branch…"),u=(await Hn(n,`${c}/repos/${o}/${l}`,d,"api.github.com"))?.default_branch||"main"),i(`reading the file tree of ${o}/${l}@${u}…`);const p=await Hn(n,`${c}/repos/${o}/${l}/git/trees/${encodeURIComponent(u)}?recursive=1`,d,"api.github.com");if(p?.truncated)throw new Error("this repository's file tree is too large for the API listing — point the link at the package folder");const m=Array.isArray(p?.tree)?p.tree:[],f=sd(s),h=xm(f,"plugin.json");if(!m.some(w=>w.type==="blob"&&w.path===h))throw new Error(`no plugin.json at ${h||"the repository root"} on ${u} — link to the folder that contains the manifest`);const g=f?`${f}/`:"",b=m.filter(w=>w.type==="blob"&&(!g||w.path.startsWith(g))&&!td(w.path.slice(g.length))),y=[];let S=0,v=0;for(const w of b){v+=1;const E=w.path.slice(g.length);i(`fetching ${v}/${b.length}: ${E}`);const k=r?await Cm(n,c,o,l,w.sha,d):await rd(n,`https://raw.githubusercontent.com/${o}/${l}/${encodeURIComponent(u)}/${w.path.split("/").map(encodeURIComponent).join("/")}`,{},"raw.githubusercontent.com");if(S+=k.length,S>Bn)throw new Error(`package exceeds the ${Math.round(Bn/1024)} KB upload limit at ${E}`);y.push({path:E,contentBase64:pi(k)})}return y}async function Cm(t,e,s,n,r,i){const o=await Hn(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 ed(l)}function Tm(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 Pm({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}=Tm(t),u=`https://dev.azure.com/${encodeURIComponent(l)}/${encodeURIComponent(c)}/_apis/git/repositories/${encodeURIComponent(d)}`,m={authorization:i==="pat"?`Basic ${pi(new TextEncoder().encode(`:${r}`))}`:`Bearer ${r}`},f=sd(s),h=`/${f}`,g=e?`&versionDescriptor.version=${encodeURIComponent(e)}&versionDescriptor.versionType=branch`:"";o(`reading ${d}${f?`/${f}`:""}…`);const b=await Hn(n,`${u}/items?scopePath=${encodeURIComponent(h)}&recursionLevel=Full${g}&api-version=7.1`,m,"dev.azure.com"),S=(Array.isArray(b?.value)?b.value:[]).filter(T=>T?.gitObjectType==="blob"&&!T?.isFolder),v=f?`/${f}/`:"/";if(!S.find(T=>T.path===`${v}plugin.json`.replace("//","/")))throw new Error(`no plugin.json under ${h} — link to the folder that contains the manifest`);const E=[];let k=0,x=0;for(const T of S){const A=String(T.path||"").slice(v.length);if(!A||td(A))continue;x+=1,o(`fetching ${x}/${S.length}: ${A}`);const R=await rd(n,`${u}/blobs/${encodeURIComponent(T.objectId)}?api-version=7.1&$format=octetStream`,{...m,accept:"application/octet-stream"},"dev.azure.com");if(k+=R.length,k>Bn)throw new Error(`package exceeds the ${Math.round(Bn/1024)} KB upload limit at ${A}`);E.push({path:A,contentBase64:pi(R)})}return E}async function Mm(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=Jc(t);if(i.error)throw new Error(i.error);const o={fetchImpl:e,token:s,tokenKind:n,onProgress:r},l=i.kind==="github"?await Nm(i,o):await Pm(i,o);if(l.length===0)throw new Error("the package folder is empty");return{kind:i.kind,files:l}}function _m(t=[]){const e=(Array.isArray(t)?t:[]).find(s=>s?.path==="plugin.json");if(!e?.contentBase64)return null;try{const s=ed(e.contentBase64),n=JSON.parse(new TextDecoder().decode(s));return String(n?.name||"").trim()||null}catch{return null}}function co(t){return t?.isSystem?Pc(t):Number.MAX_SAFE_INTEGER}function $m(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 Rm(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return $m(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 Lm(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 Ms(t){return!!(t&&!t.isSystem&&!t.parentSessionId)}function Om(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function uo(t,e){return!!(Om(t)&&e&&e.has(t.sessionId))}function po(t,e){return t.isSystem?0:t.isGroup&&uo(t,e)?1:uo(t,e)?2:t.isGroup?3:4}function mo(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function fo(t,e,s,n,r){const i=po(t,n),o=po(e,n);if(i!==o)return i-o;const l=co(t),c=co(e);if(l!==c)return l-c;if(r&&r.size>0&&Ms(t)&&Ms(e)){const y=r.has(t.sessionId)?r.get(t.sessionId):1/0,S=r.has(e.sessionId)?r.get(e.sessionId):1/0;if(y!==S)return y-S}const d=s.get(t.sessionId),u=s.get(e.sessionId);if(typeof d=="number"&&typeof u=="number"&&d!==u)return d-u;const p=mo(t),m=mo(e);if(p>0&&m>0&&p!==m)return p-m;const f=(t.createdAt||0)-(e.createdAt||0);if(f!==0)return f;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 lt(t=[],e=new Set,s=[],n=null,r=null){const i=new Map,o=new Map,l=Rm(s),c=Lm(r),d=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const g of t)i.set(g.sessionId,g);const u=[];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),u.push(y)}const p=new Set(u.map(g=>g.sessionId));u.length>0&&(t=[...t,...u]);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)=>fo(b,y,l,d,c));const m=t.filter(g=>!(g.parentSessionId||!g.isGroup&&g.groupId)).sort((g,b)=>fo(g,b,l,d,c)),f=[];function h(g,b){const y=o.get(g.sessionId)||[];if(f.push({sessionId:g.sessionId,depth:b,hasChildren:y.length>0,collapsed:e.has(g.sessionId),...p.has(g.sessionId)?{standIn:g}:{}}),!e.has(g.sessionId))for(const S of y)h(S,b+1)}for(const g of m)h(g,0);return f}const Fm=Object.freeze({author:"author",owner:"author",agent:"agent",status:"status",group:"group",folder:"group",model:"model",id:"id",topic:"topic",summary:"summary"}),Dm=Object.freeze({title:12,id:11,author:10,agent:9,summary:7,group:6,model:5,status:4});function ft(t){return String(t||"").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9@._+-]+/g," ").trim().replace(/\s+/g," ")}function id(t){const e=String(t||"").trim(),s=[],n=[],r=/(?:(\w+):)?(?:"([^"]+)"|(\S+))/g;let i;for(;(i=r.exec(e))!==null;){const o=String(i[1]||"").toLowerCase(),l=i[2]??i[3]??"",c=ft(l);if(!c)continue;const d=Fm[o];d?n.push({field:d,value:c}):s.push(ft(o?`${o} ${l}`:l))}return{source:e,terms:s.filter(Boolean),filters:n}}function Bm(t,e,s){if(Math.abs(t.length-e.length)>s)return s+1;let n=Array.from({length:e.length+1},(r,i)=>i);for(let r=1;r<=t.length;r+=1){const i=[r];let o=i[0];for(let l=1;l<=e.length;l+=1){const c=Math.min(i[l-1]+1,n[l]+1,n[l-1]+(t[r-1]===e[l-1]?0:1));i.push(c),o=Math.min(o,c)}if(o>s)return s+1;n=i}return n[e.length]}function ho(t,e){if(!t||!e)return 0;if(t===e)return 16;const s=t.split(" ");if(s.includes(e))return 14;if(t.includes(e))return e.includes(" ")?13:11;if(e.length>=2&&s.some(r=>r.startsWith(e)))return 9;if(e.length>=4&&s.some(r=>r.includes(e)))return 7;if(e.length<4)return 0;const n=e.length>=6?2:1;return s.some(r=>Bm(r,e,n)<=n)?4:0}function Hm(t){return!t||typeof t!="object"?[]:[t.topic,t.intent,t.summary,t.title].filter(e=>typeof e=="string"&&e.trim())}function Um(t,{owner:e=null,groupTitle:s=""}={}){const n=ft(t?.title),r=ft([t?.shortSummary,...Hm(t?.summaryState)].filter(Boolean).join(" ")),i=ft([e?.displayName,e?.email,e?.subject].filter(Boolean).join(" "));return{title:n,summary:r,topic:ft(`${n} ${r}`),author:i,agent:ft(t?.agentId),status:ft(t?.status),group:ft(s),model:ft(`${t?.model||""} ${t?.reasoningEffort||""}`),id:ft(t?.sessionId)}}function jm(t,e){const s=typeof e=="string"?id(e):e;if(!s||s.terms.length===0&&s.filters.length===0)return 1;let n=0;for(const i of s.filters){const o=ho(t?.[i.field]||"",i.value);if(!o)return 0;n+=o*14}for(const i of s.terms){let o=0;for(const[l,c]of Object.entries(Dm))l==="id"&&(/^\d+$/.test(i)||i.length<8)||(o=Math.max(o,ho(t?.[l]||"",i)*c));if(!o)return 0;n+=o}const r=s.terms.join(" ");return r&&t?.title?.includes(r)?n+=120:r&&t?.summary?.includes(r)&&(n+=60),n}const yt="VS Code",Os="Retro",is="Others",go=Object.freeze([yt,Os,is]);function Gm(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function Mr(t){return Number.parseInt(t,16)/255}function Wm(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 _r(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function qm(t){const e=Wm(t);if(!e)return 0;const s=_r(Mr(e.slice(1,3))),n=_r(Mr(e.slice(3,5))),r=_r(Mr(e.slice(5,7)));return .2126*s+.7152*n+.0722*r}function zm(t){const e=t?.page?.background||t?.tui?.background||t?.terminal?.background;return qm(e)>=.5}function je({id:t,label:e,description:s,group:n=is,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 Gm({id:t,label:e,description:s,group:n,icon:l||null,page:r,terminal:i,tui:{...c,...o}})}const Km=je({id:"github-dark",label:"GitHub Dark",description:"GitHub dark palette with soft blue accents and cool neutrals.",group:yt,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"}}),Vm=je({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",group:yt,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"}}),ad=je({id:"workspace-dark",label:"Workspace Dark",description:"Flat workspace chrome: tone surfaces and hairlines instead of panel borders.",group:is,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"}}),Ym=je({id:"cobalt2",label:"Cobalt2",description:"Electric blue shell with bright yellow accents and saturated syntax colors.",group:yt,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"}}),Xm=je({id:"dracula",label:"Dracula",description:"Classic Dracula contrast with neon green, pink, and violet accents.",group:yt,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"}}),Qm=je({id:"catppuccin-mocha",label:"Catppuccin Mocha",description:"Creamy dark palette with soft pastels and high legibility.",group:yt,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"}}),Zm=je({id:"hacker-x-matrix",label:"Hacker X - Matrix",description:"Black-and-phosphor terminal palette with vivid green glow and CRT-style contrast.",group:yt,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"}}),Jm=je({id:"hacker-x-orion-prime",label:"Hacker X - Orion Prime",description:"Deep-space navy palette with electric cyan, violet, and amber accents.",group:yt,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"}}),ef=je({id:"gruvbox-dark",label:"Gruvbox Dark",description:"Retro warm palette with earthy browns, oranges, and high readability.",group:yt,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"}}),tf=je({id:"noctis",label:"Noctis",description:"Dark cyan-tinted palette with warm and cold medium contrast accents.",group:yt,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"}}),sf=je({id:"noctis-obscuro",label:"Noctis Obscuro",description:"Deep obsidian palette with cool blue accents and restrained contrast for long sessions.",group:yt,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"}}),nf=je({id:"terminal-green",label:"Terminal Green",description:"Classic black terminal with phosphor green text, amber warnings, and crisp operator contrast.",group:Os,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"}}),rf=je({id:"high-contrast-mono",label:"High Contrast Mono",description:"Accessibility-first monochrome theme with cobalt selection and severity colors only where they matter.",group:is,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"}}),af=je({id:"win95",label:"Windows 95",description:"Authentic 3D-bevelled grey, navy title bars, teal desktop, and the 16-colour VGA terminal set.",group:Os,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"}}),of=je({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:Os,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"}}),lf=je({id:"doom",label:"DOOM",description:"STBAR brown metal, bone type, and the three keycards as the status palette.",group:Os,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"}}),cf=je({id:"winamp",label:"WinAMP",description:"Bevelled grey chrome, black glass panes, phosphor green, and the spectrum ramp as the status palette.",group:Os,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"}}),df=je({id:"rust",label:"Rust",description:"Graphite and iron oxide, Ferris in the corner, and rustc's diagnostic levels as the status palette.",group:is,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"}}),uf="#a35838",pf="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",mf=je({id:"duroxide",label:"Duroxide",description:"Iron oxide pressed into black felt - the durable-execution runtime's own mark, traced from the banner.",group:is,icon:{viewBox:"0 0 64 64",paths:[{d:pf,fill:uf}]},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"}}),ff=je({id:"spongebob",label:"SpongeBob",description:"Bikini Bottom at depth, sponge-yellow accents, and the cast as the status palette.",group:is,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 hf(t,e){const s=go.indexOf(t.group),n=go.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 od=Object.freeze([ad,Xm,Km,Vm,Ym,Jm,Zm,Qm,ef,tf,sf,nf,rf,af,of,lf,cf,df,mf,ff].sort(hf)),gf=new Map(od.map(t=>[t.id,t])),yf=ad.id;function bf(){return od}function kt(t){return t?gf.get(t)??null:null}const Sf=new Set(["agent","user","system"]);function Zs(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 vf(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:Sf.has(t.source)?t.source:"agent"}}function Un(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const r of e){const i=vf(r);!i||n.has(i.filename)||(n.add(i.filename),s.push(i))}return s}function wf(t,e){const s=String(e||"").trim();return s&&Un(t).find(n=>n.filename===s)||null}function Ji(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 jn(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 ea(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 mi(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 Ef(t){return t==="canvas"?"canvas":"panes"}const ir=Object.freeze(["paneAdjust","activityPaneAdjust","canvasPaneAdjust","diagnosticsPaneAdjust","diagnosticsSplitAdjust"]),kf=Object.freeze(["desktop","mobile"]),If=300;function fi(){const t={};for(const e of ir)t[e]=0;return{canvasOpen:!1,diagnosticsOpen:!1,zen:!1,layout:t,at:0}}function xf(t){if(!t||typeof t!="object"||Array.isArray(t))return null;const e=fi();e.canvasOpen=t.canvasOpen===!0,e.diagnosticsOpen=t.diagnosticsOpen===!0,e.zen=e.canvasOpen&&t.zen===!0;const s=t.layout&&typeof t.layout=="object"?t.layout:{};for(const r of ir){const i=Number(s[r]);e.layout[r]=Number.isFinite(i)?Math.trunc(i):0}const n=Number(t.at);return e.at=Number.isFinite(n)&&n>0?Math.trunc(n):0,e}function ld(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e=[];for(const[n,r]of Object.entries(t)){const i=String(n||"").trim();if(!i||!r||typeof r!="object"||Array.isArray(r))continue;const o={};let l=0;for(const c of kf){const d=xf(r[c]);d&&(o[c]=d,l=Math.max(l,d.at))}Object.keys(o).length>0&&e.push([i,o,l])}e.sort((n,r)=>r[2]-n[2]);const s={};for(const[n,r]of e.slice(0,If))s[n]=r;return s}function cd(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 it(t,e){const s=String(t||""),n=Number(e);return Number.isInteger(n)&&n>=2&&n<=5?`${s}#${n}`:s}function Af(t){const e=/^(.*)#([2-5])$/.exec(String(t||""));return e?{sessionId:e[1],slot:Number(e[2])}:{sessionId:String(t||""),slot:1}}function ta(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 dd(t){if(t==null)return null;const e=String(t).trim();return e||null}const Nf=Object.freeze(["limit","allowance","hold","no_provider"]);function _s(t){const e=t?.pauseState;if(!e||typeof e!="object")return null;const s=String(e.kind||"");if(!Nf.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 Cf=Object.freeze(["day","week","month"]),Gn=Object.freeze([14,30,90]),Fe=14;function hi({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:u=null,desktopPanes:p=null,canvasPrefs:m=null}={}){const f=cd(p,Ef(u)),h=r!=null,g=l!=null,b=Ji(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:L.SESSIONS,budgetOpen:!1,inspectorTab:gt[0],nodeMapSelectedNode:null,sequenceExpandedTurns:[],sequenceSelectedTurn:null,rightPaneMode:f.canvasOpen?"canvas":"panes",canvasOpen:f.canvasOpen,diagnosticsOpen:f.diagnosticsOpen,canvasZen:f.zen,canvasMaximized:!1,sessionViews:{},sessionViewsLoaded:!1,sessionViewDevice:null,statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:kt(n)?.id||yf,touchScale:!1,sessionDetailCollapsed:!0,agentPickerUsage:{},modal:null,fullscreenPane:null,revealedCreatedSessionId:null,layout:{...b,viewportWidth:120,viewportHeight:40},scroll:{chat:0,inspector:0,activity:0,filePreview:0},chatScrollBySession:{},chatFollowBottomBySession:{},followBottom:{chat:!0,inspector:!0,activity:!0}},connection:{mode:t,connected:!1,workersOnline:null,error:null},sessions:{byId:{},groupRows:[],flat:[],activeSessionId:dd(c),collapsedIds:mi(l),collapsedIdsExplicit:g,pinnedIds:jn(o),manualOrder:ea(d),listingSeen:!1,groupsListingSeen:!1,selectedIds:[],selectMode:!1,listDeselected:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:h,ownerFilter:Zs(r),navigationIntent:null,filterExceptionId:null,ownerFilterAutoAdmitted: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:ta(m),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:{tab:"providers",summary:{loading:!1,error:null,fetchedAt:0,days:14,preset:"all",providers:[],data:null},agents:{loading:!1,error:null,fetchedAt:0,data:null},loading:!1,refreshing:!1,loaded:!1,error:null,fetchedAt:0,grid:[],overall:!1,rangeDays:Fe,selectedProvider:null,selectedScope:"*",missingProvider:null,series:{provider:null,scope:"*",rangeDays:Fe,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:{provider:null,scope:"*",rangeDays:Fe,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",features:{mode:"mine",userId:null,data:null,users:[],drafts:{},loading:!1,saving:!1,error:null,generation:0,fetchedAt:null,userQuery:""},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}}}}const Tf=5,yo=16,F0=920,gi=t=>t&&typeof t=="object"&&!Array.isArray(t),yi=t=>typeof t=="string"&&/^[a-zA-Z0-9_-]{1,100}$/.test(t),D0=()=>({id:crypto.randomUUID(),type:"empty"}),bi=t=>t?t.type==="split"?[...bi(t.first),...bi(t.second)]:[t]:[];function Pf(t){if(!gi(t))throw new Error("Invalid MoA layout.");const e=new Set;let s=0,n=0;function r(i,o=0){if(!gi(i)||o>15||++n>31||!yi(i.id)||e.has(i.id))throw new Error("Invalid MoA panel tree.");if(e.add(i.id),i.type==="split"){if(!["row","column"].includes(i.direction)||!Number.isFinite(i.ratio))throw new Error("Invalid MoA split.");return{id:i.id,type:"split",direction:i.direction,ratio:Math.min(90,Math.max(10,i.ratio)),first:r(i.first,o+1),second:r(i.second,o+1)}}if(++s>yo)throw new Error(`A MoA supports up to ${yo} panels.`);if(i.type==="empty")return{id:i.id,type:"empty"};if(!["chat","canvas"].includes(i.type)||!yi(i.sessionId))throw new Error("Invalid MoA session reference.");if(i.type==="canvas"&&(!Number.isInteger(i.slot)||i.slot<1||i.slot>5))throw new Error("Invalid canvas slot.");return{id:i.id,type:i.type,sessionId:i.sessionId,...i.type==="canvas"?{slot:i.slot}:{}}}return{name:typeof t.name=="string"&&t.name.trim().slice(0,64)||"Untitled MoA",tree:t.tree==null?null:r(t.tree)}}function Js(t){const e=(n,r="moa-1",i="MoA 1")=>{let o=null;try{o=Pf(n).tree}catch{}const l=bi(o);return{id:r,name:typeof n?.name=="string"&&n.name.trim().slice(0,64)||i,tree:o,...Number.isFinite(n?.aspectRatio)&&n.aspectRatio>=.2&&n.aspectRatio<=8?{aspectRatio:n.aspectRatio}:{},focusedPanelId:l.some(c=>c.id===n?.focusedPanelId)?n.focusedPanelId:l[0]?.id||null}};if(t?.version===3&&Array.isArray(t.dashboards)){const n=new Set,r=t.dashboards.slice(0,Tf).map((i,o)=>{let l=yi(i?.id)&&!n.has(i.id)?i.id:`moa-${o+1}`;for(;n.has(l);)l+="-copy";return n.add(l),e(i,l,`MoA ${o+1}`)});return r.length||r.push(e(null)),{version:3,activeDashboardId:r.some(i=>i.id===t.activeDashboardId)?t.activeDashboardId:r[0].id,dashboards:r}}let s=t;if(!(t?.version===2||gi(t)&&Object.hasOwn(t,"tree"))){const n=Array.isArray(t?.slots)?t.slots.slice(0,5):[],r=Number.isInteger(t?.activeSlot)?Math.max(0,Math.min(4,t.activeSlot)):0;s=e(n[r]).tree?n[r]:n.find(i=>e(i).tree)}return{version:3,activeDashboardId:"moa-1",dashboards:[e(s)]}}const B0=t=>t.dashboards.find(e=>e.id===t.activeDashboardId)||t.dashboards[0];function H0(t,e,s){return Js({...t,dashboards:t.dashboards.map(n=>n.id===e?{...n,...s}:n)})}function U0(t,e,s){const n=Js(t),r=n.dashboards.findIndex(l=>l.id===e);if(r<0||!Number.isInteger(s))return n;const i=[...n.dashboards],[o]=i.splice(r,1);return i.splice(Math.max(0,Math.min(i.length,s)),0,o),{...n,dashboards:i}}function bo(t,e,s){if(!t)return null;if(t.id===e)return s;if(t.type!=="split")return t;const n=bo(t.first,e,s),r=bo(t.second,e,s);return n?r?n===t.first&&r===t.second?t:{...t,first:n,second:r}:n:r}function Si(t){const e=String(t??"");if(!e.includes("\\n"))return e;const s=new RegExp("(`+)[\\s\\S]*?\\1(?!`)|(~{3,})[\\s\\S]*?\\2|([\"'])[A-Za-z]:\\\\[^\\r\\n]*?\\3|(?<!\\w)(?:[A-Za-z]:\\\\|\\\\\\\\)(?:(?!\\\\n\\\\n|\\\\r\\\\n\\\\r\\\\n)[^\\s\"'`])+|([\"'])(?:\\\\r\\\\n|\\\\[nr])\\4|\\\\\\\\|\\\\r\\\\n|\\\\n","g");return e.replace(s,n=>n==="\\n"||n==="\\r\\n"?`
|
|
32
|
-
`:n)}const ud="activeHighlightBackground",sa="activeHighlightForeground";function Mf(t){return t==="anthropic-wif"}const $r="userChat",_f="userChatLabel",$f="otherUserChatLabel",So=new WeakMap,vo=new WeakMap;function Rf(t){return t||sa}function pd(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Rf(s?.color):sa,backgroundColor:ud,bold:s?.bold??!0}))}function bt(t,{color:e=sa,bold:s=!0}={}){return{text:t,color:e,backgroundColor:ud,bold:s}}function ht(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Lf=72;function md(t){const e=Number(t)||0;return e>0&&e<=Lf}function fd(t){if(!t)return"unknown";const e=t.status||"unknown",s=e==="waiting"||e==="idle"||e==="unknown";return s&&_s(t)?"budget_paused":t.cronActive===!0&&s?"cron_waiting":s&&(Number(t.activeChildCount)||0)>0?"awaiting_children":e}const wo={day:"daily",week:"weekly",month:"monthly"};function hd(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 Of(t,e=Date.now()){const s=t?.provider||"this session's provider",n=t?.resetsAtUtc?ba(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=wo[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=wo[t?.period],o=t?.modelQualified?` for ${t.modelQualified}`:"";return`${s} has reached its ${i?`${i} `:""}limit${o}.${r}`}}}function Ff(t,e){const s=_s(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?_s({pauseState:i.pause}):null}function Df(t,e=null){const s=Ff(t,e);return s?{kind:s.kind,provider:s.provider,period:s.period,resetsAtUtc:s.kind==="no_provider"?null:s.resetsAtUtc,label:hd(s),reason:Of(s),clears:og(s),color:"red"}:null}function Bf(t,e){if(e==="budget_paused")return hd(_s(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 Hf(t){if(!t)return null;const e=t.updatedAt||t.summaryUpdatedAt||t.latestSummaryUpdatedAt||t.createdAt||0;return{status:gd(t)||"unknown",timestampMs:e||null,relative:e?Ea(e):"—"}}function gd(t){const e=yd(t);return!e||e==="unknown"?"":Bf(t,e)}function yd(t){return t?.rowVisualStatus||fd(t)}function vi(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function na(t){const e=fd(t);return t?.orchestrationStatus==="Failed"?"failed":vi(t?.orchestrationStatus)?null:e==="failed"?"failed":e==="error"||!["completed","cancelled","terminated","input_required"].includes(t?.status)&&String(t?.error||"").trim()&&!vi(t?.orchestrationStatus)?"warning":null}function ra(t,e="local"){const s=na(t);if(s)return s;const n=yd(t);if(e==="remote"&&vi(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 ks(t,e="local"){switch(ra(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 bd(t,e="local"){switch(ra(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 Ae(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function sn(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const nn=Ae({provider:"system",subject:"system"});function Eo(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 wi(t){return Eo(t?.displayName)||Eo(t?.email)||"?"}function Uf(t,e=!1){return Ms(t)?e?t.isGroup?"pinned:folders":"pinned:sessions":t.isGroup?"folders":t.groupId?`g:${t.groupId}`:"":null}function Sd(t,{isMine:e=!1,hueByKey:s=null}={}){if(!t)return null;const n=sn(t,t?.email||""),r=Ed(t,t?.email);return{initials:wi(t),hue:s?.get?.(r)??wd(r),name:n||"unknown user",isMine:!!e}}function jf(t){const e=[...new Set([...t].map(r=>String(r||"").trim().toLowerCase()).filter(Boolean))].sort(),s=new Set,n=new Map;for(const r of e){let i=wd(r);if(s.size<An){let o=0;for(;s.has(i)&&o<An;)i=(i+1)%An,o+=1}s.add(i),n.set(r,i)}return n}let dn=null;function vd(t){if(dn&&dn.byId===t)return dn.map;const e=[];for(const n of Object.values(t||{})){if(!n||n.isSystem||n.isGroup)continue;const r=n.owner,i=Ae(r);!i||i===nn||e.push(Ed(r,r?.email))}const s=jf(e);return dn={byId:t,map:s},s}function Gf(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=Ae(n);r&&!e.has(r)&&e.set(r,n)}return e}function Wf(t,e){if(t?.owner?.displayName||t?.owner?.email)return t.owner;const s=e?.get?.(Ae(t?.owner))||null;return s||(t?.createdBy?{email:t.createdBy}:null)}const An=12;function wd(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%An}function Ed(t,e){return String(e||t?.email||t?.displayName||(t?.provider&&t?.subject?`${t.provider}:${t.subject}`:"")||"").trim().toLowerCase()}function qf(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=Ae(o.owner);if(!(!l||l===nn)&&ki(o,n,r)&&(i.add(l),i.size>=e))break}return i.size}function Ei(t){return qf(t,2)>1}function kd(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function Yt(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of kd(t,e)){const r=Ae(n?.owner);r&&!s.has(r)&&s.set(r,n.owner)}return s.size===1?s.values().next().value:null}function ko(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Io(t,e){const s=ko(t),n=ko(e?.agentId);return!!(s&&n&&s===n)}function zf(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&&Io(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&&Io(o,t))return{displayTitle:l,agentTitle:o}}return null}function Kf(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 Vf=[[/</g,"<"],[/>/g,">"],[/"/g,'"'],[/�?39;/g,"'"],[/'/g,"'"],[/ /g," "],[/&/g,"&"]];function Yf(t){let e=String(t??"");if(!e.includes("&"))return e;for(const[s,n]of Vf)e=e.replace(s,n);return e}function ia(t){return Yf(Xf(t))}function Xf(t){const e=String(t?.title||"").trim(),s=zf(t);if(!s)return e;const n=Kf(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function Id(t,e){const s=_e(t?.sessionId);if(t?.isSystem)return`${rs(t,e)} (${s})`;const n=ia(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function ki(t,e={},s={},n=void 0){if(!e||e.all===!0||t?.isGroup)return!0;if(t?.isSystem)return e.includeSystem===!0;const r=Ae(n!==void 0?n:t?.owner);if(!r)return e.includeUnowned===!0;if(r===nn)return e.includeSystem===!0;const i=Ae(s?.principal);return e.includeMe&&i&&r===i||e.includeShared===!0&&r!==i?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(r)}function aa(t,e={},s={},n=null){const r=Yt(t,n||{});if(ki(t,e,s,r))return!0;if(!n)return!1;if(t?.isGroup)return kd(t,n).some(l=>aa(l,e,s,n));let i=t,o=0;for(;i?.parentSessionId&&o<16;){const l=n[i.parentSessionId];if(!l)return!1;if(ki(l,e,s))return!0;i=l,o+=1}return!1}function Qf(t){return(t||[]).map(e=>e?.text||"").join("")}function oa(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 xo(t){const{childMap:e}=oa(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 Ao(t=[],e={}){const{parentMap:s}=oa(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 la(t={}){if(!t||typeof t!="object")return xo(t);const e=So.get(t);if(e)return e;const s=xo(t);return So.set(t,s),s}function ca(t=[],e={}){if(!Array.isArray(t))return Ao(t,e);const s=vo.get(t);if(s)return s;const n=Ao(t,e);return vo.set(t,n),n}function xd(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 Wn(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 Zf(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${Wn(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${Zt(t.cronInterval)}]`,color:"magenta"}:null}function Ad(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Jf(t,e){const s=[];typeof t?.regenStage=="string"&&t.regenStage&&s.push({text:`↻ regen:${t.regenStage}`,color:"magenta"});const n=gd(t);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:ks(t,e)}));const r=ha(t?.model,t?.reasoningEffort);r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r,color:"cyan"}));const i=up(t?.contextUsage);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i.text,color:i.color}));const o=pp(t?.contextUsage);return o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color})),s}function eh(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:[]),u=!!s.sessions?.selectMode,p=d.has(t.sessionId),m=c.has(t.sessionId);if(p&&i.push({text:"▌",color:"cyan",bold:!0,role:"selection"}),t.depth===0&&Ad(e)&&c.size>0&&(m&&!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 M=bd(e,o);i.push({text:M?`${M} `:" ",color:ks(e,o),role:"status"})}const f=e?.isGroup?"cyan":e?.isSystem?"yellow":ks(e,o),h=Yt(e,s.sessions?.byId||{}),g=_e(e?.sessionId),b=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,y=b?ey(b):"",S=ha(e?.model,e?.reasoningEffort),v=e?.isSystem?rs(e,s.branding?.title||"PilotSwarm"):ia(e),w=!!(e?.isSystem||e?.isGroup||v&&v.trim()),E=[...i];if(Ei(s)&&!e?.isSystem&&!e?.isGroup){const M=Ae(s?.auth?.principal),B=!!(M&&Ae(h)===M),D=h?wi(h):"?";E.push({text:`[${D}] `,color:B?"green":"cyan",bold:!0,ownerChip:!0})}w?E.push({text:v,color:f,bold:!!(e?.isSystem||e?.isGroup)}):(E.push({text:g,color:f}),y&&(E.push({text:" · ",color:"gray"}),E.push({text:y,color:"gray"})),S&&(E.push({text:" · ",color:"gray"}),E.push({text:S,color:"green"})));const k=xd(e?.sessionId,t,n,r);k&&E.push({text:` ${k.text}`,color:k.color,bold:k.bold,role:"collapseBadge"});const x=ra(e,o)==="budget_paused"||e?.status==="waiting"?Df(e,s):null;x&&E.push({text:` ${x.label}`,color:x.color});const T=Zf(e);T&&E.push({text:" ⏱",color:"magenta"});const A=[],R=e?.contextUsage?.compaction?.state,N=Gi(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&A.push({text:`${e.memberCount}`,color:"gray"}):R==="running"?A.push({text:"⇊",color:"magenta"}):R==="failed"?A.push({text:"!",color:"red"}):N!=null?A.push({text:`${N}%`,color:N>=85?"red":N>=70?"yellow":"green"}):A.push({text:"—",color:"gray"});const $=[];e?.isGroup&&e?.memberCount!=null&&($.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),y&&($.push({text:" · ",color:"gray"}),$.push({text:y,color:"gray"})));const F=[],I=()=>{F.length&&F.push({text:" · ",color:"gray"})};if(e?.isGroup)F.push(...$);else{w&&(F.push({text:g,color:"cyan"}),y&&(I(),F.push({text:y,color:"gray"})),S&&(I(),F.push({text:S,color:"green"})));const M=e?.contextUsage;M&&Number.isFinite(M.currentTokens)&&Number.isFinite(M.tokenLimit)&&M.tokenLimit>0&&(I(),F.push({text:`ctx ${ne(M.currentTokens)}/${ne(M.tokenLimit)}`,color:"gray"}));const B=n?.[e?.sessionId];B&&(I(),F.push({text:`${B} child${B===1?"":"ren"}`,color:"gray"})),T&&(I(),F.push({text:T.text,color:T.color})),x&&(I(),F.push({text:x.reason,color:x.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(I(),F.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...E,...w&&y&&!e?.isGroup?[{text:" ",color:"gray"},{text:y,color:"gray"}]:[],...A.length&&!e?.isGroup?[{text:" · ",color:"gray"},...A]:[],...e?.isGroup&&$.length?[{text:" ",color:"gray"},...$]:[]],titleRuns:E,ctxRuns:A,metaRuns:$,badgeRuns:[],selectedMetaRuns:F,detailRuns:F,childCount:n?.get?.(e?.sessionId)||0,chrome:{kind:e?.isGroup?"group":e?.isSystem?"system":e?.serviceKind?"service":"session",title:w?v:g,untitled:!w,statusColor:ks(e,o),accentColor:f,pinned:m,selectMode:u,checked:p,owner:Ei(s)&&!e?.isSystem&&!e?.isGroup?{initials:h?wi(h):"?",isMine:!!(Ae(s?.auth?.principal)&&Ae(h)===Ae(s?.auth?.principal))}:null,childBadge:k?{text:k.text,color:k.color}:null,pause:x,cron:!!T,age:y||null,model:S||null,shortId:g,ctx:A.length>0?{text:A[0].text,color:A[0].color}:null}}}function th(t){return String(t||"").trim().toLowerCase()}function Is(t,e){const s=th(e);return s?String(t||"").toLowerCase().includes(s):!0}const No=new WeakMap;function sh(t,e){if(t?.isGroup)return t.title||"";if(t?.groupId)return e?.[`group:${t.groupId}`]?.title||"";let s=t;const n=new Set;for(;s?.parentSessionId&&!n.has(s.parentSessionId);)if(n.add(s.parentSessionId),s=e?.[s.parentSessionId],s?.groupId)return e?.[`group:${s.groupId}`]?.title||"";return""}function nh(t,e){const s=Yt(t,e);if(s)return s;let n=t;const r=new Set;for(;n?.parentSessionId&&!r.has(n.parentSessionId);)if(r.add(n.parentSessionId),n=e?.[n.parentSessionId],n?.owner)return n.owner;return null}function rh(t,e){const s=Array.isArray(t.sessions?.flat)?t.sessions.flat:[];if(!e)return s;const n=No.get(s);if(n?.query===e)return n.result;const r=t.sessions?.byId||{},i=id(e),o=lt(Object.values(r),new Set,t.sessions?.orderById,t.sessions?.pinnedIds,t.sessions?.manualOrder),l=new Map,c=new Map,d=new Map,u=[];for(let v=0;v<o.length;v+=1){const w=o[v];u[w.depth]=w.sessionId,u.length=w.depth+1,l.set(w.sessionId,w.depth>0?u[w.depth-1]:null),c.set(w.sessionId,w),d.set(w.sessionId,v)}const p=new Map;for(const v of o){const w=r[v.sessionId]||v.standIn;if(!w||!aa(w,t.sessions?.ownerFilter,t.auth||{},r))continue;const E=nh(w,r),k=Um(w,{owner:E,groupTitle:sh(w,r)}),x=jm(k,i);x>0&&p.set(v.sessionId,x)}const m=new Set(p.keys()),f=t.sessions?.filterExceptionId;f&&c.has(f)&&p.set(f,Number.MAX_SAFE_INTEGER);const h=new Set,g=new Map;for(const[v,w]of p){let E=v;const k=new Set;for(;E&&!k.has(E);)k.add(E),h.add(E),g.set(E,Math.max(g.get(E)||0,w)),E=l.get(E)||null}const b=new Map;for(const v of h){const w=l.get(v)||null;b.has(w)||b.set(w,[]),b.get(w).push(v)}for(const v of b.values())v.sort((w,E)=>(g.get(E)||0)-(g.get(w)||0)||(d.get(w)||0)-(d.get(E)||0));const y=[],S=(v,w)=>{const E=c.get(v);if(!E)return;const k=b.get(v)||[];y.push({...E,depth:w,collapsed:!1,hasChildren:k.length>0,searchIncluded:!0,searchMatch:m.has(v),searchScore:p.get(v)||0});for(const x of k)S(x,w+1)};for(const v of b.get(null)||[])S(v,0);return No.set(s,{query:e,result:y}),y}function ih(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 Co=new WeakMap;function ah(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 ns(t){const e=String(t.sessions?.filterQuery||"").trim(),s=rh(t,e),n=la(t.sessions.byId),r=ca(s,t.sessions.byId),i=t.sessions?.ownerFilter||{all:!0},o=t.auth||{},l=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),c=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]),d=ih(t.sessions);let u=Co.get(s);return u||(u=new Map,Co.set(s,u)),s.filter(p=>!!(t.sessions.byId[p.sessionId]||p.standIn)).map(p=>{const m=t.sessions.byId[p.sessionId]||p.standIn,f=p.sessionId===t.sessions.activeSessionId&&!t.sessions.listDeselected,h=l.has(p.sessionId),g=c.has(p.sessionId),b=[p,m,f,h,g,e,i,o,t.connection?.mode,t.sessions.selectMode,n,r,t.branding?.title,t.canvas?.bySessionId?.[p.sessionId],t.canvas?.prefs?.[p.sessionId],m?.pauseState,t.budget?.paused],y=u.get(p.sessionId);if(y&&ah(y.deps,b))return y.row;const S=eh(p,m,t,n,r),v={sessionId:p.sessionId,text:Qf(S.runs),...S,depth:p.depth,status:m?.status,statusColor:ks(m,t.connection?.mode||"local"),active:f,groupId:m?.groupId||p?.groupId||null,isSystem:!!m?.isSystem,isGroup:!!m?.isGroup,hasChildren:p.hasChildren,collapsed:p.collapsed,pinned:h,selected:g,canPin:Ad(m),ownerBadge:Ei(t)&&!m?.isSystem&&!m?.isGroup&&Yt(m,t.sessions.byId)?Sd(Yt(m,t.sessions.byId),{isMine:!!(Ae(t?.auth?.principal)&&Ae(Yt(m,t.sessions.byId))===Ae(t?.auth?.principal)),hueByKey:vd(t.sessions.byId)}):null,orderable:Ms(m),orderContainer:Uf(m,h),canvasMark:Lh(t,p.sessionId),pause:S.chrome?.pause||null,searchMatch:p.searchMatch===!0,searchScore:Number(p.searchScore)||0};return u.set(p.sessionId,{deps:b,row:v}),v}).filter(p=>{if(e||d?.has(p.sessionId))return!0;const m=t.sessions.byId[p.sessionId];if(!aa(m,i,o,t.sessions.byId))return!1;const f=Yt(m,t.sessions.byId),h=f?`${sn(f,"")} ${f.email||""}`:"";return Is(p.text,e)||Is(p.sessionId,e)||Is(h,e)})}function Ii(t,e=8){const s=ns(t);if(s.length===0)return[];const n=new Set(s.map(p=>p.sessionId)),r=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(p=>n.has(p.sessionId)),i=r.findIndex(p=>p.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 u=r.slice(c,d);return la(t.sessions.byId),ca(r,t.sessions.byId),s.filter(p=>u.some(m=>m.sessionId===p.sessionId))}function ut(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function oh(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 j0(t){const e=t.sessions?.ownerFilterAutoAdmitted||null,s=e?.ownerKey&&Array.isArray(t.sessions?.ownerFilter?.ownerKeys)&&t.sessions.ownerFilter.ownerKeys.includes(e.ownerKey);if(e?.sessionId&&s&&t.sessions?.byId?.[e.sessionId]){const r=t.sessions.byId[e.sessionId]?.owner;return`Added ${sn(r,"its owner")} to your session filters so the linked session is listed.`}const n=t.sessions?.filterExceptionId||null;return!n||!t.sessions?.byId?.[n]?null:"Showing linked session outside your current filters."}function Nd(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function Cd(t=[],e=[],s=()=>!0){const n=new Set(e);for(let r=(t||[]).length-1;r>=0;r-=1){const i=t[r];if(!i||!n.has(i.eventType)||!s(i))continue;const o=i.createdAt,l=o instanceof Date?o.getTime():typeof o=="number"?o:new Date(o||0).getTime();return Number.isFinite(l)&&l>0?l:null}return null}function lh(t,e=[]){const s=t?.pendingQuestion;if(!s?.question)return null;const n=[Si(s.question).trim()],r=Array.isArray(s.choices)?s.choices.filter(i=>typeof i=="string"&&i.trim()):[];if(r.length>0){n.push("","Choices:");for(const i of r)n.push(`- ${Si(i)}`)}return r.length>0&&s.allowFreeform===!1?n.push("","Reply with one of the choices above in the prompt below."):r.length>0?n.push("","Reply with one of the choices above, or type a free-form answer below."):n.push("","Type your answer in the prompt below and press Enter."),{id:`pending-question:${t.sessionId}:${s.question}`,role:"system",text:n.join(`
|
|
33
|
-
`),time:"",createdAt:Cd(e,["session.input_required_started"]),cardTitle:"Question",cardTitleColor:"cyan",cardBorderColor:"cyan"}}function ch(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),r=String(s?.answer||"").trim();if(!n||!r||Td(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}"
|
|
34
|
-
The user responded: "${r}"`,time:"",createdAt:o,optimistic:!0,pendingPhase:i}}function dh(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 Td(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>nr(n?.text||"")?.question?.trim()===s):!1}function uh(t,e=[]){const s=String(t?.error||"").trim();if(!s||On(s))return null;const n=na(t);if(!n)return null;const r=n==="failed",i=r?s:`${s}
|
|
35
|
-
|
|
36
|
-
The orchestration is still running, so this may be transient.`;return{id:`session-error:${t.sessionId}`,role:"system",text:i,time:"",createdAt:Cd(e,["session.error","session.turn_completed"],o=>sr(o.eventType==="session.error"?o.data?.message:o.data?.resultType==="error"?o.data?.errorMessage:null,s)),cardTitle:r?"Error":"Warning",cardTitleColor:r?"red":"yellow",cardBorderColor:r?"red":"yellow"}}function To(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 ph(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function mh(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=ph(i.text);if(o)return{...i,summaryText:o}}return null}function fh(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(E=>E?.role==="user"||E?.role==="assistant"),o=i[i.length-1]||null,l=o?.role==="user",c=l&&o?.optimistic===!0,d=(n||[]).filter(E=>E?.phase==="pending").length,u=(n||[]).filter(E=>E?.phase==="queued").length,p=(n||[]).filter(E=>E?.phase==="cancelling").length,m=Array.isArray(e?.events)?e.events:[],f=To(m,"user.message"),h=To(m,"assistant.message"),g=f>h;if(r==="waiting"||r==="input_required"||!l&&!g&&r!=="running"&&!c)return null;const b=Math.max(f,h),y=m.filter(E=>E?.eventType==="assistant.reasoning"&&Number(E?.seq||0)>b),S=y[y.length-1]||null,v=String(S?.data?.content||S?.data?.text||S?.data?.message||"").trim();if(v)return{kind:"thinking",label:"Thinking",text:v,createdAt:S?.createdAt||t.updatedAt||Date.now(),lastUserSeq:f,lastAssistantSeq:h,tokenSeq:S?.seq||0};const w=mh(e,b);return w?.summaryText?{kind:r==="running"?"working":"sending",label:r==="running"?"Working":"Sending",text:w.summaryText,createdAt:w.createdAt||t.updatedAt||Date.now(),lastUserSeq:f,lastAssistantSeq:h,tokenSeq:w.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:f,lastAssistantSeq:h,tokenSeq:0}:u>0?{kind:"queued",label:u===1?"Queued":`Queued ${u}`,text:u===1?"One prompt is durably queued, waiting for the LLM to receive it.":`${u} prompts are durably queued, waiting for the LLM to receive them.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:f,lastAssistantSeq:h,tokenSeq:0}:p>0?{kind:"cancelling",label:p===1?"Cancelling":`Cancelling ${p}`,text:p===1?"One queued prompt is waiting for cancellation confirmation.":`${p} queued prompts are waiting for cancellation confirmation.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:f,lastAssistantSeq:h,tokenSeq:0}:c?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:o?.createdAt||t.updatedAt||Date.now(),lastUserSeq:f,lastAssistantSeq:h,tokenSeq:0}:r==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:t.updatedAt||Date.now(),lastUserSeq:f,lastAssistantSeq:h,tokenSeq:0}:null}function da(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return cn(t.branding);if(s?.isGroup){const u=Object.values(t.sessions.byId||{}).filter(h=>h&&!h.isGroup&&h.groupId===s.groupId&&!h.parentSessionId),p=h=>String(h??"").replace(/\|/g,"\\|").replace(/[\r\n]+/g," ").trim()||" ",m=u.map(h=>`| ${p(h.title||h.sessionId)} | ${p(h.status||"unknown")} |`),f=[`# ${s.title||s.groupId}`,s.shortSummary||"","","| Metric | Count |","|---|---:|",`| Members | ${s.memberCount??u.length} |`,`| Running | ${s.runningCount??0} |`,`| Waiting | ${s.waitingCount??0} |`,`| Completed | ${s.completedCount??0} |`,`| Failed | ${s.failedCount??0} |`,`| Cancelled | ${s.cancelledCount??0} |`,"","## Members",...m.length>0?["| Session | Status |","|---|---|",...m]:["_No top-level members._"]];return[{id:`group-details:${s.sessionId}`,role:"system",noChrome:!0,text:f.filter((h,g)=>g===1||String(h||"").length>0).join(`
|
|
37
|
-
`),createdAt:s.updatedAt||Date.now()}]}const n=t.history.bySessionId.get(e),r=n?.chat||[];if(!r.length&&n?.loadState==="loading"){const u=cn(t.branding,s,{loading:!0});if(u.length)return u}if(!r.length&&["loading","failed"].includes(n?.loadState))return[{id:`history-load:${e}:${n.loadState}`,role:"system",noChrome:!0,text:n.loadState==="loading"?"Loading conversation…":"Could not load this conversation. Select the session again to retry."}];const i=n?.events||[],o=s?.pendingQuestion?.question&&!Td(r,s.pendingQuestion.question)?lh(s,i):null,l=ch(s,r),c=s?.chatWarnings?.length?null:uh(s,i);if((!n||r.length===0)&&!o&&!l&&!c&&!s?.chatWarnings?.length)return cn(t.branding,s);const d=Hp(r.length>0?r:cn(t.branding,s),s,i);if(o&&d.push(o),l&&d.push(l),c){const u=d.findLastIndex(p=>p.kind==="session-warning"&&sr(p.text,s.error));if(u<0){const p=d.findIndex(m=>c.createdAt!=null&&m.createdAt>c.createdAt);d.splice(p<0?d.length:p,0,c)}else if(u===d.length-1||c.cardTitle==="Error"){const p=d[u];d[u]={...p,...c,id:p.id,createdAt:p.createdAt,time:p.time}}}return d}function Rr(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function Pd(t){return t?.role==="user"&&t?.sender?.kind==="system"}function hh(t,e={}){const s=We(t?.createdAt||t?.time),n=t?.sender,r=n?.kind==="user"?Ae(n):null,i=e?.viewerKey||null,o=e?.ownerKey||null,l=e?.sharedContext===!0,c=t?.role==="user",u=c&&!!r&&!!i&&!(c&&r&&i&&r===i),m=l&&c&&o&&(r&&r===o||!r&&i&&i===o)?" (owner)":"",f=Pd(t)?n?.display||"System":c?(u?n.display||n.subject||"User":"You")+m: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":u?$f:t?.role==="user"?_f:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white";return{time:s,glyph:h,glyphColor:g,roleLabel:f,roleColor:b,fromOtherPerson:u}}function Po(t,e={}){const{time:s,glyph:n,glyphColor:r,roleLabel:i,roleColor:o}=hh(t,e),l=s?`[${s}] `:"",c=[...Rr(l,"gray")];return n&&c.push(...Rr(`${n} `,r)),c.push(...Rr(`${i}: `,o,{bold:!0})),c}function Bt(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function Md(){return[{text:"",color:null}]}function gh(t){const e=(t||[]).find(n=>Bt(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=Bt(e).trimStart();return/^[┌│└]/.test(s)}function qn(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(Bt(s).trim().length>0)break;e.shift()}return e}function yh(t){const e=String(t||"").replace(/\r\n/g,`
|
|
38
|
-
`),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(`
|
|
39
|
-
|
|
40
|
-
[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 bh.test(s)?{leadingText:"",systemText:s}:null}const bh=/^(?: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 _d(t){const e=yh(t);if(e){const o=[];e.leadingText&&o.push({kind:"text",text:e.leadingText});const l=Dt(e.systemText);return l&&o.push({kind:"system",text:l}),o}const s=String(t||"").replace(/\r\n/g,`
|
|
41
|
-
`).split(`
|
|
42
|
-
`),n=[];let r=[];function i(){r.length!==0&&(n.push({kind:"text",text:r.join(`
|
|
43
|
-
`)}),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 m=Dt(c[1].trim());if(!m){o+=1;continue}n.push({kind:"system",text:m}),o+=1;continue}const d=[l.replace(/^\s*\[SYSTEM:\s*/i,"")];let u=-1;for(let m=o+1;m<s.length;m+=1){const f=s[m];if(f.trim()==="]"){u=m;break}if(/\]\s*$/.test(f.trim())){const h=f.replace(/\]\s*$/,"");h.trim()&&d.push(h),u=m;break}d.push(f)}if(u===-1){r.push(l),o+=1;continue}i();const p=Dt(d.join(`
|
|
44
|
-
`).trim());if(!p){o=u+1;continue}n.push({kind:"system",text:p}),o=u+1}return i(),n}function Sh(t){return t?t?.role==="system"?!Yi(t?.text||"")||!!Dt(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:_d(t?.text||"").some(e=>e.kind==="system"):!1}function Mo(t){return Sh(t)?"system":t?.role||"other"}function $d(t,e){return!t||!e||t.kind==="chat-call"||e.kind==="chat-call"?!1:Mo(t)!==Mo(e)}function vh(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 wh(t,e=""){const s=vh(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:Vt(t),color:"gray"}}function xi({title:t,summary:e,body:s,timestamp:n="",color:r="gray",callPreview:i,callKey:o}){const l=String(t||"System").trim()||"System",c=String(e||"").replace(/\s+/g," ").trim();return{kind:"systemNotice",text:`${n?`[${n}] `:""}${l}${c?`: ${c}`:""}`,summary:c,body:Vt(s||c),color:r,...i!==void 0?{callPreview:`${l} — ${Ts(i)}`,callKey:o}:{}}}function Eh(t){return t?.label?[{text:t.label,color:t.kind==="working"?"yellow":"cyan",bold:!0}]:null}function kh(t,e){return e?(t||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||e})):s):t}function Ih(t){const e=(t||[]).find(s=>Bt(s).trim().length>0);return e?Bt(e).trimStart().startsWith("┌"):!1}function en(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&Ih(e)&&Bt(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function xh(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 Ah(t,e,s){const n=Math.max(20,Number(s)||20),r=We(e?.createdAt||e?.time),i=xh(t),o=l=>{const c=String(l||"").replace(/^session-/i,"");return _e(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,u)=>u===2||d).join(`
|
|
45
|
-
`);return[xi({title:`Sub-agent Response — ${l}`,callPreview:i.result||i.status,callKey:`${e.id}:agent:${l}`,summary:i.status||"completed",timestamp:r,body:c,color:"cyan"})]}if(i?.kind==="subAgentMulti"){const l=i.agents.map(d=>{const u=o(d.agentId),p=d.task?`**Task:** ${d.task}`:"",m=d.status?`**Status:** ${d.status}`:"";return`${[`### ${u}`,p,m].filter(Boolean).join(`
|
|
46
|
-
`)}
|
|
47
|
-
|
|
48
|
-
${d.result||"_(no result)_"}`}),c=i.agents.map(d=>`${o(d.agentId)} ${d.status||"completed"}`).join(" · ");return[xi({title:`Sub-agent Responses (${i.agents.length})`,callPreview:i.agents.map(d=>Ts(d.result)||d.status).join(" · "),callKey:`${e.id}:agents`,summary:c,timestamp:r,body:l.join(`
|
|
49
|
-
|
|
50
|
-
---
|
|
51
|
-
|
|
52
|
-
`),color:"cyan"})]}return He({title:"System",timestamp:r,body:t,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function _o(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),r=We(t?.createdAt||t?.time),i=String(t?.thinkingLabel||"Thinking…").trim()||"Thinking…",o=t?.progressKind==="working"?"yellow":(t?.progressKind==="sending","cyan"),l=Ce([{text:` ⠋ ${i} `,color:o,bold:!0},...r?[{text:` ${r} `,color:"gray"}]:[]],Math.max(1,s-3)),c=l.reduce((m,f)=>m+String(f?.text||"").length,0),d=Math.max(0,s-c-3),u=String(t?.text||"").trim()?qn(ss(Vt(t.text),{width:n})).flatMap(m=>xc(m,n)):[],p=[[{text:"┌─",color:"gray"},...l,{text:`${"─".repeat(d)}┐`,color:"gray"}]];for(const m of u)p.push([{text:"│ ",color:"gray"},...Ic(m.map(f=>({...f,color:f?.color&&f.color!=="white"?f.color:"gray"})),n),{text:" │",color:"gray"}]);return p.push([{text:`└${"─".repeat(Math.max(1,s-2))}┘`,color:"gray"}]),p.push([{text:"",color:null}]),p}function Nh(t){return String(t||"").split(`
|
|
53
|
-
`).reduce((e,s)=>Math.max(e,Wi(s).length),0)}const $o=new WeakMap;function xs(t,e,s={}){if(!t||typeof t!="object")return Ro(t,e,s);const n=JSON.stringify([e,s]);let r=$o.get(t);if(r?.has(n))return r.get(n);const i=Ro(t,e,s);return r||(r=new Map,$o.set(t,r)),r.size>=4&&r.delete(r.keys().next().value),r.set(n,i),i}function Ro(t,e,s={}){if(t?.kind==="chat-call")return s.tableMode==="sentinel"?[qp(t)]:[];if(s.tableMode==="sentinel"&&(t?.sender?.kind==="agent"||t?.agentCallPreview!==void 0)){const d=t.cardTitle||t.sender?.display||"Agent message";return[{kind:"chatCall",callKey:t.id,category:"Agent",text:`${d} — ${Ts(t.agentCallPreview??t.text)}`,body:t.text,time:t.time}]}if(t?.splash){const d=t.mobileText&&Nh(t.text)>e;return[{kind:"markup",value:d?t.mobileText:t.text,splashAlt:!d&&t.mobileText?t.mobileText:null}]}if(t?.thinking)return _o(t,e);if((t?.liveTurn||t?.streamSettling||t?.assistantPreview)&&s.tableMode==="sentinel"){const d=!t?.assistantPreview&&!!(t?.liveTurn||t?.streamSettling);return[{kind:"assistantPreview",width:e,text:d?"Message preview":"Agent update",statusText:d?t?.liveTurn?t?.text?"Responding":"Thinking":t?.streamSettling?"Finishing":"":"",previewKey:`assistant:${t?.liveKey||t?.messageId||t?.id||"active-turn"}`,body:Vt(t?.text||""),reasoningText:String(t?.reasoningText||t?.liveReasoningText||""),isLive:t?.liveTurn===!0,final:t?.responseFinal===!0,truncated:t?.truncated===!0,liveStartedAt:Number(t?.liveStartedAt||t?.createdAt)||0,time:t?.time||"",headerRuns:Po(t,s)}]}if(t?.liveTurn&&s.tableMode!=="sentinel"&&t.reasoningText){const d=_o({...t,text:t.reasoningText},e);return t.text?[...d,...xs({...t,reasoningText:""},e,s)]:d}if(t?.noChrome)return qn(ss(Vt(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const d=nr(t?.text||"");if(d)return[...d.question==="a question"?[]:He({title:"Question",timestamp:We(t?.createdAt||t?.time),body:Si(d.question),width:Math.max(20,e),titleColor:$r,borderColor:$r,tableMode:s.tableMode}),...xs({...t,text:d.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const d=_d(t?.text||"");if(d.some(u=>u.kind==="system")){const u=[];let p=!1;for(const f of d)f.kind!=="system"&&f.text.trim()&&(en(u,xs({...t,text:f.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:p})),p=!0);if(u.length>0)return u;const m=[];for(const f of d)f.kind!=="system"||!f.text.trim()||en(m,Ah(f.text,t,e));if(m.length>0)return m}}if(Pd(t))return[xi({title:t?.sender?.display||"Agent kickoff",summary:"opening instruction",timestamp:We(t?.createdAt||t?.time),body:t?.text||"",color:"gray"})];if(t?.role!=="user"&&t?.role!=="assistant"){const d=Dt(t?.text||"");if(t?.role==="system"&&!d)return[];const u=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!u)return[wh(d||t?.text||"",We(t?.createdAt||t?.time))];const p=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return He({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),cardKey:t?.id,timestamp:We(t?.createdAt||t?.time),body:Vt(t?.text||""),width:Math.max(20,e),titleColor:t?.cardTitleColor||(t?.role==="system"?"yellow":"cyan"),borderColor:t?.cardBorderColor||"gray",tableMode:s.tableMode,...p?{bodyColor:"gray",fitToContent:!0}:{}})}const n=qn(ss(Vt(t?.text||""),{width:e,tableMode:s.tableMode})),r=kh(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?$r:null),i=s.skipPrefix?[]:Po(t,s),o=Ch(t,s);if(r.length===0){const d=i.length>0?[i]:[];return o.length>0?[...d,...o]:d}if(gh(r)){const d=i.length>0?[i,...r]:r;return t?.streaming&&Lo(d),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 t?.streaming&&Lo(l),l.push(...o),l}function Lo(t){const e=[...t].reverse().find(s=>Array.isArray(s)&&s.some(n=>String(n?.text||"").trim()));e?e.push({text:" ▍",color:"cyan",role:"streamingCaret"}):t.push([{text:"▍",color:"cyan",role:"streamingCaret"}])}function Ch(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 Th=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 Ph(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 Mh=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),_h=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function $h(t,e){const s=String(t||"").toLowerCase();return s==="search_skills"||s.includes("skill")?e?"loading skills…":"loaded skills":Mh.has(s)?e?"reading facts…":"read facts":_h.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 Rh(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=$h(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"model.call_start":return`calling ${String(t?.text||"").replace(/^.*\bcalling\s+/i,"").trim()||"model"}…`;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 ar(t,e={}){const s=ut(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 S=i.length-1;S>=0;S-=1)if(i[S]?.role==="user"){o=Number(i[S]?.createdAt||0);break}const l=Array.isArray(r?.activity)?r.activity:[];let c=0,d=0;for(let S=l.length-1;S>=0;S-=1){const v=l[S],w=v?.eventType,E=Number(v?.createdAt||0);if(!c&&w==="assistant.turn_start"&&(c=E),!d&&(w==="assistant.turn_end"||w==="session.turn_completed")&&(d=E),c&&d)break}let u=0;o>d?u=o:c>d&&(u=c);let p=null;for(let S=l.length-1;S>=0;S-=1){const v=l[S];if(!(!v||Th.has(v.eventType))){if(Number(v.createdAt||0)<=d)break;p=v;break}}const m=Number.isFinite(e.now)?e.now:Date.now(),f=u>0?Ph(m-u):"",h=String(e.spinnerFrame||"").trim()||"●",g=p?Rh(p):"",b=[{text:`${h} `,color:"cyan"},{text:"Working",color:"cyan"},...f?[{text:` · ${f}`,color:"gray"}]:[],...g?[{text:` — ${g}`,color:"gray"}]:[]],y=Math.max(24,Math.min(120,Math.floor(Number(e.maxWidth)||80)));return[Ce(b,y)]}const Oo=4;let un=[];function ua(t,e=80,s={}){const n=t?.sessions?.activeSessionId??null,r=n?t?.sessions?.byId?.[n]??null:null,i={sessionId:n,session:r,byId:t?.sessions?.byId??null,chat:t?.history?.bySessionId?.get?.(n)?.chat??null,events:r?.chatWarnings?.length||r?.error||r?.pendingQuestion?t?.history?.bySessionId?.get?.(n)?.events??null:null,branding:t?.branding??null,principal:t?.auth?.principal??null,maxWidth:e,tableMode:s?.tableMode??null};for(const g of un)if(g.sessionId===i.sessionId&&g.session===i.session&&g.byId===i.byId&&g.chat===i.chat&&g.events===i.events&&g.viewMode===i.viewMode&&g.branding===i.branding&&g.principal===i.principal&&Object.is(g.maxWidth,i.maxWidth)&&g.tableMode===i.tableMode)return g.lines;const o=g=>(un.unshift({...i,lines:g}),un.length>Oo&&(un.length=Oo),g),l=da(t);if(!l||l.length===0)return o([{text:"No messages yet.",color:"gray"}]);const c=Ae(t?.auth?.principal),d=t?.sessions?.activeSessionId,u=d?t?.sessions?.byId?.[d]:null,p=Ae(u?.owner),m=!!(u&&(u.visibility&&u.visibility!=="private"||p&&c&&p!==c||c&&l.some(g=>g?.role==="user"&&g?.sender?.kind==="user"&&Ae(g.sender)&&Ae(g.sender)!==c))),f={...s?.tableMode?{tableMode:s.tableMode}:{},...c?{viewerKey:c}:{},...p?{ownerKey:p}:{},...m?{sharedContext:!0}:{}},h=[];for(const[g,b]of l.entries()){if(b?.kind==="native-task-group")if(s.tableMode==="sentinel")h.push({kind:"nativeTasks",group:b});else{const S={starting:"Starting",running:"Running",waiting:"Waiting",completed:"Done",failed:"Failed",cancelled:"Cancelled",interrupted:"Interrupted"};en(h,xs({...b,cardTitle:"Native tasks",cardTitleColor:"cyan",cardBorderColor:"cyan",text:b.tasks.map(v=>`[${S[v.status]||v.status}] ${v.title}`+(v.toolCalls?` · ${v.toolCalls} calls`:"")+(v.error||v.result||v.preview?`
|
|
54
|
-
${String(v.error||v.result||v.preview).replace(/\s+/g," ").slice(0,240)}`:"")).join(`
|
|
55
|
-
|
|
56
|
-
`)},e,f))}else if(b?.kind==="epoch-divider")h.push(Bh(b,e));else if(b?.kind==="regen-refused")h.push(Uh(b,e));else if(b?.kind==="regen-failed")h.push(jh(b,e));else if(b?.kind==="canvas-update")h.push(Dh(b,b.sessionId||n));else if(b?.kind==="canvas-action")h.push(Fh(b));else{const S=xs(b,e,f);en(h,S)}const y=l[g+1];y&&$d(b,y)&&Bt(h[h.length-1]).trim().length>0&&h.push(Md())}return o(h.length>0?h:[{text:"No messages yet.",color:"gray"}])}function Lh(t,e){if(!e)return null;let s=null;for(let n=1;n<=5;n+=1){const r=it(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}let Fo=null;function pa(t){const e=t?.sessions?.activeSessionId||null,s=t?.canvas?.bySessionId,n=t?.canvas?.prefs,r=t?.ui?.canvasSlot,i=t?.ui?.canvasOpen,o=t?.canvas?.flipSeq,l=Fo;if(l&&l.sessionId===e&&l.bySessionId===s&&l.prefs===n&&l.canvasSlot===r&&l.canvasOpen===i&&l.flipSeq===o)return l.result;const c=Oh(t);return Fo={sessionId:e,bySessionId:s,prefs:n,canvasSlot:r,canvasOpen:i,flipSeq:o,result:c},c}function Oh(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[it(e,g)];if(!b||(b.latestRev||0)<=0||b.sizeBytes===0)continue;const y=t?.canvas?.prefs?.[it(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?it(e,i):null,l=o?n[o]:null,c=o?t?.canvas?.prefs?.[o]:null,d=l?.latestRev||0,u=c?.lastViewedRev||0,p=l?.latestDataRev||0,m=c?.lastViewedDataRev||0,f=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:f,exists:h,latestRev:d,note:l?.note||"",sizeBytes:l?.sizeBytes??null,snapshotLoaded:!!l?.snapshotLoaded,optedOut:!!c?.optedOut,lastViewedRev:u,flipSeq:t?.canvas?.flipSeq||0,responseContract:l?.responseContract||null,latestDataRev:p,lastViewedDataRev:m,dataPayload:l?.dataPayload||null,dataPatch:l?.dataPatch||null,planeSeq:l?.planeSeq||0,unseen:h&&(d>u||p>m)&&f!=="canvas"}}function Fh(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):"";let n="";if(e.length)try{n=JSON.stringify(t.data,null,2)}catch{n=""}return{runs:[{text:"[canvas] ",color:"cyan",bold:!0},{text:`${t.action||"action"}`,color:"white"},...s?[{text:` — ${s}`,color:"gray"}]:[]],canvasAction:!0,canvasActionName:t?.action||"action",canvasActionDetail:s,canvasActionPayload:n,canvasActionTime:t?.time||""}}function Dh(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 ma(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 Bh(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 ma(n,"magenta",e)}const Hh={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 Uh(t,e){const s=String(t?.reason||"unknown"),r=` ↻ regeneration refused · ${Hh[s]||s.replace(/_/g," ")} `;return ma(r,"yellow",e)}function jh(t,e){const s=String(t?.stage||"unknown"),n=String(t?.error||"").split(`
|
|
57
|
-
`)[0],r=n.length>120?`${n.slice(0,117)}…`:n,i=` ✕ regeneration failed at ${s}${r?` · ${r}`:""} `;return ma(i,"red",e)}function Rd(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>dh(e,s)).filter(Boolean):[]:[]}function fa(t,e=80,s={}){const n=Rd(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 m=[[{text:` queued prompts: ${d.length>0?d.join(" · "):"queued prompts"} `,color:"gray",trailingRule:!0}]],f=s?.tableMode?{tableMode:s.tableMode}:{};for(const[h,g]of n.entries()){en(m,xs(g,r,f));const b=n[h+1];b&&$d(g,b)&&Bt(m[m.length-1]).trim().length>0&&m.push(Md())}return m}function Gh(t){const e=da(t),s=[],n=new Set;for(const r of e||[])for(const i of Ap(r?.text||"")){const o=`${i.sessionId}/${i.filename}`;n.has(o)||(n.add(o),s.push(i))}return s}function Wh(t){const e=da(t),s=[],n=new Set;for(const r of e||[])for(const i of Np(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 ha(t,e){const s=Cs(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function qh(t){return Cs(t)||"(unknown)"}function Ld(t,e={}){const s=ut(t),n=t.sessions?.byId||{},r=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],i=la(n),o=ca(r,n),l=md(e?.width);if(!s)return{color:"cyan",title:ht("Chat","cyan"),titleRight:null,animateTitleRight:!1};const c=_e(s.sessionId),d=s.isSystem?"yellow":"cyan",u=ht(s.isSystem?`⚙ ${rs(s,t.branding?.title||"PilotSwarm")}`:ia(s)||"Chat",d),p=r.find(w=>w.sessionId===s.sessionId),m=xd(s.sessionId,p,i,o);m&&u.push({text:` ${m.text}`,color:m.color}),l||u.push({text:` [${c}]`,color:"gray"});const f=t.history?.bySessionId?.get(s.sessionId)||null,h=Array.isArray(t.outbox?.bySessionId?.[s.sessionId])?t.outbox.bySessionId[s.sessionId]:[],g=fh(s,f,f?.chat||[],h),b=t.connection?.mode||"local",y=Jf(s,b),S=Eh(g),v=S?[...y,...y.length?[{text:" · ",color:"gray"}]:[],...S]:y;return{color:s.isSystem?"yellow":"cyan",title:u,titleRight:v.length?v:null,animateTitleRight:!!g}}function zh(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function Od(t){const e=qd(t),s=e.selected?e.nodes.find(o=>o.label===e.selected):null,n=ht("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?bt(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 ga(t,e=12){const s=zh(t),n=ut(t),r=ht("Activity","gray");return n?.isGroup?{title:r,disabled:!0,lines:[{text:Vd,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 Fd(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 Dd(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":Fd(e)}function Kh(t){return t==="raw"?"raw summary":"pretty text"}function Vh(t){return t?.sessionId?`session-${t.sessionId}`:null}function Yh(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},r=Vh(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 Xh(t){const e=rn(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:Dd(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${_e(s)}] `,color:"gray"}]:[],{text:`${n} `,color:Fd(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function Qh(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${_e(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:Dd(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function Zh(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:Kh(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=Yh(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"?Xh(o):Qh(o))]}function Do(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function Jh(t){return/\.(json|jsonl)$/i.test(String(t||""))}function eg(t){return gt.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function tg(t=""){const e=String(t||"").split(`
|
|
58
|
-
`);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function Bo(t,{selected:e=!1,width:s=24,label:n=null}={}){const r=Math.max(8,s),i=Do(t)?"# ":Jh(t)?"{ ":"• ",o=Hd(`${i}${n||t}`,r).padEnd(r," ");return e?bt(o):{text:o,color:Do(t)?"cyan":"white",bold:!1}}function ct(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function sg(t,e={}){if(!t)return new Set;const{childMap:s}=oa(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 zn(t,e=ct(t)){const s=ut(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=sg(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 Ho(t){const s=ut(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 u;for(;(u=l.exec(d))!==null;){const p=`${u[1]}/${u[2]}`;i.has(p)||(i.add(p),o.push(p))}}return o}function Xt(t){const e=ct(t);ut(t)?.sessionId;const s=t.files?.filter?.query||"",n=zn(t,e),r=e==="allSessions"||n.length>1,i=[];for(const o of n){const l=Un(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?`[${_e(o)}] ${d}`:d})}}return i.filter(o=>Is(o.filename,s)||Is(o.sessionId,s)||Is(o.label,s))}function Rt(t){const e=Xt(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(ct(t)==="allSessions"){const o=ut(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=ut(t)?.sessionId||null,i=r&&t.files?.bySessionId?.[r]?.selectedFilename||null;return e.find(o=>o.sessionId===r&&o.filename===i)||e[0]}function ya(t,e={}){const s=ut(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=ct(t),c=t.files?.filter?.query||"",d=Xt(t),u=Rt(t),p=u?.filename||null,m=Math.max(0,d.findIndex($=>$.id===u?.id)),f=u?.sessionId&&p&&t.files?.bySessionId?.[u.sessionId]?.previews?.[p]||null,h=f||u?.entry||null,g=s?_e(s.sessionId):"",b=zn(t,l),y=l!=="allSessions"&&b.some($=>$&&$!==o),S=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map($=>$?.sessionId||$):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),v=l==="allSessions"&&S.some($=>!t.files?.bySessionId?.[$]?.loaded||t.files?.bySessionId?.[$]?.loading),w=l==="allSessions"&&S.map($=>t.files?.bySessionId?.[$]?.error).find(Boolean)||null,E=[eg("files"),...s||l==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(l==="allSessions")v&&d.length===0?E.push({text:"Loading exported files across all sessions…",color:"gray"}):w&&d.length===0?E.push({text:w,color:"red"}):d.length===0?(E.push({text:c?`No artifacts matched "${c}" across any session.`:"No exported files across any session yet.",color:"gray"}),E.push({text:c?"Clear the query or switch back to the selected session.":"Switch the filter back to the selected session or wait for agents to export artifacts.",color:"gray"})):E.push(...d.map(($,F)=>Bo($.filename,{selected:F===m,width:n,label:$.label})));else if(s){const $=o?t.files?.bySessionId?.[o]:null;Array.isArray($?.entries)&&$.entries;const F=d.filter(I=>b.includes(I.sessionId));$?.loading?E.push({text:"Loading exported files…",color:"gray"}):$?.error?E.push({text:$.error,color:"red"}):F.length===0&&b.every(I=>{const O=t.files?.bySessionId?.[I]?.entries;return!Array.isArray(O)||O.length===0})?(E.push({text:c?`No artifacts matched "${c}" for this ${y?"session tree":"session"}.`:`No exported files for this ${y?"session tree":"session"} yet.`,color:"gray"}),E.push({text:c?"Clear the query or upload an artifact to this session.":y?"Artifacts exported by this session or any child session will appear here.":"Agents must write/export artifacts before they appear here.",color:"gray"})):E.push(...F.map((I,O)=>Bo(I.filename,{selected:O===m,width:n,label:I.label})))}let k,x;!s&&l!=="allSessions"?(x=[{text:"Preview",color:"cyan",bold:!0}],k=[{text:"No session selected.",color:"gray"}]):p?f?.loading?(x=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||u?.sessionId&&u.sessionId!==o)&&u?.sessionId?[{text:` · ${_e(u.sessionId)}`,color:"gray"}]:[]],k=[{text:"Loading file preview…",color:"gray"}]):f?.error?(x=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||u?.sessionId&&u.sessionId!==o)&&u?.sessionId?[{text:` · ${_e(u.sessionId)}`,color:"gray"}]:[]],k=[{text:f.error,color:"red"}]):(x=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||u?.sessionId&&u.sessionId!==o)&&u?.sessionId?[{text:` · ${_e(u.sessionId)}`,color:"gray"}]:[],...f?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:f?.isBinary===!0?[{text:" [file]",color:"gray"}]:f?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],k=f?.renderMode==="markdown"?qn(ss(f?.content||"",{width:r})):tg(f?.content||"")):(x=[{text:"Preview",color:"cyan",bold:!0}],k=[{text:"Select a file to preview it here.",color:"gray"}]);const T=l==="allSessions"?"Files: all sessions":s?`Files: ${g}${y?" tree":""}`:"Files",A=l==="allSessions"?"all sessions":s?`${g}${y?" tree":""}`:"Files",R=l==="allSessions"?`Artifacts${d.length>0?` [${d.length}]`:""}`:`Artifacts${y?" tree":""}${d.length>0?` [${d.length}]`:""}`,N=c?` · @${c}`:"";return{panelTitle:[{text:`${T}${N}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${A}${N}`,color:"magenta",bold:!0}],listTitle:[{text:`${R}${N}`,color:"cyan",bold:!0}],listLines:E,listBodyLines:E.slice(1),selectedIndex:m,selectedFilename:p,selectedSessionId:u?.sessionId||null,scope:l,previewTitle:x,previewLines:k,previewContent:f?.content||"",previewContentType:f?.contentType||"",previewRenderMode:f?.renderMode||null,previewIsBinary:h?.isBinary===!0,previewSizeBytes:h?.sizeBytes??null,previewUploadedAt:h?.uploadedAt||"",previewSource:h?.source||null,previewError:f?.error||null,previewLoading:!!f?.loading,previewScrollOffset:t.ui.scroll.filePreview||0,fullscreen:!!t.files?.fullscreen,fullscreenTitle:[{text:T,color:"magenta",bold:!0},...p?[{text:" · ",color:"gray"},{text:p,color:"cyan",bold:!0}]:[],...i?[{text:" [f filter] [u upload] [a download] [x delete] [o open] [v/esc close fullscreen]",color:"gray"}]:[]]}}function Uo(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);return Number.isNaN(e.getTime())?"—":e.toISOString().slice(0,10)}function gs(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 ng(t){const e=String(t||"").toLowerCase();return e.endsWith(".md")?"markdown":e.endsWith(".json")?"json":/\.(mjs|cjs|js)$/.test(e)?"javascript":"text"}function At(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=t.auth?.adminScope??s?.adminScope??"unrestricted",c=o&&l==="unrestricted",d=e.modelProviders||{},u=Array.isArray(d.providers)?d.providers:[],p=Array.isArray(d.models)?d.models:[],m=u.filter(P=>P?.class!=="shared"&&(P?.mine===!0||P?.usableByMe===!0)),f=u.filter(P=>P?.class==="shared"),h=P=>P.flatMap(z=>p.filter(oe=>oe?.providerId===z.name||oe?.providerId===z.typeId).map(oe=>{const ge=oe?.modelName||oe?.name||String(oe?.qualifiedName||"").split(":").pop(),Me=oe?.providerId===z.name&&oe?.qualifiedName?oe.qualifiedName:`${z.name}:${ge}`;return{provider:z.name,providerClass:z.class,model:ge,qualifiedName:Me,supportedReasoningEfforts:Array.isArray(oe?.supportedReasoningEfforts)?oe.supportedReasoningEfforts:[],defaultReasoningEffort:oe?.defaultReasoningEffort||null,supportedContextTiers:Array.isArray(oe?.supportedContextTiers)?oe.supportedContextTiers:[],defaultContextTier:oe?.defaultContextTier||null}})),g=d.defaults||{},b=new Map;for(const P of p)!P?.providerId||b.has(P.providerId)||b.set(P.providerId,{id:P.providerId,label:P.providerType||P.providerId,usesWorkloadIdentity:Mf(P.providerType)});const y=P=>({name:P.name,typeId:P.typeId||P.type||null,usesWorkloadIdentity:b.get(P.typeId||P.type)?.usesWorkloadIdentity===!0,class:P.class==="shared"?"shared":"personal",hasCredential:!!P.hasCredential,usableByMe:P.usableByMe!==!1,systemUseEnabled:!!P.systemUseEnabled,systemEligible:!!P.systemEligible,isClusterDefault:!!P.isClusterDefault,isMyDefault:!!P.isMyDefault,isSystemDefault:!!P.isSystemDefault}),S=o&&Array.isArray(g.systemOverrides)?g.systemOverrides:[],v=new Map(S.map(P=>[P.agentId,P])),w=new Map;for(const P of Object.values(t.sessions?.byId||{}))!P?.isSystem||!P?.agentId||w.has(P.agentId)||w.set(P.agentId,{agentId:P.agentId,title:rs(P,t.branding?.title||"PilotSwarm")});for(const P of S)w.has(P.agentId)||w.set(P.agentId,{agentId:P.agentId,title:P.agentId});const E=g.system?.effective||null,k=[...w.values()].sort((P,z)=>P.title.localeCompare(z.title)).map(P=>{const z=v.get(P.agentId)||null;return{...P,effectiveModel:(z||E)?.model||null,source:z?"agent_override":E?.source||"system_default",override:z}}),x=d.selection||{},T=d.page==="shared"&&o?"shared":"mine",A={loading:!!d.loading,error:d.error||null,page:T,providerTypes:[...b.values()].sort((P,z)=>P.id.localeCompare(z.id)),myProviders:m.map(P=>({...y(P),selected:P.name===x.providerName})),sharedProviders:f.map(P=>({...y(P),selected:P.name===x.providerName})),userChoices:h([...f.filter(P=>P.usableByMe!==!1),...m.filter(P=>P.usableByMe!==!1)]),clusterChoices:o?h(f):[],systemChoices:o?h([...f,...m.filter(P=>P.systemUseEnabled===!0)]):[],mySessionDefault:g.userSession||{configured:null,effective:null},clusterSessionDefault:o?g.clusterSession||{configured:null,effective:null}:null,systemSessionDefault:o?g.system||{configured:null,effective:null}:null,systemAgentOverrides:S,systemAgentRoutes:o?k.map(P=>({...P,selected:P.agentId===x.agentId})):[],selection:{focus:x.focus==="agents"?"agents":"providers",providerName:x.providerName||(T==="shared"?f[0]?.name:m[0]?.name)||null,agentId:x.agentId||k[0]?.agentId||null},mutation:{pending:d.mutation?.pending||null,error:d.mutation?.error||null}},R=o&&!!n.storeAsSystem,N=R?!!i.configured:!!s?.githubCopilotKeySet,$=R?"System key":"key",F=i.configured&&i.changedBy?` (set by ${i.changedBy})`:"",I=n.saving?"Saving...":n.editing?"Editing — Enter to save, Esc to cancel":R?i.configured?`System key configured — ownerless system sessions use it for GitHub Copilot models${F}`:"System key not configured — ownerless system sessions fall back to env GITHUB_TOKEN":s?.githubCopilotKeySet?"Configured (overrides env GITHUB_TOKEN for this user)":"Not configured (using env GITHUB_TOKEN fallback)",O=e.packages||{},M=Array.isArray(O.list)?O.list:[],B=P=>!!(c||P?.owner&&r&&P.owner.provider===r.provider&&P.owner.subject===r.subject),D=P=>B(P)||!!P?.canEdit,j=Gf(t?.sessions?.byId),V=vd(t?.sessions?.byId),C=new Set;for(const P of M){if(P?.scope==="shared")continue;const z=Ae(P?.owner)||String(P?.createdBy||"").trim().toLowerCase();!z||z===nn||C.add(z)}const U=C.size>1,H=(P,z,oe)=>`${P}${z==="shared"?"shared":"user"}${z==="shared"?"":oe?.subject??""}`,Y=O.selectedName?H(O.selectedName,O.selectedSelector?.scope??null,O.selectedSelector?.owner??r??null):null,te=P=>e.section!=="packages"||O.selectedName!==P.name?!1:O.selectedSelector?.scope?H(P.name,P.scope,P.owner)===Y:!0,ee=P=>({name:P.name,scope:P.scope==="shared"?"shared":"user",owner:P.owner??null,enabled:!!P.enabled,semver:P.active?.semver||null,sha7:P.active?.sha256?String(P.active.sha256).slice(0,7):null,agentCount:Array.isArray(P.active?.manifest?.agents)?P.active.manifest.agents.length:0,canManage:D(P),ownerBadge:P.scope==="shared"||!U?null:Sd(Wf(P,j),{hueByKey:V}),selected:te(P)}),J=P=>!!(P?.owner&&r&&P.owner.provider===r.provider&&P.owner.subject===r.subject),ae=t.sessions?.ownerFilter,de=P=>{if(!ae||ae.all===!0)return!0;const z=Ae(P?.owner);return z?Array.isArray(ae.ownerKeys)&&ae.ownerKeys.includes(z):ae.includeUnowned===!0},Z=M.filter(P=>P.scope==="shared").map(ee),le=M.filter(P=>P.scope!=="shared"&&J(P)).map(ee),$e=M.filter(P=>P.scope!=="shared"&&!J(P)&&de(P)).map(P=>({...ee(P),ownerLabel:P?.createdBy||P?.owner?.subject||"another user"})),be=["providers","packages","workers","features"].includes(e.section)?e.section:"providers",Re=[{id:"providers",kind:"section",depth:0,label:"Model Providers",selected:!1},{id:"myProviders",kind:"subsection",depth:1,label:"My Providers",selected:be==="providers"&&T==="mine"},...o?[{id:"sharedProviders",kind:"subsection",depth:1,label:"Shared Providers",selected:be==="providers"&&T==="shared"}]:[],{id:"features",kind:"section",depth:0,label:"Feature flags",selected:be==="features"},{id:"agents",kind:"section",depth:0,label:"Agents",selected:be==="packages"&&!O.selectedName},{id:"group:shared",kind:"group",depth:1,label:"Shared",count:Z.length},...Z.map(P=>({id:`pkg:shared:${P.name}`,kind:"package",depth:2,label:P.name,...P})),{id:"group:user",kind:"group",depth:1,label:"User",count:le.length},...le.map(P=>({id:`pkg:user:${P.name}`,kind:"package",depth:2,label:P.name,...P})),...$e.length>0?[{id:"group:others",kind:"group",depth:1,label:"Other users",count:$e.length},...$e.map(P=>({id:`pkg:user:${P.owner?.subject??"?"}:${P.name}`,kind:"package",depth:2,label:P.name,...P}))]:[],...o?[{id:"workers",kind:"section",depth:0,label:"Workers",selected:be==="workers"}]:[]],Se=O.detail||null;let rt=null;if(O.selectedName){const P=M.filter(re=>re.name===O.selectedName),z=(O.selectedSelector?.scope?P.find(re=>H(re.name,re.scope,re.owner)===Y):P[0])??P[0]??null,oe=Se?.versions?.find(re=>re.versionId===Se.activeVersionId)||null,ge=oe?.manifest||z?.active?.manifest||{},G=Date.now()-9e4,W=(Array.isArray(O.workerState)?O.workerState:[]).filter(re=>{const et=re?.updatedAt instanceof Date?re.updatedAt:new Date(re?.updatedAt??0);return!Number.isNaN(et.getTime())&&et.getTime()>=G}),ie=W.length,pe=re=>{const et=re.installed||{},It=Se?.scope||z?.scope||O.selectedSelector?.scope||null,os=Se?.owner?.subject||z?.owner?.subject||O.selectedSelector?.owner?.subject||"",ls=It==="user"?`${O.selectedName}#user${os?`:${os.slice(0,8)}`:""}`:`${O.selectedName}#shared`;return et[ls]??et[O.selectedName]},X=oe?W.filter(re=>pe(re)?.semver===oe.semver&&pe(re)?.status==="ok").length:0,me=z??Se,ye=me?B(me):!1,Oe=me?D(me):!1;rt={name:O.selectedName,loading:!!O.detailLoading,error:O.detailError||null,scope:(Se?.scope||z?.scope)==="shared"?"shared":"user",enabled:Se?!!Se.enabled:!!z?.enabled,canManage:ye,canEdit:Oe,editors:Array.isArray(Se?.editors)?Se.editors.map(re=>({provider:re.provider,subject:re.subject,label:re.displayName||re.email||re.subject,grantedByDisplay:re.grantedByDisplay||null})):[],createdBy:Se?.createdBy||z?.createdBy||null,createdAtText:Uo(Se?.createdAt||z?.createdAt),description:typeof ge.description=="string"?ge.description:"",activeSemver:oe?.semver||z?.active?.semver||null,activeSha12:oe?.sha256?String(oe.sha256).slice(0,12):null,sizeText:gs(oe?.sizeBytes??z?.active?.sizeBytes),agents:Array.isArray(ge.agents)?ge.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:(Se?.versions||[]).map(re=>({semver:re.semver,sha12:String(re.sha256||"").slice(0,12),dateText:Uo(re.createdAt),active:re.versionId===Se?.activeVersionId})),fleet:ie>0&&oe?{current:X,total:ie,text:`${X}/${ie} workers current`}:null,actionPending:O.action?.pending||null,actionError:O.action?.error||null,hasSharedCounterpart:P.some(re=>re.scope==="shared"),hasOwnUserCounterpart:P.some(re=>re.scope!=="shared"&&J(re)),copyCount:P.length}}const ce=O.workspace||{};let Ke=null;if(O.selectedName){const P=ce.tree,z=new Set(ce.expandedDirs||[]),oe=[];if(P){const Me=X=>{const me=X.split("/");for(let ye=1;ye<me.length;ye++)if(!z.has(me.slice(0,ye).join("/")))return!1;return!0},G=Array.isArray(P.dirs)?P.dirs:[],W=Array.isArray(P.files)?P.files:[],ie=X=>String(X).split("/").join("\0"),pe=[...G.map(X=>({type:"dir",path:X})),...W.map(X=>({type:"file",path:X.path,size:X.size}))].sort((X,me)=>ie(X.path)<ie(me.path)?-1:1);for(const X of pe){if(!Me(X.path))continue;const me=X.path.split("/").length-1;oe.push({type:X.type,path:X.path,label:X.path.split("/").pop()+(X.type==="dir"?"/":""),depth:me,expanded:X.type==="dir"?z.has(X.path):void 0,sizeText:X.type==="file"?gs(X.size):null,selected:ce.selectedPath===X.path})}}const ge=ce.file;Ke={loading:!!ce.treeLoading,error:ce.treeError||null,semver:ce.tree?.semver||null,treeRows:oe,file:ge?{path:ge.path,sizeText:gs(ge.size),truncated:!!ge.truncated,isBinary:ge.encoding==="base64",text:ge.encoding==="base64"?null:String(ge.content||""),language:ng(ge.path)}:null,fileLoading:!!ce.fileLoading,fileError:ce.fileError||null,selectedPath:ce.selectedPath||null}}const Ne=e.workers||{},Xe=Array.isArray(Ne.list)?Ne.list:[],q=9e4,he=Date.now(),Be=P=>!Number.isFinite(P)||P<0?"—":P<6e4?`${Math.round(P/1e3)}s ago`:P<36e5?`${Math.round(P/6e4)}m ago`:`${Math.round(P/36e5)}h ago`,Ee=P=>{if(!Number.isFinite(P)||P<0)return null;if(P<60)return`${Math.round(P)}s`;if(P<3600)return`${Math.floor(P/60)}m`;const z=Math.floor(P/3600);return z<48?`${z}h ${Math.floor(P%3600/60)}m`:`${Math.floor(z/24)}d ${z%24}h`},Pe=Xe.map(P=>{const z=P?.updatedAt instanceof Date?P.updatedAt:new Date(P?.updatedAt??0),oe=Number.isNaN(z.getTime())?Number.NaN:he-z.getTime(),ge=P?.health||{},Me=P?.info||{},G=P?.state?.["agent-packages"]||null,W=G?.installed&&typeof G.installed=="object"?Object.values(G.installed):[],ie=W.filter(pe=>pe?.status==="error").length;return{id:String(P?.workerNodeId??""),pool:String(P?.pool??"default"),phase:["starting","ready","draining"].includes(P?.phase)?P.phase:"ready",live:Number.isFinite(oe)&&oe<=q,agoText:Be(oe),uptimeText:Ee(ge.uptimeS),rssText:gs(ge.rssBytes),sessions:Number.isFinite(ge.activeSessions)?ge.activeSessions:null,eventLoopText:Number.isFinite(ge.eventLoopDelayP99Ms)?`${ge.eventLoopDelayP99Ms}ms`:null,sdkVersion:typeof Me.sdkVersion=="string"?Me.sdkVersion:null,substrate:typeof Me.runtime?.substrate=="string"?Me.runtime.substrate:null,consumes:Array.isArray(Me.consumes)?Me.consumes:[],owner:P?.owner?.subject?String(P.owner.subject):null,pkgEpoch:Number.isFinite(G?.epoch)?G.epoch:null,pkgText:G?`${W.length-ie} ok${ie?` · ${ie} error`:""}`:null}}).sort((P,z)=>P.pool===z.pool?P.id<z.id?-1:1:P.pool<z.pool?-1:1),Te=Pe.filter(P=>P.live),Le={loading:!!Ne.loading,error:Ne.error||null,empty:Pe.length===0&&!Ne.loading,rows:Pe,counts:{registered:Pe.length,live:Te.length,ready:Te.filter(P=>P.phase==="ready").length,starting:Te.filter(P=>P.phase==="starting").length,draining:Te.filter(P=>P.phase==="draining").length,pools:[...new Set(Te.map(P=>P.pool))].length},summaryText:Pe.length?`${Te.length} live / ${Pe.length} registered`:null},St={loading:!!O.loading,error:O.error||null,empty:M.length===0&&!O.loading,sharedCount:Z.length,userCount:le.length,selectedName:O.selectedName||null,detail:rt,workspace:Ke,changelog:O.changelog||null,addDialog:{open:!!O.addDialog?.open,kind:O.addDialog?.kind||"repo",scope:O.addDialog?.scope||"user",repoUrl:O.addDialog?.repoUrl||"",ref:O.addDialog?.ref||"",path:O.addDialog?.path||"",url:O.addDialog?.url||"",authToken:O.addDialog?.authToken||"",submitting:!!O.addDialog?.submitting,progress:O.addDialog?.progress||null,error:O.addDialog?.error||null}},K=[];return be==="workers"?(K.push({id:"workersRefresh",label:"Refresh workers",key:"r"}),K.push({id:"showPackages",label:"Agents",key:"a"}),K.push({id:"showProviders",label:"Model Providers",key:"m"}),K.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:r,isAdmin:o,adminScope:l,adminPolicyLabel:l==="cluster"?"Cluster-scoped admin · system-session access retained":"Unrestricted admin access",section:be,settingsTree:Re,packages:St,workers:Le,modelProviders:A,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:N,storeAsSystem:R,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:I},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:K}):be==="packages"?(K.push({id:"packagesRefresh",label:"Refresh packages",key:"r"}),K.push({id:"packagesNext",label:"Next package",key:"j"}),K.push({id:"packagesPrev",label:"Previous package",key:"k"}),K.push({id:"showProviders",label:"Model Providers",key:"m"}),K.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:r,isAdmin:o,adminScope:l,adminPolicyLabel:l==="cluster"?"Cluster-scoped admin · system-session access retained":"Unrestricted admin access",section:be,settingsTree:Re,packages:St,workers:Le,modelProviders:A,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:N,storeAsSystem:R,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:I},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:K}):be==="providers"?(K.push({id:"addProvider",label:"Add GitHub provider",key:"e"}),K.push({id:"cycleUserDefault",label:"Cycle my default",key:"u"}),o&&(K.push({id:"cycleClusterDefault",label:"Cycle cluster default",key:"l"}),K.push({id:"cycleSystemDefault",label:"Cycle system default",key:"s"}),K.push({id:"toggleSystemUse",label:"Toggle system use",key:"t"}),K.push({id:"cycleSystemOverride",label:"Cycle system-agent override",key:"o"})),K.push({id:"refreshProviders",label:"Refresh",key:"r"}),K.push({id:"showPackages",label:"Agents",key:"a"}),K.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:r,isAdmin:o,adminScope:l,adminPolicyLabel:l==="cluster"?"Cluster-scoped admin · system-session access retained":"Unrestricted admin access",section:be,settingsTree:Re,packages:St,workers:Le,modelProviders:A,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:N,storeAsSystem:R,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:I},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:K}):(n.editing?(K.push({id:"save",label:"Save",key:"Enter"}),K.push({id:"cancel",label:"Cancel",key:"Esc"})):(K.push({id:"edit",label:N?`Replace ${$}`:`Set ${$}`,key:"e"}),N&&K.push({id:"clear",label:`Clear ${$}`,key:"c"}),K.push({id:"refresh",label:"Refresh",key:"r"})),K.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),be==="ghcp"&&K.splice(K.length-1,0,{id:"showPackages",label:"Agents",key:"a"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:r,isAdmin:o,adminScope:l,adminPolicyLabel:l==="cluster"?"Cluster-scoped admin · system-session access retained":"Unrestricted admin access",section:be,settingsTree:Re,packages:St,workers:Le,modelProviders:A,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:N,storeAsSystem:R,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:I},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:K})}const rg={day:"Day",week:"Week",month:"Month"};function ig(t){const e=t.auth?.authorization?.role;return e==="admin"||e==="anonymous"||!!t.admin?.profile?.isAdmin}function ag(t){const e=/T(\d{2}:\d{2})/.exec(String(t||""));return e?`${e[1]} UTC`:null}function ba(t,e=Date.now()){const s=t?Date.parse(t):NaN;if(!Number.isFinite(s))return null;const n=ag(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 og(t){return t?.kind==="no_provider"||t?.kind==="hold"||t?.resetsAtUtc?null:"waits until someone changes it"}function lg(t,e){return new Date(t-e*864e5).toISOString().slice(0,10)}function Vs(t,e,s){return t===1?e:s}function Lr(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,u=l?ne(o):"—",p=Number.isFinite(i)?ne(i):"∞",m=Number(t?.quotaTokens),f=Number(t?.usedTokens),h=Number.isFinite(m)&&m>0&&Number.isFinite(f)&&f>=m,g=!e&&h&&(d==null||d<100),b=w=>{const E=e?t?.[w]:t?.[`your${w[0].toUpperCase()}${w.slice(1)}`];return E==null?null:Number(E)},y=b("inputTokens"),S=Number.isFinite(y)?{input:y,output:b("outputTokens")||0,cacheRead:b("cacheReadTokens")||0,cacheWrite:b("cacheWriteTokens")||0}:null,v=S?`in ${ne(S.input)} (cache r ${ne(S.cacheRead)} · w ${ne(S.cacheWrite)}) · out ${ne(S.output)}`:null;return{providerExhausted:g,ruleId:t?.ruleId||null,split:S,splitText:v,usedTokens:l?o:null,quotaTokens:Number.isFinite(i)?i:null,usedLabel:u,quotaLabel:p,text:`${u} / ${p}`,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:ba(t?.resetsAtUtc,s)}}function cg(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",u=Number.isFinite(Number(t?.allowancePct))?Number(t.allowancePct):100,p=t?.holdUntilUtc||null,m=t?.holdIndefinite===!0,f=m||(p?Date.parse(p)>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,S=o===s&&(l==="provider"?n==="*":c===n),v=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:u,allowanceLabel:l==="provider"&&e&&u<100&&g?["day","week","month"].some(w=>t?.periods?.[w]?.quotaTokens!=null)?`Per-user allowance: ${u}% of each limit`:`Per-user allowance: ${u}%, but no limit is set to divide`:null,hold:f?{indefinite:m||!p,untilUtc:p,label:m||!p?"lifts when an administrator releases it":`lifts ${ba(p,r)}`}:null,modelRowCount:h,selected:S,expanded:o===s&&h>0,expandLabel:h===0?null:o===s?`hide ${h} ${Vs(h,"model","models")}`:i>0?`show ${h} ${Vs(h,"model","models")} — ${i} over limit`:`show ${h} ${Vs(h,"model","models")}`,overModels:l==="provider"?i:0,cells:{day:Lr(v.day,e,r),week:Lr(v.week,e,r),month:Lr(v.month,e,r)}}}function dg(t){const e=t.budget||{},s=e.agents||{},n=e.summary||{},r=s.data&&typeof s.data=="object"?s.data:null,i=[14,30,90].includes(Number(n.days))?Number(n.days):14,o=(Array.isArray(r?.agents)?r.agents:[]).map(p=>{const m=Number(p.turns)||0,f=Number(p.total)||0;return{agent:String(p.agent||"(none)"),models:Array.isArray(p.models)?p.models.map(String):[],turns:m,sessions:Number(p.sessions)||0,input:Number(p.input)||0,output:Number(p.output)||0,cacheRead:Number(p.cacheRead)||0,cacheWrite:Number(p.cacheWrite)||0,total:f,perTurn:m>0?f/m:0,daily:Array.isArray(p.daily)?p.daily:[]}}),l=o.reduce((p,m)=>p+m.total,0);for(const p of o)p.share=l>0?p.total/l:0;const c=typeof r?.today=="string"?r.today:new Date().toISOString().slice(0,10),d=[];{const p=new Date(`${c}T00:00:00Z`).getTime();for(let m=i-1;m>=0;m-=1)d.push(new Date(p-m*864e5).toISOString().slice(0,10))}const u=new Map(d.map(p=>[p,new Map]));for(const p of Array.isArray(r?.daily)?r.daily:[]){const m=u.get(p.day);m&&m.set(String(p.agent||"(none)"),Number(p.total)||0)}return{loading:!!s.loading,error:s.error||null,loaded:!!r,days:i,scope:r?.scope==="cluster"?"cluster":"mine",agents:o,windowTotal:l,dayKeys:d,daily:u}}function Bd(t){const e=t.budget||{},s=e.summary||{},n=s.data&&typeof s.data=="object"?s.data:null,r=[14,30,90].includes(Number(s.days))?Number(s.days):14,i=[],o=new Set;for(const b of Array.isArray(e.grid)?e.grid:[])b?.rowKind!=="provider"||!b?.providerName||o.has(b.providerName)||(o.add(b.providerName),i.push({name:b.providerName,class:b.class==="shared"?"shared":"personal"}));const l=new Set(Array.isArray(s.providers)?s.providers:[]),c=s.preset||"all",d=typeof n?.today=="string"?n.today:new Date().toISOString().slice(0,10),u=[];{const b=new Date(`${d}T00:00:00Z`).getTime();for(let y=r-1;y>=0;y-=1)u.push(new Date(b-y*864e5).toISOString().slice(0,10))}const p=new Map((Array.isArray(n?.daily)?n.daily:[]).map(b=>[b.day,b])),m=u.map(b=>{const y=p.get(b)||{};return{day:b,input:Number(y.input)||0,output:Number(y.output)||0,cacheRead:Number(y.cacheRead)||0,cacheWrite:Number(y.cacheWrite)||0,total:Number(y.total)||0,turns:Number(y.turns)||0}}),f=m.reduce((b,y)=>b+y.total,0),h=(Array.isArray(n?.models)?n.models:[]).map(b=>{const y=new Map((Array.isArray(b.daily)?b.daily:[]).map(v=>[v.day,Number(v.total)||0])),S=Number(b.total)||0;return{model:String(b.model||"?"),providers:Number(b.providers)||0,turns:Number(b.turns)||0,input:Number(b.input)||0,output:Number(b.output)||0,cacheRead:Number(b.cacheRead)||0,cacheWrite:Number(b.cacheWrite)||0,total:S,share:f>0?S/f:0,sparkline:u.map(v=>y.get(v)||0)}}),g=b=>{const y=n?.windows?.[b]||{};return{input:Number(y.input)||0,output:Number(y.output)||0,cacheRead:Number(y.cacheRead)||0,cacheWrite:Number(y.cacheWrite)||0,total:Number(y.total)||0,turns:Number(y.turns)||0,sessions:Number(y.sessions)||0}};return{loading:!!s.loading,error:s.error||null,loaded:!!n,scope:n?.scope==="mine"?"mine":"cluster",days:r,today:d,preset:c,selectedProviders:Array.from(l),providers:i,windows:{day:g("day"),week:g("week"),month:g("month")},series:m,windowTotal:f,models:h,classes:(Array.isArray(n?.classes)?n.classes:[]).map(b=>({chargeClass:String(b.chargeClass||"?"),total:Number(b.total)||0,turns:Number(b.turns)||0}))}}function ug(t){const e=t.budget||{},s=Date.now(),n=ig(t),r=e.overall===!0,i=Gn.includes(Number(e.rangeDays))?Number(e.rangeDays):Fe,o=Array.isArray(e.grid)?e.grid:[],l=e.error||null,c=e.loaded===!0,d=e.selectedProvider||null,u=e.selectedScope||"*",p=o.reduce((H,Y)=>H+(Y?.rowKind==="model"?0:1),0),m=[],f=new Map;for(const H of o){if(H?.rowKind!=="model")continue;["day","week","month"].some(te=>{const ee=H?.periods?.[te],J=Number(ee?.quotaTokens),ae=Number(r?ee?.usedTokens:ee?.yourUsedTokens);return Number.isFinite(J)&&J>0&&Number.isFinite(ae)&&ae>J})&&f.set(H.providerName,(f.get(H.providerName)||0)+1)}for(const H of o)H?.rowKind==="model"&&H?.providerName!==d||m.push(cg(H,{overall:r,selectedProvider:d,selectedScope:u,nowMs:s,overModels:f.get(H?.providerName)||0}));const h=m.find(H=>H.selected)||m.find(H=>H.kind==="provider"&&H.providerName===d)||null,g=m.find(H=>H.kind==="provider"&&H.providerName===d)||null,b=Array.isArray(e.paused)?e.paused:[],y=new Map;for(const H of b){const te=_s({pauseState:H?.pause})?.provider||null;te&&y.set(te,(y.get(te)||0)+1)}const S=[...y.entries()].sort((H,Y)=>Y[1]-H[1]||H[0].localeCompare(Y[0]))[0]||null,v=b.length,w=S&&S[1]===v?S[0]:null,E=e.pausedError||null,k={count:v,error:E,stale:!!E&&v>0,provider:S?S[0]:null,sentence:v===0?null:`${v} ${Vs(v,"session is","sessions are")} waiting${w?` on ${w}`:""}.`},x=e.missingProvider||null,T=x&&y.get(x)||0,A=T>0?{provider:x,count:T,sentence:`No provider is named ${x}, and ${T} ${Vs(T,"session waits","sessions wait")} on it. They run again as soon as a provider takes that name.`}:null,R=e.series||{},N=new Map((Array.isArray(R.days)?R.days:[]).map(H=>[String(H?.dayUtc||"").slice(0,10),H])),$=[];for(let H=i-1;H>=0;H-=1){const Y=lg(s,H),te=N.get(Y);$.push({dayUtc:Y,label:Y.slice(5),tokens:Number(te?.tokensTotal)||0,turns:Number(te?.turns)||0})}const F=$.reduce((H,Y)=>Math.max(H,Y.tokens),0),I=h?.cells?.day||null,O=I?.quotaTokens??null,M=Math.max(F,O||0);for(const H of $)H.pct=M>0?Math.round(H.tokens/M*100):0;const B=R.error||null,D=R.loaded===!0,j={provider:R.provider||null,days:$,peak:F,peakLabel:ne(F),scaleMax:M,quotaTokens:O,quotaLabel:I?.quotaLabel??"∞",quotaPct:O!=null&&M>0?Math.round(O/M*100):null,rangeDays:i,rangeLabel:`Last ${i} days`,loading:R.loading===!0,loaded:D,error:B,failed:!!B&&!D,stale:!!B&&D,empty:D&&!B&&F===0,mixedScope:!1},V=e.systemUsage||{},C=n&&h&&V.provider===d&&(V.scope||"*")===u&&(V.rangeDays||Fe)===i,U=!n||!h?null:{loading:C&&V.loading===!0,loaded:C&&V.loaded===!0,error:C&&V.error||null,stale:C&&!!V.error&&V.loaded===!0,rangeDays:i,rangeLabel:`Last ${i} days`,tokens:Number(C?V.totals?.tokensTotal:0)||0,tokensLabel:ne(Number(C?V.totals?.tokensTotal:0)||0),turns:Number(C?V.totals?.turns:0)||0,models:(C&&Array.isArray(V.breakdown)?V.breakdown:[]).map(H=>({key:String(H?.key||H?.label||"unknown"),label:String(H?.label||H?.key||"Unknown model"),tokens:Number(H?.tokensTotal)||0,tokensLabel:ne(Number(H?.tokensTotal)||0),turns:Number(H?.turns)||0})).sort((H,Y)=>Y.tokens-H.tokens||H.label.localeCompare(Y.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&&p===0,overall:r,rangeDays:i,rangeOptions:Gn.map(H=>({value:H,label:`${H}d`})),overallLabel:"Show all user spend",usageHeading:r?"All user spend":"My spend",columns:Cf.map(H=>({id:H,label:rg[H]})),rows:m,providerCount:p,selectedProvider:d,selectedScope:u,selected:h,selectedProviderRow:g,paused:k,missing:A,series:j,systemSpend:U}}function pg(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=ut(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",u=c&&t.ui.promptEdit?.phase==="cancelling",p=s===e?"v/esc close fullscreen":"v fullscreen";if(t.ui.modal?.type==="artifactUpload")return{left:"Upload a local file into this session's artifact store",right:"type path · left/right move · enter upload · esc cancel"};if(t.ui.modal?.type==="renameSession")return{left:"Rename the selected session title",right:"type title · left/right move · enter save · esc cancel"};if(t.ui.modal?.type==="shareSession")return{left:"Share the selected session",right:"name [r|w] grants · -name revokes · enter apply · esc close"};if(t.ui.modal?.type==="artifactPicker")return{left:"Select a linked artifact or URL",right:"up/down move · enter open/download · a/esc close"};if(t.ui.modal?.type==="modelPicker")return{left:"Select a model for the new session",right:"up/down move · enter next · esc cancel"};if(t.ui.modal?.type==="reasoningEffortPicker")return{left:"Select reasoning effort for the new session",right:"up/down move · enter create · esc cancel"};if(t.ui.modal?.type==="themePicker")return{left:"Select a 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:"type to search · up/down move · 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 m=!!t.sessions?.selectMode,f=Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds.length:0;if(m&&e===L.SESSIONS)return{left:`Select mode · ${f} selected`,right:"up/down move · space toggle · ctrl-g group · c cancel · d complete · D hard delete · V/esc exit"};const h={[L.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",[L.CHAT]:`j/k scroll · ctrl-u/ctrl-d page · e older history · g/G top/bottom · d done · ${p} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane · p prompt`,[L.INSPECTOR]:t.ui.inspectorTab==="logs"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · t tail · f filter · ${p} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane`:t.ui.inspectorTab==="stats"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f cycle session/fleet/users · d done · ${p} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:t.ui.inspectorTab==="files"?t.files?.fullscreen?"a download · x delete · u/ctrl-a upload · o open · f filter · j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · v/esc close fullscreen · left/right tab · [/] resize pane · {/} columns · T themes · ? help · tab next pane":"j/k files · a download · x delete · u/ctrl-a upload · o open · f filter · ctrl-u/ctrl-d page preview · g/G preview top/bottom · d done · v fullscreen · left/right tab · [/] resize pane · {/} columns · T themes · ? help · tab next pane":t.ui.inspectorTab==="history"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f format · r refresh · a save artifact · d done · ${p} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:t.ui.inspectorTab==="sequence"?`j/k turn · enter expand · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${p} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${p} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · h/l focus · a linked items · drag copy · m next tab · tab next pane`,[L.ACTIVITY]:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${p} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · h left · tab next pane`,[L.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"}`:u?`cancelling prompt selected · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:`edit pending prompt · enter send batch · up/down cycle pending · esc cancel · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:l?`type message · enter queues · enter on empty sends batch · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:o?`type message · enter queues behind durable items · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:`type message · enter send · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`};let g=h[e]||h[L.SESSIONS];return Nd(ut(t))&&(g=`ctrl-x stop · ${g}`),{left:t.ui.statusText,right:g}}function as(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function Ce(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 nt(t){return Array.from(String(t||"")).length}function Hd(t,e){const s=String(t||"");return e<=0?"":nt(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function As(t,e){const s=Hd(t,e),n=Math.max(0,e-nt(s));return s+" ".repeat(n)}function fe(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function ze(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 jo(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 Ud(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?nt(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function mg(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 jd(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 fg(t,e=""){return jd([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function hg(t,e=""){return jd([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function rn(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 gg=300*1e3,yg="last 5m";function Sa(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-gg,endMs:e,label:yg}}function bg(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 Gd(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 Sg=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done","model"]);function vg(t){return Sg.has(t)}function wg(t){const e=wc(t?.createdAt),s=rn(t?.workerNodeId),n=mg(t),r=Ud(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 ${Zt(t?.data?.seconds??0)}`};case"session.wait_completed":return{...o,type:"timer",color:"yellow",detail:`${Zt(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const l=hg(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 ${fg(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||_e(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${Zt(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${Wn(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 ${Wn(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=Cs(t?.data?.oldModel)||"default",c=Cs(t?.data?.newModel)||"default",d=t?.data?.newReasoningEffort,u=d&&d!==t?.data?.oldReasoningEffort;return{...o,type:"model",color:"cyan",detail:`model ${l} → ${c}${u?`:${d}`:""}`}}case"session.error":return{...o,type:"error",color:"red",detail:r||"error"};default:return null}}function Wd(t=[]){const e=[];for(const s of t||[]){const n=wg(s);n&&e.push({...n,nodeLabel:vg(n.type)?"orch":n.nodeLabel||"orch"})}return e}function Eg(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 kg(t){const e=String(t?.error||"").trim();if(!e)return null;const s=na(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),r=Number.isFinite(n)?n:Date.now();return{time:wc(r),createdAtMs:r,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${Ud(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function Ig(t,e){const s=kg(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 xg(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=Wd(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 Ag(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const r of n?.events||[]){if(!Gd(r,e))continue;const i=rn(r?.workerNodeId);i&&s.add(i)}return Array.from(s).sort((n,r)=>n.localeCompare(r))}function va(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 Go(t){return Array.isArray(t?.runs)?t.runs.reduce((e,s)=>e+nt(String(s.text??"")),0):Array.isArray(t)?t.reduce((e,s)=>e+nt(String(s.text??"")),0):nt(String(t?.text??""))}function Ng(t,e,s){const n=[{text:As("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((r,i)=>{i>0&&n.push({text:" ",color:null}),n.push({text:As(r,s),color:"white",bold:!0})}),va(n)}function Cg(t,e,s,n=1/0){const r=`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`;return fe(Number.isFinite(n)?r.slice(0,Math.max(e,n)):r,"gray")}function Tg(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=ze(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(ze(i.kvTotalValueBytes)),r=s<=40?l.join(" · "):o.join(" | "),r||(r="orchestration stats unavailable")}return He({title:"Stats",body:r,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function Pg(t,e,s,n){const r=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],i=[{text:As(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:As(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):i.push({text:As("│",n),color:"gray"})}),va(i)}const Mg=new Set(["none","minimal","low","medium","high","xhigh","max"]);function _g(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&&Mg.has(n)?s.length-2:s.length-1;return s[Math.max(0,r)]||s[0]||"unknown"}function Wo(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 jt(t){return Number(t||0).toLocaleString("en-US")}function $g(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 Rg(t,{expanded:e,selected:s,maxWidth:n}){const r=e?"v":">",i=_g(t?.model),o=t?.durationMs!=null?`${(Number(t.durationMs)/1e3).toFixed(1)}s`:"n/a",l=`${r} Mod: ${i} tok ${Wo(t?.tokensInput)}/${Wo(t?.tokensOutput)} dur ${o}`,c=[];if(s?c.push(bt(As(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?`${jt(t.durationMs)} ms`:null],["tokens",`${jt(t?.tokensInput)} in / ${jt(t?.tokensOutput)} out`],["cache",`${jt(t?.tokensCacheRead)} read / ${jt(t?.tokensCacheWrite)} write`],["tools",`${jt(t?.toolCalls)} calls / ${jt(t?.toolErrors)} errors`],["names",Array.isArray(t?.toolNames)&&t.toolNames.length?t.toolNames.join(", "):null],["worker",t?.workerNodeId||null],["result",t?.resultType||null],["error",t?.errorMessage||null]].filter(([,u])=>u!=null&&u!=="");for(const[u,p]of d)c.push([{text:` ${u}: `,color:"gray"},{text:String(p),color:"white"}])}return c}function Lg(t,e,s,n={}){const r=!!n?.allowWideColumns,i=Tg(t,e,s),o=t.history.bySessionId.get(e.sessionId),l=Ig(Eg(Wd(o?.events||[])),e);if(l.length===0)return{stickyLines:i,lines:[fe("No events yet - interact with this session to populate the sequence diagram.")]};const c=Sa(t),d=l.filter(N=>bg(N,c)),u=(d.length>0?d:l).slice(-48),p=xg(t,c.startMs,c.endMs),m=Array.from(new Set(u.map(N=>N.nodeLabel).filter(N=>N&&N!=="orch"))).sort((N,$)=>N.localeCompare($)),f=p.length>0?p:m,h=Math.min(13,Math.max(8,...u.map(N=>nt(String(N.time||""))))),g=Math.max(18,s),b=Math.max(1,Math.floor((g-h-1)/6));let y=["orch",...f];if(!r&&y.length>b){const N=Math.max(1,b-1);y=[...y.slice(0,N),"…"]}const S=Math.max(0,y.length-1),v=Math.max(4,Math.floor((g-h-1-S)/Math.max(1,y.length))),w=n?.sequenceExpansion||null,E=w?$g(o?.events||[]):null,k=w?new Set((w.expandedTurns||[]).map(Number)):null,x=w&&w.selectedTurn!=null?Number(w.selectedTurn):null,T=[];for(const N of u)if(T.push(Pg(N,y,h,v)),w&&N.completedTurn!=null){const $=Number(N.completedTurn),F=E.get($);if(F)for(const I of Rg(F,{expanded:k.has($),selected:x===$,maxWidth:g}))T.push(I)}const A=Ng(y,h,v),R=T.reduce((N,$)=>Math.max(N,Go($)),Go(A));return{stickyLines:[...i,fe(`Window: ${c.label}`,"gray"),A,Cg(y,h,v,R)],lines:T}}function Og(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 Fg(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!Gd(s[n],e))continue;const r=rn(s[n]?.workerNodeId);if(r)return r}return null}function Dg(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 Bg(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 Hg(t,e,s){const n=t?.isSystem?rs(t,e):t?.title||_e(t?.sessionId),r=t?.isSystem?"⚙ ":t?.serviceKind?"⚗ ":`${bd(t)||"."} `;return{sessionId:t?.sessionId||null,text:`${r}${n}`,color:t?.isSystem?"yellow":ks(t),bold:!!t?.isSystem,active:!!s}}function qd(t){const e=Sa(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 f of r){const h=rn(f?.workerNodeId);if(!h)continue;const g=f?.updatedAt instanceof Date?f.updatedAt.getTime():new Date(f?.updatedAt??0).getTime(),b=Number.isFinite(g)?i-g:Number.NaN,y=f?.health||{};l.set(h,{label:h,workerNodeId:String(f?.workerNodeId??""),registered:!0,live:Number.isFinite(b)&&b<=o,phase:["starting","ready","draining"].includes(f?.phase)?f.phase:"ready",pool:String(f?.pool??"default"),agoText:Dg(b),uptimeText:Bg(y.uptimeS),rssText:Number.isFinite(y.rssBytes)?gs(y.rssBytes):null,heapText:Number.isFinite(y.heapUsedBytes)?gs(y.heapUsedBytes):null,eventLoopText:Number.isFinite(y.eventLoopDelayP99Ms)?`${y.eventLoopDelayP99Ms}ms`:null,sessions:Number.isFinite(y.activeSessions)?y.activeSessions:null,sdkVersion:typeof f?.info?.sdkVersion=="string"?f.info.sdkVersion:null,substrate:typeof f?.info?.runtime?.substrate=="string"?f.info.runtime.substrate:null,capabilities:f?.info?.capabilities&&typeof f.info.capabilities=="object"?Object.entries(f.info.capabilities).filter(([,S])=>!!S).map(([S])=>S).sort():[],consumes:Array.isArray(f?.info?.consumes)?f.info.consumes:[],owner:f?.owner?.subject?String(f.owner.subject):null,pkgEpoch:Number.isFinite(f?.state?.["agent-packages"]?.epoch)?f.state["agent-packages"].epoch:null,pkgInstalled:f?.state?.["agent-packages"]?.installed&&typeof f.state["agent-packages"].installed=="object"?Object.entries(f.state["agent-packages"].installed).map(([S,v])=>({name:S,semver:v?.semver??null,status:v?.status==="error"?"error":"ok",error:v?.error?String(v.error):null})):[],pkgLastError:f?.state?.["agent-packages"]?.lastError?String(f.state["agent-packages"].lastError):null,executing:[]})}for(const f of Ag(t,e))l.has(f)||l.set(f,{label:f,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 f of Og(t)){const h=t.sessions.byId[f];if(!h)continue;const g=t.history.bySessionId.get(f);g?.events||(c+=1);const b=Fg(g,e),y=b?l.get(b):null;y&&y.executing.push(Hg(h,s,f===n))}const d=Array.from(l.values()).sort((f,h)=>{if(f.registered!==h.registered)return f.registered?-1:1;if(f.live!==h.live)return f.live?-1:1;const g=String(f.pool??"~").localeCompare(String(h.pool??"~"));return g!==0?g:f.label.localeCompare(h.label)});d.forEach((f,h)=>{f.ordinal=h+1});const u=d.filter(f=>f.registered),p=t.ui?.nodeMapSelectedNode,m=p&&d.some(f=>f.label===p)?p:d[0]?.label??null;return{windowLabel:e.label,degraded:u.length===0,registryError:t.admin?.workers?.error||null,registryFetchedAt:t.admin?.workers?.fetchedAt||0,registryLoading:!!t.admin?.workers?.loading,registryAttempts:t.admin?.workers?.attempts||0,registryLastAttemptAt:t.admin?.workers?.lastAttemptAt||0,registryLastSkip:t.admin?.workers?.lastSkip||null,registered:u.length,liveCount:u.filter(f=>f.live).length,executingTotal:d.reduce((f,h)=>f+h.executing.length,0),missingHistoryCount:c,selected:m,nodes:d}}function Ug(t,e,s={}){const n=qd(t);if(n.nodes.length===0)return[fe(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(fe("","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 u=[i.executing.length?`${i.executing.length} sess`:null,i.rssText,i.uptimeText?`up ${i.uptimeText}`:null,i.agoText].filter(Boolean).join(" · ");u&&d.push({text:` ${u}`,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(va(d))}return r.push(fe("","gray")),r.push(fe("Click a node (or press 1-9) — its details fill the pane below.","gray")),n.missingHistoryCount>0&&r.push(fe(`Loading worker history for ${n.missingHistoryCount} session(s)…`,"gray")),r}function jg(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 f of n){const h=Ce([{text:`${f.providerId}`,color:"cyan",bold:!0},{text:` (${f.providerType||"provider"})`,color:"gray"}],i);o.push(h),l.push(null);for(const g of f.models||[]){const b=Array.isArray(s.items)?s.items.findIndex(E=>E.id===g.id):-1,y=b===r,S=!!g.disabled,v=Ce([{text:"· ",color:"gray"},{text:g.modelName||g.qualifiedName||g.id,color:S?"gray":"white",bold:!!g.isDefault&&!S},...g.cost?[{text:` [${g.cost}]`,color:"gray"}]:[],...S?[{text:" ⊘ needs GitHub key",color:"yellow"}]:[],...g.isDefault?[{text:" ← current default",color:"gray"}]:[]],i),w=y?bt(v.map(E=>E.text).join("").padEnd(i," ")):v;y&&(c=o.length),o.push(w),l.push(b>=0?b:null)}}const d=Array.isArray(s.items)&&s.items[r]||null,u=Array.isArray(d?.supportedReasoningEfforts)?d.supportedReasoningEfforts.filter(Boolean):[],p=typeof d?.defaultReasoningEffort=="string"?d.defaultReasoningEffort:null,m=d?[[{text:d.modelName||d.qualifiedName||d.id,color:"white",bold:!0}],[{text:`${d.providerId} (${d.providerType||"provider"})`,color:"gray"}],...d.cost?[[{text:`Cost: ${d.cost}`,color:"gray"}]]:[],...u.length>0?[[{text:`Reasoning: ${u.join(", ")}`,color:"gray"}]]:[],...p?[[{text:`Default reasoning: ${p}`,color:"gray"}]]:[],...d.disabled?[[{text:"Unavailable: 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:m,idealWidth:Math.min(Math.max(46,o.reduce((f,h)=>Array.isArray(h)?Math.max(f,as(h)):Math.max(f,String(h?.text||"").length),0)+4),e)}}function Gg(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((f,h)=>{const g=h===r,b=" ".repeat(Math.max(0,Number(f?.depth)||0)*2);let y;if(f?.kind==="section"){const S=f.collapsed?"▸":"▾",v=f.sectionKind==="package"&&f.packageScope==="user"&&!f.mine?" [private]":"";y=Ce([{text:`${b}${S} `,color:"cyan"},{text:f.title||"Section",color:"white",bold:!0},...v?[{text:v,color:"cyan"}]:[],...f.meta?[{text:` · ${f.meta}`,color:"gray"}]:[]],i)}else{const S=f?.kind==="generic"||f?.supportsDirectStart!==!1,v=f?.kind==="generic"?"○ ":"★ ",w=f?.title||f?.agentName||f?.id||"Agent",E=f?.kind==="generic"?"":f?.packageTitle||f?.packageName||"",k=s.sort==="used"&&Number(f?.usageCount)>0?` ${f.usageCount}×`:"";y=Ce([{text:`${b}${v}`,color:S?"yellow":"gray"},{text:w,color:S?"white":"gray",bold:S},...E?[{text:` ${E}`,color:"gray"}]:[],...k?[{text:k,color:"cyan"}]:[]],i)}o.push(g?bt(y.map(S=>S.text).join("").padEnd(i," ")):y),l.push(h)});const c=n[r]||null,d=s.sessionOptions?.model||null,u=s.sessionOptions?.reasoningEffort||null,p=c?.kind==="section"?[[{text:c.title||"Section",color:"white",bold:!0}],...c.sectionKind==="package"?[[{text:`${c.packageName||"package"}@${c.packageSemver||"?"}`,color:"gray"}],...c.ownerLabel?[[{text:`Published by ${c.ownerLabel}`,color:"gray"}]]:[]]:[[{text:c.sectionKind==="builtin"?"Agents baked into this deployment.":"Agent packages installed on this deployment.",color:"gray"}]],[{text:"",color:"gray"}],[{text:c.meta||"",color:"gray"}],[{text:"",color:"gray"}],[{text:c.collapsed?"Enter or → to open.":"Enter or ← to close.",color:"gray"}]]:c?[[{text:c.title||c.agentName||c.id||"Agent",color:"white",bold:!0}],...c.kind==="generic"?[[{text:"Open-ended session",color:"gray"}]]:[[{text:c.agentName||c.id||"agent",color:"gray"}]],...c.packageName?[[{text:`Package: ${c.packageName}@${c.packageSemver||"?"} · ${c.packageScope||"shared"}`,color:"gray"}]]:c.kind==="agent"?[[{text:"Built-in agent",color:"gray"}]]:[],...c.startedBy?.length?[[{text:`Started by: ${c.startedBy.join(", ")}`,color:"gray"}]]:[],...c.kind!=="generic"&&c.supportsDirectStart===!1?[[{text:"Cannot be started on its own",color:"yellow"}]]:[],...d?[[{text:`Model: ${d}`,color:"gray"}]]:[],...u?[[{text:`Reasoning: ${u}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:c.description||(c.kind==="generic"?"Create a general-purpose session without a specialized named agent.":"No description available for this agent."),color:c.description?"white":"gray"}],[{text:"",color:"gray"}],[{text:c.tools?.length?`Tools: ${c.tools.join(", ")}`:"Tools: system defaults only",color:"gray"}]]:[[{text:"No agent selected.",color:"gray"}]],m=l.indexOf(r);return{title:s.title||"Select agent for new session",rows:o,rowItemIndexes:l,selectedRowIndex:m>=0?m:0,detailsTitle:"Agent Details",detailsLines:p,idealWidth:Math.min(Math.max(52,o.reduce((f,h)=>Array.isArray(h)?Math.max(f,as(h)):Math.max(f,String(h?.text||"").length),0)+4),e)}}function Wg(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((u,p)=>{const m=p===r,f=Ce([{text:"· ",color:"gray"},{text:String(u?.label||u?.id||"effort"),color:"white",bold:!0},...u?.isDefault?[{text:" ← model default",color:"gray"}]:[]],i);return m?bt(f.map(h=>h.text).join("").padEnd(i," ")):f}),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((u,p)=>Array.isArray(p)?Math.max(u,as(p)):Math.max(u,String(p?.text||"").length),0)+4),e)}}function qg(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((p,m)=>{const f=m===r,h=Ce([{text:"· ",color:"gray"},{text:String(p?.label||p?.id||"tier"),color:"white",bold:!0},...p?.isDefault?[{text:" ← model default",color:"gray"}]:[]],i);return f?bt(h.map(g=>g.text).join("").padEnd(i," ")):h}),l=n[r]||null,c=s.modelItem||null,d=l?.label||l?.id,u=[[{text:c?.modelName||c?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${c?.providerId||"provider"} (${c?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:d?`Using context window: ${d}`:"Choose a context window.",color:"white"}],[{text:"Long context costs more per token.",color:"gray"}]];return{title:s.title||"Select context window",rows:o,selectedRowIndex:r,detailsTitle:"Context Window",detailsLines:u,idealWidth:Math.min(Math.max(46,o.reduce((p,m)=>Array.isArray(m)?Math.max(p,as(m)):Math.max(p,String(m?.text||"").length),0)+4),e)}}function zg(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((u,p)=>{const m=p===r,f=u?.kind==="noGroup"?"○ ":u?.kind==="newGroup"?"+ ":"🗂 ",h=Ce([{text:f,color:u?.kind==="group"?"cyan":"gray",bold:u?.kind!=="noGroup"},{text:u?.label||u?.groupId||"Group",color:"white",bold:!0},...u?.kind==="group"?[{text:` (${u.memberCount??0})`,color:"gray"}]:[]],i);return m?bt(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((u,p)=>Array.isArray(p)?Math.max(u,as(p)):Math.max(u,String(p?.text||"").length),0)+4),e)}}function Kg(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,nt(i||"(untitled session)")+18,nt(o)+18),e)}}function Vg(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,nt(i)+18),e)}}function Yg(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?Id(i,t.branding?.title):_e(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,nt(n||"~/path/to/file.md")+20,nt(o)+20),e)}}function wa(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,u)=>{const p=e?.[d.id]||d.options?.[0]?.id,m=(d.options||[]).map(f=>f.id===p?bt(f.label):{text:f.label,color:"white"});return{id:d.id,title:d.label,focused:u===o,description:d.description||"",lines:m.length>0?m:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(d.label||"").length+4,...(d.options||[]).map(f=>String(f?.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,u)=>d+u.idealWidth,0)+Math.max(0,c.length-1)*2+4),s)}}function zd(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&&!!Ae(s?.principal):t.kind==="shared"?e?.includeShared===!0:t.kind==="owner"?Array.isArray(e?.ownerKeys)&&e.ownerKeys.includes(t.ownerKey):!1:!1}function qo(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(r=>r?.kind!=="all"&&zd(r,e,s)).map(r=>r.kind==="me"?"Me":r.label);return n.length>0?n.join(" + "):"All sessions"}function Xg(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((u,p)=>{const m=zd(u,r,i),f=u.kind==="system"?"yellow":u.kind==="unowned"?"gray":u.kind==="all"?"cyan":"white",h=[{text:m?"[x] ":"[ ] ",color:m?"cyan":"gray",bold:m},{text:u.label||u.id,color:f,bold:m}];return p===o?pd(h,{preserveColors:!0}):h}),d=[[{text:"Active: ",color:"gray"},{text:qo(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((u,p)=>Math.max(u,Array.isArray(p)?as(p):nt(p?.text||"")),0)+8,nt(qo(n,r,i))+16),e)}}function Qg(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:wa(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function Zg(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:wa(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function Jg(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(f=>f.kind==="artifact"),l=n.filter(f=>f.kind==="url"),c=o.reduce((f,h)=>{const g=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];return f+(g?.localPath?1:0)},0),d=Math.max(0,o.length-c),u=n.map((f,h)=>{let g;if(f.kind==="downloadAll")g=Ce([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${d} pending]`,color:"gray"}],i);else if(f.kind==="url")g=Ce([{text:"go ",color:"cyan",bold:!0},{text:f.text&&f.text!==f.href?f.text:f.href,color:"white",bold:!0},...f.text&&f.text!==f.href?[{text:` ${f.href}`,color:"gray"}]:[]],i);else{const b=t.files?.bySessionId?.[f.sessionId]?.downloads?.[f.filename];g=Ce([{text:b?.localPath?"ok ":"dl ",color:b?.localPath?"green":"cyan",bold:!0},{text:`${_e(f.sessionId)}/`,color:"gray"},{text:f.filename,color:"white"}],i)}return h!==r?g:bt(g.map(b=>b.text).join("").padEnd(i," "))}),p=n[r]||null;let m=[[{text:"No linked item selected.",color:"gray"}]];if(p?.kind==="downloadAll")m=[[{text:`${o.length} artifacts available`,color:"white",bold:!0}],...l.length>0?[[{text:`${l.length} links available`,color:"gray"}]]:[],[{text:`${c} already downloaded`,color:"gray"}],[{text:`${d} pending download`,color:"gray"}],...s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:"Press Enter to download all pending artifacts.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(p?.kind==="url")m=[[{text:p.text||p.href,color:"white",bold:!0}],[{text:p.href,color:"gray"}],[{text:"",color:"gray"}],[{text:"Press Enter to open this link in the browser.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(p?.kind==="artifact"){const f=t.sessions?.byId?.[p.sessionId]||null,h=t.files?.bySessionId?.[p.sessionId]?.downloads?.[p.filename]||null;m=[[{text:p.filename,color:"white",bold:!0}],[{text:f?Id(f,t.branding?.title):_e(p.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:u.length>0?u:[{text:"No linked items available.",color:"gray"}],selectedRowIndex:r,detailsTitle:"Linked Item Details",detailsLines:m,confirmLabel:l.length>0?o.length>0?"Open / Download":"Open":"Download",idealWidth:Math.min(Math.max(54,u.reduce((f,h)=>Array.isArray(h)?Math.max(f,as(h)):Math.max(f,String(h?.text||"").length),0)+4),e)}}function ne(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 Ea(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 ey(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 zo(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 Ko(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 Ws(t){return["session","fleet","users"].includes(t)?t:"session"}function or(t,e){const s=Ws(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"}),Ce(n,e)}function ty(t,e,s){if(!e)return[fe("No session selected.")];const n=t.sessionStats?.bySessionId?.[e.sessionId]||null;if(!n||n.loading&&!n.summary)return[fe("Loading session stats...")];const r=n.summary;if(!r)return[fe("Session stats unavailable.")];const i=[],o=Math.max(24,s);i.push(or("session",o)),i.push(fe("")),i.push(Ce([{text:"Session ",color:"cyan",bold:!0},{text:_e(e.sessionId),color:"white"}],o));const l=e.isSystem?"system":e.owner?"user":"unowned",c=e.isSystem?"system":e.owner?sn(e.owner):"(?) unowned",d=e.owner?.email||"—";i.push(Ce([{text:"Owner ",color:"cyan",bold:!0},{text:c,color:e.owner?"white":"gray"}],o)),i.push(Ce([{text:"Email ",color:"cyan",bold:!0},{text:d,color:e.owner?.email?"white":"gray"}],o)),i.push(Ce([{text:"Type ",color:"cyan",bold:!0},{text:l,color:l==="user"?"white":"gray"}],o)),r.agentId&&i.push(Ce([{text:"Agent ",color:"cyan",bold:!0},{text:r.agentId,color:"white"}],o));const u=ha(r.model||e.model,r.reasoningEffort||e.reasoningEffort);u&&i.push(Ce([{text:"Model ",color:"cyan",bold:!0},{text:u,color:"white"}],o)),e.createdAt&&i.push(Ce([{text:"Created ",color:"cyan",bold:!0},{text:Ko(e.createdAt),color:"white"}],o)),e.updatedAt&&i.push(Ce([{text:"Updated ",color:"cyan",bold:!0},{text:Ko(e.updatedAt),color:"white"}],o)),i.push(fe(""));const p=Array.isArray(n.tokensByModel)?n.tokensByModel:[];p.length>1&&(i.push(...He({title:"Models",body:p.map(N=>`${qh(N.model)} · ${N.turnCount||0} turns · ${ne(N.totalTokensInput)} in / ${ne(N.totalTokensOutput)} out`).join(`
|
|
59
|
-
`),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(fe("")));const m=(r.tokensInput||0)+(r.tokensOutput||0),f=r.cacheHitRatio,h=f==null?"—":`${(f*100).toFixed(1)}%`;i.push(...He({title:"Tokens",body:es([["Input",ne(r.tokensInput)],["Output",ne(r.tokensOutput)],["Total",ne(m)],["Cache Read",ne(r.tokensCacheRead)],["Cache Write",ne(r.tokensCacheWrite)],["Hit Ratio",h]],{maxWidth:Math.max(12,o-4)}),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0})),i.push(fe(""));const g=Number(r.regenCount)||0,b=r.lastRegenStats&&typeof r.lastRegenStats=="object"?r.lastRegenStats:null,y=Number.isFinite(b?.toEpoch)?b.toEpoch:g,S=b?b.distillMode==="deterministic"||!b.distillMode&&!b.distillerModel?"fast":String(b.distillerModel||"llm").replace(/^[^:]*:/,""):null,v=b?`${b.turnsArchived??0} turn${b.turnsArchived===1?"":"s"} · ${(Number(b.totalMs)/1e3).toFixed(1)}s${S?` · ${S}`:""}`:null;i.push(...He({title:"Persistence",body:es([["Epoch",String(y)],["Regens",g>0?String(g):null],["Last Regen",v],["Snapshot",ze(r.snapshotSizeBytes)],["Uncompressed",r.rawSizeBytes?ze(r.rawSizeBytes):null],["Compression",jo(r.rawSizeBytes,r.snapshotSizeBytes)],["Dehydrations",String(r.dehydrationCount)],["Hydrations",String(r.hydrationCount)],["Lossy Handoffs",String(r.lossyHandoffCount)],["Last Dehydrated",r.lastDehydratedAt?zo(r.lastDehydratedAt):null],["Last Hydrated",r.lastHydratedAt?zo(r.lastHydratedAt):null]],{maxWidth:Math.max(12,o-4)}),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const w=n.treeStats?.tree;if(w&&w.sessionCount>1){const N=w.cacheHitRatio,$=N==null?"—":`${(N*100).toFixed(1)}%`,F=(w.totalTokensInput||0)+(w.totalTokensOutput||0);i.push(fe("")),i.push(...He({title:`Tree (${w.sessionCount} sessions)`,body:es([["Input",ne(w.totalTokensInput)],["Output",ne(w.totalTokensOutput)],["Total",ne(F)],["Cache Read",ne(w.totalTokensCacheRead)],["Cache Write",ne(w.totalTokensCacheWrite)],["Hit Ratio",$],["Snapshot",ze(w.totalSnapshotSizeBytes)],["Uncompressed",w.totalRawSizeBytes?ze(w.totalRawSizeBytes):null],["Compression",jo(w.totalRawSizeBytes,w.totalSnapshotSizeBytes)],["Dehydrations",String(w.totalDehydrationCount)],["Hydrations",String(w.totalHydrationCount)]]),width:o,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const I=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];I.length>1&&(i.push(fe("")),i.push(...He({title:"Tree By Model",body:oy(I),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const E=Array.isArray(n.skillUsage)?n.skillUsage:[];E.length>0&&(i.push(fe("")),i.push(...He({title:`Skills (${E.length})`,body:Vo(E,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const k=n.treeSkillUsage,x=Array.isArray(k?.rolledUp)?k.rolledUp:[],T=Array.isArray(k?.perSession)?k.perSession.length:0;x.length>0&&T>1&&(i.push(fe("")),i.push(...He({title:`Tree Skills (${x.length})`,body:Vo(x,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const A=n.factsStats,R=n.treeFactsStats;if(A&&Array.isArray(A.rows)&&A.rows.length>0){i.push(fe(""));const N=Kd(A.rows),$=N?N.split(`
|
|
60
|
-
`).length:0,F=`${A.totalCount} · ${ze(A.totalBytes)}`;let I=N;R&&R.totalCount>A.totalCount&&(I+=`
|
|
61
|
-
Tree (${R.sessionIds.length} sessions): ${R.totalCount} · ${ze(R.totalBytes)}`),$>0&&i.push(...He({title:`Facts (${F})`,body:I,width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return i}function es(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,[u])=>Math.max(d,String(u).length),0),i=n.reduce((d,[,u])=>Math.max(d,String(u).length),0),o=" ".repeat(s),l=Number(e.maxWidth),c=!Number.isFinite(l)||r+s+i<=l;return n.map(([d,u])=>c?`${String(d).padEnd(r)}${o}${String(u).padStart(i)}`:`${String(d).padEnd(r)}${o}${String(u)}`).join(`
|
|
62
|
-
`)}function lr(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 an(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 u=c==null?"":String(c);return d===0?u.padEnd(i[d]):u.padStart(i[d])}).join(o)).join(`
|
|
63
|
-
`)}function Vo(t,e){const s=t.slice().sort((p,m)=>(m.invocations||0)-(p.invocations||0)).slice(0,12),n=s.map(p=>`${p.invocations||0} inv`),r=n.reduce((p,m)=>Math.max(p,m.length),0),l=4+2+r,c=Number.isFinite(e)&&e>0?Math.max(8,Math.floor(e)-l):1/0,d=s.map((p,m)=>{const f=p.kind==="learned"?"L":"S",h=String(p.name||"(unknown)");return[lr(`${f} ${h}`,c),n[m]]}),u=an(d);return t.length>s.length?`${u}
|
|
64
|
-
… ${t.length-s.length} more`:u}function Kd(t){const s=t.slice().sort((n,r)=>(r.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),ze(n.totalValueBytes||0)]);return an(s)}function sy(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":Zt(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return an([["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 ny(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 ry(t,e){const s=t.slice().sort((p,m)=>(Number(m.calls)||0)-(Number(p.calls)||0)).slice(0,12),n=s.map(p=>`${Number(p.calls)||0} calls`),r=s.map(p=>`${Number(p.totalResults)||0} res`),i=n.reduce((p,m)=>Math.max(p,m.length),0),o=r.reduce((p,m)=>Math.max(p,m.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((p,m)=>{const f=p.namespace?` ${p.namespace}`:"";return[lr(`${ny(p.operation)}${f}`,c),n[m],r[m]]}),u=an(d);return t.length>s.length?`${u}
|
|
65
|
-
… ${t.length-s.length} more`:u}function iy(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.data)return[fe("Loading fleet stats...")];const n=s.data;if(!n)return[fe("Fleet stats unavailable.")];const r=[],i=Math.max(24,e);r.push(or("fleet",i)),r.push(fe(""));const o=n.windowStart?`Since: ${Ea(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(Ce([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],i)),r.push(Ce([{text:`Sessions: ${n.totals.sessionCount}`,color:"white"},{text:` Tokens: ${ne(n.totals.totalTokensInput)} in / ${ne(n.totals.totalTokensOutput)} out`,color:"white"}],i)),r.push(fe(""));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 S=y.totalTokensInput>0?y.totalTokensCacheRead/y.totalTokensInput:null;g.push(b),g.push(ka(y,S)),g.push("")}r.push(...He({title:"Tokens By Model",body:g.join(`
|
|
66
|
-
`).trimEnd(),width:i,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),r.push(fe(""))}const d=n.totals.cacheHitRatio,u=d==null?"—":`${(d*100).toFixed(1)}%`;r.push(...He({title:"Fleet Totals",body:es([["Sessions",String(n.totals.sessionCount)],["Tokens In",ne(n.totals.totalTokensInput)],["Tokens Out",ne(n.totals.totalTokensOutput)],["Total Tokens",ne(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",ne(n.totals.totalTokensCacheRead)],["Cache Write",ne(n.totals.totalTokensCacheWrite)],["Hit Ratio",u],["Snapshots",ze(n.totals.totalSnapshotSizeBytes)]]),width:i,titleColor:"green",borderColor:"gray",fitToContent:!0}));const p=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(g=>!(g&&g.agentId==="facts-manager"&&String(g.name||"").startsWith("skills/")));p.length>0&&(r.push(fe("")),r.push(...He({title:`Fleet Skills (${p.length})`,body:ay(p,e),width:i,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const m=Array.isArray(s.retrievalUsage?.rows)?s.retrievalUsage.rows:[];if(m.length>0){const g=m.reduce((b,y)=>b+(Number(y.calls)||0),0);r.push(fe("")),r.push(...He({title:`Fleet Retrieval (${ne(g)})`,body:ry(m,e),width:i,titleColor:"magenta",borderColor:"gray",fitToContent:!0}))}const f=s.sharedFactsStats;if(f&&Array.isArray(f.rows)&&f.rows.length>0){r.push(fe(""));const g=`${f.totalCount} · ${ze(f.totalBytes)}`;r.push(...He({title:`Shared Facts (${g})`,body:Kd(f.rows),width:i,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const h=s.factsTombstoneStats;return h&&Number(h.pendingTotal)>0&&(r.push(fe("")),r.push(...He({title:`Fact Tombstones (${Number(h.pendingTotal)||0})`,body:sy(h),width:i,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),r}function ay(t,e){const n=t.slice().sort((h,g)=>{const b=E=>E==="learned"?1:0,y=b(h.kind)-b(g.kind);if(y!==0)return y;const S=h.agentId?0:1,v=g.agentId?0:1;if(S!==v)return S-v;const w=String(h.agentId||"").localeCompare(String(g.agentId||""));return w!==0?w: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,u=c+d+o+d+l,p=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-u):1/0,m=n.map((h,g)=>{const b=h.kind==="learned"?"L":"S",y=h.agentId||".",S=String(h.name||"(unknown)");return[lr(`${b} ${y}/${S}`,p),r[g],i[g]]}),f=an(m);return t.length>n.length?`${f}
|
|
67
|
-
… ${t.length-n.length} more`:f}function oy(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(ka(n,r)),s.push("")}return s.join(`
|
|
68
|
-
`).trimEnd()}function ka(t,e){const s=e==null?"—":`${(e*100).toFixed(1)}%`,n=(Number(t.totalTokensInput)||0)+(Number(t.totalTokensOutput)||0),r=[["Input",ne(t.totalTokensInput||0)],["Output",ne(t.totalTokensOutput||0)],["Total",ne(n)],["Turns",ne(t.turnCount||0)],["Cache Read",ne(t.totalTokensCacheRead||0)],["Cache Write",ne(t.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",ze(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&r.push(["Orch",ze(t.totalOrchestrationHistorySizeBytes||0)]),es(r).split(`
|
|
69
|
-
`).map(o=>` ${o}`).join(`
|
|
70
|
-
`)}function Ai(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":sn(t?.owner,"Unknown User")}function ly(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=Ai(t);return e&&e!==s?e:""}function cy(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=lr(String(i.model||"(default)"),Math.max(12,e-10));r.push(`${o} · ${i.sessionCount||0} sess · ${i.turnCount||0} turns`),r.push(ka(i,i.cacheHitRatio)),r.push("")}return s.length>n.length&&r.push(`… ${s.length-n.length} more models`),r.join(`
|
|
71
|
-
`).trimEnd()}function dy(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.userStats)return[fe("Loading user stats...")];const n=s.userStats;if(!n)return[fe("User stats unavailable.")];const r=[],i=Math.max(24,e);r.push(or("users",i)),r.push(fe(""));const o=n.windowStart?`Since: ${Ea(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(Ce([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],i)),r.push(Ce([{text:`Users: ${Array.isArray(n.users)?n.users.length:0}`,color:"white"},{text:` Sessions: ${n.totals.sessionCount||0}`,color:"white"}],i)),r.push(fe(""));const c=n.totals.cacheHitRatio,d=c==null?"—":`${(c*100).toFixed(1)}%`;r.push(...He({title:"User Totals",body:es([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",ne(n.totals.totalTokensInput||0)],["Tokens Out",ne(n.totals.totalTokensOutput||0)],["Total Tokens",ne((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",ne(n.totals.totalTokensCacheRead||0)],["Cache Write",ne(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",d],["Snapshots",ze(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",ze(n.totals.totalOrchestrationHistorySizeBytes||0)]]),width:i,titleColor:"green",borderColor:"gray",fitToContent:!0}));const u=Array.isArray(n.users)?n.users:[],p=u.slice().sort((m,f)=>(f.totalTokensInput||0)-(m.totalTokensInput||0)||(f.totalSnapshotSizeBytes||0)-(m.totalSnapshotSizeBytes||0)).slice(0,8);for(const m of p){const f=ly(m),h=m.cacheHitRatio,g=h==null?"—":`${(h*100).toFixed(1)}%`,b=f?`${Ai(m)} <${f}>`:Ai(m),y=es([["Sessions",String(m.sessionCount||0)],["Tokens In",ne(m.totalTokensInput||0)],["Tokens Out",ne(m.totalTokensOutput||0)],["Total Tokens",ne((m.totalTokensInput||0)+(m.totalTokensOutput||0))],["Cache Read",ne(m.totalTokensCacheRead||0)],["Cache Write",ne(m.totalTokensCacheWrite||0)],["Hit Ratio",g],["Snapshots",ze(m.totalSnapshotSizeBytes||0)],["Orch Size",ze(m.totalOrchestrationHistorySizeBytes||0)]]),S=cy(m,i);r.push(fe("")),r.push(...He({title:`${b} (${m.sessionCount||0})`,body:S?`${y}
|
|
72
|
-
|
|
73
|
-
${S}`:y,width:i,titleColor:m.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return u.length>p.length&&(r.push(fe("")),r.push(fe(`… ${u.length-p.length} more users`))),r}function Ht(t,e={}){const s=ut(t),n=t.ui.inspectorTab,r=Math.max(18,Number(e?.width)||36),i=!!e?.allowWideColumns,o=md(r);if(s?.isGroup)return{title:ht("Inspector","magenta"),activeTab:n,tabs:gt,disabled:!0,stickyLines:[],lines:[fe(Vd,"gray")]};const l=s?_e(s.sessionId):"",c=n==="sequence"||n==="nodes"?Sa(t):null,d=n==="nodes"?[...ht("Node Map","magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:s?n==="sequence"?[...ht(o?"Sequence":`Sequence: ${l}`,"magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:n==="logs"?[...ht(o?"Logs":`Logs: ${l}`,"magenta")]:n==="history"?[...ht(o?"Duroxide Events":`Duroxide Event History: ${l}`,"magenta")]:n==="stats"?[...ht(o?"Stats":`Stats: ${l}`,"magenta"),{text:` [${Ws(t.ui?.statsViewMode)}]`,color:"gray"}]:[...ht(o?"Files":`Files: ${l}`,"magenta")]:n==="stats"?`Stats: ${Ws(t.ui?.statsViewMode).replace(/^./u,m=>m.toUpperCase())}`:"No session selected";let u,p=[];switch(n){case"sequence":{const m=s?Lg(t,s,r,{allowWideColumns:i,sequenceExpansion:e?.sequenceExpansion||null}):{stickyLines:[],lines:["No session selected."]};p=m.stickyLines||[],u=m.lines;break}case"logs":u=s?Zh(t,s):["No session selected."];break;case"nodes":u=Ug(t,r,{});break;case"files":u=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":u=s?fy(t,s):["No session selected."];break;case"stats":u=Ws(t.ui?.statsViewMode)==="users"?dy(t,r):Ws(t.ui?.statsViewMode)==="fleet"?iy(t,r):s?ty(t,s,r):[or("session",Math.max(24,r)),fe(""),fe("No session selected. Press f to cycle to fleet or users view.")];break;default:u=["Inspector view is scaffolded in the new architecture."];break}return{title:d,activeTab:n,tabs:gt,stickyLines:p,lines:u}}const uy={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"},Vd="Select a session to see details.";function py(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=uy[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 my(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function fy(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=my(n[o]).split(`
|
|
74
|
-
`);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=py(n[o]);for(const c of l)i.push(c);o<n.length-1&&i.push({text:"────────────────────────────────",color:"gray"})}return i}function hy(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:wa(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function Yo(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 gy(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(m=>m.id===o)||null,c=i&&i.id!==o,d=Math.max(24,e-4),u=n.map((m,f)=>{const h=m.id===o?" [current]":"",g=`${m.label}${h}`.slice(0,d);return f===r?bt(g.padEnd(d," ")):[{text:g,color:m.id===o?"cyan":"white",bold:m.id===o}]}),p=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.",color:c?"yellow":"green"}],Yo([{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"}]),Yo([{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:u,selectedRowIndex:r,detailsTitle:"Theme Details",detailsLines:p}}function yy(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 Hs(t,e){return t.selectedName!==e.name?!0:typeof e.seq=="number"?(t.selectionSeq??0)!==e.seq:!1}function Xo(t){return{mode:"mine",userId:null,data:null,users:[],drafts:{},loading:!1,saving:!1,error:null,generation:(t?.generation||0)+1,fetchedAt:null,userQuery:""}}function pn(t){return JSON.stringify([t?.provider,t?.subject])}function $t(t){const e=String(t??"").trim();return e||null}function Or(t){return new Map(t)}function qs(t){return new Set(t)}function by(t){return Array.isArray(t)?[...t]:[]}function Sy(t){return Array.isArray(t)?[...t]:[]}const vy=5e3;function Qo(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 Yd(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function mn(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||Yd(i))&&s.push(r)}return s}function wy(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?.[Af(i).sessionId];d&&d.isGroup||(n[i]=c)}return n}function Xd(t){return qs(t)}function Ey(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 Zo(t,e,s){const n=Xd(t);if(!s||!e?.[s])return n;for(const r of Ey(s,e))n.delete(r);return n}function Jo(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 ky(t){return{...t||{}}}function vt(t){return{...t||{}}}function el(t){return{...t||{}}}function fn(t){return{...t||{}}}function Fr(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function Iy(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function xy(t){return[L.SESSIONS,L.CHAT,L.INSPECTOR,L.ACTIVITY].includes(t)?t:null}function Dr(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(ke,Number(e)||ke);return s.length>n?s.slice(-n):s}function Ni(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(!Ni(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)||!Ni(t[r],e[r]))return!1;return!0}function Mt(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 Ay(t,e){const s=Mt(t),n=Mt(e);return s>0&&n>0&&n<=s}const Ny=new Set(["completed","failed","cancelled","error"]);function Ys(t){const e=t?.statusVersion;if(e==null||e===""||typeof e=="boolean")return null;const s=Number(e);return Number.isSafeInteger(s)&&s>0?s:null}function Cy(t,e){const s=Ys(t),n=Ys(e);if(s!=null&&n!=null){if(n<s)return!0;if(n>s)return!1}const r=t?.status,i=e?.status;if(!r||!i||r===i||Ny.has(i))return!1;if(s!=null&&n!=null)return!0;if(r==="running")return Ay(t,e);const o=Mt(t),l=Mt(e);return i==="running"&&o>0&&l>0&&l<o}const Ty=new Set(["status","statusVersion","updatedAt","orchestrationStatus","pendingQuestion","waitReason","pauseState","error","result"]);function tl(t={},e={}){let s=t||{};const n=Cy(t,e),r=Ys(t);for(const[i,o]of Object.entries(e||{}))if(o!==void 0&&!(n&&Ty.has(i))&&!(i==="updatedAt"&&r!=null&&r===Ys(e)&&Mt(e)<Mt(t))&&!(i==="statusVersion"&&r!=null&&Ys(e)==null)){if(i==="pendingQuestion"&&_y(t,o,e)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}Ni(t?.[i],o)||(s===t&&(s={...t||{}}),s[i]=o)}return s}function sl(t){if(!t)return"unknown";const e=t.status||"unknown",s=e==="waiting"||e==="idle"||e==="unknown";return s&&_s(t)?"budget_paused":t.cronActive===!0&&s?"cron_waiting":s&&(Number(t.activeChildCount)||0)>0?"awaiting_children":e}function Py(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=sl(e),r=t?.rowVisualStatus||sl(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>=vy?{...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 My=new Set(["running","input_required"]);function Br(t){const e=new Map;for(const r of Object.values(t||{})){if(!r?.sessionId||r.isGroup||!My.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 nl(t={},e={},s){let n=!1;const r={};for(const[i,o]of Object.entries(e)){const l=Py(t[i],o,s);r[i]=l,l!==o&&(n=!0)}return n?r:e}function rl(t){return String(t?.question||"").trim()}function _y(t,e,s){const n=rl(e);if(!n)return!1;const r=Mt({updatedAt:e?.askedAt})||Mt(s);return[t?.answeredPendingQuestion,t?.resolvedInputQuestion].some(i=>{if(rl(i)!==n)return!1;const o=Mt({updatedAt:i?.answeredAt});return!r||!o||r<=o})}function $y(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&Pc(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function il(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 al(t={}){const e=String(t?.filterQuery||"").trim(),s=Zs(t?.ownerFilter);return!!e||s.all!==!0}function Ry(t,e=[]){const s=ns(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(i=>i.sessionId===n)||t.sessions?.navigationIntent||n&&t.sessions?.byId?.[n]&&!al(t.sessions)||n&&!t.sessions?.listingSeen)return n;if(al(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 $y(r)}function Ly(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||{},chat:!0,inspector:!0,activity:!0}}}function Oy(t,e,s){const n=e.byId?.[s];if(!n||n.isGroup||n.isSystem)return null;const r=Zs(e.ownerFilter);if(r.all===!0)return null;const i=Ae(n.owner);if(!i||i===nn)return null;const o=Ae(t.auth?.principal);if(o&&i===o||r.includeShared||r.ownerKeys.includes(i))return null;const l={...e,ownerFilterExplicit:!0,ownerFilter:{...r,ownerKeys:[...r.ownerKeys,i]},ownerFilterAutoAdmitted:{sessionId:s,ownerKey:i}};return ns({...t,sessions:l}).some(d=>d.sessionId===s)?l:null}function Fy(t,e){const s=e?.ownerKey;return!s||t.all===!0||t.includeShared||t.ownerKeys.includes(s)?t:{...t,ownerKeys:[...t.ownerKeys,s]}}function us(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 p=Zo(s.collapsedIds,s.byId,i);Jo(p,s.collapsedIds)||(s={...s,collapsedIds:p,flat:lt(Object.values(s.byId||{}),p,s.orderById,s.pinnedIds,s.manualOrder)})}if(r&&s.filterExceptionId!==r&&s.ownerFilterAutoAdmitted?.sessionId!==r&&!ns({...t,sessions:s}).some(m=>m.sessionId===r)){const m=Oy(t,s,r);m?s=m:s={...s,filterExceptionId:r}}const o={...t,sessions:s},l=Ry(o,Object.values(s.byId||{})),c=Zo(s.collapsedIds,s.byId,l);return{sessions:{...!Jo(c,s.collapsedIds)?{...s,collapsedIds:c,flat:lt(Object.values(s.byId||{}),c,s.orderById,s.pinnedIds,s.manualOrder)}:s,activeSessionId:l},ui:Ly(t,l)}}function Hr(t={},e=0,s=[]){const n=ky(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 Dy(t=[],e=[]){const s=lt(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 By(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 ol(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 Hy(t,e){const s=e.sessionId??e.session?.sessionId,n=/^(history|files|canvas|orchestration|executionHistory|sessionStats|outbox)\//.test(e.type)||e.type==="sessions/merged";if(s&&n&&t.sessions?.goneIds?.includes(s))return t;const r=Gy(t,e);return r===t?r:Uy(t,r,e)}function Uy(t,e,s){const n=e.ui;if(n.sessionViewDevice!=="desktop")return e;const r=e.sessions.activeSessionId||null;if(!r||e.sessions.byId?.[r]?.isGroup)return e;const i=t.sessions.activeSessionId||null;if(s.type==="profileSettings/apply")return{...e,ui:ll(n,n.sessionViews?.[r]?.desktop||fi())};if(r!==i)return n.sessionViewsLoaded?{...e,ui:ll(n,n.sessionViews?.[r]?.desktop||fi())}:e;const o=Ci(n),l=Ci(t.ui);if(Qd(o,l))return e;const c={...n.sessionViews?.[r]||{},desktop:{...o,at:Date.now()}};return{...e,ui:{...n,sessionViews:{...n.sessionViews||{},[r]:c}}}}function Ci(t){const e={};for(const s of ir)e[s]=Number(t.layout?.[s])||0;return{canvasOpen:t.canvasOpen===!0,diagnosticsOpen:t.diagnosticsOpen===!0,zen:t.canvasOpen===!0&&t.canvasZen===!0,layout:e}}function Qd(t,e){if(t.canvasOpen!==e.canvasOpen||t.diagnosticsOpen!==e.diagnosticsOpen||t.zen!==e.zen)return!1;for(const s of ir)if(t.layout[s]!==e.layout[s])return!1;return!0}function ll(t,e){const s=Ci(t),n={canvasOpen:e.canvasOpen===!0,diagnosticsOpen:e.diagnosticsOpen===!0,zen:e.canvasOpen===!0&&e.zen===!0,layout:e.layout||{}};return Qd(s,{...n,layout:{...s.layout,...n.layout}})?t:{...t,canvasOpen:n.canvasOpen,diagnosticsOpen:n.diagnosticsOpen,canvasZen:n.zen,rightPaneMode:n.canvasOpen?"canvas":"panes",...n.canvasOpen?{}:{canvasMaximized:!1},layout:{...t.layout||{},...n.layout}}}function jy(t,e){const s={...t||{}};for(const[n,r]of Object.entries(e||{})){const i=Number(r?.desktop?.at)||0,o=Number(s[n]?.desktop?.at)||0;(!s[n]||i>o)&&(s[n]=r)}return s}function Gy(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,admin:pn(t.auth?.principal)!==pn(e.principal)||t.auth?.authorization?.role!==e.authorization?.role?{...t.admin,features:Xo(t.admin.features)}:t.admin,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/sessionViewDevice":{const s=e.device==="desktop"||e.device==="mobile"?e.device:null;return s===t.ui.sessionViewDevice?t:{...t,ui:{...t.ui,sessionViewDevice:s}}}case"ui/touchScale":return!!e.enabled==!!t.ui.touchScale?t:{...t,ui:{...t.ui,touchScale:!!e.enabled}};case"ui/agentPickerUsage":{const s=e.usage&&typeof e.usage=="object"&&!Array.isArray(e.usage)?e.usage:{};return{...t,ui:{...t.ui,agentPickerUsage:s}}}case"ui/sessionDetailCollapsed":return!!e.collapsed==!!t.ui.sessionDetailCollapsed?t:{...t,ui:{...t.ui,sessionDetailCollapsed:!!e.collapsed}};case"ui/moaSaveStatus":return{...t,ui:{...t.ui,moaSaveStatus:e.status,moaDirty:e.status==="saved"&&t.ui.moaRevision===e.revision?!1:t.ui.moaDirty}};case"ui/moa":return{...t,ui:{...t.ui,moa:Js(e.value),moaDirty:!0,moaRevision:(t.ui.moaRevision||0)+1}};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,"sessionDetailCollapsed")&&typeof s.sessionDetailCollapsed=="boolean",c=Object.prototype.hasOwnProperty.call(s,"agentPickerUsage")&&s.agentPickerUsage&&typeof s.agentPickerUsage=="object"&&!Array.isArray(s.agentPickerUsage),d=Object.prototype.hasOwnProperty.call(s,"rightPaneMode")&&(s.rightPaneMode==="canvas"||s.rightPaneMode==="panes"),u=Object.prototype.hasOwnProperty.call(s,"desktopPanes")&&s.desktopPanes&&typeof s.desktopPanes=="object",m=Object.prototype.hasOwnProperty.call(s,"sessionViews")&&s.sessionViews&&typeof s.sessionViews=="object"?jy(ld(s.sessionViews),t.ui.sessionViews):t.ui.sessionViews,f=u||d?cd(u?s.desktopPanes:null,d?s.rightPaneMode:null):null,h=Object.prototype.hasOwnProperty.call(s,"canvasPrefs"),g=Object.prototype.hasOwnProperty.call(s,"pinnedSessionIds"),b=Object.prototype.hasOwnProperty.call(s,"collapsedSessionIds"),y=Object.prototype.hasOwnProperty.call(s,"sessionOrder"),S=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.status!=="failed"),v=Object.prototype.hasOwnProperty.call(s,"activeSessionId")&&!S&&!t.sessions.localSelectionMade,w=Object.keys(t.sessions.byId||{}).length>0,E=i?{...t.ui.layout||{},...Ji(s.layoutAdjustments)}:t.ui.layout,k=g?w?mn(jn(s.pinnedSessionIds),t.sessions.byId):jn(s.pinnedSessionIds):t.sessions.pinnedIds,x=b?w?Xd(mi(s.collapsedSessionIds),t.sessions.byId):mi(s.collapsedSessionIds):t.sessions.collapsedIds,T=y?ea(s.sessionOrder):t.sessions.manualOrder,A=v?dd(s.activeSessionId):t.sessions.activeSessionId,R={...t.sessions,...r?{ownerFilter:Fy(Zs(s.sessionOwnerFilter),t.sessions.ownerFilterAutoAdmitted),ownerFilterExplicit:!0}:{},pinnedIds:k,manualOrder:T,collapsedIds:x,collapsedIdsExplicit:b?!0:t.sessions.collapsedIdsExplicit,activeSessionId:A,flat:g||b||y?lt(Object.values(t.sessions.byId),x,t.sessions.orderById,k,T):t.sessions.flat},N=w&&(r||g||b||v)?us(t,R):{sessions:R,ui:t.ui};return{...t,sessions:N.sessions,ui:{...N.ui,moa:!t.ui.moaDirty&&Object.prototype.hasOwnProperty.call(s,"moa")?Js(s.moa):N.ui.moa,moaLoaded:!0,themeId:n?s.themeId.trim():N.ui.themeId,touchScale:o?s.touchScale:N.ui.touchScale,sessionDetailCollapsed:l?s.sessionDetailCollapsed:N.ui.sessionDetailCollapsed,agentPickerUsage:c?s.agentPickerUsage:N.ui.agentPickerUsage,rightPaneMode:d?s.rightPaneMode:N.ui.rightPaneMode,...f?{canvasOpen:f.canvasOpen,diagnosticsOpen:f.diagnosticsOpen,canvasZen:f.zen===!0}:{},layout:E,sessionViews:m,sessionViewsLoaded:!0},canvas:h?{...t.canvas,prefs:wy(t.canvas.prefs,ta(s.canvasPrefs),w?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"budget/tab":{const s=["summary","agents"].includes(e.tab)?e.tab:"providers";return t.budget.tab===s?t:{...t,budget:{...t.budget,tab:s}}}case"budget/summary/filter":{const s=t.budget.summary,n=[14,30,90].includes(Number(e.days))?Number(e.days):s.days,r=Array.isArray(e.providers)?e.providers.map(o=>String(o??"").trim()).filter(Boolean):s.providers,i=["all","shared","users","custom"].includes(e.preset)?e.preset:Array.isArray(e.providers)?"custom":s.preset;return{...t,budget:{...t.budget,summary:{...s,days:n,providers:r,preset:i}}}}case"budget/summary/loading":return{...t,budget:{...t.budget,summary:{...t.budget.summary,loading:!0}}};case"budget/summary/loaded":return{...t,budget:{...t.budget,summary:{...t.budget.summary,loading:!1,error:null,fetchedAt:Number(e.fetchedAt)||Date.now(),data:e.data&&typeof e.data=="object"?e.data:null}}};case"budget/agents/loading":return{...t,budget:{...t.budget,agents:{...t.budget.agents,loading:!0}}};case"budget/agents/loaded":return{...t,budget:{...t.budget,agents:{...t.budget.agents,loading:!1,error:null,fetchedAt:Number(e.fetchedAt)||Date.now(),data:e.data&&typeof e.data=="object"?e.data:null}}};case"budget/agents/failed":return{...t,budget:{...t.budget,agents:{...t.budget.agents,loading:!1,error:String(e.error||"The agent pivot could not be read.")}}};case"budget/summary/failed":return{...t,budget:{...t.budget,summary:{...t.budget.summary,loading:!1,error:String(e.error||"The summary could not be read.")}}};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,ownerFilterAutoAdmitted:null};return{...t,sessions:s}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:Zs(e.filter),navigationIntent:null,filterExceptionId:null,ownerFilterAutoAdmitted:null},n=us(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,ownerFilterAutoAdmitted:null},r=us(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!=="chat"&&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===L.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:By(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:Es(e.prompt),promptAttachments:ol(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:ol(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,i=t.history.bySessionId.has(s)||[t.files,t.canvas,t.orchestration,t.executionHistory,t.outbox,t.sessionStats].some(p=>Object.hasOwn(p?.bySessionId||{},s));if(!n&&!r&&!i)return t;const o={...t.sessions.byId};delete o[s];const l=Br(o),c=Array.isArray(t.sessions.selectedIds)?t.sessions.selectedIds.filter(p=>p!==s):t.sessions.selectedIds,d=new Map(t.history.bySessionId);d.delete(s);const u=p=>{if(!p?.bySessionId)return p;const m={...p.bySessionId};return delete m[s],{...p,bySessionId:m}};return{...t,history:{...t.history,bySessionId:d},files:u(t.files),orchestration:u(t.orchestration),executionHistory:u(t.executionHistory),canvas:u(t.canvas),outbox:u(t.outbox),sessionStats:u(t.sessionStats),sessions:{...t.sessions,byId:l,selectedIds:c,activeSessionId:r?null:t.sessions.activeSessionId,goneIds:[...new Set([...t.sessions.goneIds||[],s])].slice(-1e3)}}}case"sessions/loaded":{const s={};let n=!1;const r=Date.now();for(const k of t.sessions.groupRows||[])s[k.sessionId]=t.sessions.byId[k.sessionId]||k;for(const k of e.sessions){const x=t.sessions.byId[k.sessionId];s[k.sessionId]=no(x,tl(x,k),t.history.bySessionId.get(k.sessionId)?.events,r)}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=Br(s),o=nl(t.sessions.byId,i,r);for(const[k,x]of Object.entries(o))if(x!==t.sessions.byId[k]){n=!0;break}const l=Object.keys(t.sessions.byId),c=Object.keys(o);if(l.length!==c.length&&(n=!0),!n){for(const k of c)if(!t.sessions.byId[k]){n=!0;break}}if(!n)return t;const d=Object.values(o),u=Object.keys(t.sessions.orderById||{}).length>0,p=il(d),m=!!t.sessions.collapsedIdsExplicit,{orderById:f,nextOrderOrdinal:h}=u?Hr(t.sessions.orderById,t.sessions.nextOrderOrdinal,d):Dy(d,t.sessions.pinnedIds),g=m?qs(t.sessions.collapsedIds):p,b=t.sessions.listingSeen===!0;if(m&&b){const k=il(Object.values(t.sessions.byId));for(const x of p)k.has(x)||g.add(x)}const y=mn(t.sessions.pinnedIds,o),S=Qo(t.sessions.selectedIds,o),v=lt(d,g,f,y,t.sessions.manualOrder),w={...t.sessions,byId:o,goneIds:(t.sessions.goneIds||[]).filter(k=>!e.sessions.some(x=>x.sessionId===k)),collapsedIds:g,collapsedIdsExplicit:m,listingSeen:!0,pinnedIds:y,selectedIds:S,selectMode:t.sessions.selectMode&&S.length>0,flat:v,activeSessionId:t.sessions.activeSessionId,orderById:f,nextOrderOrdinal:h},E=us(t,w);return{...t,sessions:E.sessions,ui:E.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=mn(t.sessions.pinnedIds,n),{orderById:c,nextOrderOrdinal:d}=Hr(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(n)),u=t.sessions.groupsListingSeen===!0,p=qs(t.sessions.collapsedIds);for(const h of s)u&&(t.sessions.byId[h.sessionId]||p.add(h.sessionId));const m={...t.sessions,groupRows:[...s,...o],byId:n,pinnedIds:l,orderById:c,nextOrderOrdinal:d,collapsedIds:p,groupsListingSeen:!0,flat:lt(Object.values(n),p,c,l,t.sessions.manualOrder)},f=us(t,m);return{...t,sessions:f.sessions,ui:f.ui}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=no(s,tl(s,e.session),t.history.bySessionId.get(e.session.sessionId)?.events),r=nl(t.sessions.byId,Br({...t.sessions.byId,[e.session.sessionId]:n}),Date.now());let i=!1;for(const[p,m]of Object.entries(r))if(m!==t.sessions.byId[p]){i=!0;break}if(!i)return t;const o=mn(t.sessions.pinnedIds,r),{orderById:l,nextOrderOrdinal:c}=Hr(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(r)),d={...t.sessions,byId:r,pinnedIds:o,flat:lt(Object.values(r),t.sessions.collapsedIds,l,o,t.sessions.manualOrder),activeSessionId:t.sessions.activeSessionId,orderById:l,nextOrderOrdinal:c},u=us(t,d);return{...t,sessions:u.sessions,ui:u.ui}}case"sessions/selected":{t={...t,sessions:{...t.sessions,listDeselected:!1,localSelectionMade:!0}};const s=t.sessions.activeSessionId,n={...t.ui.chatScrollBySession||{}},r={...t.ui.chatFollowBottomBySession||{}};s&&s!==e.sessionId&&(n[s]=Number(t.ui.scroll?.chat)||0,r[s]=t.ui.followBottom?.chat!==!1);const i=s!==e.sessionId,o={...t.ui.promptDraftBySession||{}};let l=t.ui.prompt,c=t.ui.promptCursor,d=t.ui.promptAttachments,u=t.ui.promptEdit??null;if(i){if(!!!t.ui.promptEdit&&s){const h={prompt:String(t.ui.prompt||""),attachments:Array.isArray(t.ui.promptAttachments)?t.ui.promptAttachments:[]};h.prompt||h.attachments.length>0?o[s]=h:delete o[s]}const f=e.sessionId?o[e.sessionId]:null;delete o[e.sessionId],l=f?.prompt||"",c=l.length,d=Array.isArray(f?.attachments)?f.attachments:[],u=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,ownerFilterAutoAdmitted:null}:{}},ui:{...t.ui,chatScrollBySession:n,chatFollowBottomBySession:r,promptDraftBySession:o,prompt:l,promptCursor:c,promptRows:Es(l),promptAttachments:d,promptEdit:u,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||{},chat:r[e.sessionId]!==!1,inspector:!0,activity:!0}}}}case"ui/revealCreatedSession":return{...t,files:{...t.files,fullscreen:!1,paneOpen:!1},ui:{...t.ui,revealedCreatedSessionId:e.sessionId,fullscreenPane:null}};case"ui/fullscreenPane":{const s=xy(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=qs(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:lt(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds,t.sessions.manualOrder)}}}case"sessions/expand":{const s=qs(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:lt(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(!Yd(n))return t;const r=by(t.sessions.pinnedIds),o=r.indexOf(s)>=0?r.filter(l=>l!==s):[...r,s];return{...t,sessions:{...t.sessions,pinnedIds:o,flat:lt(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(!Ms(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(u=>u.sessionId).filter(u=>Ms(t.sessions.byId[u]))).filter(u=>u!==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((u,p)=>u===t.sessions.manualOrder[p])?t:{...t,sessions:{...t.sessions,manualOrder:c,flat:lt(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=Sy(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=Qo(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/loadState":{if(!t.sessions.byId[e.sessionId])return t;const s=Or(t.history.bySessionId);return s.set(e.sessionId,{...s.get(e.sessionId),loadState:e.loadState}),{...t,history:{...t.history,bySessionId:s}}}case"history/set":{const s=t.history.bySessionId.get(e.sessionId)||null,n=s?.chat||[],r=Math.max(ke,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??ke)||ke),i=Dr(Ss(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=Or(t.history.bySessionId);return d.set(e.sessionId,{...e.history||{},chat:i,activity:Dr(e.history?.activity||[],r),events:Dr(e.history?.events||[],r),loadedEventLimit:r}),{...t,history:{...t.history,bySessionId:d},ui:c&&t.ui.followBottom?.chat!==!1?{...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=Or(t.history.bySessionId);for(const c of s)n.delete(c);const r=el(t.outbox?.bySessionId);for(const c of s)delete r[c];const i={...t.ui.chatScrollBySession||{}};for(const c of s)delete i[c];const o={...t.ui.chatFollowBottomBySession||{}};for(const c of s)delete o[c];const l={...t.ui.promptDraftBySession||{}};for(const c of s)delete l[c];return{...t,history:{...t.history,bySessionId:n},outbox:{...t.outbox,bySessionId:r},ui:{...t.ui,chatScrollBySession:i,chatFollowBottomBySession:o,promptDraftBySession:l}}}case"outbox/setSessionItems":{const s=e.sessionId;if(!s)return t;const n=Array.isArray(e.items)?e.items.filter(Boolean):[],r=el(t.outbox?.bySessionId);return n.length===0?delete r[s]:r[s]=n,{...t,outbox:{...t.outbox,bySessionId:r}}}case"orchestration/statsLoading":{const s=fn(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=fn(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=fn(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=fn(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,features:pn(t.admin.profile)!==pn(e.profile)||!!t.admin.profile?.isAdmin!=!!e.profile?.isAdmin?Xo(t.admin.features):t.admin.features,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/mutationDismissed":return t.admin?.modelProviders?.mutation?.error?{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,mutation:{...t.admin.modelProviders.mutation,error:null}}}}:t;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||""),n=e.mode==="update";return{...t,admin:{...t.admin,modelProviders:{...t.admin.modelProviders,create:{editing:!0,mode:n?"update":"create",stage:n||e.stage==="credential"?"credential":"name",name:n?s:"",typeId:String(e.typeId||""),shared:e.shared===!0,draft:n?"":s,cursorIndex:n?0: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=["providers","packages","workers","features","ghcp"].includes(e.section)?e.section:"ghcp";return{...t,admin:{...t.admin,section:s}}}case"admin/features":return{...t,admin:{...t.admin,features:{...t.admin.features,...e.patch}}};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.selectedSelector,i=s.selectedName&&n.some(o=>o.name===s.selectedName&&(!r?.scope||o.scope===r.scope)&&(!r?.owner||o.owner?.provider===r.owner.provider&&o.owner?.subject===r.owner.subject));return{...t,admin:{...t.admin,packages:{...s,loading:!1,error:null,list:n,workerState:Array.isArray(e.workerState)?e.workerState:[],fetchedAt:Date.now(),selectedName:i?s.selectedName:null,selectedSelector:i?s.selectedSelector??null:null,...i?{}:{selectionSeq:(s.selectionSeq??0)+1,detail:null,changelog: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 Hs(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 Hs(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 Hs(t.admin.packages,e)?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,changelog:e.content||null}}};case"admin/packages/tree/loaded":{if(Hs(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 Hs(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={...hi().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:{...hi().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=vt(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=vt(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=vt(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},r=Un(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=vt(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=vt(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:$t(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(p=>p?.providerName===s.selectedProvider),o=i?null:s.selectedProvider,l=s.selectedScope||"*",c=n&&!i&&l!=="*"&&!e.grid.some(p=>p?.providerName===s.selectedProvider&&p?.rowKind==="model"&&p?.scope===l),d=i||c?"*":l,u=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:u,series:o===s.selectedProvider&&d===l?s.series:{provider:null,scope:"*",rangeDays:s.rangeDays??Fe,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:o===s.selectedProvider&&d===l?s.systemUsage:{provider:null,scope:"*",rangeDays:s.rangeDays??Fe,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!Gn.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=$t(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??Fe,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:{provider:null,scope:"*",rangeDays:t.budget.rangeDays??Fe,totals:null,days:[],breakdown:[],loading:!1,loaded:!1,error:null,fetchedAt:0}}}}case"budget/series/loading":{const s=$t(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=Number(e.rangeDays)||t.budget.rangeDays||Fe;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=$t(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=e.rangeDays===void 0?t.budget.rangeDays||Fe:Number(e.rangeDays);return s!==t.budget.selectedProvider||n!==(t.budget.selectedScope||"*")||r!==(t.budget.rangeDays||Fe)?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=$t(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=e.rangeDays===void 0?t.budget.rangeDays||Fe:Number(e.rangeDays);if(s!==t.budget.selectedProvider||n!==(t.budget.selectedScope||"*")||r!==(t.budget.rangeDays||Fe))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=$t(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=Number(e.rangeDays)||t.budget.rangeDays||Fe;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=$t(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=e.rangeDays===void 0?t.budget.rangeDays||Fe:Number(e.rangeDays);if(s!==t.budget.selectedProvider||n!==(t.budget.selectedScope||"*")||r!==(t.budget.rangeDays||Fe))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=$t(e.provider),n=typeof e.scope=="string"&&e.scope?e.scope:"*",r=e.rangeDays===void 0?t.budget.rangeDays||Fe:Number(e.rangeDays);if(s!==t.budget.selectedProvider||n!==(t.budget.selectedScope||"*")||r!==(t.budget.rangeDays||Fe))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=it(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=it(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=it(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=it(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=it(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=it(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=vt(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=vt(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=vt(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=vt(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(p=>p!==`${e.sessionId}/${e.filename}`)}};const s=vt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},r=Un(n.entries).filter(p=>p.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||{},u=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===u?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:{...Fr(t.files.filter),...Fr(e.filter)},...Fr(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:Iy(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 Ia(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 Zd(t){const e=Array.isArray(t)?t:[];return e.length<=1?String(e[0]?.url||""):e.map(s=>`${s.label}: ${s.url}`).join(`
|
|
75
|
-
`)}function Wy(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 cl(t,e,s){const n=e?.nativeTaskSnapshot;return n?.ownerId?$c({...t,nativeTaskSnapshot:void 0},{version:1,...n,tasks:(e.chat||[]).filter(r=>r.kind==="native-task-group").flatMap(r=>r.tasks).filter(r=>r.ownerId===n.ownerId)},{sessionId:s,seq:n.liveSeq}):t}function qy(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 zy=2e4,Ky=2e4,Vy=3e4,Yy=30,dl="Session refresh failed",Xy=3,Qy=200,Zy=5,Jy=new Set([L.SESSIONS,L.CHAT,L.INSPECTOR,L.ACTIVITY]);function eb(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 hn(t){return!t?.sessionId||t.isGroup?t:{...t,groupId:t.viewerGroupId??null,parentSessionId:t.parentSessionId??null}}function Nn(t){return String(t||"").startsWith("group:")?String(t).slice(6):null}function Us(t){return Nn(t)!==null}function tb(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 Ur(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 js(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||e===403||s==="NOT_FOUND"||s==="FORBIDDEN"}async function sb(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<Zy;n+=1){const r=await t.listSessionsPage({limit:Qy,cursor:s}),i=Array.isArray(r?.sessions)?r.sessions:[];if(e.push(...i),!r?.hasMore||!r?.nextCursor)break;s=r.nextCursor}return e}function nb(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 ul(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 Cn(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 pl(t){const e=Cn(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 Tn(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 rb(t){const e=Tn(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 Jd={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function ib(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 ab(t,e){const s=ib(e);return s?t==="long_context"?`Long context (${s} tokens, higher cost)`:`Default (${s} tokens)`:Jd[t]||t}function Ti(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 ob(t){return Ti([t])}function ml(t,e=[]){let s=yc(t);for(const n of e){const r=bc(s,n?.eventType,n?.data,{timestamp:n?.createdAt});r&&(s=r)}return s}function Kn(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(!Kn(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)||!Kn(t[r],e[r]))return!1;return!0}function Xs(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 xa(t,e){const s=l=>{if(l==null||l===""||typeof l=="boolean")return null;const c=Number(l);return Number.isSafeInteger(c)&&c>0?c:null},n=s(t?.statusVersion),r=s(e?.statusVersion);if(n!=null&&r!=null)return r<=n;const i=Xs(t?.updatedAt),o=Xs(e?.updatedAt);return i>0&&o>0&&o<=i}function lb(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function cb(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&lb(e?.status)&&xa(t,e)}function db(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!tu(e?.status)&&!eu(e?.orchestrationStatus)&&xa(t,e)}function ub(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||Kn(t?.[l],c)||(s[l]=c,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&!xa(t,e)&&(s.pendingQuestion=null,n=!0),cb(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),Dp(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),db(t,e))for(const l of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[l]!=null&&(Kn(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((tu(e.status)||eu(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}if(n)for(const l of["statusVersion","updatedAt"])e[l]!==void 0&&(s[l]=e[l]);return n?s:null}function fl(t){return String(t||"").replace(/\r\n/g,`
|
|
76
|
-
`).trim()}function eu(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function tu(t){return t==="completed"||t==="failed"||t==="cancelled"}function Ze(t){return String(t||"").slice(0,8)}function Vn(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function gn(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const pb=Vn({provider:"system",subject:"system"});function hl(t){const e=t.auth?.principal||null,s=Vn(e),n=[{id:"all",kind:"all",label:"All",description:"Every session you can see — your own, ones shared with you, and system 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=gn(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=Vn(o);!l||l===s||l===pb||r.has(l)||r.set(l,o)}for(const[i,o]of[...r.entries()].sort((l,c)=>gn(l[1]).localeCompare(gn(c[1])))){const l=gn(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 Yn(t){return Vn(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,includeShared:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function mb(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||t?.includeShared||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function fb(t,e,s){const n=t||Yn(s);if(!e)return n;if(e.kind==="all")return n.all?Yn(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 mb(r)?r:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function Aa(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 hb(t){const e=Aa(t);return e?Math.max(1,60-`${e}: `.length):60}function gb(t){const e=String(t?.title||"").trim();if(!e)return"";const s=Aa(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===Ze(t?.sessionId)?"":n}return e===Ze(t?.sessionId)?"":e}function yb(t,e){const s=String(e||"").trim();if(s)return s;const n=String(t||"").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):"Agent"}function bb(t){const e=String(t?.packageScope||t?.scope||"shared"),s=String(t?.ownerLabel||"");return`pkg:${e}:${s}:${String(t?.packageName||"")}`}function yn(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/g,"")}function Sb(t){const e=new Map;for(const u of t)u?.agentName&&e.set(yn(u.agentName),u);const s=new Map,n=new Map;for(const u of t){const p=yn(u.agentName),m=(u.startedBy||[]).map(h=>yn(h)).filter(h=>h&&e.has(h)&&h!==p);if(m.length===0)continue;const f=m[0];n.set(u,f),s.has(f)||s.set(f,[]),s.get(f).push(u)}const r=u=>n.has(u),i=u=>typeof u.supportsDirectStart=="boolean"?u.supportsDirectStart:!r(u),o=[],l=new Set,c=(u,p,m)=>{if(!l.has(u)){l.add(u),o.push({...u,depth:p,parentAgentName:m||null,supportsDirectStart:i(u)});for(const f of s.get(yn(u.agentName))||[])c(f,p+1,u.agentName)}};for(const u of t)r(u)||c(u,0,null);const d=u=>{const p=new Set;let m=u;for(;m&&!p.has(m);)if(p.add(m),m=e.get(n.get(m)),m===u)return!0;return!1};for(const u of t)!l.has(u)&&d(u)&&c(u,0,null);for(const u of t)c(u,0,null);return o}function vb(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}const gl=["used","name","package"],su="used",jr="agentPickerUsage";function wb(t){return[t?.label,t?.agentName,t?.title,t?.description,t?.packageTitle,t?.packageName,...Array.isArray(t?.tools)?t.tools:[]].filter(Boolean).join(" ").toLowerCase()}function yl(t,e){const s=String(e||"").toLowerCase().split(/\s+/).filter(Boolean);if(s.length===0)return 0;const n=wb(t),r=`${t?.label||""} ${t?.agentName||""}`.toLowerCase();let i=0;for(const o of s){if(!n.includes(o))return-1;r.startsWith(o)?i+=6:new RegExp(`\\b${o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`).test(r)?i+=4:r.includes(o)?i+=3:i+=1}return i}function Pi(t,e){return!t||!e?.agentName?0:Number(t[String(e.agentName)])||0}function Eb(t,e){const s=(n,r)=>String(n.label||n.agentName||"").localeCompare(String(r.label||r.agentName||""),void 0,{sensitivity:"base"});return t==="name"?s:t==="package"?(n,r)=>String(n.packageTitle||n.packageName||"").localeCompare(String(r.packageTitle||r.packageName||""),void 0,{sensitivity:"base"})||s(n,r):(n,r)=>Pi(e,r)-Pi(e,n)||s(n,r)}function bl(t=[],e={}){const{query:s="",sort:n=su,usage:r=null,genericItem:i=null}=e||{},o=[],l=String(s||"").trim();i&&(!l||yl({label:i.label,description:i.description},l)>=0)&&o.push({...i,depth:0});const c=t.filter(f=>f&&f.kind!=="section"),d=new Map;for(const f of c){const h=f.builtin?"builtin":bb(f);d.has(h)||d.set(h,[]),d.get(h).push(f)}const u=[];for(const f of d.values())for(const h of Sb(f))u.push({...h,depth:0});const p=l?u.map(f=>({agent:f,score:yl(f,l)})).filter(f=>f.score>=0):u.map(f=>({agent:f,score:0})),m=Eb(n,r);p.sort((f,h)=>(l?h.score-f.score:0)||m(f.agent,h.agent));for(const{agent:f}of p)o.push({...f,depth:0,usageCount:Pi(r,f)});return o}function Sl(t){return`📎 ${String(t||"").trim()}`}function vl(t,e){const s=String(t||""),n=De(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 kb(t,e,s,n){const r=String(t||""),i=De(r,e),o=De(r,s),l=String(n||"");return{prompt:`${r.slice(0,i)}${l}${r.slice(o)}`,cursor:i+l.length}}function Ib(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function xb(t){const e=String(t?.sessionId||"").trim(),s=Ze(e)||"session";return`Referenced session: ${Ib(t?.title,s)} — session://${e}`}function wl(t,e,s){if(!e)return Nt(t,String(t||"").length,s);const n=String(t||""),r=n.slice(e.tokenEnd,e.tokenEnd+1),i=!r||/\s/u.test(r);return kb(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${i?" ":""}`)}function Ab(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,`
|
|
77
|
-
`).replace(/\n[ \t]+/g,`
|
|
78
|
-
`).replace(/[ \t]{2,}/g," ").trim()}const El=new Set(["image/png","image/jpeg","image/gif","image/webp"]),kl=4*1024*1024,Gr=4;function Nb(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=Ab(t,s);return n.join(`
|
|
79
|
-
`)+(r?`
|
|
80
|
-
|
|
81
|
-
${r}`:"")}function ps(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function nu(t){return Array.from(String(t||"")).length}function Cb(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=Sc(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 Tb(t,e){const s=Math.max(1,Number(e)||1),n=nu(t);return Math.max(1,Math.ceil(n/s))}function ms(t,e){const s=Math.max(1,Number(e)||1);return Cb(t).reduce((n,r)=>{if(!r)return n+1;if(Array.isArray(r)){const i=r.reduce((o,l)=>o+nu(l?.text||""),0);return n+Math.max(1,Math.ceil(i/s))}return n+Tb(r.text||"",s)},0)}function De(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function ru(t){return String(t||"").split(`
|
|
82
|
-
`)}function Pb(t,e){const n=String(t||"").slice(0,De(t,e)).split(`
|
|
83
|
-
`),r=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:r.length}}function Mb(t,e,s){const n=ru(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 De(t,o+i)}function Nt(t,e,s){const n=String(t||""),r=De(n,e),i=String(s||"");return{prompt:`${n.slice(0,r)}${i}${n.slice(r)}`,cursor:r+i.length}}function Gt(t,e){const s=String(t||""),n=De(s,e);return n<=0?{prompt:s,cursor:n}:{prompt:`${s.slice(0,n-1)}${s.slice(n)}`,cursor:n-1}}function bn(t){return/\s/u.test(t||"")}function iu(t,e,s){const n=String(t||"");let r=De(n,e);if(s<0){for(;r>0&&bn(n[r-1]);)r-=1;for(;r>0&&!bn(n[r-1]);)r-=1;return r}for(;r<n.length&&bn(n[r]);)r+=1;for(;r<n.length&&!bn(n[r]);)r+=1;return r}function _b(t,e){const s=String(t||""),n=De(s,e),r=iu(s,n,-1);return r===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,r)}${s.slice(n)}`,cursor:r}}function $b(t,e,s){const n=ru(t);if(n.length<=1)return De(t,e);const r=Pb(t,e),i=Math.max(0,Math.min(r.line+s,n.length-1));return i===r.line?De(t,e):Mb(t,i,r.column)}const Mi=3e3,Rb=new Set(["logs","sequence"]),Lb=2e5,Ob=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),Fb=new Set([".json",".jsonl"]),Db=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function au(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function Bb(t,e=""){const s=au(t),n=String(e||"").toLowerCase();return Db.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}const Wr=12e4;function Il(t,e=Lb){const s=String(t??"");return s.length<=e?s:`${s.slice(0,e)}
|
|
84
|
-
|
|
85
|
-
[Preview truncated at ${e.toLocaleString()} characters. Open the artifact directly if you need the full file.]`}function Hb(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 Ub(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${Hb(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
|
|
86
|
-
`)}function xl(t,e,s="",n=null){const r=String(s||"").toLowerCase(),i=au(t);if(n?.isBinary===!0||Bb(t,s))return{content:Ub(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=Il(e);if(Ob.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(Fb.has(i)||r.includes("json"))try{return{content:Il(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 jb=1e4,Gb=140,Wb=1500,qb={day:"Daily",week:"Weekly",month:"Monthly"};function fs(t){const e=typeof t?.message=="string"?t.message.trim():"";return e||String(t??"").trim()||"The request failed."}function zb(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,u=l?.ceilingTokens==null?null:Number(l.ceilingTokens),p=Number(l?.yourUsedTokens)||0;return{periodLabel:qb[l?.period]||String(l?.period||""),pct:c>0?Math.floor(d/c*100):0,atLimit:c>0&&d>=c,atCeiling:u!=null&&u>0&&p>=u}})].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 Kb{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(L.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(!El.has(c)){o.push({name:l.name||"image",reason:"unsupported type"});continue}if((Number(l.size)||0)>kl){o.push({name:l.name||"image",reason:"over 4 MB"});continue}if(r.length+i.length>=Gr){o.push({name:l.name||"image",reason:`max ${Gr} 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!El.has(n)||(Number(e?.sizeBytes)||0)>kl||this.getPromptAttachments().filter(i=>i?.kind==="image").length>=Gr?!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((u,p)=>p!==c)),this.getPromptEditSessionMatch(e)?.itemId===d?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const i=fl(s);if(!i)return!1;const o=r.findIndex(c=>(c?.phase==="pending"||c?.phase==="queued"||c?.phase==="cancelling")&&fl(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(u=>n.has(u)));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(`
|
|
87
|
-
|
|
88
|
-
`),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}:{}},u=new Set(i.map(h=>h.id)),p=this.getSessionOutbox(e).filter(h=>!u.has(h.id));this.setSessionOutboxItems(e,[...p,d]);const m=this.getPromptEditSessionMatch(e);m&&u.has(m.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const f=(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(S=>S.id===d.id?{...S,phase:"rejected"}:S);this.setSessionOutboxItems(e,y),setTimeout(()=>{const S=this.getSessionOutbox(e),v=S.filter(w=>!(w.id===d.id&&w.phase==="rejected"));v.length!==S.length&&this.setSessionOutboxItems(e,v)},6e3)}else{const y=b.map(S=>S.id===d.id?{...d,phase:"pending",attempted:!0}:S);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,f),await f}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 vl(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=Rt(s),r=n?.sessionId||s.sessions.activeSessionId||null,i=n?.filename||null;if(!r||!i)return!1;const o=Sl(i),l=wl(s.ui.prompt,e,o),c=this.getPromptAttachments(),d=c.findIndex(m=>m?.sessionId===r&&m?.filename===i),u={...d>=0?c[d]:{},id:`${r}/${i}`,sessionId:r,filename:i,resolvedPath:i,token:o},p=d>=0?c.map((m,f)=>f===d?u:m):[...c,u];return this.setPrompt(l.prompt,l.cursor),this.setPromptAttachments(p),this.setFocus(L.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=ns(s)[0]||null,i=r?.sessionId&&s.sessions.byId[r.sessionId]||null;if(!i?.sessionId)return!1;const o=xb(i),l=wl(s.ui.prompt,e,o);return this.setPrompt(l.prompt,l.cursor),this.setFocus(L.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${Ze(i.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}openSessionOwnerFilter(){const e=this.getState(),s=hl(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=fb(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=hl(e),r=Array.isArray(s.items)?s.items:[];if(r.length===n.length&&r.every((d,u)=>d?.id===n[u]?.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=vl(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(zn(this.getState(),"selectedSession")),l=Xt(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:Yn(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.catalogPollInFlight||(this.catalogPollInFlight=!0,this.refreshSessions().catch(i=>{this.dispatch({type:"connection/error",error:i?.message||String(i),statusText:dl})}).finally(()=>{this.catalogPollInFlight=!1}))},4e3)}async stop(){this._featureRefreshSerial=(this._featureRefreshSerial||0)+1,this._featureUserSerial=(this._featureUserSerial||0)+1;for(const e of this._liveTurnIdleTimers?.values()||[])clearTimeout(e);this._liveTurnIdleTimers?.clear(),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(){const e=this.activeSessionSubscriptionId;if(e){clearTimeout(this._liveTurnIdleTimers?.get(e)),this._liveTurnIdleTimers?.delete(e);const s=this.getState().history.bySessionId.get(e);s&&this.dispatch({type:"history/set",sessionId:e,history:{...s,chat:s.chat.filter(n=>!n.liveTurn)}})}this.activeSessionUnsub&&(this.activeSessionUnsub(),this.activeSessionUnsub=null),this.activeSessionSubscriptionId=null}handleSessionGone(e){e&&(Us(e)||(this.sessionRefreshSeq=(this.sessionRefreshSeq||0)+1,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(()=>{}),this.refreshFeatureFlagsIfStale().catch(()=>{});const e=this.sessionRefreshSeq=(this.sessionRefreshSeq||0)+1,s=this.getState(),n=!s.connection.connected||!!s.connection.error,r=s.ui.statusText===dl,i=this.getState().sessions.activeSessionId,o=this.navigationGeneration,l=typeof this.transport.listSessionGroups=="function"?Promise.resolve().then(()=>this.transport.listSessionGroups()).then(g=>(Array.isArray(g)?g:[]).map(eb).filter(Boolean)).catch(g=>(console.warn(`[PilotSwarmUi] session-group fetch failed, keeping the known folders: ${g?.message||g}`),null)):Promise.resolve(null);let c=(await sb(this.transport)).map(hn);const d=await l,u=s.sessions.navigationIntent;if(u?.status==="pending"&&!c.some(g=>g?.sessionId===u.sessionId)&&typeof this.transport.getSession=="function")try{const g=await this.transport.getSession(u.sessionId);g?.sessionId?c=[...c,hn(g)]:this.dispatch({type:"sessions/navigationIntentFailed",sessionId:u.sessionId,errorKind:"not_found"})}catch(g){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:u.sessionId,errorKind:Ur(g)})}const p=i;if(p&&!Us(p)&&!c.some(g=>g?.sessionId===p)&&typeof this.transport.getSession=="function"){const g=await this.transport.getSession(p).catch(()=>null);g?.sessionId&&(c=[...c,hn(g)])}if(e!==this.sessionRefreshSeq)return;n&&this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,...r?{statusText:"Connected"}:{}}),d&&this.dispatch({type:"sessions/groupsLoaded",groups:d,sessions:c});const m=[];for(const g of c)for(const b of Array.isArray(g?.canvases)?g.canvases:[])m.push({sessionId:g.sessionId,slot:b.slot,name:b.name,latestRev:b.latestRev,sizeBytes:b.sizeBytes});m.length&&this.dispatch({type:"canvas/seed",entries:m}),this.dispatch({type:"sessions/loaded",sessions:c}),this.refreshBudgetPausesIfStale(c).catch(()=>{}),this.refreshOpenSessionOwnerFilterModal();const f=this.getState().sessions.activeSessionId,h=new Set;if(f){if(f!==i){if(!this.getState().sessions.byId[f]?.isGroup){const S=this.getState().sessions.navigationIntent;if(S&&S.sessionId===f&&S.status!=="failed")try{await this.loadSession(f)}catch(v){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:f,errorKind:Ur(v)})}else await this.loadSession(f)}return}if(this.getState().sessions.byId[f]?.isGroup||(this.getState().history.bySessionId.get(f)?.events?.length||await this.ensureSessionHistory(f,{force:!0}).catch(()=>{}),this.getState().sessions.activeSessionId!==f||this.navigationGeneration!==o))return;this.ensureCanvasSnapshot(f).catch(()=>{}),this.activeSessionSubscriptionId!==f&&this.attachActiveSession(f),await this.syncSessionDetail(f).catch(()=>{}),await this.syncSessionEvents(f).catch(()=>{}),h.add(f);const b=this.getState(),y=b.sessions.byId[f]||null;if(y?.parentSessionId&&typeof this.transport.getSession=="function"){const S=Object.values(b.sessions.byId).filter(v=>v?.parentSessionId===y.parentSessionId).map(v=>v.sessionId).filter(v=>v&&v!==f).slice(0,6);await Promise.all(S.map(v=>this.syncSessionDetail(v).catch(()=>{})));for(const v of S)h.add(v)}}await this.syncVisibleSessionDetails(h).catch(()=>{}),this.ensureInspectorData().catch(()=>{}),this.evictStaleSessionState()}async refreshWorkerRegistryIfStale(){const e=this.getState().admin?.workers,s=this.getState().auth?.authorization?.role;if(!(s==="admin"||s==="anonymous"||this.getState().admin?.profile?.isAdmin===!0)){this.dispatch({type:"admin/workers/attempt",skip:"not admin"});return}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 u=o.filter(([p,m])=>p!==s&&!m?.loading).sort((p,m)=>(p[1]?.fetchedAt||0)-(m[1]?.fetchedAt||0)).slice(0,o.length-i).filter(([,p])=>n-(p?.fetchedAt||0)>r);u.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:u.map(([p])=>p)})}const l=Object.entries(e.executionHistory?.bySessionId||{});if(l.length>i){const u=l.filter(([p,m])=>p!==s&&!m?.loading).sort((p,m)=>(p[1]?.fetchedAt||0)-(m[1]?.fetchedAt||0)).slice(0,l.length-i).filter(([,p])=>n-(p?.fetchedAt||0)>r);u.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:u.map(([p])=>p)})}const c=Object.entries(e.files.bySessionId||{});if(c.length>i){const u=c.filter(([p])=>p!==s).slice(0,c.length-i);u.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:u.map(([p])=>p)})}const d=[...e.history.bySessionId.entries()];if(d.length>i*2){const u=d.filter(([p])=>p!==s).slice(0,d.length-i*2).map(([p])=>p);u.length>0&&this.dispatch({type:"history/evict",sessionIds:u})}}async syncVisibleSessionDetails(e=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=Ks({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??Es(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),r=this.getSessionListMaxRows(n),i=Ii(s,r),o=[...new Set(i.map(l=>l.sessionId).filter(l=>l&&!Us(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(u){return js(u)&&this.handleSessionGone(e),null}if(!Array.isArray(i)||i.length>=1e3)return null;if(i.length===0)return s;let o=this.getState().history.bySessionId.get(e)||s;for(const u of i)u.seq<=(o.lastSeq||0)||(o=Ir(o,u));o={...o,loadedEventLimit:Math.max(Number(s.loadedEventLimit)||0,Array.isArray(o.events)?o.events.length:0)},this.dispatch({type:"history/set",sessionId:e,history:o});for(const u of i)this.reconcileOutboxAgainstEvent(e,u);const l=Ti(i),c=this.getState().sessions.byId[e]||{},d=ml(c.contextUsage,i);return(l||d)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...l||{},...d?{contextUsage:d}:{}}}),o}async ensureSessionHistory(e,s={}){if(!e)return null;if(this.sessionHistoryLoads.has(e))return this.sessionHistoryLoads.get(e);const n=this.getState().history.bySessionId.get(e);if(!s.force&&n?.events&&n?.loadState!=="failed")return n;this.dispatch({type:"history/loadState",sessionId:e,loadState:"loading"});const r=this.loadSessionHistory(e,{...s,force:!0});this.sessionHistoryLoads.set(e,r);try{const i=await r;return this.dispatch({type:"history/loadState",sessionId:e,loadState:"loaded"}),i}catch(i){throw this.dispatch({type:"history/loadState",sessionId:e,loadState:"failed"}),i}finally{this.sessionHistoryLoads.get(e)===r&&this.sessionHistoryLoads.delete(e)}}async loadSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),r=Math.min(Wb,Math.max(ke,Number(n?.loadedEventLimit??ke)||ke));if(!s&&n?.events)return n;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}return(async()=>{let l;try{l=await this.transport.getSessionEvents(e,void 0,r)}catch(g){if(js(g))return this.handleSessionGone(e),null;throw g}const c=this.getState().history.bySessionId.get(e),d=[...new Map([...l||[],...c?.events||[]].map(g=>[g.seq,g])).values()].sort((g,b)=>g.seq-b.seq);let u={...Bs(d,{requestedLimit:r}),lastSeq:d.at(-1)?.seq||0};u.closedLiveKeys=c?.closedLiveKeys||[],u.closedLiveStreams=c?.closedLiveStreams||[];const p=d.some(g=>g.seq>(c?.lastSeq||0)&&["session.turn_completed","session.turn_stopped"].includes(g.eventType));for(const g of c?.chat||[])if(g.streamSettling)u.chat=u.chat.map(b=>b.messageId===g.messageId?{...g,...b}:b);else if(g.liveTurn&&!p)if(!u.chat.some(b=>b.messageId&&b.messageId===g.messageId))u.chat.push(g);else{const b=d.find(y=>y.eventType==="assistant.message"&&y.data?.messageId===g.messageId);if(b){const y=Ir({chat:[g],events:[],activity:[],lastSeq:0},b).chat[0];u.chat=u.chat.map(S=>S.messageId===g.messageId?{...y,...S}:S)}}u=cl(u,c,e),this.dispatch({type:"history/set",sessionId:e,history:u});for(const g of l||[])this.reconcileOutboxAgainstEvent(e,g);const m=Ti(l),f=this.getState().sessions.byId[e]||{},h=ml(f.contextUsage,l);return(m||h)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...m||{},...h?{contextUsage:h}:{}}}),u})()}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=Ks({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??Es(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),r=this.getSessionListMaxRows(n),i=Ii(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(ct(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<zy)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 js(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<Ky)){this.dispatch({type:"sessionStats/loading",sessionId:s});try{const[i,o,l,c,d,u,p]=await Promise.all([this.transport.getSessionMetricSummary(s),typeof this.transport.getSessionTokensByModel=="function"?this.transport.getSessionTokensByModel(s).catch(()=>[]):[],typeof this.transport.getSessionTreeStats=="function"?this.transport.getSessionTreeStats(s):null,typeof this.transport.getSessionSkillUsage=="function"?this.transport.getSessionSkillUsage(s).catch(()=>null):null,typeof this.transport.getSessionTreeSkillUsage=="function"?this.transport.getSessionTreeSkillUsage(s).catch(()=>null):null,typeof this.transport.getSessionFactsStats=="function"?this.transport.getSessionFactsStats(s).catch(()=>null):null,typeof this.transport.getSessionTreeFactsStats=="function"?this.transport.getSessionTreeFactsStats(s).catch(()=>null):null]);this.dispatch({type:"sessionStats/loaded",sessionId:s,summary:i,tokensByModel:o,treeStats:l,skillUsage:c,treeSkillUsage:d,factsStats:u,treeFactsStats:p})}catch{this.dispatch({type:"sessionStats/loaded",sessionId:s,summary:null,tokensByModel:[],treeStats:null,skillUsage:null,treeSkillUsage:null,factsStats:null,treeFactsStats:null})}}}async ensureFleetStats({force:e=!1}={}){if(typeof this.transport.getFleetStats!="function")return;const s=this.getState().fleetStats,n=Date.now();if(!(!e&&s?.loading)&&!(!e&&s?.data&&Number.isFinite(s.fetchedAt)&&n-s.fetchedAt<Vy)){this.dispatch({type:"fleetStats/loading"});try{const i={since:new Date(Date.now()-Yy*864e5),includeDeleted:!0},[o,l,c,d,u,p]=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:u,factsTombstoneStats:p})}catch{this.dispatch({type:"fleetStats/loaded",data:null,userStats:null,skillUsage:null,retrievalUsage:null,sharedFactsStats:null,factsTombstoneStats:null})}}}async openAdminConsole(){this.getState().ui?.budgetOpen&&this.closeBudget(),this.dispatch({type:"admin/visibility",visible:!0}),await this.refreshAdminProfile().catch(()=>{}),this.getState().admin?.section==="features"&&this.refreshFeatureFlags(),this.refreshAdminModelProviders().catch(()=>{}),this.refreshAdminAgentPackages().catch(()=>{})}closeAdminConsole(){this.dispatch({type:"admin/visibility",visible:!1})}openWorkspace(){this.getState().admin?.visible&&this.closeAdminConsole(),this.getState().ui?.budgetOpen&&this.closeBudget()}currentMode(){const e=this.getState();return e.admin?.visible?"admin":e.ui?.budgetOpen?"budget":"workspace"}revealCreatedSession(){this.getState().admin?.visible&&this.closeAdminConsole(),this.closeBudget(),this.dispatch({type:"ui/revealCreatedSession",sessionId:this.getState().sessions.activeSessionId}),this.setFocus(L.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}}dismissAdminModelProviderMutationError(){this.dispatch({type:"admin/modelProviders/mutationDismissed"})}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 updateAdminProviderCredential({name:e,credentials:s,shared:n=!1}={}){const r=n?"updateSharedProviderCredential":"updateMyProviderCredential";if(typeof this.transport[r]!="function"){const i=n?"Shared provider credential updates are not available on this transport.":"Provider credential updates are not available on this transport.";return this.dispatch({type:"admin/modelProviders/mutationFailed",error:i}),{ok:!1,result:null,error:i}}return this._runAdminModelProviderMutation("updateCredential",()=>this.transport[r]({name:e,credentials:s}))}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,mode:"create"})}beginAdminCreateGithubProvider(){this.beginAdminCreateProvider({shared:!1})}beginAdminUpdateProviderCredential(e){!e?.name||e.class==="shared"||this.dispatch({type:"admin/modelProviders/createBegin",name:e.name,typeId:e.typeId,shared:!1,mode:"update",stage:"credential"})}_adminProviderTypeUsesWorkloadIdentity(e){return(At(this.getState()).modelProviders?.providerTypes||[]).find(n=>n.id===e)?.usesWorkloadIdentity===!0}cycleAdminProviderCreateType(){const e=At(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=Nt(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=Gt(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,De(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=this._adminProviderTypeUsesWorkloadIdentity(e.typeId),n=String(e.draft||"").trim();if(!n&&!s){this.dispatch({type:"admin/modelProviders/createFailed",error:"Enter a provider credential."});return}const r={name:e.name,type:e.typeId,credentials:s?{kind:"workloadIdentity"}:/github/i.test(e.typeId)?{githubToken:n}:{apiKey:n},shared:s?!0:e.shared===!0};this.dispatch({type:"admin/modelProviders/createSaving"});const i=e.mode==="update"?await this.updateAdminProviderCredential({name:r.name,credentials:r.credentials}):await this.createAdminProvider(r);this.dispatch(i?.ok?{type:"admin/modelProviders/createEnd"}:{type:"admin/modelProviders/createFailed",error:i?.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=At(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=At(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=At(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=At(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:L.ADMIN}})}async cycleAdminModelDefault(e,{restartDisposition:s=null}={}){const n=At(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=At(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==="features"&&this.refreshFeatureFlags(),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(()=>{})}async selectFeatureScope(e,s=null){["mine","cluster","users"].includes(e)&&(this.getState().admin?.features?.saving||e!=="mine"&&!this._featureIsAdmin()||e==="users"&&s!==null&&(!Number.isSafeInteger(s)||s<=0)||(this.dispatch({type:"admin/features",patch:{mode:e,userId:e==="users"?s:null,data:null,error:null,notice:null,fetchedAt:null,dirtyDrafts:{}}}),await this.refreshFeatureFlags()))}_featureIsAdmin(){const e=this.getState(),s=e.auth?.authorization?.role;return e.admin?.profile?.isAdmin===!0&&(!s||s==="admin"||s==="anonymous")}_featureContext(){const e=this.getState(),s=e.admin.features;return JSON.stringify([s.generation,s.mode,s.userId,e.auth?.principal?.provider,e.auth?.principal?.subject,e.auth?.authorization?.role,e.admin.profile?.provider,e.admin.profile?.subject,e.admin.profile?.isAdmin])}async _featureRequest(e){let s;try{return await Promise.race([Promise.resolve().then(e),new Promise((n,r)=>{s=setTimeout(()=>r(new Error("Feature request timed out. Retry or refresh the settings.")),1e4),s?.unref?.()})])}finally{clearTimeout(s)}}async refreshFeatureFlagsIfStale(){const e=this.getState().admin,s=e?.features;!e?.visible||e.section!=="features"||s?.loading||s?.saving||Object.keys(s?.dirtyDrafts||{}).length||s?.fetchedAt&&Date.now()-s.fetchedAt<2e4||await this.refreshFeatureFlags({background:!0})}setFeatureDraftDirty(e,s){const n={...this.getState().admin.features.dirtyDrafts};s?n[e]=!0:delete n[e],this.dispatch({type:"admin/features",patch:{dirtyDrafts:n}})}_featureDraftKey(e){const s=this.getState().admin.features;return JSON.stringify([s.mode,s.mode==="users"?s.userId:null,e])}getFeatureDraft(e){return this.getState().admin.features.drafts?.[this._featureDraftKey(e)]}getFeatureDraftCount(e){return Object.values(this.getState().admin.features.drafts||{}).filter(s=>s.mode===e).length}setFeatureDraft(e,s){const n=this.getState().admin.features;if(n.saving||n.mode!=="mine"&&!this._featureIsAdmin()||n.mode==="users"&&!n.userId)return;const r=n.data?.flags?.find(u=>u.featureKey===e);if(!r?.supported)return;const i=this._featureDraftKey(e),o=n.drafts?.[i],l=n.mode==="cluster"?r.cluster:r.user,c=s===null?!l:n.mode==="cluster"?s.enabled===(r.cluster?.enabled??r.defaultEnabled)&&s.allowUserOverride===(r.cluster?.allowUserOverride??r.defaultAllowUserOverride):!!l&&s.enabled===l.enabled,d={...n.drafts};c&&!o?.uncertain&&!o?.needsReview?delete d[i]:d[i]={featureKey:e,mode:n.mode,userId:n.userId,values:s===null?null:{...s},expectedRevision:o?.expectedRevision??r.revision,...o?.uncertain?{uncertain:!0}:{},...o?.needsReview?{needsReview:!0}:{}},this.dispatch({type:"admin/features",patch:{drafts:d,error:null,notice:null}})}async discardFeatureDraft(e){if(this.getState().admin.features.saving)return;const s=this.getFeatureDraft(e),n=this._featureContext();if(s?.uncertain&&!await this.refreshFeatureFlags()||n!==this._featureContext()||this.getFeatureDraft(e)!==s)return;if(s?.uncertain){const i=this.getState().admin.features.data?.flags?.find(o=>o.featureKey===e)?.revision;if(!i||BigInt(i)<=BigInt(s.expectedRevision)){this.dispatch({type:"admin/features",patch:{error:"The earlier save is still unconfirmed. Retry Save or refresh before discarding changes."}});return}}const r={...this.getState().admin.features.drafts};delete r[this._featureDraftKey(e)],this.dispatch({type:"admin/features",patch:{drafts:r,error:null,notice:null}})}reviewFeatureDraft(e){const s=this.getState().admin.features;if(s.saving||s.loading||s.mode!=="mine"&&!this._featureIsAdmin())return;const n=this._featureDraftKey(e),r=s.drafts?.[n],i=s.data?.flags?.find(o=>o.featureKey===e);!r||!i?.supported||r.needsReview&&r.expectedRevision===i.revision||this.dispatch({type:"admin/features",patch:{drafts:{...s.drafts,[n]:{...r,expectedRevision:i.revision,needsReview:!1,uncertain:!1}},error:null,notice:"Latest saved setting reviewed. Your changes are still unsaved."}})}async saveFeatureDraft(e){const s=this.getFeatureDraft(e);if(!s)return;const n=this.getState().admin.features.data?.flags?.find(r=>r.featureKey===e);if(s.needsReview||s.expectedRevision!==n?.revision){this.dispatch({type:"admin/features",patch:{error:"Settings changed elsewhere. Review the latest saved setting before saving your changes."}});return}await this.saveFeatureFlag(e,s.values,{draft:s})}async searchFeatureUsers(e=""){if(!this._featureIsAdmin())return;const s=this._featureUserSerial=(this._featureUserSerial||0)+1,n=this._featureContext();this.dispatch({type:"admin/features",patch:{userQuery:String(e),usersLoading:!0,metadataError:null}});const r=()=>this._featureUserSerial===s&&this._featureContext()===n;try{const i=await this._featureRequest(()=>this.transport.listFeatureFlagUsers(String(e)));if(r()){const o=this.getState().admin.features,l=o.users?.find(d=>d.userId===o.userId),c=!!(l&&!i.some(d=>d.userId===l.userId));this.dispatch({type:"admin/features",patch:{users:c?[l,...i]:i,selectedUserOutsideResults:c,usersLoading:!1}})}}catch(i){r()&&this.dispatch({type:"admin/features",patch:{usersLoading:!1,metadataError:`User directory: ${i?.message||i}`}})}}async refreshFeatureFlags({background:e=!1}={}){const s=(this._featureRefreshSerial??0)+1;this._featureRefreshSerial=s;const n=this.getState().admin?.features||{mode:"mine"};if(n.mode!=="mine"&&!this._featureIsAdmin())return;const r=this._featureContext(),i=()=>this._featureRefreshSerial===s&&this._featureContext()===r;this.dispatch({type:"admin/features",patch:{loading:!0,...e?{}:{error:null}}}),!e&&this._featureIsAdmin()&&(this.searchFeatureUsers(n.userQuery||""),this.refreshWorkerRegistryIfStale());try{const o=await this._featureRequest(()=>n.mode==="cluster"?this.transport.getClusterFeatureFlags():n.mode==="users"?n.userId?this.transport.getUserFeatureFlags(n.userId):null:this.transport.getMyFeatureFlags());return i()?(this.dispatch({type:"admin/features",patch:{data:o,loading:!1,fetchedAt:Date.now()}}),!0):!1}catch(o){return i()&&this.dispatch({type:"admin/features",patch:{loading:!1,fetchedAt:Date.now(),error:String(o?.message||o)}}),!1}}async saveFeatureFlag(e,s,{draft:n}={}){const r=this.getState().admin?.features;if(!r||r.saving||r.loading||r.mode!=="mine"&&!this._featureIsAdmin())return;const i=r.data?.flags?.find(m=>m.featureKey===e);if(!i?.supported||r.mode==="users"&&!r.userId)return;const o=this._featureContext(),l=this._featureDraftKey(e),c=n?.expectedRevision??i.revision,d=JSON.stringify([o,e,c,s]);this._featureMutationRetries??=new Map;const u=this._featureMutationRetries.get(d)??globalThis.crypto.randomUUID();this._featureMutationRetries.set(d,u);const p={featureKey:e,expectedRevision:c,requestId:u,...s||{}};this.dispatch({type:"admin/features",patch:{saving:!0,error:null,notice:null}});try{const m=await this._featureRequest(()=>r.mode==="cluster"?this.transport[s?"setClusterFeatureFlag":"resetClusterFeatureFlag"](p):r.mode==="users"?this.transport[s?"setUserFeatureFlag":"unsetUserFeatureFlag"](r.userId,p):this.transport[s?"setMyFeatureFlag":"unsetMyFeatureFlag"](p));if(this._featureMutationRetries.delete(d),this._featureContext()===o){if(/^[1-9]\d*$/.test(String(m?.revision))&&Object.hasOwn(m,"setting")){const f={...i,revision:m.revision,[r.mode==="cluster"?"cluster":"user"]:m.setting},h=f.cluster?.allowUserOverride??f.defaultAllowUserOverride;f.effective=h&&f.user?f.user.enabled:f.cluster?.enabled??f.defaultEnabled,f.source=h&&f.user?"user":f.cluster?"cluster":"default",f.userOverrideIgnored=!!(f.user&&!h);const g=this.getState().admin.features.data;this.dispatch({type:"admin/features",patch:{data:{...g,flags:g.flags.map(b=>b.featureKey===e?f:b)}}})}if(n&&this.getState().admin.features.drafts?.[l]===n){const f={...this.getState().admin.features.drafts};delete f[l],this.dispatch({type:"admin/features",patch:{drafts:f}})}await this.refreshFeatureFlags(),this._featureContext()===o&&this.dispatch({type:"admin/features",patch:{notice:"Setting saved."}})}}catch(m){if(this._featureContext()===o){if(n&&(m?.status===409||m?.code==="FEATURE_CONFLICT")){this._featureMutationRetries.delete(d),this.dispatch({type:"admin/features",patch:{drafts:{...this.getState().admin.features.drafts,[l]:{...n,needsReview:!0}}}});const f=await this.refreshFeatureFlags({background:!0});this._featureContext()===o&&this.dispatch({type:"admin/features",patch:{error:f?"Settings changed elsewhere. Review the latest saved setting before saving your changes.":"Settings changed elsewhere, but the latest setting could not be loaded. Refresh settings before reviewing and saving your changes."}});return}n&&!(m?.status>=400&&m?.status<500)&&this.dispatch({type:"admin/features",patch:{drafts:{...this.getState().admin.features.drafts,[l]:{...n,uncertain:!0}}}}),this.dispatch({type:"admin/features",patch:{error:String(m?.message||m)}})}}finally{this._featureContext()===o&&this.dispatch({type:"admin/features",patch:{saving:!1}})}}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,qy(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;case"grantEditor":await this.transport.grantAgentPackageEditor(r,s);break;case"revokeEditor":await this.transport.revokeAgentPackageEditor(r,s);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)?`
|
|
89
|
-
${r.validation.errors.map(o=>`[${o.code}] ${o.message}`).join(`
|
|
90
|
-
`)}`:"";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=Jc(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 Mm(s,{token:i,tokenKind:o,onProgress:d=>this.dispatch({type:"admin/packages/addDialog/progress",message:d})});if(e.updateName){const d=_m(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)?`
|
|
91
|
-
${r.validation.errors.map(o=>`[${o.code}] ${o.message}`).join(`
|
|
92
|
-
`)}`:"";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=Nt(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=Gt(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,De(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.getState().admin?.visible&&this.closeAdminConsole(),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})}setBudgetTab(e){this.dispatch({type:"budget/tab",tab:e}),e==="summary"&&this.loadUsageSummary().catch(()=>{}),e==="agents"&&this.loadUsageAgents().catch(()=>{})}async setUsageSummaryFilter({days:e,providers:s,preset:n}={}){this.dispatch({type:"budget/summary/filter",days:e,providers:s,preset:n});const r=[this.loadUsageSummary()];(this.getState().budget?.agents?.data||this.getState().budget?.tab==="agents")&&r.push(this.loadUsageAgents()),await Promise.all(r)}async loadUsageAgents(){if(typeof this.transport.getProviderUsageAgents!="function"){this.dispatch({type:"budget/agents/failed",error:"The agent pivot is not available on this transport."});return}const e=this.getState().budget?.summary||{};this.dispatch({type:"budget/agents/loading"});try{const s=await this.transport.getProviderUsageAgents({days:e.days||14,...Array.isArray(e.providers)&&e.providers.length?{providers:e.providers}:{}});this.dispatch({type:"budget/agents/loaded",data:s,fetchedAt:Date.now()})}catch(s){this.dispatch({type:"budget/agents/failed",error:fs(s)})}}async loadUsageSummary(){if(typeof this.transport.getProviderUsageSummary!="function"){this.dispatch({type:"budget/summary/failed",error:"The cluster summary is not available on this transport."});return}const e=this.getState().budget?.summary||{};this.dispatch({type:"budget/summary/loading"});try{const s=await this.transport.getProviderUsageSummary({days:e.days||14,...Array.isArray(e.providers)&&e.providers.length?{providers:e.providers}:{}});this.dispatch({type:"budget/summary/loaded",data:s,fetchedAt:Date.now()})}catch(s){this.dispatch({type:"budget/summary/failed",error:fs(s)})}}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(!Gn.includes(s))return;const n=this.getState().budget?.rangeDays??Fe;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??Fe;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:fs(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??Fe;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:fs(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:fs(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=fs(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=ct(this.getState()),{force:s=!1}={}){const n=zn(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=Rt(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<jb)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=wf(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?xl(s,"",o.contentType||"",o):xl(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=Rt(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||ct(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:r}=s,i=ct(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 ${Ze(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=Rt(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=Xt(this.getState()),n=this.getState().files.markedIds||[],r=n.length>0?n[n.length-1]:this.getState().files.selectedArtifactId,i=s.findIndex(u=>u.id===r),o=s.findIndex(u=>u.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(u=>u.id);this.dispatch({type:"files/setMarks",artifactIds:[...new Set([...n,...d])]})}clearArtifactMarks(){this.dispatch({type:"files/clearMarks"})}async deleteMarkedArtifacts({confirmed:e=!1}={}){const s=this.getState(),n=s.files.markedIds||[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No artifacts marked"}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifacts",message:`Delete ${n.length} artifact${n.length===1?"":"s"}? This action cannot be undone.`,confirmLabel:`Delete ${n.length}`,action:"deleteMarkedArtifacts",previousFocus:s.ui.focusRegion}}),!1;const 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),u=l.slice(c+1);try{await this.transport.deleteArtifact(d,u),this.dispatch({type:"files/deleted",sessionId:d,filename:u}),r.add(d),i+=1}catch(p){o.push(`${u}: ${p?.message||String(p)}`)}}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=Rt(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const r=ct(s),i=r==="allSessions"?`${Ze(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=Rt(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 ${Ze(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=Gh(e),r=Wh(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=ct(this.getState());await this.ensureFilesForScope(s);const n=Xt(this.getState());if(n.length===0)return;const r=Rt(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 ${Ze(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=ct(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 ${Ze(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===L.PROMPT?n:s;if(!Jy.has(r)||r===L.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===L.PROMPT&&this.setFocus(r)}openFilesFilter(){const e=ct(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:Ur(r)})});return}Object.keys(n.sessions.byId).length>0&&this.scheduleSessionsRefresh(0)}async loadSession(e){if(!e)return;const s=this.navigationGeneration=(this.navigationGeneration||0)+1;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 Promise.all([this.ensureSessionHistory(e,{force:!0}),this.syncSessionDetail(e).catch(()=>{})]),!(this.navigationGeneration!==s||this.getState().sessions.activeSessionId!==e)&&(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"||s.eventType==="system.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,s.eventType==="user.message"?n:void 0,i);else s.eventType==="user.message"&&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>Wr)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[it(e,i)]?.optedOut)return!0;const l=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(l)&&Date.now()-l>Wr||this.dispatch({type:"canvas/flip",sessionId:e,slot:i}),!0}submitCanvasAction(e,s,n=1){if(!e)return Promise.resolve({ok:!1,reason:"no session"});if(!Number.isInteger(n)||n<1||n>5)return Promise.resolve({ok:!1,reason:"invalid canvas slot"});const r=this.getState().canvas.bySessionId[it(e,n)]?.responseContract||null,i=Rp(r,s);if(!i.ok)return Promise.resolve(i);this.canvasActionLimiters||(this.canvasActionLimiters=new Map);let o=this.canvasActionLimiters.get(e);if(o||(o=Fp(),this.canvasActionLimiters.set(e,o)),!o())return Promise.resolve({ok:!1,reason:"rate limited"});const l=Lp(i.action,i.data);return this.transport.sendMessage(e,l,{enqueueOnly:!0}).then(()=>(this.syncSessionEvents(e).catch(()=>{}),{ok:!0,action:i.action})).catch(c=>({ok:!1,reason:c?.message||String(c)}))}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[it(e,r)]?.optedOut)return!1;const o=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(o)&&Date.now()-o>Wr?!1:(this.dispatch({type:"canvas/flip",sessionId:e,slot:r}),!0)}subscribeCanvasKv(e,s){if(!e||typeof s!="function")return()=>{};this._canvasKvListeners||(this._canvasKvListeners=new Map),this._canvasKvListeners.has(e)||this._canvasKvListeners.set(e,new Set);const n=this._canvasKvListeners.get(e);return n.add(s),()=>{n.delete(s),n.size===0&&this._canvasKvListeners.delete(e)}}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.eventType==="session.access_revoked")return this.handleSessionGone(e),!0;if(s.transient===!0){if(s.eventType==="session.native_tasks_tick"){const p=this.getState().history.bySessionId.get(e),m=$c(p,s.data,{sessionId:e,seq:s.liveSeq});return m&&m!==p&&this.dispatch({type:"history/set",sessionId:e,history:m}),!0}if(s.eventType==="assistant.live_tick"){const p=s.liveUpdatedAt?new Date(s.liveUpdatedAt).getTime():NaN;if(s.data?.phase==="live"&&Number.isFinite(p)&&this.getState().history.bySessionId.get(e)?.events?.some(b=>["session.turn_completed","session.turn_stopped"].includes(b.eventType)&&new Date(b.createdAt).getTime()>p))return!1;this._liveTurnIdleTimers||(this._liveTurnIdleTimers=new Map);const m=this._liveTurnIdleTimers.get(e);if(m&&s.data?.phase==="idle"&&(clearTimeout(m),this._liveTurnIdleTimers.delete(e)),s.data?.phase==="idle"){const g=this.getState().history.bySessionId.get(e);if(!g)return!0;const b=s.data?.streamId||null,y=new Set(g.chat.filter(v=>v.liveTurn&&(!b||v.streamId===b||(g.closedLiveStreams||[]).includes(v.streamId)||(g.closedLiveKeys||[]).includes(v.liveKey))).map(v=>v.liveKey));this.dispatch({type:"history/set",sessionId:e,history:{...zs(g,null,b),chat:g.chat.filter(v=>!v.liveTurn||!y.has(v.liveKey)||Date.now()-v.liveStartedAt>=200)}});const S=setTimeout(()=>{this._liveTurnIdleTimers?.delete(e);const v=this.getState().history.bySessionId.get(e);if(!v)return;const w=v.chat.filter(k=>!k.liveTurn||!y.has(k.liveKey)),E=w.length===v.chat.length?v:{...v,chat:w};E!==v&&this.dispatch({type:"history/set",sessionId:e,history:E})},1200);return S.unref?.(),this._liveTurnIdleTimers.set(e,S),!0}const f=this.getState().history.bySessionId.get(e)||{chat:[],activity:[],events:[],lastSeq:0},h=this.preservePausedChatWindow(e,f);return this.dispatch({type:"history/set",sessionId:e,history:om(h,s.data,{sessionId:e,seq:s.liveSeq,createdAt:Date.now()})}),!0}if(s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(e,s),s.eventType==="session.canvas_kv"){const p=this._canvasKvListeners?.get(e);if(p)for(const m of p)try{m(s.data)}catch{}}return s.eventType==="session.canvas_plane_released"&&this.dispatch({type:"canvas/planeReleased",sessionId:e}),!1}this._liveTurnIdleTimers?.has(e)&&(s.eventType==="session.turn_completed"||s.eventType==="session.turn_stopped")&&(clearTimeout(this._liveTurnIdleTimers.get(e)),this._liveTurnIdleTimers.delete(e));const n=this.getState(),r=this.preservePausedChatWindow(e,n.history.bySessionId.get(e)||{chat:[],activity:[],events:[],lastSeq:0});if(s.seq<=(r.lastSeq||0))return!1;this.dispatch({type:"history/set",sessionId:e,history:Ir(r,s)});const i=this.getState().sessions.byId[e],o=Xs(s.createdAt),l=Xs(i?.updatedAt);if(s.eventType==="session.input_required_started"&&s.data?.question&&(!o||!l||o>=l)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,status:"input_required",pendingQuestion:{question:s.data.question,...o?{askedAt:o}:{},...Number.isSafeInteger(s.data.questionIteration)?{iteration:s.data.questionIteration}:{},choices:Array.isArray(s.data.choices)?s.data.choices:void 0,allowFreeform:s.data.allowFreeform??!0}}}),s.eventType==="user.message"&&i?.pendingQuestion){const p=nr(s.data?.content),m=Math.max(l,Xs(i.pendingQuestion.askedAt));p?.question===i.pendingQuestion.question&&(!o||!m||o>=m)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,pendingQuestion:null,resolvedInputQuestion:{question:p.question,answeredAt:o}}})}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 c=ob(s),d=this.getState().sessions.byId[e]||{sessionId:e},u=bc(d.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(c||u)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...c||{},...u?{contextUsage:u}:{}}}),this.maybeFlushQueuedOutbox(e,this.getState().sessions.byId[e]||d),this.scheduleSessionDetailSync(e),!0}preservePausedChatWindow(e,s){const n=this.getState();if(n.sessions.activeSessionId!==e||n.ui.followBottom?.chat!==!1)return s;const r=Math.max(ke,Number(s?.loadedEventLimit??ke)||ke),i=Math.max(r,(Array.isArray(s?.events)?s.events.length:0)+1,(Array.isArray(s?.chat)?s.chat.length:0)+4,(Array.isArray(s?.activity)?s.activity.length:0)+1);return i===r?s:{...s,loadedEventLimit:i}}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(js(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||Us(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||Us(e))return;let s=null;try{s=await this.transport.getSession(e)}catch(i){if(js(i)){this.handleSessionGone(e);return}throw i}if(!s)return;const n=this.getState().sessions.byId[e]||null,r=ub(n,s);(r||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:r||{sessionId:e}}),this.maybeFlushQueuedOutbox(e,s)}async openCreatedSession(e,s={}){const n=e.sessionId;this.sessionRefreshSeq=(this.sessionRefreshSeq||0)+1,this.getState().ui.promptEdit&&this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"sessions/selected",sessionId:n}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null}),this.dispatch({type:"sessions/navigationIntent",sessionId:n}),this.dispatch({type:"sessions/merged",session:hn({...e,...s.groupId?{viewerGroupId:s.groupId}:{}})}),this.revealCreatedSession(),this.dispatch({type:"ui/status",text:`Created session ${n.slice(0,8)}`});try{await this.loadSession(n)}catch(r){this.getState().sessions.activeSessionId===n&&this.dispatch({type:"ui/status",text:`Created session ${n.slice(0,8)}; could not load it yet: ${r?.message||r}`})}this.scheduleSessionsRefresh(0)}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.openCreatedSession(n,s),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 this._recordAgentPickerUse(e),await this.placeCreatedSessionInGroup(r,n.groupId??null),await this.openCreatedSession(r,n),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(p=>String(p||"").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(p=>p.placed!==!0):[],c=o?o.filter(p=>p.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",u=l.length>0?` · skipped ${l.length} (${tb(l)})`:"";return this.dispatch({type:"ui/status",text:c>0?`Moved ${c} session${c===1?"":"s"} to ${d}${u}`:`No sessions moved to ${d}${u}`}),c>0}async confirmSessionGroupPickerModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="newGroup"){const 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=ps(e,n.maxLength||80),i=De(r,s);this.updateSessionGroupNameModal({value:r,cursorIndex:i})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=Nt(s.value||"",s.cursorIndex||0,ps(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=Gt(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||"",De(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||Nn(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(h){r(),this.dispatch({type:"ui/status",text:`Could not load agents: ${h?.message||h}`});return}const l=(typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0;if(!Array.isArray(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 h of i){const g=String(h?.name||"").trim();g&&c.push({id:g,kind:"agent",agentName:g,title:yb(g,h?.title),description:String(h?.description||"").trim(),tools:Array.isArray(h?.tools)?h.tools.filter(Boolean):[],splash:typeof h?.splash=="string"&&h.splash.trim()?h.splash:null,splashMobile:typeof h?.splashMobile=="string"&&h.splashMobile.trim()?h.splashMobile:null,initialPrompt:typeof h?.initialPrompt=="string"&&h.initialPrompt.trim()?h.initialPrompt:null,group:h?.source==="package"&&h?.scope==="user"&&h?.mine!==!1?"mine":"shared",packageName:h?.packageName||null,packageTitle:h?.packageTitle||null,packageSemver:h?.packageSemver||null,packageScope:h?.scope||null,ownerLabel:h?.ownerLabel||null,startedBy:Array.isArray(h?.startedBy)?h.startedBy.filter(Boolean):[],supportsDirectStart:typeof h?.supportsDirectStart=="boolean"?h.supportsDirectStart:void 0,builtin:h?.source!=="package"})}const d=[...c.filter(h=>h.group==="shared"),...c.filter(h=>h.group==="mine")],u=l?{id:"__generic__",kind:"generic",group:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,splashMobile:null,initialPrompt:null,supportsDirectStart:!0}:null,p=await this._loadAgentPickerUsage(),m=gl.includes(this._agentPickerSort)?this._agentPickerSort:su,f=bl(d,{query:"",sort:m,usage:p,genericItem:u});this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",catalog:d,genericItem:u,items:f,query:"",sort:m,usage:p,selectedIndex:vb(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=Cn(e?.supportedReasoningEfforts),o=s?.reasoningEffort||pl(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=Tn(e?.supportedContextTiers),o=s?.contextTier||rb(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:ab(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(m=>m.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 m of s){const f=m?.providerId;f&&(i.has(f)||i.set(f,[]),i.get(f).push(m))}const o=new Map(e.status.map(m=>[m.name,m])),l=Date.now(),c=[...r].sort((m,f)=>{const h=g=>g.isMyDefault===!0?0:g.isClusterDefault===!0?1:g.class==="personal"?2:3;return h(m)-h(f)||String(m.name).localeCompare(String(f.name))}),d=n?.model||e.defaults?.mine?.model||e.defaults?.cluster?.model||(typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0),u=[],p=c.map(m=>{const f=zb(m,o.get(m.name)||null,l),h=m.hasCredential===!1?`${m.name} has no credential`:null;return{providerId:m.name,providerType:m.typeId,providerClass:m.class,isClusterDefault:m.isClusterDefault===!0,isMyDefault:m.isMyDefault===!0,hasCredential:m.hasCredential!==!1,budgetState:f.state,budgetNote:f.text,models:(i.get(m.name)||i.get(m.typeId)||[]).map(g=>{const b=g.providerId===m.name&&g.qualifiedName?g.qualifiedName:`${m.name}:${g.modelName}`,y=h||(g.credentialAvailable===!1?`${m.name} has no usable credential or endpoint`:null),S={id:b,qualifiedName:b,modelName:g.modelName||b,providerId:m.name,providerType:m.typeId,providerClass:m.class,description:g.description||"",cost:g.cost||null,supportedReasoningEfforts:Cn(g.supportedReasoningEfforts),defaultReasoningEffort:g.defaultReasoningEffort||null,supportedContextTiers:Tn(g.supportedContextTiers),defaultContextTier:g.defaultContextTier||null,contextWindowSizes:g.contextWindowSizes||null,isDefault:d===b,budgetState:f.state,budgetNote:f.text,disabledReason:y,disabled:!!y};return u.push(S),S})}}).filter(m=>m.models.length>0);return u.length===0?{refusal:"No provider in your namespace offers a model to run."}:{items:u,groups:p,selectedIndex:ul(u,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():nb(e),i=await this._resolveGhcpUserKeySet(),o=[],l=r.map(c=>({providerId:c.providerId,providerType:c.type||c.providerType,models:(c.models||[]).map(d=>{const u=d.providerType||c.type||c.providerType,p=u==="github"&&d.credentialAvailable===!1&&i===!1,m={id:d.qualifiedName,qualifiedName:d.qualifiedName,modelName:d.modelName||d.qualifiedName,providerId:d.providerId||c.providerId,providerType:u,description:d.description||"",cost:d.cost||null,supportedReasoningEfforts:Cn(d.supportedReasoningEfforts),defaultReasoningEffort:d.defaultReasoningEffort||null,supportedContextTiers:Tn(d.supportedContextTiers),defaultContextTier:d.defaultContextTier||null,contextWindowSizes:d.contextWindowSizes||null,isDefault:n===d.qualifiedName,ghcpKeyMissing:p,disabledReason:p?"needs GitHub key":null,disabled:p};return o.push(m),m})})).filter(c=>c.models.length>0);return{items:o,groups:l,selectedIndex:ul(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?` · ${Jd[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=bf().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 (${Ze(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=De(r,s);this.updateArtifactUploadModal({value:r,cursorIndex:i})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=Nt(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=Gt(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||"",De(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:L.CHAT}),{collapsedRightColumn:!!e}}expandRightColumn(){this.dispatch({type:"ui/paneAdjust",paneAdjust:0});const e=this.getCurrentLayout({paneAdjust:0}),s=this.getState().ui.focusRegion,n=mt(s,e);n!==s&&this.setFocus(n)}collapseRightColumn(){const s=(this.getState().ui.layout||{}).viewportWidth??120,n=Math.floor(s*Vc),r=s-xn-n;this.dispatch({type:"ui/paneAdjust",paneAdjust:r});const i=this.getCurrentLayout({paneAdjust:r}),o=this.getState().ui.focusRegion,l=mt(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(L.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:L.CHAT})}async stepArtifactPreview(e){const s=this.getState();if(s.files.previewOrigin!=="chat"){await this.moveFileSelection(e);return}const n=Ho(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),u=l.slice(c+1);this.dispatch({type:"files/select",sessionId:d,filename:u}),await this.ensureFilePreview(d,u).catch(()=>{})}canStepArtifactPreview(e){const s=this.getState(),n=s.files.previewOrigin==="chat"?Ho(s):Xt(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=Sl(e.filename),o=this.getState().ui.prompt,l=this.getState().ui.promptCursor,c=this.getPromptAttachments(),d=c.findIndex(p=>p?.sessionId===r&&p?.filename===e.filename);if(this.getState().sessions.activeSessionId!==r&&await this.loadSession(r),d===-1||!o.includes(c[d]?.token||i)){const p=Nt(o,l,`${i} `);this.setPrompt(p.prompt,p.cursor)}const u=d>=0?c.map((p,m)=>m===d?{...p,sessionId:r,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:i}:p):[...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(u),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(L.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=gb(n),i=Aa(n),o=hb(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:n.isGroup?"Rename folder":`Rename (${Ze(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 (${Ze(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=ps(e,n.maxLength),i=De(r,s);this.updateRenameSessionModal({value:r,cursorIndex:i})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=Nt(s.value||"",s.cursorIndex||0,ps(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=Gt(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||"",De(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||Nn(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 ${Ze(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${Ze(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=cs(["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 (${Ze(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=ps(e,120),i=De(r,s);this.updateShareSessionModal({value:r,cursorIndex:i})}insertShareSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=Nt(s.value||"",s.cursorIndex||0,ps(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=Gt(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||"",De(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 f=i.toLowerCase(),h=(e.shares||[]).find(g=>g.subject&&String(g.subject).toLowerCase()===f||g.email&&String(g.email).toLowerCase()===f||g.displayName&&String(g.displayName).toLowerCase()===f);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",u=c&&l[c]?o.slice(0,-1).join(" "):n,p=u.toLowerCase();let m=null;if(typeof this.transport.listKnownUsers=="function"){let f=[];try{f=await this.transport.listKnownUsers({limit:500})}catch{f=[]}const h=Array.isArray(f)?f:[];if(m=h.find(g=>g.displayName&&g.displayName.toLowerCase()===p||g.email&&g.email.toLowerCase()===p||g.subject&&g.subject.toLowerCase()===p)||null,!m){const g=h.filter(b=>b.displayName&&b.displayName.toLowerCase().includes(p)||b.email&&b.email.toLowerCase().includes(p)||b.subject&&b.subject.toLowerCase().includes(p));if(g.length===1)m=g[0];else if(g.length>1){this.dispatch({type:"ui/status",text:`"${u}" is ambiguous (${g.length} matches)`});return}}}m||(m={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:u,email:null,displayName:null}),this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.grantSessionShare(s,{provider:m.provider,subject:m.subject,email:m.email??null,displayName:m.displayName??null},d),this.dispatch({type:"ui/status",text:`Granted ${d} to ${u}`})}catch(f){this.dispatch({type:"ui/status",text:f?.message||String(f)})}}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"}))}async _loadAgentPickerUsage(){try{if(typeof this.transport.getCurrentUserProfile!="function")return null;const s=(await this.transport.getCurrentUserProfile())?.profileSettings?.[jr];if(!s||typeof s!="object")return{};const n={};for(const[r,i]of Object.entries(s)){const o=Number(i);Number.isFinite(o)&&o>0&&(n[r]=o)}return n}catch{return null}}async _recordAgentPickerUse(e){const s=String(e||"").trim();if(s)try{if(typeof this.transport.getCurrentUserProfile!="function"||typeof this.transport.setCurrentUserProfileSettings!="function")return;const r={...(await this.transport.getCurrentUserProfile())?.profileSettings||{}},i={...r[jr]||{}};i[s]=(Number(i[s])||0)+1,r[jr]=i,this.dispatch({type:"ui/agentPickerUsage",usage:i}),await this.transport.setCurrentUserProfileSettings({settings:r})}catch{}}_refreshAgentPicker(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionAgentPicker")return;const n={...s,...e},r=bl(n.catalog||[],{query:n.query,sort:n.sort,usage:n.usage,genericItem:n.genericItem||null}),i=s.items?.[s.selectedIndex||0]?.id,o=r.findIndex(l=>l.id===i);this.dispatch({type:"ui/modal",modal:{...n,items:r,selectedIndex:o>=0?o:0}})}setAgentPickerQuery(e){this._refreshAgentPicker({query:String(e??"")})}setAgentPickerSort(e){gl.includes(e)&&(this._agentPickerSort=e,this._refreshAgentPicker({sort:e}))}moveAgentPickerSection(){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(p=>p.id).filter(Boolean);if(l.length===0)return;const c=s.type==="filesFilter"?this.getState().files.filter?.[o.id]||l[0]:s.type==="historyFormat"?this.getState().executionHistory?.format||l[0]:this.getState().logs.filter?.[o.id]||l[0],d=cs(l,c,e),u=o.options.find(p=>p.id===d)||o.options[0];this.dispatch({type:s.type==="filesFilter"?"files/filter":s.type==="historyFormat"?"executionHistory/format":"logs/filter",filter:s.type==="historyFormat"?void 0:{[o.id]:d},...s.type==="historyFormat"?{format:d}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(d).catch(()=>{}),this.ensureSelectedFilePreview().catch(()=>{})),this.dispatch({type:"ui/status",text:`${s.type==="filesFilter"?"Files":s.type==="historyFormat"?"History":"Log"} filter updated: ${o.label} = ${u?.label||d}`});return}const n=Math.max(0,Number(s.selectedIndex)||0),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=kt(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=pl(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&&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=Nb(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,u=!!d?.question,p=this.getPromptEditSessionMatch(o);if(p){const g=this.getSessionOutbox(o).find(b=>b.id===p.itemId);if(g?.phase==="queued"||g?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(o).catch(()=>{});return}if(u&&typeof this.transport.sendAnswer=="function"){const g=Date.now(),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,{expectedQuestion:{question:d.question,...Number.isSafeInteger(d.iteration)?{iteration:d.iteration}:{}}}),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 m=n.filter(g=>g?.kind==="image");let f=null;if(m.length>0){if(m.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 ${m.length} image${m.length>1?"s":""}...`});try{f=await this.uploadPendingImageAttachments(o,m,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:f&&f.length>0?"See the attached image(s).":i;this.queuePromptInOutbox(o,h,f?{attachments:f}: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=Nt(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=Gt(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=_b(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,De(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,iu(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=$b(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 Ks({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??Es(r),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===L.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=mt(o,i);l!==o&&this.setFocus(l)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:mt(e,this.getCurrentLayout()),requestedFocusRegion:e})}focusNext(){const e=this.getCurrentLayout(),s=mt(this.getState().ui.focusRegion,e),n=ui(e);this.setFocus(cs(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=mt(this.getState().ui.focusRegion,e),n=ui(e);this.setFocus(cs(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=mt(this.getState().ui.focusRegion,e);this.setFocus(Em(s,e))}focusRight(){const e=this.getCurrentLayout(),s=mt(this.getState().ui.focusRegion,e);this.setFocus(km(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=mt(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=mt(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=mt(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,u)=>{const p=Math.max(d,u);return Math.max(d,Math.min(p,(l||0)+c))};if(s===L.SESSIONS||s===L.CHAT){const l=Qc(r),c=Ps+1,d=Math.min(Zc(i,r),r-rr-1),u=s===L.CHAT?-e:e,p=o(n.sessionPaneAdjust,u,c-l,d-l);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:p})}else if(s===L.INSPECTOR||s===L.ACTIVITY){const l=Math.max(ws,Math.floor(r*Xc)),c=ws+1,d=r-Dn-1,u=s===L.INSPECTOR?-e:e,p=o(n.activityPaneAdjust,u,c-l,d-l);this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:p})}}getActiveSequenceCompletedTurns(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return[];const n=e.history.bySessionId?.get?.(s),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=cs(gt,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=cs(gt,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){gt.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=ns(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(()=>{})},Gb))}getSessionPageSize(){const e=this.getCurrentLayout(),s=e.fullscreenPane===L.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 Rb.has(this.getState().ui.inspectorTab)}paneUsesStickyBottomFollow(e,s=this.getState()){return e==="chat"||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),e==="chat"&&s>0?l<=0?this.handleChatTopHistoryScrollIntent(c).catch(()=>{}):c<=0&&this.armChatTopHistoryLoad():e==="chat"&&s<0&&this.disarmChatTopHistoryLoad();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),e==="chat"&&(r>0&&i<=0?this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad());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:Xy,preserveDomAnchor:s.preserveDomAnchor===!0,force:!0})}}artifactPreviewOwnsActivitySlot(e=this.getState()){return e.ui.inspectorTab==="files"&&!!e.files?.selectedArtifactId}focusIsArtifactList(e=this.getState()){return e.ui.focusRegion===L.INSPECTOR&&e.ui.inspectorTab==="files"}getScrollablePaneForFocus(){const e=this.getState(),s=e.ui.focusRegion;return s===L.CHAT?"chat":s===L.ACTIVITY?this.artifactPreviewOwnsActivitySlot(e)?"filePreview":"activity":s===L.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.scrollPaneTo(e,0);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=ua(e,n),o=[...fa(e,n),...ar(e)],l=Math.min(Math.max(0,Math.floor(r*.34)),ms(o,n)),c=ms(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=ga(o);return{contentWidth:n,contentHeight:r,totalLines:ms(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=Ht(o,{width:n}),c=l.tabs.map(m=>({text:m===l.activeTab?`[${m}] `:`${m} `,color:m===l.activeTab?"magenta":"gray",bold:m===l.activeTab})),d=(l.lines||[]).map(m=>typeof m=="string"?{text:m,color:"white"}:m),u=l.activeTab==="sequence"?[c,...(l.stickyLines||[]).map(m=>typeof m=="string"?{text:m,color:"white"}:m)]:[],p=l.activeTab==="sequence"?d:[c,...d];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:ms(u,n),totalLines:ms(p,n)}}getFilePreviewRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if((s.rightHidden||s.inspectorHidden)&&!e.files?.fullscreen)return{contentWidth:20,contentHeight:1,totalLines:0};const n=e.ui.inspectorTab==="files"&&!!e.files?.fullscreen,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,u={sessions:{activeSessionId:c,byId:c&&d?{[c]:d}:{},flat:e.sessions.flat},files:{bySessionId:e.files.bySessionId,fullscreen:!!e.files.fullscreen,selectedArtifactId:e.files.selectedArtifactId,filter:e.files.filter},ui:{scroll:{filePreview:e.ui.scroll.filePreview}}},p=ya(u,{listWidth:l,previewWidth:l}),m=Math.max(9,i-4),f=Math.max(5,Math.min(10,Math.floor(m*.35)));let h=Math.max(5,Math.min(f,(p.listBodyLines||[]).length+2)),g=Math.max(5,m-h-1);const b=8;if(g<b){const y=b-g;h=Math.max(5,h-y),g=Math.max(5,m-h-1)}return{contentWidth:l,contentHeight:Math.max(1,g-2),totalLines:ms(p.previewLines,l)}}getPaneMaxScrollOffset(e,s=this.getState()){if(!e)return 0;if(e==="chat"){const n=this.getActiveChatRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="activity"){const n=this.getActivityRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="inspector"){const n=this.getInspectorRenderMetrics(s),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)>=Mi){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,preserveDomAnchor:s.preserveDomAnchor===!0,eventTypes:Kp})}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(ke,Number(r?.loadedEventLimit??ke)||ke),o=ke,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),u=c?this.getActiveChatRenderMetrics(n).totalLines:0,p=(async()=>{let m;const f=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){m=r||Bs([],{requestedLimit:i});for(let y=0;y<f;y+=1){const S=Array.isArray(m?.events)&&m.events.length>0?Number(m.events[0]?.seq||0):0;if(!m?.hasOlderEvents||S<=1){m={...m,hasOlderEvents:!1};break}if(Number(m.loadedEventCount||0)>=Mi)break;const v=await this.transport.getSessionEventsBefore(e,S,o,h);if(!Array.isArray(v)||v.length===0){m={...m,hasOlderEvents:!1};break}const w=Bs(v,{requestedLimit:o}),E=[...w.events||[],...m?.events||[]],k=new Map((m?.chat||[]).map(T=>[T.id,T])),x=Bs(E,{requestedLimit:E.length});if(m={...m,chat:Ss([...x.chat.map(T=>({...k.get(T.id),...T})),...(m?.chat||[]).filter(T=>T.liveTurn||T.optimistic)]),activity:[...w.activity||[],...m?.activity||[]],events:E,lastSeq:m?.lastSeq||m?.events?.[m?.events?.length-1]?.seq||v[v.length-1]?.seq||0,loadedEventLimit:E.length,loadedEventCount:E.length,hasOlderEvents:v.length>=o&&Number(v[0]?.seq||0)>1},!m.hasOlderEvents)break}}else{const y=gm(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 S=await this.transport.getSessionEvents(e,void 0,y);m={...Bs(S,{requestedLimit:y}),lastSeq:S[S.length-1]?.seq||0}}m=cl(m,this.getState().history.bySessionId.get(e),e),this.dispatch({type:"history/set",sessionId:e,history:m});for(const y of m?.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&&s.autoTriggered&&!s.preserveDomAnchor){const y=this.getState(),S=this.getActiveChatRenderMetrics(y).totalLines,v=Math.max(0,S-u);v>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:d+v})}const b=m.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${m.loadedEventCount} events loaded)`:`Loaded older history page (${m.loadedEventCount} events loaded)`:`Loaded full available history (${m.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:b}),m.hasOlderEvents?s.autoTriggered&&c&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,p),p}async cancelActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:o,skippedCount:l}=this.getBulkSelectedSessionActions(s);if(o.length===0){this.dispatch({type:"ui/status",text:"No cancellable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Sessions",message:`Cancel ${o.length} selected session${o.length===1?"":"s"}?${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Cancel Sessions",action:"cancelSession",previousFocus:s.ui.focusRegion}});return}let c=0;const d=[];for(const p of o)try{await this.transport.cancelSession(p.sessionId),c+=1}catch(m){d.push(`${p.sessionId.slice(0,8)}: ${m?.message||String(m)}`)}this.dispatch({type:"sessions/selectClear"});const u=d.length===0?`Cancelled ${c} session${c===1?"":"s"}`:`Cancelled ${c}/${o.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),await this.refreshSessions();return}const 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 u=d?.title||c.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Regenerate Session",message:`Regenerate context for "${u}"? The transcript is archived and distilled, then the session rebuilds fresh from it at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved. As an operator action this overrides the rate limits (cooldown / minimum age).`,confirmLabel:"Regenerate",action:"regenerateSession",sessionId:c,previousFocus:l.ui.focusRegion,extras:{instructions:"",distillMode:"llm",distillerModel:"",distillerEffort:"",distillerContextTier:"",distillerModelOptions:await this._loadDistillerModelOptions()}}});return}try{const u=String(s||"").trim();await this.transport.regenerateSession(c,{force:!0,...u?{instructions:u.slice(0,4e3)}:{},...n==="deterministic"?{distillMode:"deterministic"}:{},...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(u){this.dispatch({type:"ui/status",text:`Regenerate failed: ${u?.message||String(u)}`});return}await this.refreshSessions()}async _loadDistillerModelOptions(){if(typeof this.transport.listModels!="function")return[];try{const e=await this.transport.listModels({groupByProvider:!0});return(Array.isArray(e)?e:Array.isArray(e?.providers)?e.providers:Array.isArray(e?.models)?e.models:[]).flatMap(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 u=[];for(const m of l)try{await this.transport.completeSession(m.sessionId,e),d+=1}catch(f){u.push(`${m.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const p=u.length===0?`Completed ${d} session${d===1?"":"s"}`:`Completed ${d}/${l.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:p}),await this.refreshSessions();return}const 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 p of o)try{await this.transport.deleteSession(p.sessionId),this.handleSessionGone(p.sessionId),c+=1}catch(m){d.push(`${p.sessionId.slice(0,8)}: ${m?.message||String(m)}`)}this.dispatch({type:"sessions/selectClear"});const u=d.length===0?`Deleted ${c} session${c===1?"":"s"}`:`Deleted ${c}/${o.length}; ${d.length} failed: ${d.slice(0,2).join(", ")}${d.length>2?"…":""}`;this.dispatch({type:"ui/status",text:u}),await this.refreshSessions();return}const r=s.sessions.activeSessionId;if(!r)return;const i=s.sessions.byId[r];if(i?.isGroup){const o=i.groupId||Nn(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 _.REFRESH:await this.refreshSessions();return;case _.NEW_SESSION:await this.openNewSessionFlow();return;case _.OPEN_MODEL_PICKER:await this.openModelPicker();return;case _.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case _.OPEN_THEME_PICKER:this.openThemePicker();return;case _.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case _.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case _.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case _.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case _.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case _.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case _.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case _.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case _.CLOSE_MODAL:this.closeModal();return;case _.MODAL_PREV:this.moveModalSelection(-1);return;case _.MODAL_NEXT:this.moveModalSelection(1);return;case _.MODAL_PANE_PREV:this.moveModalPane(-1);return;case _.MODAL_PANE_NEXT:this.moveModalPane(1);return;case _.MODAL_CONFIRM:await this.confirmModal();return;case _.SEND_PROMPT:await this.sendPrompt();return;case _.FOCUS_NEXT:this.focusNext();return;case _.FOCUS_PREV:this.focusPrev();return;case _.FOCUS_LEFT:this.focusLeft();return;case _.FOCUS_RIGHT:this.focusRight();return;case _.FOCUS_PROMPT:this.setFocus(L.PROMPT);return;case _.FOCUS_SESSIONS:this.setFocus(L.SESSIONS);return;case _.MOVE_SESSION_UP:await this.moveSession(-1);return;case _.MOVE_SESSION_DOWN:await this.moveSession(1);return;case _.EXPAND_SESSION:this.expandActiveSession();return;case _.COLLAPSE_SESSION:this.collapseActiveSession();return;case _.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case _.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case _.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case _.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case _.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case _.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case _.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case _.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case _.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case _.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case _.OPEN_HELP:this.openHelpModal();return;case _.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case _.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case _.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case _.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case _.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case _.OPEN_LOG_FILTER:this.openLogFilter();return;case _.OPEN_FILES_FILTER:this.openFilesFilter();return;case _.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case _.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case _.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case _.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case _.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case _.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case _.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case _.SCROLL_UP:this.scrollCurrentPane(1);return;case _.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case _.PAGE_UP:if(this.getState().ui.focusRegion===L.SESSIONS){await this.moveSessionPage(-1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(-10);return}this.scrollCurrentPane(10);return;case _.PAGE_DOWN:if(this.getState().ui.focusRegion===L.SESSIONS){await this.moveSessionPage(1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(10);return}this.scrollCurrentPane(-10);return;case _.EXPAND_HISTORY:await this.expandActiveHistory();return;case _.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case _.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case _.CANCEL_SESSION:await this.cancelActiveSession();return;case _.STOP_TURN:await this.stopActiveSessionTurn();return;case _.DONE_SESSION:await this.completeActiveSession();return;case _.DELETE_SESSION:await this.deleteActiveSession();return;case _.REGENERATE_SESSION:await this.regenerateActiveSession();return;case _.PIN_SESSION:this.togglePinActiveSession();return;case _.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case _.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case _.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case _.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case _.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case _.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case _.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case _.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case _.OPEN_WORKSPACE:this.openWorkspace();return;case _.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case _.ADMIN_SHOW_GHCP:this.setAdminSection("providers");return;case _.ADMIN_SHOW_PACKAGES:this.setAdminSection("packages");return;case _.ADMIN_SHOW_WORKERS:this.setAdminSection("workers");return;case _.ADMIN_WORKERS_REFRESH:await this.refreshAdminWorkers();return;case _.ADMIN_PACKAGES_REFRESH:await this.refreshAdminAgentPackages();return;case _.ADMIN_PACKAGES_NEXT:await this.stepAdminPackageSelection(1);return;case _.ADMIN_PACKAGES_PREV:await this.stepAdminPackageSelection(-1);return;case _.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case _.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case _.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case _.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)}`})}}}function _i(t=""){return String(t||"").replace(/\s+/g," ").trim()}const Vb=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],Yb=24,Xb=32,Qb=6,Al=30,Zb=56,qr=.4,Jb=1.4,eS=2;function ou(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,longestToken: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=_i(g[b]||"");y.length>r[b].max&&(r[b].max=y.length),h>0&&/\s/.test(y)&&(r[b].spaceCells+=1);for(const S of y.split(/\s+/))S.length>r[b].longestToken&&(r[b].longestToken=S.length)}}let i=-1,o=0;for(let h=0;h<e;h+=1){const g=r[h];if(g.max<Yb||g.spaceCells/n<.4)continue;const y=_i(s[h]||"").toLowerCase(),S=Vb.some(w=>y.includes(w))?60:0,v=g.max+S;v>o&&(o=v,i=h)}if(i<0)return null;const l=r.map((h,g)=>g===i?0:Math.max(Qb,Math.min(h.max+2,Xb),h.longestToken+2)),c=l.reduce((h,g)=>h+g,0),d=r[i],u=Math.max(Al,Math.min(d.max*.45,Zb,Math.max(Al,c*Jb))),p=l.map((h,g)=>g===i?u:h),m=p.reduce((h,g)=>h+g,0);if(m>0&&p[i]/m<qr){const h=m-p[i];p[i]=h*(qr/(1-qr))}const f=p.reduce((h,g)=>h+g,0);return f>0?{widths:p.map(h=>`${(h/f*100).toFixed(2)}%`),flexIndex:i,minWidth:`${Math.ceil(f+eS)}ch`}:null}const cr=0;function at(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 zr(){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 tS(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 sS(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 nS(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 rS(t=2e3){const[e,s]=a.useState(()=>zr());return a.useEffect(()=>{if(zr()==null)return;const n=()=>{const i=zr();i!=null&&s(o=>o===i?o:i)};n();const r=setInterval(n,t);return()=>clearInterval(r)},[t]),a.useMemo(()=>tS(e),[e])}function Fs(t,e){return t&&e?{[t]:e}:{}}function Nl(t){return typeof t=="string"?{text:t,color:"white"}:t}function on(t,e,s,n,r,i){const o=(e.tabs||gt).map(p=>({text:p===e.activeTab?`[${p}] `:`${p} `,color:p===e.activeTab?"magenta":"gray",bold:p===e.activeTab})),l=(e.lines||[]).map(Nl),c=(e.stickyLines||[]).map(Nl),d=e.activeTab==="sequence"?[o,...c]:[],u=e.activeTab==="sequence"?l:[o,...l];return a.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:r,stickyLines:d,marginBottom:cr,lines:u,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="sequence"||e.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:i})}function Cl(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=pt(),c=rS(),d=se(e,h=>({sessions:h.sessions,mode:h.connection?.mode||"local",brandingTitle:h.branding?.title||"PilotSwarm",focused:h.ui.focusRegion==="sessions",identityLabel:sS(h.auth)}),at),u=a.useMemo(()=>nS(c,o,d.identityLabel),[c,o,d.identityLabel]),p=a.useMemo(()=>({sessions:d.sessions,connection:{mode:d.mode},branding:{title:d.brandingTitle}}),[d.brandingTitle,d.mode,d.sessions]),m=a.useMemo(()=>Ii(p,s),[p,s]),f=a.useMemo(()=>m.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:m.map(h=>h.active?pd(h.runs,{preserveColors:!0}):h.runs),[m]);return a.createElement(l.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:u,color:"yellow",focused:d.focused,width:n,height:r,marginBottom:cr,lines:f,paneId:"sessions",paneLabel:"Sessions",frame:i})});a.memo(function({controller:e,width:s,height:n,frame:r}){const i=pt(),o=se(e,v=>{const w=v.sessions.activeSessionId;return{activeSessionId:w,activeSession:w&&v.sessions.byId[w]||null,activeHistory:w&&v.history.bySessionId.get(w)||null,activeOutbox:w&&v.outbox?.bySessionId?.[w]||null,authPrincipal:v.auth?.principal||null,branding:v.branding,connectionError:v.connection.error,connectionMode:v.connection.mode,chatScroll:v.ui.scroll.chat,followBottom:v.ui.followBottom?.chat!==!1,focused:v.ui.focusRegion==="chat"}},at),l=Math.max(20,s-4),c=a.useMemo(()=>{const v=new Map;return o.activeSessionId&&o.activeHistory&&v.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:Fs(o.activeSessionId,o.activeSession)},history:{bySessionId:v},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(()=>Ld(c,{width:l}),[l,c]),u=hc(!!d?.animateTitleRight),p=a.useMemo(()=>gc(d?.titleRight,u),[u,d?.titleRight]),m=!o.activeSessionId&&o.connectionError,f=a.useMemo(()=>m?[{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"}]:ua(c,l),[o.branding.splash,o.connectionError,l,c,m]),h=String(o.activeSession?.status||"").toLowerCase()==="running",g=ji(h),b=a.useMemo(()=>m?[]:ar(c,{spinnerFrame:g,maxWidth:l}),[c,m,g,l]),y=a.useMemo(()=>m?[]:fa(c,l),[c,m,l]),S=a.useMemo(()=>y.length>0||b.length>0?[...y,...b]:[],[y,b]);return a.createElement(i.Panel,{title:d.title,titleRight:p,color:d.color,focused:o.focused,width:s,height:n,lines:f,bottomStickyLines:S,scrollOffset:o.chatScroll,scrollMode:o.followBottom?"bottom":"top",paneId:"chat",paneLabel:"Chat",frame:r})});const iS=a.memo(function({controller:e,width:s,height:n,shellTitle:r,focused:i=!1,frame:o,showFullscreenTitle:l=!1,embedded:c=!1}){const d=pt(),u=se(e,R=>({activeSessionId:R.sessions.activeSessionId,activeSession:R.sessions.activeSessionId&&R.sessions.byId[R.sessions.activeSessionId]||null,sessionsFlat:R.sessions.flat,filesBySessionId:R.files.bySessionId,filesFullscreen:!!R.files.fullscreen,selectedArtifactId:R.files.selectedArtifactId,filesFilter:R.files.filter,filePreviewScroll:R.ui.scroll.filePreview}),at),p=Math.max(20,s-4),m=a.useMemo(()=>({sessions:{activeSessionId:u.activeSessionId,byId:u.activeSessionId&&u.activeSession?{[u.activeSessionId]:u.activeSession}:{},flat:u.sessionsFlat},files:{bySessionId:u.filesBySessionId,fullscreen:u.filesFullscreen,selectedArtifactId:u.selectedArtifactId,filter:u.filesFilter},ui:{scroll:{filePreview:u.filePreviewScroll}}}),[u]),f=a.useMemo(()=>ya(m,{listWidth:Math.max(8,p-4),previewWidth:Math.max(8,p-4)}),[p,m]),h=r||(l?f.fullscreenTitle:f.panelTitle||f.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,(f.listBodyLines||[]).length+2)),S=Math.max(5,g-y-1);const v=8;if(S<v){const R=v-S;y=Math.max(5,y-R),S=Math.max(5,g-y-1)}const w=Math.max(1,y-2),E=Math.max(0,f.selectedIndex-Math.floor(w/2)),k=!c&&o?{x:o.x+2,y:o.y+2,width:p,height:y}:null,x=!c&&o?{x:o.x+2,y:o.y+2+y+1,width:p,height:S}:null,T=gt.map(R=>({text:R==="files"?`[${R}] `:`${R} `,color:R==="files"?"magenta":"gray",bold:R==="files"})),A=a.createElement(d.Column,{width:p},a.createElement(d.Lines,{lines:[T]}),a.createElement(d.Panel,{title:f.listTitle,color:"gray",focused:!1,width:p,height:y,lines:f.listBodyLines||f.listLines.slice(1),scrollOffset:E,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:k}),a.createElement(d.Panel,{title:f.previewTitle,color:"gray",focused:!1,width:p,height:S,lines:f.previewLines,scrollOffset:f.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:x}));return c?A:a.createElement(d.Panel,{title:h,color:"magenta",focused:i,width:s,height:n,marginBottom:cr,paneId:"inspector",paneLabel:"Inspector",frame:o},A)}),aS=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=pt(),l=Math.max(20,s-4),c=se(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null}),at),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Fs(c.activeSessionId,c.activeSession)},ui:{inspectorTab:"files"}}),[c.activeSession,c.activeSessionId]),u=a.useMemo(()=>Ht(d,{width:l}),[l,d]);return a.createElement(o.Panel,{title:u.title,color:"magenta",focused:i.focused,width:s,height:n,marginBottom:cr,paneId:"inspector",paneLabel:"Inspector",frame:r},a.createElement(iS,{controller:e,width:s,height:n,frame:r,focused:i.focused,embedded:!0}))}),oS=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=pt(),l=Math.max(20,s-4),c=se(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,activeOrchestration:p.sessions.activeSessionId&&p.orchestration.bySessionId?.[p.sessions.activeSessionId]||null,histories:p.history.bySessionId,expandedTurns:p.ui.sequenceExpandedTurns,selectedTurn:p.ui.sequenceSelectedTurn}),at),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Fs(c.activeSessionId,c.activeSession)},history:{bySessionId:c.histories},orchestration:{bySessionId:c.activeSessionId&&c.activeOrchestration?{[c.activeSessionId]:c.activeOrchestration}:{}},ui:{inspectorTab:"sequence"}}),[c.activeOrchestration,c.activeSession,c.activeSessionId,c.histories]),u=a.useMemo(()=>Ht(d,{width:l,sequenceExpansion:{expandedTurns:c.expandedTurns||[],selectedTurn:c.selectedTurn??null}}),[l,d,c.expandedTurns,c.selectedTurn]);return on(o,u,i,s,n,r)}),lS=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=pt(),l=Math.max(20,s-4),c=se(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,logs:p.logs}),at),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Fs(c.activeSessionId,c.activeSession)},logs:c.logs,ui:{inspectorTab:"logs"}}),[c.activeSession,c.activeSessionId,c.logs]),u=a.useMemo(()=>Ht(d,{width:l}),[l,d]);return on(o,u,i,s,n,r)}),cS=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=pt(),l=Math.max(20,s-4),c=se(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,executionHistory:p.executionHistory}),at),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Fs(c.activeSessionId,c.activeSession)},executionHistory:c.executionHistory,ui:{inspectorTab:"history"}}),[c.activeSession,c.activeSessionId,c.executionHistory]),u=a.useMemo(()=>Ht(d,{width:l}),[l,d]);return on(o,u,i,s,n,r)}),dS=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=pt(),l=Math.max(20,s-4),c=se(e,p=>({activeSessionId:p.sessions.activeSessionId,sessionsById:p.sessions.byId,sessionsFlat:p.sessions.flat,histories:p.history.bySessionId}),at),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:c.sessionsById,flat:c.sessionsFlat},history:{bySessionId:c.histories},ui:{inspectorTab:"nodes"}}),[c.activeSessionId,c.histories,c.sessionsById,c.sessionsFlat]),u=a.useMemo(()=>Ht(d,{width:l}),[l,d]);return on(o,u,i,s,n,r)}),uS=a.memo(function({controller:e,width:s,height:n,frame:r,meta:i}){const o=pt(),l=Math.max(20,s-4),c=se(e,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,sessionStats:p.sessionStats,fleetStats:p.fleetStats,statsViewMode:p.ui.statsViewMode}),at),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Fs(c.activeSessionId,c.activeSession)},sessionStats:c.sessionStats,fleetStats:c.fleetStats,ui:{inspectorTab:"stats",statsViewMode:c.statsViewMode}}),[c.activeSession,c.activeSessionId,c.fleetStats,c.sessionStats,c.statsViewMode]),u=a.useMemo(()=>Ht(d,{width:l}),[l,d]);return on(o,u,i,s,n,r)});a.memo(function({controller:e,width:s,height:n,frame:r}){const i=se(e,o=>({inspectorTab:o.ui.inspectorTab,inspectorScroll:o.ui.scroll.inspector,inspectorFollowBottom:o.ui.followBottom?.inspector!==!1,focused:o.ui.focusRegion==="inspector"}),at);return i.inspectorTab==="files"?a.createElement(aS,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="sequence"?a.createElement(oS,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="logs"?a.createElement(lS,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="history"?a.createElement(cS,{controller:e,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="stats"?a.createElement(uS,{controller:e,width:s,height:n,frame:r,meta:i}):a.createElement(dS,{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=pt(),l=se(e,p=>{const m=p.sessions.activeSessionId;return{sessionsById:p.sessions.byId,activeSessionId:m,activeSession:m&&p.sessions.byId[m]||null,activeHistory:m&&p.history.bySessionId.get(m)||null,scroll:p.ui.scroll.activity,followBottom:p.ui.followBottom?.activity!==!1,focused:p.ui.focusRegion==="activity",inspectorTab:p.ui.inspectorTab,nodeMapSelectedNode:p.ui.nodeMapSelectedNode,adminWorkers:p.admin?.workers,branding:p.branding,historyBySessionId:p.history.bySessionId,sessionsFlat:p.sessions.flat}},at),c=l.inspectorTab==="nodes",d=a.useMemo(()=>{const p=new Map;return l.activeSessionId&&l.activeHistory&&p.set(l.activeSessionId,l.activeHistory),{branding:l.branding,admin:{workers:l.adminWorkers},ui:{nodeMapSelectedNode:l.nodeMapSelectedNode},sessions:{activeSessionId:l.activeSessionId,byId:l.sessionsById,flat:l.sessionsFlat},history:{bySessionId:c?l.historyBySessionId:p}}},[l.activeHistory,l.activeSessionId,l.sessionsById,l.adminWorkers,l.branding,l.historyBySessionId,l.nodeMapSelectedNode,l.sessionsFlat,c]),u=a.useMemo(()=>c?Od(d):ga(d,r),[r,c,d]);return a.createElement(o.Panel,{title:u.title,color:"gray",focused:l.focused,width:s,height:n,lines:u.lines,scrollOffset:l.scroll,scrollMode:l.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:i})});a.memo(function({controller:e,rows:s}){const n=pt(),r=se(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")}},at);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=pt(),n=se(e,u=>({connected:u.connection.connected,workersOnline:u.connection.workersOnline,focusRegion:u.ui.focusRegion,inspectorTab:u.ui.inspectorTab,fullscreenPane:u.ui.fullscreenPane||null,logsAvailable:u.logs.available,logsTailing:u.logs.tailing,filesFullscreen:!!u.files.fullscreen,mode:u.connection.mode,statusText:u.ui.statusText,modal:u.ui.modal,activeSessionId:u.sessions.activeSessionId,activeSession:u.sessions.activeSessionId&&u.sessions.byId[u.sessions.activeSessionId]||null,selectedIds:u.sessions.selectedIds,selectMode:u.sessions.selectMode}),at),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(()=>pg(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:Cl(i.left,d),right:Cl(i.right,c)})});const pS="modulepreload",mS=function(t){return"/"+t},Tl={},lu=function(e,s,n){let r=Promise.resolve();if(s&&s.length>0){let c=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");r=c(s.map(d=>{if(d=mS(d),d in Tl)return;Tl[d]=!0;const u=d.endsWith(".css"),p=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const m=document.createElement("link");if(m.rel=u?"stylesheet":pS,u||(m.as="script"),m.crossOrigin="",m.href=d,l&&m.setAttribute("nonce",l),document.head.appendChild(m),u)return new Promise((f,h)=>{m.addEventListener("load",f),m.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)})},Q=a.createElement,Ct=t=>t?"On":"Off",Kr=t=>typeof t=="string"&&/^[1-9]\d{0,18}$/.test(t)&&BigInt(t)<=9223372036854775807n,Pl=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);function fS(t,e=[],s=Date.now()){const n=e.map(i=>{const o=s-new Date(i.updatedAt).getTime(),l=i.state?.["feature-flags"],c=Number.isFinite(o)&&o>=-5e3&&o<9e4,d=i.phase==="ready"&&c,u=Pl(l)&&l.protocolVersion===1&&typeof l.initialized=="boolean"&&Array.isArray(l.supportedKeys)&&l.supportedKeys.every(f=>typeof f=="string")&&Pl(l.appliedRevisions);let p="unknown";d&&u&&Kr(t.revision)&&(l.supportedKeys.includes(t.featureKey)?l.initialized?Kr(l.appliedRevisions[t.featureKey])&&(p=BigInt(l.appliedRevisions[t.featureKey])>=BigInt(t.revision)?"updated":"pending"):p="loading":p="unsupported");const m=d&&u&&["sync","off"].includes(l.nativeCapability)?l.nativeCapability:"unknown";return{workerNodeId:i.workerNodeId,phase:i.phase,recent:c,eligible:d,delivery:p,capability:m,revision:u&&Kr(l.appliedRevisions[t.featureKey])?l.appliedRevisions[t.featureKey]:null,refreshError:d&&u&&(l.hasRefreshError===!0||typeof l.lastError=="string"&&l.lastError.length>0)}}),r=n.filter(i=>i.eligible);return{reports:n,eligible:r.length,updated:r.filter(i=>i.delivery==="updated").length,unknown:r.filter(i=>i.delivery==="unknown").length,unsupported:r.filter(i=>i.delivery==="unsupported").length,capable:r.filter(i=>i.capability==="sync").length,incapable:r.filter(i=>i.capability==="off").length,capabilityUnknown:r.filter(i=>i.capability==="unknown").length,refreshErrors:r.filter(i=>i.refreshError).length,stale:n.filter(i=>!i.recent&&i.phase!=="draining").length,draining:n.filter(i=>i.phase==="draining").length,other:n.filter(i=>i.recent&&!i.eligible&&i.phase!=="draining").length}}function hS(t,e){return e||!t.eligible||t.unknown===t.eligible?"Settings delivery: status unavailable":`Settings delivery: ${t.updated} of ${t.eligible} reporting workers updated.${t.unknown?` Status unavailable for ${t.unknown}.`:""}${t.unsupported?` ${t.unsupported} do not support this feature.`:""}${t.refreshErrors?` ${t.refreshErrors} reported a refresh problem.`:""}`}function Ml(t,e){return`${Ct(t)} ${e?"by default. Users can choose On or Off.":"for everyone. Personal settings do not apply."}`}function Vr({legend:t,name:e,value:s,options:n,disabled:r,onChange:i}){return Q("fieldset",{className:"ps-feature-choice-group",disabled:r},Q("legend",null,t),Q("div",{className:"ps-feature-choices"},n.map(o=>Q("label",{className:`ps-feature-choice${s===o.value?" is-selected":""}`,key:o.value},Q("input",{type:"radio",name:e,value:o.value,checked:s===o.value,onChange:()=>i(o.value)}),Q("span",null,o.label)))))}function gS({flag:t,mode:e,busy:s,saving:n,controller:r,workers:i,workersError:o,isAdmin:l,userName:c}){const d=a.useId(),u=r.getFeatureDraft?.(t.featureKey),p=u!==void 0,m=p&&(u.needsReview||u.expectedRevision!==t.revision),f=m&&u.needsReview&&u.expectedRevision===t.revision,h=t.cluster?.enabled??t.defaultEnabled,g=t.cluster?.allowUserOverride??t.defaultAllowUserOverride,b=e!=="cluster"&&!g,y=t.user?String(t.user.enabled):"inherit",S=p?u.values===null?"inherit":String(u.values.enabled):y,v=p?u.values??{enabled:t.defaultEnabled,allowUserOverride:t.defaultAllowUserOverride}:{enabled:h,allowUserOverride:g},w=e==="mine"?"you":c,E=e==="mine"?"Your":`${c}’s`,k=e==="cluster"?`${Ct(h)} ${g?"by default":"for everyone"}`:`${Ct(t.effective)} for ${w}`,x=e==="cluster"?g?"Users can choose On or Off.":"Personal settings do not apply.":b?"Required by the cluster.":t.user?e==="mine"?"Using your choice.":"Using the saved personal choice.":"Following the cluster setting.",T=fS(t,i),A=t.featureKey==="copilot.native_tasks",R=e==="cluster"?h:t.effective,N=l&&A&&R&&!o&&T.eligible>0&&T.incapable===T.eligible,$=s||!t.supported;let F=null;return p&&(e==="cluster"?F=`${u.values===null?"Restore the default policy. ":""}${Ml(v.enabled,v.allowUserOverride)}${!g&&v.allowUserOverride?" Previously saved personal choices will apply again.":""}`:b?F=`${E} future preference will ${S==="inherit"?"follow the cluster setting":`be ${Ct(S==="true")}`}. ${Ct(h)} still applies while the cluster requires it.`:F=`${Ct(S==="inherit"?h:S==="true")} for ${w}. ${S==="inherit"?"Following the cluster setting.":"Using the personal choice."}`),Q("section",{className:"ps-feature-flag","data-feature-key":t.featureKey,"aria-labelledby":`${d}-title`},Q("div",{className:"ps-feature-flag-heading"},Q("h3",{id:`${d}-title`},t.displayName),p?Q("span",{className:"ps-feature-unsaved"},"Unsaved changes"):null),Q("p",{className:"ps-feature-description"},A?"Lets Copilot delegate short tasks in the same session workspace. On permits use; Copilot decides when to use native tasks.":t.description),Q("div",{className:"ps-feature-saved"},Q("span",{className:"ps-feature-label"},"Saved setting"),Q("strong",{className:`ps-feature-value${(e==="cluster"?h:t.effective)?" is-on":""}`},k),Q("p",{className:"ps-feature-explanation"},x),e!=="cluster"?Q("p",{className:"ps-feature-context"},`Cluster setting: ${Ct(h)}. Personal settings ${g?"allowed":"not allowed"}.`):null,b?Q("p",{className:"ps-feature-retained"},`Saved future preference: ${y==="inherit"?"Use cluster setting":Ct(t.user.enabled)}. This will apply if personal settings are allowed again.`):null),t.supported?null:Q("p",{role:"status"},"This server does not support changing this feature."),N?Q("p",{className:"ps-feature-blocker",role:"status"},`The saved setting is On, but none of the ${T.eligible} reporting workers is configured for native tasks. Native tasks cannot run on those workers.`):null,Q("div",{className:"ps-feature-editor"},e==="cluster"?[Q(Vr,{key:"enabled",legend:"Cluster setting",name:`${d}-cluster`,value:String(v.enabled),disabled:$,options:[{value:"false",label:"Off"},{value:"true",label:"On"}],onChange:I=>r.setFeatureDraft(t.featureKey,{...v,enabled:I==="true"})}),Q(Vr,{key:"override",legend:"Personal settings",name:`${d}-override`,value:String(v.allowUserOverride),disabled:$,options:[{value:"true",label:"Allowed"},{value:"false",label:"Not allowed"}],onChange:I=>r.setFeatureDraft(t.featureKey,{...v,allowUserOverride:I==="true"})})]:Q(Vr,{legend:b?"Preference for when personal settings are allowed":e==="mine"?"Your choice":`${c}’s choice`,name:`${d}-user`,value:S,disabled:$,options:[{value:"inherit",label:`Use cluster setting (currently ${Ct(h)})`},{value:"true",label:e==="mine"?"On for me":"On for this user"},{value:"false",label:e==="mine"?"Off for me":"Off for this user"}],onChange:I=>r.setFeatureDraft(t.featureKey,I==="inherit"?null:{enabled:I==="true"})})),p?Q("div",{className:"ps-feature-preview",role:"status"},Q("strong",null,"After saving: "),F):null,m?Q("p",{className:"ps-feature-conflict",role:"status"},f?"Settings changed since this edit began. Refresh settings to load the latest saved value.":"Settings changed since this edit began. Review the saved setting and your proposed change before saving."):null,Q("div",{className:"ps-feature-actions"},Q("button",{type:"button",className:"ps-mini-button ps-feature-save",disabled:$||!p||m,onClick:()=>r.saveFeatureDraft(t.featureKey)},n&&p?"Saving…":b?"Save future preference":"Save changes"),Q("button",{type:"button",className:"ps-mini-button",disabled:s||!p,onClick:()=>r.discardFeatureDraft(t.featureKey)},"Discard changes"),m?Q("button",{type:"button",className:"ps-mini-button",disabled:s||f,onClick:()=>r.reviewFeatureDraft(t.featureKey)},"Review latest settings"):null),l?Q("p",{className:"ps-feature-delivery",role:"status"},hS(T,o)):null,Q("details",{className:"ps-feature-details"},Q("summary",null,"Technical details"),Q("p",null,Q("code",null,t.featureKey),` · Saved revision ${t.revision}`),Q("p",null,"Workers normally check for settings changes within 20 seconds. Settings delivery does not confirm that each session has refreshed its tools."),A?Q("p",null,"After a worker receives On, native tasks become available on the next turn. After it receives Off, new native tasks are blocked. Tasks already running can finish."):null,l&&A?Q("p",null,o||!T.eligible||T.capabilityUnknown===T.eligible?"Native task support: status unavailable.":`Native task support: ${T.capable} of ${T.eligible} reporting workers configured; ${T.incapable} configured Off; ${T.capabilityUnknown} unknown.`):null,l&&(T.stale||T.draining||T.other)?Q("p",null,`Excluded from current delivery counts: ${T.stale} stale or undated reports; ${T.draining} draining workers; ${T.other} other worker reports.`):null,l?Q("ul",{className:"ps-feature-worker-list"},T.reports.map(I=>Q("li",{key:I.workerNodeId},`${I.workerNodeId}: ${I.eligible?{updated:"settings received",pending:"waiting for latest settings",loading:"loading settings",unsupported:"feature unsupported",unknown:"status unavailable"}[I.delivery]:I.phase==="draining"?"draining; excluded":I.recent?"not reporting ready; excluded":"stale or undated report; status unavailable"}${I.eligible&&I.revision?`; revision ${I.revision}`:""}${I.eligible&&A?`; native task configuration ${I.capability==="sync"?"On":I.capability==="off"?"Off":"unknown"}`:""}${I.refreshError?"; settings refresh problem":""}`))):null,e==="cluster"?Q("div",{className:"ps-feature-defaults"},Q("p",null,`Default policy: ${Ml(t.defaultEnabled,t.defaultAllowUserOverride)}`),Q("button",{type:"button",className:"ps-mini-button",disabled:$||!t.cluster,onClick:()=>r.setFeatureDraft(t.featureKey,null)},"Preview default policy"),Q("p",{className:"ps-feature-explanation"},"Preview stages removal of the cluster override. Save changes to use the code-defined defaults; personal choices are kept.")):null))}function yS({controller:t,features:e={},isAdmin:s,workers:n=[],workersError:r=null}){const i=e.mode||"mine",[o,l]=a.useState(e.userQuery||""),c=e.users?.find(p=>p.userId===e.userId),d=c?.displayName||c?.email||c?.subject||(e.userId?`user ${e.userId}`:"this user"),u=e.saving||e.loading;return Q("section",{className:"ps-feature-flags-panel","aria-label":"Feature flags"},Q("header",{className:"ps-feature-flag-heading"},Q("h2",null,"Feature flags"),Q("button",{type:"button",className:"ps-mini-button",disabled:u,onClick:()=>t.refreshFeatureFlags()},"Refresh settings")),Q("div",{role:"tablist","aria-label":"Feature settings scope",className:"ps-feature-tabs"},[{mode:"mine",label:"My settings"},...s?[{mode:"cluster",label:"Cluster settings"},{mode:"users",label:"User settings"}]:[]].map(p=>{const m=t.getFeatureDraftCount?.(p.mode)||0;return Q("button",{type:"button",key:p.mode,role:"tab","aria-selected":i===p.mode,disabled:e.saving,className:"ps-mini-button",onClick:()=>t.selectFeatureScope(p.mode)},p.label,m?Q("span",{className:"ps-feature-unsaved"},`${m} unsaved`):null)})),i==="users"&&s?Q("div",{className:"ps-feature-user"},Q("form",{onSubmit:p=>{p.preventDefault(),t.searchFeatureUsers(o)}},Q("label",null,"Find user ",Q("input",{type:"search",value:o,"aria-label":"Find feature settings user",placeholder:"Name, email or identity",onChange:p=>l(p.target.value)})),Q("button",{className:"ps-mini-button",disabled:e.usersLoading||e.saving},"Search")),Q("label",null,"User ",Q("select",{"aria-label":"Feature settings user",value:e.userId??"",disabled:e.saving,onChange:p=>t.selectFeatureScope("users",p.target.value?Number(p.target.value):null)},Q("option",{value:""},"Select a user"),(e.users||[]).map(p=>Q("option",{key:p.userId,value:p.userId},`${p.displayName||p.email||p.subject}${p.displayName&&p.email?` — ${p.email}`:""}${e.selectedUserOutsideResults&&p.userId===e.userId?" (current selection)":""}`)))),e.selectedUserOutsideResults?Q("p",{className:"ps-feature-explanation"},"Current selection kept while you search."):null,c?Q("p",{className:"ps-feature-user-identity"},Q("strong",null,d),c.email?Q("span",null,c.email):null):e.userId?Q("p",null,`Selected user ID: ${e.userId}`):null,e.users?.length>=500?Q("p",null,"Showing the first 500 users. Refine your search to find another user."):null):null,e.error?Q("p",{role:"alert"},e.error):null,e.metadataError?Q("p",{role:"status"},e.metadataError):null,s&&r?Q("p",{role:"status"},"Worker reports could not be refreshed. Settings delivery status is unavailable."):null,e.notice?Q("p",{role:"status"},e.notice):null,e.loading?Q("p",{role:"status"},"Loading feature settings…"):null,(i==="mine"||s?e.data?.flags||[]:[]).map(p=>Q(gS,{key:`${i}:${e.userId}:${p.featureKey}`,flag:p,mode:i,busy:u,saving:e.saving,controller:t,workers:n,workersError:r,isAdmin:s,userName:d})),!e.loading&&e.data?.flags?.length===0?Q("p",null,"No feature definitions are published."):null)}const bS=new Set(["completed","failed","cancelled","interrupted"]),SS={starting:"◷",running:"◷",waiting:"Ⅱ",completed:"✓",failed:"!",cancelled:"■",interrupted:"↯"};function vS(t,e){const s=t.durationMs??(t.startedAt?(t.completedAt||e)-t.startedAt:null);if(!Number.isFinite(s)||s<0)return"";const n=Math.floor(s/1e3);return n<60?`${n}s`:`${Math.floor(n/60)}m ${n%60}s`}const wS=a.memo(function({group:e,colors:s}){const[n,r]=a.useState(!1),[i,o]=a.useState(Date.now),l=e.tasks.some(p=>!bS.has(p.status));a.useEffect(()=>{if(!l)return;const p=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(p)},[l]);const c=e.tasks.reduce((p,m)=>{const f=Ln[m.status]||"Unknown";return p[f]=(p[f]||0)+1,p},{}),d=Object.entries(c).map(([p,m])=>`${m} ${p.toLowerCase()}`).join(" · "),u=n?e.tasks:e.tasks.slice(0,3);return a.createElement("section",{className:"ps-native-tasks","aria-label":"Native tasks","data-task-group":e.id},a.createElement("header",{className:"ps-native-tasks-header"},a.createElement("span",{className:"ps-native-tasks-title"},a.createElement("span",{className:"ps-native-task-branch","aria-hidden":!0},"⑂"),"Native tasks"),a.createElement("span",{className:"ps-native-tasks-count","aria-live":"polite"},d)),u.map(p=>{const m=s[p.status]||s.running,f=p.error||p.result||p.preview||(p.status==="completed"?"Task completed.":""),h=vS(p,i);return a.createElement("details",{key:p.id,className:"ps-native-task","data-task-id":p.id,"data-status":p.status,style:{"--ps-native-task-accent":m}},a.createElement("summary",null,a.createElement("span",{className:"ps-native-task-mark","aria-hidden":!0},SS[p.status]||"?"),a.createElement("span",{className:"ps-native-task-main"},a.createElement("span",{className:"ps-native-task-title"},p.title),f?a.createElement("span",{className:"ps-native-task-preview"},f.replace(/\s+/g," ").slice(0,240)):null),a.createElement("span",{className:"ps-native-task-meta"},a.createElement("span",{className:"ps-native-task-status"},p.telemetryStale?"Reconnecting":Ln[p.status]||p.status),a.createElement("span",null,[h,`${p.toolCalls||0} calls`].filter(Boolean).join(" · "))),a.createElement("span",{className:"ps-native-task-chevron","aria-hidden":!0},"›")),a.createElement("div",{className:"ps-native-task-detail"},a.createElement("div",{className:"ps-native-task-scope"},[p.profile,p.model,p.reasoningEffort,"Same worker"].filter(Boolean).join(" · ")),p.result&&!p.error?a.createElement("div",{className:"ps-native-task-scope"},"Result excerpt"):null,a.createElement("p",{className:"ps-native-task-result"},p.error||p.result||p.preview||(p.status==="completed"?"Task completed. A result excerpt is not available in this recording.":"No result available yet.")),p.recentActivity?.length?a.createElement("ul",{className:"ps-native-task-activity"},p.recentActivity.map((g,b)=>a.createElement("li",{key:b},g.message))):null))}),e.tasks.length>3?a.createElement("button",{type:"button",className:"ps-native-tasks-more","aria-expanded":n,onClick:()=>r(p=>!p)},n?"Show fewer tasks":`Show ${e.tasks.length-3} more tasks`):null)}),ES=920,cu=7,kS=19,Na=.24,du=16,uu=8,Ca=224,IS=190,xS=48,wt=16,pu=.5,Wt=pu,AS=24,NS=700,CS=5e3,TS=new Set(["low","medium","high","xhigh"]),PS=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],MS=["pilotswarm_theme","pilotswarm_session_owner_filter"],_S={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"Duroxide Event History",files:"Files",stats:"Stats"},_l={sequence:kw,logs:xw,nodes:Aw,history:Pw,files:Mw,stats:_w};function $S(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 RS(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function LS(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function OS(t){return typeof t?.transport?.listArtifacts=="function"}function FS(t){return typeof t?.transport?.deleteArtifact=="function"}function DS(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const BS="Session link copied to clipboard",mu="Artifact link copied to clipboard",HS=140,US="Only people with access can open this link.";function fu(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function dr(t,e,{fullscreen:s=!0}={}){const n=fu(t);return!n||!e?n:`${n}&artifact=${encodeURIComponent(e)}${s?"&view=full":""}`}let ur=[];function G0(t){ur=Array.isArray(t)?t:[]}function Xn(t){const e=Zd(Ia(t,ur));navigator?.clipboard?.writeText&&navigator.clipboard.writeText(e).catch(()=>{})}function hu({url:t,keyPrefix:e,copied:s,onCopy:n}){const r=Ia(t,ur),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,Zd(r))},s===o?"Copied all":"Copy all")))}async function jS(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 GS(){if(!(typeof window>"u")){try{for(const t of PS)window.localStorage.removeItem(t)}catch{}try{for(const t of MS)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function ts(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{},s={};if(Ie(e,"moa")&&(s.moa=Js(e.moa)),typeof e.themeId=="string"&&e.themeId.trim()&&(s.themeId=e.themeId.trim()),typeof e.sessionDetailCollapsed=="boolean"&&(s.sessionDetailCollapsed=e.sessionDetailCollapsed),e.agentPickerUsage&&typeof e.agentPickerUsage=="object"&&!Array.isArray(e.agentPickerUsage)){const n={};for(const[i,o]of Object.entries(e.agentPickerUsage)){const l=Number(o);typeof i=="string"&&i&&Number.isFinite(l)&&l>0&&(n[i]=Math.min(Math.round(l),1e6))}const r=Object.entries(n).sort((i,o)=>o[1]-i[1]).slice(0,200);r.length>0&&(s.agentPickerUsage=Object.fromEntries(r))}if(typeof e.touchScale=="boolean"&&(s.touchScale=e.touchScale),typeof e.touchScaleMobile=="boolean"&&(s.touchScaleMobile=e.touchScaleMobile),Ie(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=Ie(n,"includeShared")?n:{...n,includeShared:!0}}if(Ie(e,"layoutAdjustments")&&(s.layoutAdjustments=Ji(e.layoutAdjustments)),Ie(e,"pinnedSessionIds")&&(s.pinnedSessionIds=jn(e.pinnedSessionIds)),Ie(e,"sessionOrder")&&(s.sessionOrder=ea(e.sessionOrder)),Ie(e,"collapsedSessionIds")&&(s.collapsedSessionIds=WS(e.collapsedSessionIds)),Ie(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),Ie(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}),Ie(e,"canvasPrefs")&&(s.canvasPrefs=ta(e.canvasPrefs)),Ie(e,"sessionViews")&&(s.sessionViews=ld(e.sessionViews)),s}function pr(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches}function Qn(){return pr()?"touchScaleMobile":"touchScale"}function Zn(){return pr()?"touchScale":"touchScaleMobile"}function WS(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 Ie(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function $l(t){return{...t.ui,...t.ui.layout,ownerFilter:t.sessions.ownerFilter,pinnedIds:t.sessions.pinnedIds,manualOrder:t.sessions.manualOrder,collapsedSessionIds:t.sessions.collapsedIds,activeSessionId:t.sessions.activeSessionId,canvasPrefs:t.canvas?.prefs}}function Yr(t,e=null,s=null,n=null){return ts({...t.moa?{moa:t.moa}:{},themeId:t.themeId,[Qn()]:t.touchScale,sessionDetailCollapsed:t.sessionDetailCollapsed,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,...pr()?{...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,sessionViews:t.sessionViews,...typeof e=="boolean"?{[Zn()]:e}:{},...t.agentPickerUsage&&typeof t.agentPickerUsage=="object"&&Object.keys(t.agentPickerUsage).length>0?{agentPickerUsage:t.agentPickerUsage}:{}})}function Rl(t,e=null,s=null){return ts({...t?.ui?.moa?{moa:t.ui.moa}:{},themeId:t?.ui?.themeId,[Qn()]:t?.ui?.touchScale,sessionDetailCollapsed:t?.ui?.sessionDetailCollapsed,sessionOwnerFilter:Yn(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,sessionOrder:t?.sessions?.manualOrder,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,...pr()?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"?{[Zn()]:e}:{}})}function qS(t,e){const s=ts(t),n=ts(e);return ts({...Ie(s,"moa")?{moa:s.moa}:{},themeId:Ie(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:Ie(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:Ie(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:Ie(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,sessionOrder:Ie(s,"sessionOrder")?s.sessionOrder:n.sessionOrder,...Ie(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...Ie(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...Ie(s,"desktopPanes")?{desktopPanes:s.desktopPanes}:{},...Ie(s,"sessionViews")?{sessionViews:s.sessionViews}:{},...Ie(s,"rightPaneMode")?{rightPaneMode:s.rightPaneMode}:{},...Ie(s,"canvasPrefs")?{canvasPrefs:s.canvasPrefs}:{},...Ie(s,Qn())?{touchScale:s[Qn()]}:{},...Ie(s,"sessionDetailCollapsed")?{sessionDetailCollapsed:s.sessionDetailCollapsed}:{},...Ie(s,"agentPickerUsage")?{agentPickerUsage:s.agentPickerUsage}:{}})}const Sn=new WeakMap;async function zS(t,e){if(typeof t?.transport?.setCurrentUserProfileSettings!="function")return null;const n=(Sn.get(t)||Promise.resolve()).catch(()=>{}).then(()=>t.transport.setCurrentUserProfileSettings({settings:ts(e)}));Sn.set(t,n);try{return await n}finally{Sn.get(t)===n&&Sn.delete(t)}}function Ta(t){return OS(t)?gt:gt.filter(e=>e!=="files")}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 Ns(t,e,s){return Math.max(e,Math.min(s,t))}const Pn=120,Pa=640,Ma=320;function $i(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-du-uu*2),n=s*Na,r=Math.max(0,s-Ca);return{minAdjust:-n,maxAdjust:r-n}}function KS(t,e){const s=$i(t),n=Math.max(0,Number(t)||0),i=Math.max(0,n-du-uu*2)*Na;return Ns(i+(Number(e)||0),0,i+s.maxAdjust)}function VS(t){return t<=xS?"hidden":t<=IS?"compact":"wrap"}function gu(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:Es(t?.ui?.prompt||"")}function mr(t){return Ks({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,gu(t),t.ui.layout?.sessionPaneAdjust??0)}function YS(t,e,s=!1){return Math.max(20,t-(s?6:4))}function yu({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 u=o.querySelector(".ps-line")||o,p=window.getComputedStyle(u),m=document.createElement("span");m.style.cssText="position:absolute;visibility:hidden;white-space:pre;",m.style.fontFamily=p.fontFamily,m.style.fontSize=p.fontSize,m.style.fontWeight=p.fontWeight,m.style.letterSpacing=p.letterSpacing,m.textContent="0".repeat(100),o.appendChild(m);const f=m.getBoundingClientRect().width/100||0;if(m.remove(),!(f>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/f)-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 Je(t){const e=[],s=n=>{const r=String(n||"");return!r.includes("\\n")||r.includes(`
|
|
93
|
-
`)?r:r.replace(/\\n/g,`
|
|
94
|
-
`)};for(const n of t||[]){if(n?.kind==="chatCall"||n?.callPreview!==void 0){e.push(n);continue}if(n?.kind==="assistantPreview"||n?.kind==="nativeTasks"){e.push(n);continue}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 Sc(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(`
|
|
95
|
-
`)){const l=o.split(`
|
|
96
|
-
`);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(`
|
|
97
|
-
`)){const i=r.split(`
|
|
98
|
-
`);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 Ue(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function bu(t=[]){return t.map(e=>String(e?.text||"")).join("")}function Ll(t){return Array.isArray(t)?bu(t):String(t||"")}function Ol(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 XS(t){typeof document>"u"||(t?document.documentElement.dataset.psTouch="1":delete document.documentElement.dataset.psTouch)}function QS(t){const e=kt(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 Fl(t,e=!1){const[s,n]=a.useState({width:0,height:0});return a.useLayoutEffect(()=>{if(e)return;const r=t.current;if(!r)return;const i=()=>{n({width:r.clientWidth,height:r.clientHeight})};i();const o=new ResizeObserver(i);return o.observe(r),window.addEventListener("resize",i),()=>{o.disconnect(),window.removeEventListener("resize",i)}},[t,e]),s}function ZS(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/cu)),height:Math.max(18,Math.floor(s/kS))}}function _a(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function JS(t){return _a(t)<=pu}function ev(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)*wt;return s==="bottom"?Math.max(0,r-i):Math.min(r,i)}function tv(t){return t?t.kind==="runs"?t.runs?.map(e=>e?.text||"").join("")||"":t.kind==="assistantPreview"?`assistant:${t.previewKey||t.messageId||t.id||""}`:`${t.kind||"text"}:${t.text||t.value||t.id||""}`:""}function Dl(t,e=!1){return(e?t.slice(-8):t.slice(0,8)).map(tv).join("␞")}function sv(t,e,s,n,r,i,{stickyBottom:o=!1}={}){const l=a.useMemo(()=>Je(e),[e]),c=a.useRef(null),d=a.useRef({scrollMode:n,scrollOffset:s}),u=a.useRef(null),p=a.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),m=a.useRef({width:null,height:null}),[f,h]=a.useState(0);a.useLayoutEffect(()=>{const k=t.current;if(!k||typeof ResizeObserver>"u")return;m.current={width:k.clientWidth,height:k.clientHeight};const x=new ResizeObserver(()=>{const T={width:k.clientWidth,height:k.clientHeight},A=m.current;T.width===A.width&&T.height===A.height||(m.current=T,h(R=>R+1))});return x.observe(k),()=>x.disconnect()},[t]),a.useLayoutEffect(()=>{const k=t.current;if(!k)return;const x=d.current,T=Dl(l),A=Dl(l,!0),R=u.current,N=p.current,$=typeof performance<"u"?performance.now():Date.now(),F=N.touching||$-(N.lastUserScrollAt||0)<NS,I=N.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-N.lastDispatchedOffset)<2,O=o&&n==="top"&&x?.scrollMode==="top"&&x?.scrollOffset===s,M=o&&R?.lastLine===A&&R?.firstLine!==T&&k.scrollHeight>R.scrollHeight&&(O||k.scrollTop<=Wt);if(!M&&F&&n===x?.scrollMode&&(s===x?.scrollOffset||I)){d.current={scrollMode:n,scrollOffset:s},u.current={firstLine:T,lastLine:A,scrollHeight:k.scrollHeight};return}const B=M?Math.max(0,Math.min(k.scrollTop+(k.scrollHeight-R.scrollHeight),k.scrollHeight-k.clientHeight)):ev(k,s,n,O);if(Math.abs(k.scrollTop-B)>Wt){const D={target:B};c.current=D,k.scrollTop=B,window.requestAnimationFrame(()=>{c.current===D&&(c.current=null)})}if(M&&r&&typeof i.updatePaneScrollFromViewport=="function"){const D=Math.max(0,B)/wt;p.current.lastDispatchedOffset=D,i.updatePaneScrollFromViewport(r,D,{atBottom:!1})}d.current={scrollMode:n,scrollOffset:s},u.current={firstLine:T,lastLine:A,scrollHeight:k.scrollHeight}},[l,t,n,s,o,f]);const g=av(k=>{i.dispatch({type:"ui/scroll",pane:r,offset:k})}),b=a.useCallback(()=>{const k=t.current;if(!k||!r)return;const x=c.current;if(x){if(Math.abs(k.scrollTop-x.target)<=Wt)return;c.current=null}p.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const T=Math.max(0,k.scrollHeight-k.clientHeight);if(T<=0)return;if(o&&typeof i.updatePaneScrollFromViewport=="function"){const R=Math.max(0,k.scrollTop)/wt;p.current.lastDispatchedOffset=R,i.updatePaneScrollFromViewport(r,R,{atBottom:JS(k)}),r==="chat"&&k.scrollTop<=Wt&&i.armChatTopHistoryLoad?.();return}const A=n==="bottom"?Math.max(0,T-k.scrollTop):Math.max(0,k.scrollTop);p.current.lastDispatchedOffset=A/wt,g(A/wt),r==="chat"&&n==="bottom"&&k.scrollTop<=Wt&&i.armChatTopHistoryLoad?.()},[i,g,r,t,n,o]),y=a.useCallback(k=>{const x=t.current;if(!x||r!=="chat"||k.deltaY>=0||x.scrollTop>Wt)return;const T=Math.max(0,x.scrollHeight-x.clientHeight);i.handleChatTopHistoryScrollIntent?.(T/wt,{preserveDomAnchor:!0})},[i,r,t]),S=a.useRef({startY:null,fired:!1}),v=a.useCallback(k=>{p.current.touching=!0,r==="chat"&&(S.current={startY:k.touches?.[0]?.clientY??null,fired:!1})},[r]),w=a.useCallback(()=>{p.current.touching=!1,p.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),E=a.useCallback(k=>{const x=t.current,T=S.current;if(!x||r!=="chat"||T.fired||T.startY==null||x.scrollTop>Wt)return;const A=k.touches?.[0]?.clientY;if(A==null||A-T.startY<AS)return;T.fired=!0;const R=Math.max(0,x.scrollHeight-x.clientHeight);i.handleChatTopHistoryScrollIntent?.(R/wt+1,{force:!0,preserveDomAnchor:!0})},[i,r,t]);return{normalizedLines:l,onScroll:b,onWheel:y,onTouchStart:v,onTouchMove:E,onTouchEnd:w}}function Ye({runs:t,theme:e}){return a.createElement(a.Fragment,null,(t||[]).map((s,n,r)=>{const i=n>0&&!!Jn(r[n-1]?.href),o={color:Ue(e,s.color),backgroundColor:Ue(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=Jn(l);if(d)return a.createElement(Au,{key:n,artifactRef:d,style:o});const u=i?ku(s.text||""):s.text||"";return i&&!u?null:c?a.createElement("a",{key:n,className:"ps-md-link",href:l,target:"_blank",rel:"noreferrer",style:o},u):a.createElement("span",{key:n,className:s?.role==="streamingCaret"?"ps-streaming-caret":void 0,style:o},u)}))}function Su({line:t,theme:e}){const[s,n]=a.useState(!1),r=String(t?.body||"").trim(),i=`ps-system-notice${t?.liveReasoning||t?.streamReasoning?" is-live-reasoning":""}`;return a.createElement("details",{className:i,onToggle:o=>n(o.currentTarget.open)},a.createElement("summary",{className:"ps-system-notice-summary",style:{color:Ue(e,t?.color)||"var(--ps-muted)"}},a.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),r&&s?a.createElement("div",{className:"ps-system-notice-body"},a.createElement(Da,{content:r,theme:e})):null)}function nv({line:t}){const[e,s]=a.useState(!1);return a.createElement("details",{className:"ps-system-notice ps-chat-call","data-call-id":t.callKey,onToggle:n=>s(n.currentTarget.open)},a.createElement("summary",{className:"ps-system-notice-summary ps-chat-call-summary"},a.createElement("span",{className:"ps-chat-call-tag"},t.category||"Tool"),a.createElement("span",{className:"ps-system-notice-summary-text"},t.text),t.status?a.createElement("span",{className:`ps-chat-call-status${t.status==="Failed"?" is-failed":""}`},t.status):null),e?a.createElement("div",{className:"ps-system-notice-body"},t.time?a.createElement("div",{className:"ps-chat-call-time"},t.time):null,a.createElement("pre",{className:"ps-chat-call-payload"},t.body)):null)}function rv({calls:t}){const e=t[t.length-1]||{},s=e.status==="Called"||e.status==="Started",n=t.some(f=>f.status==="Failed"),[r,i]=a.useState(s),o=a.useRef(null),l=a.useRef(!0),c=new Set(t.map(f=>f.category||"Tool")),d=c.size===1&&c.has("Tool")?`${t.length} tool ${t.length===1?"call":"calls"}`:c.size===1&&c.has("Agent")?`${t.length} agent ${t.length===1?"activity":"activities"}`:`${t.length} activities`,u=String(e.text||e.category||"activity").split(" — ")[0],p=s?"Working":n?"Failed":"Done",m=`${e.callKey||""}:${e.status||""}:${String(e.body||"").length}`;return a.useLayoutEffect(()=>{const f=o.current;r&&f&&l.current&&(f.scrollTop=f.scrollHeight)},[r,t.length,m]),a.createElement("details",{className:"ps-native-tasks ps-activity-run",open:r,onToggle:f=>i(f.currentTarget.open)},a.createElement("summary",{className:"ps-native-tasks-header ps-activity-run-summary"},a.createElement("span",{className:"ps-native-tasks-title"},a.createElement("span",{className:"ps-native-task-branch","aria-hidden":!0},"⌘"),d),a.createElement("span",{className:"ps-activity-run-latest",title:e.text||""},`latest: ${u}`),a.createElement("span",{className:`ps-activity-run-status${n?" is-failed":""}`},p),a.createElement("span",{className:"ps-activity-run-chevron","aria-hidden":!0},"›")),a.createElement("div",{ref:o,className:"ps-activity-run-viewport",role:"region","aria-label":`${d} activity log`,tabIndex:0,onScroll:f=>{f.stopPropagation(),l.current=_a(f.currentTarget)<=24},onWheel:f=>{f.stopPropagation(),f.deltaY<0&&(l.current=!1)},onTouchStart:f=>{f.stopPropagation(),l.current=!1},onTouchMove:f=>f.stopPropagation(),onTouchEnd:f=>f.stopPropagation()},t.map(f=>a.createElement(nv,{key:f.callKey,line:f}))),a.createElement("div",{className:"ps-activity-run-footer"},`Showing ${t.length} ${t.length===1?"entry":"entries"} · Scroll for earlier activity`))}function iv({line:t,theme:e}){const s=String(t?.canvasActionPayload||"").trim(),n=t?.canvasActionName||"action",r=String(t?.canvasActionDetail||"").trim(),i=String(t?.canvasActionTime||"").trim();return a.createElement("details",{className:"ps-system-notice ps-canvas-action"},a.createElement("summary",{className:"ps-system-notice-summary ps-canvas-action-summary",style:{color:Ue(e,"gray")||"var(--ps-muted)"}},a.createElement("span",{className:"ps-canvas-action-tag"},"canvas"),a.createElement("span",{className:"ps-system-notice-summary-text"},`${n}${r?` — ${r}`:""}`),i?a.createElement("span",{className:"ps-canvas-action-time"},i):null),s?a.createElement("div",{className:"ps-system-notice-body"},a.createElement("pre",{className:"ps-canvas-action-payload"},s)):null)}function av(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 st=a.memo(function({line:e,theme:s,className:n=""}){const r=n?`ps-line ${n}`:"ps-line";return e?e.kind==="systemNotice"?a.createElement(Su,{line:e,theme:s}):e.canvasAction?a.createElement(iv,{line:e,theme:s}):e.kind==="runs"?a.createElement("div",{className:r},a.createElement(Ye,{runs:e.runs,theme:s})):a.createElement("div",{className:r,style:{color:Ue(s,e.color),backgroundColor:Ue(s,e.backgroundColor),fontWeight:e.bold?700:400,textDecoration:e.underline?"underline":"none"}},e.text||" "):a.createElement("div",{className:r}," ")});function ot(t){return t?t.kind==="runs"?bu(t.runs):String(t.text||""):""}function vu(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)*wt);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)/wt})},[n,s,t])}const ov={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"},lv=new Set(["diff","patch","udiff"]),cv=/\.(patch|diff)$/i,$a=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,Ra=/\.(png|jpe?g|gif|webp|avif|bmp|svg|ico)$/i,dv={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 uv(t){const e=/\.([a-z0-9]+)$/i.exec(String(t||""));return e&&dv[e[1].toLowerCase()]||null}const pv={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 mv(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 fv=/\.(html?|xhtml)$/i;function wu(t,e){return fv.test(String(t||""))?!0:/^(text\/html|application\/xhtml\+xml)$/i.test(String(e||"").trim().split(";")[0])}const hv=/\.(csv|tsv)$/i;function Eu(t,e){return hv.test(String(t||""))?!0:/^text\/(csv|tab-separated-values)$/i.test(String(e||"").trim())}const Xr=2e3;function gv(t){const e=String(t??"");return/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function yv({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 w=!1;return n(null),lu(()=>import("./papaparse.min-LDhOsJ62.js").then(E=>E.p),[]).then(E=>{if(w)return;const k=E.default||E,x=/\.tsv$/i.test(String(e||""))?" ":"",T=k.parse(String(t||"").trim(),{delimiter:x,skipEmptyLines:"greedy"});n({rows:T.data||[],errors:T.errors||[]})}).catch(()=>{w||n({rows:null,errors:[{message:"parser unavailable"}]})}),()=>{w=!0}},[t,e]),a.useEffect(()=>{const w=()=>{o.current=null};return window.addEventListener("mouseup",w),()=>window.removeEventListener("mouseup",w)},[]);const l=a.useCallback((w,E)=>{if(!w||!E)return;const k=window.getSelection();if(!k)return;const x=!!(w.compareDocumentPosition(E)&Node.DOCUMENT_POSITION_PRECEDING),T=document.createRange();T.setStartBefore(x?E:w),T.setEndAfter(x?w:E),k.removeAllRanges(),k.addRange(T)},[]),c=w=>w.target?.closest?w.target.closest("td,th"):null,d=a.useCallback(w=>{if(w.button!==0)return;const E=c(w);E&&(w.preventDefault(),r.current?.focus(),o.current=E,l(E,E))},[l]),u=a.useCallback(w=>{if(!o.current||!(w.buttons&1))return;const E=c(w);E&&l(o.current,E)},[l]),p=a.useCallback(w=>{if(!(w.metaKey||w.ctrlKey)||w.altKey||w.key!=="a"&&w.key!=="A")return;const E=i.current,k=window.getSelection();if(!E||!k)return;w.preventDefault(),w.stopPropagation();const x=document.createRange();x.selectNodeContents(E),k.removeAllRanges(),k.addRange(x)},[]),m=a.useCallback(w=>{const E=i.current,k=window.getSelection();if(!E||!k||k.rangeCount===0)return;const x=k.getRangeAt(0),T=new Map;for(const A of E.querySelectorAll("th,td")){if(!x.intersectsNode(A))continue;const R=A.parentElement;T.has(R)||T.set(R,[]),T.get(R).push(gv(A.textContent))}T.size!==0&&(w.clipboardData.setData("text/plain",Array.from(T.values(),A=>A.join(" ")).join(`
|
|
99
|
-
`)),w.preventDefault())},[]);if(!s)return a.createElement("div",{className:"ps-csv-status"},"Parsing…");if(!s.rows||s.rows.length===0)return a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,String(t||"")));const[f,...h]=s.rows,g=h.reduce((w,E)=>Math.max(w,E.length),f.length),b=Array.from({length:g},(w,E)=>f[E]??""),y=h.length>Xr,S=y?h.slice(0,Xr):h,v=[];return y&&v.push(`showing first ${Xr} of ${h.length} rows`),s.errors.length&&v.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:u,onKeyDown:p,onCopy:m},a.createElement("table",{className:"ps-csv-table",ref:i},a.createElement("thead",null,a.createElement("tr",null,b.map((w,E)=>a.createElement("th",{key:`h${E}`},String(w??""))))),a.createElement("tbody",null,S.map((w,E)=>a.createElement("tr",{key:`r${E}`},b.map((k,x)=>a.createElement("td",{key:`c${x}`},String(w[x]??""))))))),v.length?a.createElement("div",{className:"ps-csv-status"},v.join(" · ")):null)}function La(t){const e=/\.([A-Za-z0-9]+)$/.exec(String(t||""));return e&&pv[e[1].toLowerCase()]||null}function Oa(t,e){return cv.test(String(t||""))?!0:/^text\/x-(patch|diff)$/i.test(String(e||"").trim())}function ku(t){const e=String(t??"");if(e.startsWith(wn))return e.slice(wn.length);const s=wn.trimStart();return e.startsWith(s)?e.slice(s.length):e}function Jn(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 Ri=a.createContext(null);function Iu(t){const e=String(t||""),s=(/\.([A-Za-z0-9]+)$/.exec(e)?.[1]||"").toLowerCase();return wu(e)?{kind:"page",type:"HTML",noun:"Page"}:Oa(e)?{kind:"diff",type:s.toUpperCase()||"DIFF",noun:"Diff"}:Ra.test(e)?{kind:"image",type:s.toUpperCase(),noun:"Image"}:Eu(e)?{kind:"table",type:s.toUpperCase(),noun:"Table"}:/\.md$/i.test(e)?{kind:"doc",type:"MD",noun:"Document"}:La(e)?{kind:"code",type:s.toUpperCase(),noun:"Code"}:{kind:"file",type:s.toUpperCase()||"FILE",noun:"File"}}function xu(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 bv({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 Au({artifactRef:t}){const e=a.useContext(Ri),s=Iu(t.filename),n=a.useCallback(r=>{r.preventDefault(),r.stopPropagation(),Sv(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(bv,{kind:s.kind})),a.createElement("span",{className:"ps-artifact-card-text"},a.createElement("span",{className:"ps-artifact-card-title"},xu(t.filename)),a.createElement("span",{className:"ps-artifact-card-meta"},`${s.noun} · ${s.type}`)),a.createElement("span",{className:"ps-artifact-card-open"},"Open"))}function Sv(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 Nu(t){return lv.has(String(t||"").trim().toLowerCase())}const vv=/^(?: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 wv(t){return vv.test(t)?"meta":t.startsWith("@@")?"hunk":t.startsWith("+")?"add":t.startsWith("-")?"del":"context"}const Ev={add:"green",del:"red",hunk:"cyan",meta:"gray"};function Fa(t,e){return String(t||"").replace(/\n$/,"").split(`
|
|
100
|
-
`).map((n,r)=>{const i=wv(n),o=Ev[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:Ue(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 Cu(t){return String(t||"").trim().toLowerCase()==="mermaid"}const Bl={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 kv(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 Iv={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},xv=2e4,qt=new Map,Av=120;function Nv(t,e){const s=`${e||""}\0${t}`,n=qt.get(s);if(n)return qt.delete(s),qt.set(s,n),n;const r=Cv(t,e);return qt.set(s,r),qt.size>Av&&qt.delete(qt.keys().next().value),r}function Cv(t,e){const s=ov[String(e||"").trim().toLowerCase()]||"default",n=Bl[s]||Bl.js,r=kv(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 p of r){p.re.lastIndex=o;const m=p.re.exec(t);if(m&&m.index===o&&m[0].length>0){d={type:p.type,text:m[0]};break}}if(!d){o+=1;continue}let u=d.type;if(u==="identifier")if(n.has(d.text))u="keyword";else{const p=t.slice(o+d.text.length);u=/^\s*\(/.test(p)?"fn":"plain"}if(u==="plain"){o+=d.text.length;continue}c(o),i.push({type:u,text:d.text}),o+=d.text.length,l=o}return c(t.length),i}function $s(t,e,s){const n=String(t||"");if(!n||n.length>xv)return n;let r;try{r=Nv(n,e)}catch{return n}return r.map((i,o)=>{const l=Iv[i.type];return l?a.createElement("span",{key:`t:${o}`,className:`ps-code-token is-${i.type}`,style:{color:Ue(s,l)||void 0}},i.text):a.createElement(a.Fragment,{key:`t:${o}`},i.text)})}let vn=null;function Tv(){return vn||(vn=lu(()=>import("./mermaid.core-BEG_GOf7.js").then(t=>t.bp),[]).then(t=>t.default||t).catch(t=>{throw vn=null,t})),vn}function Pv(t,e){return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"default":"dark",fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"}),t}let Hl=0,Ul=Promise.resolve();function Mv(t){const e=Ul.then(t,t);return Ul=e.then(()=>{},()=>{}),e}function Tu({code:t,theme:e,fallback:s}){const[n,r]=a.useState(null),[i,o]=a.useState(!1),[l,c]=a.useState(""),d=a.useMemo(()=>zm(e),[e]);return a.useEffect(()=>{let u=!0;const p=String(t||"").trim();if(p)return o(!1),Tv().then(m=>Mv(async()=>{if(!u)return;Pv(m,d),Hl+=1;const f=`ps-mermaid-${Hl}`;await m.parse(p);const{svg:h}=await m.render(f,p);u&&r(h)})).catch(m=>{u&&(r(null),o(!0),c(String(m?.message||m)))}),()=>{u=!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(`
|
|
101
|
-
`)[0]}`),s):s}function Et(t,e,s="md"){const n=qi(t);return n.map((r,i)=>{const o=`${s}:${i}`;if(i>0&&n[i-1]?.type==="link"&&Jn(n[i-1]?.href)){const l=ku(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"},Et(r.text,e,`${o}:strong`));if(r.type==="em")return a.createElement("em",{key:o,className:"ps-md-em"},Et(r.text,e,`${o}:em`));if(r.type==="link"){const l=Jn(r.href);return l?a.createElement(Au,{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:Ue(e,"cyan")}},r.text):a.createElement("span",{key:o,style:{color:Ue(e,"cyan")}},r.text)}return a.createElement(a.Fragment,{key:o},r.text)})}function Pu(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(i=>_i(i?.[n]||"")).filter(Boolean).join(" / ")||null)}function jl(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 Gl(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function _v(t=""){const s=String(t||"").replace(/\r\n?/g,`
|
|
102
|
-
`).split(`
|
|
103
|
-
`),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 p=l[1]||"",m=[];for(r+=1;r<s.length&&!/^```/.test(s[r].trim());)m.push(s[r]),r+=1;r<s.length&&(r+=1),n.push({type:"code",language:p,content:m.join(`
|
|
104
|
-
`)});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 p=Gl(i);r+=2;const m=[];for(;r<s.length&&s[r].includes("|")&&s[r].trim();)m.push(Gl(s[r])),r+=1;n.push({type:"table",header:p,rows:m});continue}if(/^\s*>/.test(i)){const p=[];for(;r<s.length&&/^\s*>/.test(s[r]);)p.push(s[r].replace(/^\s*>\s?/,"")),r+=1;n.push({type:"blockquote",text:p.join(`
|
|
105
|
-
`).trim()});continue}const d=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(i);if(d){const p=/\d+\./.test(d[2]),m=[];for(;r<s.length;){const f=s[r],h=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(f);if(!h||/\d+\./.test(h[2])!==p)break;const g=[h[3].trim()];for(r+=1;r<s.length&&s[r].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[r])&&!jl(s[r],s[r+1]||"");)g.push(s[r].trim()),r+=1;if(m.push(g.join(" ")),!s[r]?.trim())break}n.push({type:"list",ordered:p,items:m});continue}const u=[i.trim()];for(r+=1;r<s.length&&s[r].trim()&&!jl(s[r],s[r+1]||"");)u.push(s[r].trim()),r+=1;n.push({type:"paragraph",text:u.join(" ")})}return n}function Da({content:t,theme:e}){const s=a.useMemo(()=>_v(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}`},Et(n.text,e,`heading:${r}`));if(n.type==="code"){const i=Nu(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?Fa(n.content,e):$s(n.content,n.language,e))));return Cu(n.language)?a.createElement(Tu,{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"},Et(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"},Et(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?ou([n.header,...n.rows]):null,c=!!l,d=l?l.flexIndex:-1,u=h=>h===d?"is-flex-column":null,p=Pu([n.header],i),m=`ps-md-table${o?" is-fit-width":""}${c?" has-flex-column":""}`,f=`ps-md-table-wrap${o?" is-fit-width":""}${c?" has-flex-column":""}`;return a.createElement("div",{key:`block:${r}`,className:f},a.createElement("table",{className:m,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:u(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:u(g)||void 0},Et(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:u(y)||void 0,"data-label":p[y]||void 0},a.createElement("span",{className:"ps-table-cell-value"},Et(b,e,`table:${r}:${g}:${y}`)))))))))}return a.createElement("p",{key:`block:${r}`,className:"ps-md-paragraph"},Et(n.text,e,`para:${r}`))}))}function Qr({controller:t,title:e,color:s,focused:n,scrollOffset:r=0,paneKey:i,theme:o,className:l="",focusRegion:c=null,children:d}){const u=a.useRef(null),p=vu(u,r,i,t),m=a.useCallback(()=>{const f=Ba(i,c);f&&t?.setFocus&&t.setFocus(f)},[t,i,c]);return a.createElement(Ut,{title:e,color:s,focused:n,theme:o},a.createElement("div",{ref:u,className:`ps-scroll-panel is-preview ${l}`.trim(),onScroll:p,onMouseDown:m},d))}function $v({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 m=Ba(i,c);m&&t?.setFocus&&t.setFocus(m)},[t,i,c]),u=a.useRef(null),p=vu(u,r,i,t);return a.createElement(Ut,{title:e,color:s,focused:n,theme:o},a.createElement("div",{ref:u,className:"ps-scroll-panel ps-markdown-scroll",onScroll:p,onMouseDown:d},a.createElement(Da,{content:l,theme:o})))}function Mu(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 Wl({title:t,color:e,focused:s,theme:n,filename:r,contentType:i,sizeBytes:o,source:l,uploadedAt:c,controller:d=null,sessionId:u=null}){const p=[];i&&p.push(i),o!=null&&p.push(Mu(o)),l&&p.push(l);const m=c?new Date(c).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"",f=$a.test(String(i||""))||Ra.test(String(r||"")),[h,g]=a.useState(null);return a.useEffect(()=>{if(g(null),!f||!d||!u||!r)return;let b=!1;return Du(d,u,r).then(y=>{b||g(y)}).catch(()=>{b||g("error")}),()=>{b=!0}},[f,d,u,r]),a.createElement(Ut,{title:t,color:e,focused:s,theme:n},a.createElement("div",{className:"ps-binary-preview-card"},a.createElement("div",{className:"ps-binary-preview-kicker"},f?"Image artifact":"Binary artifact"),a.createElement("h3",{className:"ps-binary-preview-title"},r||"Artifact"),p.length>0?a.createElement("div",{className:"ps-binary-preview-meta"},p.join(" • ")):null,m?a.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${m}`):null,f&&h&&h!=="error"?a.createElement("img",{className:"ps-binary-preview-image",src:h,alt:r||"artifact image",onClick:()=>{const b=dr(u,r);if(b)try{window.open(b,"_blank","noopener")}catch{}}}):a.createElement("p",{className:"ps-binary-preview-copy"},f?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 Rv=260,Lv=28;function Ov(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 u=a.useRef(!0);a.useEffect(()=>{if(u.current){u.current=!1;return}e&&(c.current=null,d.current+=1,l(d.current))},[n,e]),a.useEffect(()=>{const m=t.current;if(!e||!m||typeof ResizeObserver>"u")return;let f=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)<Lv||(f&&clearTimeout(f),f=setTimeout(()=>{f=null,c.current=Math.round(m.getBoundingClientRect().width)||b,d.current+=1,l(d.current)},Rv))}});return h.observe(m),()=>{f&&clearTimeout(f),h.disconnect()}},[t,e]);const p=a.useCallback(m=>{const f=()=>{l(h=>h===m?null:h),i(h=>h===m?h:m)};if(typeof requestAnimationFrame!="function"){f();return}requestAnimationFrame(()=>requestAnimationFrame(f))},[]);return{live:r,pending:o,promote:p}}const Zr=1024;function _u({fitWidth:t,setFitWidth:e}){return a.createElement(ve,{icon:t?"1:1":"⤢",label:t?"Actual size":"Fit page to width",active:t,onClick:()=>e(!t)})}const zt=[.5,.67,.8,.9,1,1.1,1.25,1.5,1.75,2,2.5,3];function er({zoom:t,setZoom:e}){const s=n=>{const r=zt.findIndex(l=>Math.abs(l-t)<.005),i=r===-1?zt.indexOf(1):r,o=zt[Math.min(zt.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<=zt[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>=zt[zt.length-1]-.001,title:"Zoom in (artifact only)","aria-label":"Zoom in"},"+"))}function $u({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 Ru(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 Lu(t,e,s,n=!1){const r=t?.transport?.api?.downloadArtifactResponse;return typeof r!="function"?Promise.reject(new Error("artifact download unavailable")):r.call(t.transport.api,e,s).then(async i=>{if(!i?.ok)throw new Error(`download failed (${i?.status})`);const o=await i.arrayBuffer(),l=n?"<script>window.addEventListener('keydown',function(e){if(e.isTrusted&&!e.altKey&&!e.metaKey&&!e.ctrlKey&&(e.key==='Tab'||e.key==='Escape')){e.preventDefault();e.stopImmediatePropagation();parent.postMessage({type:'moa-panel-key',key:e.key,backwards:e.shiftKey},'*')}},true);<\/script>":"";let c=[o];if(n){const d=new TextDecoder().decode(o),u=/^(?:\uFEFF|\s|<!--[\s\S]*?-->)*<!doctype[^>]*>/i.exec(d)?.[0]||"";c=[d.slice(0,u.length),l,d.slice(u.length)]}return URL.createObjectURL(new Blob(c,{type:"text/html;charset=utf-8"}))})}function Fv({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 u=se(t,I=>I.files.htmlViewMode||"rendered"),p=a.useCallback(I=>{t.dispatch({type:"files/htmlViewMode",mode:I})},[t]),[m,f]=a.useState(null),[h,g]=a.useState(null),b=a.useRef(null),y=se(t,I=>!!I.files.htmlFitWidth),S=a.useCallback(I=>{t.dispatch({type:"files/htmlFitWidth",enabled:I})},[t]),v=Ru(b),w=y&&v.width>0&&v.width<Zr?v.width/Zr:1,E=w<1,k=se(t,I=>Number(I.files.htmlZoom)||1),x=a.useCallback(I=>{t.dispatch({type:"files/htmlZoom",zoom:I})},[t]),T=E?w*k:k,A=Ov(b,u==="rendered"&&!E,`${e}/${s}`,k);a.useEffect(()=>{if(f(null),g(null),u!=="rendered"||!t||!e||!s)return;let I=!1,O=null;return Lu(t,e,s).then(M=>{if(O=M,I){URL.revokeObjectURL(M);return}f(M)}).catch(M=>{I||g(M?.message||String(M))}),()=>{I=!0,O&&URL.revokeObjectURL(O)}},[t,e,s,u]);const R=dr(e,s),N=d?null:a.createElement(a.Fragment,null,a.createElement($u,{mode:u,setMode:p}),u==="rendered"?a.createElement(_u,{fitWidth:y,setFitWidth:S}):null,u==="rendered"?a.createElement(er,{zoom:k,setZoom:x}):null,R?a.createElement(ve,{icon:"↗",label:"Open in a new tab",onClick:()=>{try{window.open(R,"_blank","noopener")}catch{}}}):null),$=u==="source"?a.createElement(Dv,{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.")):m?[A.live,A.pending].filter((I,O,M)=>I!==null&&M.indexOf(I)===O).map(I=>a.createElement("iframe",{key:`frame:${I}`,className:`ps-html-preview-frame${I===A.live?"":" is-staging"}`,style:E?{flex:"none",width:`${Zr}px`,height:`${Math.max(1,Math.round(v.height/T))}px`,transform:`scale(${T})`,transformOrigin:"top left"}:k!==1&&v.width>0?{flex:"none",width:`${Math.max(1,Math.round(v.width/k))}px`,height:`${Math.max(1,Math.round(v.height/k))}px`,transform:`scale(${k})`,transformOrigin:"top left"}:void 0,src:m,title:s||"HTML artifact",sandbox:"allow-scripts allow-popups allow-popups-to-escape-sandbox",allow:"autoplay *",referrerPolicy:"no-referrer",onLoad:()=>A.promote(I)})):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,Mu(r)].filter(Boolean).join(" • ")):null),F=u==="rendered"?a.createElement("div",{ref:b,className:`ps-html-preview-host${E||k!==1?" is-fitting":""}`},$):$;return a.createElement(Ut,{title:c,color:o,focused:l,theme:i,actions:N,className:"ps-html-preview"},F)}function Dv({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 u=>{if(!u?.ok)throw new Error(`download failed (${u?.status})`);return u.text()}).then(u=>{d||i(u)}).catch(u=>{d||l(u?.message||String(u))}),()=>{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,$s(r,"html",n))))}function Mn(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function Jr(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function Bv(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function Qs(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function Hv(t){const e=String(ot(t)||"").trim();return Mn(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function Uv(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=ot(t);return Qs(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function jv(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 ql(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?jv(t.runs.slice(1,-1)):[{text:ot(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function Gv(t){const e=String(t||"").trim();return Qs(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function Wv(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 qv(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)=>Wv(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function zl(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>qv(t.map(r=>String(r[n]||"").trim()).filter(Boolean)))}function Ou(t=[]){const e=[];for(let s=0;s<t.length;){const n=t[s];if(n?.kind==="nativeTasks"){e.push({type:"nativeTasks",group:n.group}),s+=1;continue}if(n?.kind==="chatCall"||n?.callPreview!==void 0){const i=[];for(;s<t.length;){const o=t[s];if(o?.kind!=="chatCall"&&o?.callPreview===void 0)break;i.push(o.callPreview!==void 0?{...o,text:o.callPreview,category:"Agent"}:o),s+=1}e.push({type:"chatCallGroup",groupKey:i[0]?.callKey,calls:i});continue}if(n?.kind==="assistantPreview"){e.push({type:"assistantPreview",line:n}),s+=1;continue}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&&ot(t[s]).trim().length===0&&(s+=1),e.push({type:"card",cardKey:n.cardKey||null,headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:Ou(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=ot(n);if(Mn(r)&&r.includes("┬")){const i=[],o=[];let l=[],c=!0;for(s+=1;s<t.length;){const d=t[s],u=ot(d);if(Jr(u)){if(l.length>0){const p=zl(l);p.length>0&&(c?i.push(p):o.push(p))}s+=1;break}if(Bv(u)){if(l.length>0){const p=zl(l);p.length>0&&(c?i.push(p):o.push(p))}l=[],c=!1,s+=1;continue}if(Qs(u)){const p=Gv(u);p.length>0&&l.push(p)}s+=1}e.push({type:"table",headerRows:i,bodyRows:o});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&Mn(r)){const i=Hv(n),o=[];for(s+=1;s<t.length;){const l=t[s],c=ot(l);if(Jr(c)){s+=1;break}Qs(c)?o.push(Uv(l)):o.push(ot(l)),s+=1}s<t.length&&ot(t[s]).trim().length===0&&(s+=1),e.push({type:"code",language:i||"text",content:o.join(`
|
|
106
|
-
`)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&Mn(r)){const i=ql(n),o=n.runs[0]?.color||"gray",l=[];for(s+=1;s<t.length;){const c=t[s],d=ot(c);if(Jr(d)){s+=1;break}Qs(d)?l.push(ql(c)):l.push(c?.kind==="runs"?c.runs:[{text:ot(c),color:c?.color||null}]),s+=1}s<t.length&&ot(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 Fu({lines:t,theme:e,controller:s=null}){const n=a.useMemo(()=>Ou((t||[]).filter(r=>!r?.canvasUpdate)),[t]);return a.createElement(Bu,{blocks:n,theme:e,controller:s})}const xt=new Map,zv=60;function Du(t,e,s){const n=`${e}/${s}`,r=xt.get(n);if(r)return xt.delete(n),xt.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=uv(s),u=d&&!$a.test(c.type)?new Blob([c],{type:d}):c;return URL.createObjectURL(u)}).catch(l=>{throw xt.get(n)===o&&xt.delete(n),l});for(xt.set(n,o);xt.size>zv;){const[l,c]=xt.entries().next().value;xt.delete(l),Promise.resolve(c).then(d=>URL.revokeObjectURL(d)).catch(()=>{})}return o}function Kv({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&&Du(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"?"⚠":"🖼")}))}const Vv=a.memo(function({content:e,width:s,theme:n,controller:r}){const i=a.useMemo(()=>Je(ss(e,{width:s,tableMode:"sentinel"})),[e,s]);return a.createElement(Fu,{lines:i,theme:n,controller:r})}),Yv=a.memo(function({line:e,theme:s,controller:n}){const[r,i]=a.useState(!1),[o,l]=a.useState(!e.liveStartedAt||Date.now()-e.liveStartedAt>=200),c=a.useRef(null),d=a.useRef(null),u=a.useRef(!0),p=a.useRef(null),m=r||e.final;m&&(p.current=e);const f=p.current;return a.useEffect(()=>{if(e.final||o)return;const h=setTimeout(()=>l(!0),Math.max(0,Math.min(200,200-(Date.now()-e.liveStartedAt))));return()=>clearTimeout(h)},[e.final,e.liveStartedAt,o]),a.useLayoutEffect(()=>{if(!m||e.final)return;const h=()=>{const b=c.current;b&&e.isLive&&u.current&&(b.scrollTop=b.scrollHeight)};h();const g=new ResizeObserver(h);return d.current&&g.observe(d.current),()=>g.disconnect()},[m,e.final,e.isLive,f]),!e.final&&!o?null:a.createElement("details",{className:`ps-system-notice ps-assistant-preview${e.final?" is-final":""}`,open:m,onToggle:h=>{h.target===h.currentTarget&&!e.final&&i(h.currentTarget.open)}},a.createElement("summary",{className:"ps-system-notice-summary ps-canvas-action-summary",tabIndex:e.final?-1:void 0,onClick:h=>{e.final&&h.preventDefault()}},e.final?a.createElement(Ye,{runs:e.headerRuns,theme:s}):a.createElement(a.Fragment,null,a.createElement("span",{className:"ps-canvas-action-tag"},"Agent"),a.createElement("span",{className:"ps-system-notice-summary-text"},e.text),e.statusText?a.createElement("span",{className:"ps-preview-status"},e.statusText):null)),a.createElement("div",{ref:c,className:"ps-assistant-preview-viewport",tabIndex:m&&!e.final?0:void 0,role:e.final?void 0:"region","aria-label":e.final?void 0:e.text,onScroll:h=>{e.final||(h.stopPropagation(),u.current=_a(h.currentTarget)<=24)},onWheel:h=>{e.final||(h.stopPropagation(),h.deltaY<0&&(u.current=!1))},onTouchStart:h=>{e.final||(h.stopPropagation(),u.current=!1)},onTouchMove:h=>{e.final||h.stopPropagation()},onTouchEnd:h=>{e.final||h.stopPropagation()},onKeyDown:h=>{!e.final&&["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(h.key)&&(h.stopPropagation(),["ArrowUp","PageUp","Home"].includes(h.key)&&(u.current=!1))}},a.createElement("div",{ref:d,className:"ps-assistant-preview-content"},f?.reasoningText?a.createElement(Su,{key:"reasoning",line:{text:e.isLive?"Thinking":"Thought",body:f.reasoningText,streamReasoning:!0},theme:s}):null,f?.body?a.createElement(Vv,{key:"message",content:f.body,width:f.width,theme:s,controller:n}):null,f?.truncated&&e.isLive?a.createElement("div",{className:"ps-preview-status"},"Preview paused — the full answer will appear when complete."):null)))});function Bu({blocks:t,theme:e,controller:s=null}){return a.createElement(a.Fragment,null,(t||[]).map((n,r)=>{if(n.type==="nativeTasks")return a.createElement(wS,{key:n.group.id,group:n.group,colors:{starting:Ue(e,"cyan"),running:Ue(e,"cyan"),waiting:Ue(e,"yellow"),completed:Ue(e,"green"),failed:Ue(e,"red"),cancelled:Ue(e,"gray"),interrupted:Ue(e,"yellow")}});if(n.type==="chatCallGroup")return a.createElement(rv,{key:n.groupKey,calls:n.calls});if(n.type==="assistantPreview")return a.createElement(Yv,{key:n.line.previewKey,line:n.line,theme:e,controller:s});if(n.type==="imageAttachments")return a.createElement(Kv,{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(st,{key:`preserve:${r}:${l}`,line:o,theme:e,className:"ps-line-preserve"})))}if(n.type==="code"){const i=Nu(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?Fa(n.content||"",e):$s(n.content||"",n.language,e))));return Cu(n.language)?a.createElement(Tu,{key:`code:${r}`,code:n.content||"",theme:e,fallback:o}):o}if(n.type==="card")return a.createElement("section",{key:`card:${n.cardKey||r}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":Ue(e,n.borderColor)||"var(--ps-border)"}},a.createElement("header",{className:"ps-chat-card-header"},a.createElement(Ye,{runs:n.headerRuns,theme:e})),a.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?a.createElement(Bu,{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(Ye,{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?ou([...i,...o]):null,u=!!d,p=d?d.flexIndex:-1,m=b=>b===p?"is-flex-column":null,f=Pu(i,l),h=`ps-chat-table${c?" is-fit-width":""}${u?" has-flex-column":""}`,g=`ps-chat-table-wrap${c?" is-fit-width":""}${u?" has-flex-column":""}`;return a.createElement("div",{key:`table:${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:m(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},(S,v)=>a.createElement("th",{key:`th:${y}:${v}`,className:m(v)||void 0},Et(b[v]||"",e,`chat-table:${r}:head:${y}:${v}`)))))):null,a.createElement("tbody",null,o.map((b,y)=>a.createElement("tr",{key:`tbody:${y}`},Array.from({length:l},(S,v)=>a.createElement("td",{key:`td:${y}:${v}`,className:m(v)||void 0,"data-label":f[v]||void 0},a.createElement("span",{className:"ps-table-cell-value"},Et(b[v]||"",e,`chat-table:${r}:${y}:${v}`)))))))))}return a.createElement(st,{key:`line:${r}`,line:n.line,theme:e})}))}function Ut({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:r=null,children:i,theme:o,className:l=""}){const c=Ue(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(Ye,{runs:t,theme:o}):Ll(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(Ye,{runs:e,theme:o}):Ll(e)):null,r?a.createElement("div",{className:"ps-panel-actions"},r):null):null):null,a.createElement("div",{className:"ps-panel-body"},i))}function Xv({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(Ye,{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 Qv({lines:t,theme:e,completionByTurn:s}){const[n,r]=a.useState(()=>new Set),i=a.useCallback(u=>{r(p=>{const m=new Set(p);return m.has(u)?m.delete(u):m.add(u),m})},[]),o=u=>Number(u||0).toLocaleString("en-US"),l=u=>{const p=Number(u||0);if(!Number.isFinite(p))return"?K";const m=p/1e3,f=Math.abs(m)>=10?1:2;return`${m.toFixed(f)}K`},c=u=>{const p=Number(u||0);return Number.isFinite(p)?`${(p/1e3).toFixed(1)}s`:"?s"},d=u=>{const p=String(u||"").trim();if(!p)return"unknown";const m=p.split(":").filter(Boolean),f=m[m.length-1]||"",h=m.length>1&&TS.has(f.toLowerCase())?m.length-2:m.length-1;return m[Math.max(0,h)]||m[0]||"unknown"};return a.createElement(a.Fragment,null,t.map((u,p)=>{const m=u?.kind==="runs"&&Array.isArray(u.runs)?u.runs.find(x=>x?.completedTurn!=null)?.completedTurn:null,f=m!=null?s.get(Number(m)):null;if(!f)return a.createElement(st,{key:`line:${p}`,line:u,theme:e});const h=f.data||{},g=String(f.seq??`${h.turnIndex??m}:${f.createdAt??p}`),b=n.has(g),y=h.reasoningEffort?`${h.model||"(unknown)"}:${h.reasoningEffort}`:h.model||"(unknown)",S=d(h.model),v=h.durationMs!=null?c(h.durationMs):"duration n/a",w=h.durationMs!=null?`${o(h.durationMs)} ms`:"duration n/a",E=`${l(h.tokensInput)} / ${l(h.tokensOutput)}`,k=[["model",y],["started",h.startedAt?new Date(h.startedAt).toLocaleString():null],["ended",h.endedAt?new Date(h.endedAt).toLocaleString():null],["duration",w],["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(([,x])=>x!=null&&x!=="");return a.createElement(a.Fragment,{key:`seq:${p}`},a.createElement(st,{line:u,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"},S),a.createElement("span",{className:"ps-sequence-turn-rule"}," ("),a.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),a.createElement("span",{className:"ps-sequence-turn-tokens"},E),a.createElement("span",{className:"ps-sequence-turn-rule"},", "),a.createElement("span",{className:"ps-sequence-turn-key"},"dur: "),a.createElement("span",{className:"ps-sequence-turn-duration"},v),a.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),b?a.createElement("div",{className:"ps-sequence-turn-details"},k.map(([x,T])=>a.createElement("div",{key:x},a.createElement("span",{className:"ps-sequence-turn-detail-label"},`${x}: `),a.createElement("span",null,String(T))))):null)}))}const Zv={chat:"chat",activity:"activity",inspector:"inspector",filePreview:"inspector"};function Ba(t,e=null){return e||Zv[String(t||"")]||null}function fr({title:t,titleRight:e=null,color:s,focused:n,actions:r,lines:i,stickyLines:o=[],bottomStickyLines:l=[],reserveBottomSticky:c=!1,scrollOffset:d=0,scrollMode:u="top",paneKey:p,controller:m,className:f="",panelClassName:h="",topContent:g=null,bottomContent:b=null,structuredBlocks:y=!1,stickyBottom:S=!1,renderBody:v=null,focusRegion:w=null,panelRef:E=null,ariaLive:k=null}){const x=se(m,Z=>Z.ui.themeId),T=kt(x),A=a.useRef(null),R=a.useCallback(Z=>{A.current=Z,typeof E=="function"?E(Z):E&&(E.current=Z)},[E]),N=a.useRef(null),$=a.useRef(!1),{normalizedLines:F,onScroll:I,onWheel:O,onTouchStart:M,onTouchMove:B,onTouchEnd:D}=sv(A,i,d,u,p,m,{stickyBottom:S}),j=a.useMemo(()=>Je(o),[o]),V=a.useMemo(()=>Je(l),[l]),C=f.includes("is-preserve")&&h.includes("has-preserved-sticky"),U=`${p}:${t}`;a.useEffect(()=>{const Z=()=>{A.current&&(A.current.scrollLeft=0),N.current&&(N.current.scrollLeft=0)};Z();const le=typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{Z()}):null;return()=>{le!=null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(le)}},[U]);const H=a.useCallback(()=>{const Z=Ba(p,w);Z&&m?.setFocus&&m.setFocus(Z)},[m,p,w]),Y=a.useCallback((Z,le)=>{!Z||!le||Math.abs((le.scrollLeft||0)-(Z.scrollLeft||0))<=1||($.current=!0,le.scrollLeft=Z.scrollLeft,window.requestAnimationFrame(()=>{$.current=!1}))},[]),[te,ee]=a.useState({up:!1,down:!1}),J=a.useCallback(Z=>{if(!Z)return;const le=Z.scrollHeight-Z.scrollTop-Z.clientHeight>4,$e=Z.scrollTop>4;ee(be=>be.up===le&&be.down===$e?be:{up:le,down:$e})},[]),ae=a.useCallback(Z=>{I(),J(Z.currentTarget),!(!C||$.current)&&Y(Z.currentTarget,N.current)},[I,C,Y,J]);a.useEffect(()=>{J(A.current)},[J,F,V,j]),a.useEffect(()=>{const Z=A.current;if(!Z||typeof ResizeObserver>"u")return;const le=new ResizeObserver(()=>J(Z));return le.observe(Z),()=>le.disconnect()},[J,A]);const de=a.useCallback(Z=>{!C||$.current||Y(Z.currentTarget,A.current)},[C,Y]);return a.createElement(Ut,{title:t,titleRight:e,color:s,focused:n,actions:r,theme:T,className:h},g,j.length>0?a.createElement("div",{ref:N,className:`ps-panel-sticky${C?" is-scroll-sync":""}`,onScroll:de},j.map((Z,le)=>a.createElement(st,{key:`sticky:${le}`,line:Z,theme:T}))):null,a.createElement("div",{ref:R,className:`ps-scroll-panel ${f}${te.down?" is-scrolled-down":""}${te.up?" is-scrolled-up":""}`.trim(),"data-session-scroll":w==="sessions"?"1":void 0,"aria-live":k||void 0,"aria-atomic":k?"false":void 0,onScroll:ae,onMouseDown:H,onTouchStart:M,onWheel:O,onTouchMove:B,onTouchEnd:D,onTouchCancel:D},typeof v=="function"?v(F,T):y?a.createElement(Fu,{lines:F,theme:T,controller:m}):F.map((Z,le)=>a.createElement(st,{key:`line:${le}`,line:Z,theme:T}))),V.length>0||c?a.createElement("div",{className:`ps-panel-bottom-sticky${c?" is-reserved":""}`},V.map((Z,le)=>a.createElement(st,{key:`bottom-sticky:${le}`,line:Z,theme:T}))):null,b)}const ei="—";function Jv(t,e){const s=typeof t?.waitReason=="string"&&t.waitReason.trim()?sw(t.waitReason):null;if(!s)return null;const n=String(e||"");return n==="waiting"||n.startsWith("waiting on")||n==="input_required"?s:null}const ew=10,tw=72;function sw(t,e=ew,s=tw){const n=String(t??"").replace(/\s+/gu," ").trim();if(!n)return"";let i=n.split(" ").slice(0,e).join(" ");if(i.length>s){const o=i.slice(0,s),l=o.lastIndexOf(" ");i=l>0?o.slice(0,l):o}return i===n?n:`${i.replace(/[.,;:—-]+$/u,"")}…`}function nw(t){return t?.cronActive===!0?"On wake":"Waiting"}function rw({session:t,childCount:e=0,pause:s=null,controller:n=null,collapsed:r=!1,onToggle:i=null,onOpenBudget:o=null}){const l=(v,w,E="")=>{const k=w==null||w===""?ei:String(w),x=k===ei;return a.createElement("div",{className:`ps-session-detail-field${E?` ${E}`:""}${x?" is-none":""}`,key:v},a.createElement("span",{className:"ps-session-detail-label"},v),a.createElement("span",{className:"ps-session-detail-value",title:k},k))},c=t?.contextUsage,d=c&&Number.isFinite(c.currentTokens)&&Number.isFinite(c.tokenLimit)&&c.tokenLimit>0,u=d?Math.round(c.currentTokens/c.tokenLimit*100):null,p=d?`${ne(c.currentTokens)} / ${ne(c.tokenLimit)} · ${u}%`:null;let m=null;t&&!t.isGroup&&(m="off",t.cronActive===!0&&(m=t.cronKind==="wall-clock"?`next ${Wn(t.cronNextFireAt)}`:typeof t.cronInterval=="number"?`every ${Zt(t.cronInterval)}`:"on"));const f=t?.model?t.reasoningEffort&&!String(t.model).includes(String(t.reasoningEffort))?`${t.model}:${t.reasoningEffort}`:t.model:null,h=t?t.visibility==="shared_write"?"shared · write":t.visibility==="shared_read"?"shared · read":"private":null,g=t?.isGroup?t.memberCount==null?null:String(t.memberCount):e>0?String(e):null,b=Hf(t),y=Jv(t,b?.status),S=!s&&!y?null:a.createElement("div",{className:`ps-session-detail-pause${s?" is-paused":""}`},a.createElement("span",{className:"ps-session-detail-label"},s?"Paused":nw(t)),a.createElement("span",{className:"ps-session-detail-why",...!s&&typeof t?.waitReason=="string"&&t.waitReason.trim()?{title:t.waitReason.trim()}:{}},s?s.reason:y,s&&s.clears?a.createElement("span",{className:"ps-session-detail-clears"},s.clears):null,s&&(n||o)?a.createElement("button",{type:"button",className:"ps-budget-link",title:s.provider?`Open ${s.provider} in Providers & Budgets`:"Open providers and budgets",onClick:()=>(o||(v=>n.openBudget(v)))(s.provider?{provider:s.provider}:{}).catch(()=>{})},s.provider?`Open ${s.provider}`:"Open providers and budgets"):null));if(r){const v=[];return p&&v.push(a.createElement("span",{key:"context",className:`ps-session-detail-mark${u!=null&&u>=85?" is-hot":u!=null&&u>=70?" is-warm":""}`},u!=null?`${u}%`:p)),b&&v.push(a.createElement("span",{key:"updated",className:"ps-session-detail-mark"},`${b.relative} (${b.status})`)),(s||y)&&v.push(a.createElement("span",{key:"halt",className:`ps-session-detail-mark${s?" is-paused":""}`,title:s?s.reason:y},s?"paused":"waiting")),a.createElement("div",{className:"ps-session-detail-box is-collapsed"},a.createElement("button",{type:"button",className:"ps-session-detail-summary","aria-expanded":!1,title:"Show session details",onClick:i},a.createElement("span",{className:"ps-session-detail-twisty","aria-hidden":"true"},"▸"),a.createElement("span",{className:"ps-session-detail-summary-title"},t?.title||ei),a.createElement("span",{className:"ps-session-detail-marks"},v)),S)}return a.createElement("div",{className:"ps-session-detail-box"},a.createElement("button",{type:"button",className:"ps-session-detail-collapse","aria-expanded":!0,title:"Hide session details",onClick:i},a.createElement("span",{"aria-hidden":"true"},"▾")," Less"),l("Title",t?.title,"is-title"),l("ID",t?.sessionId,"is-id"),l("Owner",t?.owner?N0(t.owner):null),l("Model",f),l("Context",p,u!=null&&u>=85?"is-hot":u!=null&&u>=70?"is-warm":""),l("Cron",m,t?.cronActive===!0?"is-armed":""),l("Agent",t?.agentId),l("Updated",b?`${b.relative} (${b.status})`:null),l("Children",g),l("Access",h),S)}function iw(){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 Hu=13,Uu=11,ju=1.5,aw=7;function ow(t){return Hu+(t-1)*Uu+ju/2-aw/2}const lw=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 S=Array.from({length:c},(v,w)=>w);return{backgroundImage:S.map(()=>"linear-gradient(var(--ps-rail), var(--ps-rail))").join(", "),backgroundSize:S.map(()=>`${ju}px 100%`).join(", "),backgroundPosition:S.map(v=>`${Hu+v*Uu}px 0`).join(", "),backgroundRepeat:"no-repeat"}},[c]),u=a.useCallback(S=>o(e.sessionId,S),[o,e.sessionId]),p=a.useCallback(S=>i(S,e),[i,e]),m=e.groupId||null,f=!!(l?.dragging&&l.overGroupId&&m===l.overGroupId),h=f&&!!e.isGroup,g=!!(l?.dragging&&l.insertBeforeId===e.sessionId),b=!!(l?.dragging&&l.insertAfterId&&l.insertAfterId===e.sessionId),y=a.useCallback(S=>{if(l?.onPointerDown&&S.button===0){if(S.currentTarget?.setPointerCapture&&S.pointerId!=null)try{S.currentTarget.setPointerCapture(S.pointerId)}catch{}l.onPointerDown(S,e)}},[l,e]);return a.createElement("button",{type:"button",ref:u,className:`ps-list-button ps-session-list-button${e.active?" is-selected":""}${e.selected?" is-multiselected":""}${e.pinned?" is-pinned":""}${f?" 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":m||void 0,"data-order-container":e.orderContainer??void 0,"data-orderable":e.orderable?"1":void 0,onPointerDown:y,onClick:p,onContextMenu:S=>{S.ctrlKey&&(S.preventDefault(),i(S,e))}},a.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:c>0?`${ow(c)}px`:"0px"}},a.createElement(cw,{row:e,theme:s,structured:n,showInlineDetail:r})))});function Kl(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=Ue(e,r.color)||null;continue}n.push(r)}return{statusColor:s,rest:n}}function Vl({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 Li({badge:t,size:e="sm"}){const[s,n]=a.useState(null),r=a.useRef(null),i=a.useRef(null);if(a.useLayoutEffect(()=>{if(!s||!i.current||typeof window>"u")return;const d=i.current.offsetWidth/2,u=6;i.current.style.left=`${Math.max(d+u,Math.min(s.x,window.innerWidth-d-u))}px`},[s]),!t)return null;const o=t.isMine?`${t.name} (you)`:t.name,l=()=>{const d=r.current;if(!d||typeof window>"u")return;const u=d.getBoundingClientRect(),p=u.bottom+44<window.innerHeight;n({x:u.left+u.width/2,y:p?u.bottom+6:u.top-6,placement:p?"below":"above"})},c=()=>n(null);return a.createElement(a.Fragment,null,a.createElement("span",{ref:r,className:`ps-owner-avatar is-${e}${t.isMine?" is-mine":""}`,"data-owner-hue":String(t.hue??0),"aria-label":o,onMouseEnter:l,onMouseLeave:c,onFocus:l,onBlur:c},t.initials),s&&typeof document<"u"?Rs.createPortal(a.createElement("span",{ref:i,className:`ps-icon-tooltip is-${s.placement}`,role:"tooltip",style:{top:`${s.y}px`}},o),document.body):null)}function Yl(t){return Array.isArray(t)?t.filter(e=>!e?.ownerChip):t}function cw({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 f=Kl(Yl(t.runs),e);return a.createElement(a.Fragment,null,f.statusColor?a.createElement(Vl,{color:f.statusColor,node:t.depth>0}):null,a.createElement(Li,{badge:t.ownerBadge}),a.createElement(sc,{mark:t.canvasMark}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(Ye,{runs:f.rest,theme:e})))}const i=Yl(t.titleRuns),o=Kl(i.filter(f=>f?.role!=="collapseBadge"),e),l=i.filter(f=>f?.role==="collapseBadge"),c=l.length>0,d=Array.isArray(t.ctxRuns)?t.ctxRuns:[],u=d.length>0,p=Array.isArray(t.detailRuns)?t.detailRuns:Array.isArray(t.selectedMetaRuns)?t.selectedMetaRuns:[],m=n&&t.active&&p.length>0;return a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-session-row-line"},a.createElement("div",{className:"ps-session-row-title"},o.statusColor?a.createElement(Vl,{color:o.statusColor,node:t.depth>0}):null,a.createElement(Li,{badge:t.ownerBadge}),a.createElement(sc,{mark:t.canvasMark}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(Ye,{runs:o.rest,theme:e}))),c?a.createElement("div",{className:"ps-session-row-badge"},a.createElement(Ye,{runs:l,theme:e})):null,u?a.createElement("div",{className:"ps-session-row-ctx"},a.createElement(Ye,{runs:d,theme:e})):null),m?a.createElement("div",{className:"ps-session-row-detail"},a.createElement(Ye,{runs:p,theme:e})):null)}function dw(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 Xl=10,uw=1.6;function pw(t,e){return Math.abs(t)<Xl&&Math.abs(e)<Xl?null:Math.abs(t)>Math.abs(e)*uw?"x":"y"}function mw(t,e=!0){a.useEffect(()=>{const s=t.current;if(!s||!e)return;let n=0,r=0,i=0,o=0,l=null,c=!1;const d=g=>g==="x"?s.scrollWidth>s.clientWidth+1:s.scrollHeight>s.clientHeight+1,u=g=>{if(c=!1,g.targetTouches.length!==1){l="done";return}const b=g.targetTouches[0];n=i=b.clientX,r=o=b.clientY,l=null},p=g=>{if(l==="done"||g.targetTouches.length!==1)return;const b=g.targetTouches[0],y=b.clientX-n,S=b.clientY-r;if(l===null){const E=d("y");if(!E&&!d("x")){l="done";return}if(E&&g.cancelable&&g.preventDefault(),l=pw(y,S),l===null)return;if(!d(l)||!g.cancelable){l="done";return}i=b.clientX,o=b.clientY,c=!0}g.cancelable&&g.preventDefault();const v=b.clientX-i,w=b.clientY-o;l==="x"?s.scrollLeft-=v:s.scrollTop-=w,i=b.clientX,o=b.clientY},m=g=>{if(g.targetTouches.length>0){l="done";return}l=null},f=()=>{l="done"},h=g=>{!c||g.detail===0||(c=!1,g.preventDefault(),g.stopPropagation())};return s.addEventListener("touchstart",u,{passive:!0}),s.addEventListener("touchmove",p,{passive:!1}),s.addEventListener("touchend",m,{passive:!0}),s.addEventListener("touchcancel",f,{passive:!0}),s.addEventListener("click",h,!0),()=>{s.removeEventListener("touchstart",u),s.removeEventListener("touchmove",p),s.removeEventListener("touchend",m),s.removeEventListener("touchcancel",f),s.removeEventListener("click",h,!0)}},[t,e])}function fw({query:t="",onQuery:e,matchCount:s=0,mobile:n=!1,listRef:r=null}){const[i,o]=a.useState(!!t),l=a.useRef(null);a.useEffect(()=>{t&&o(!0)},[t]);const c=()=>{o(!0),requestAnimationFrame(()=>l.current?.focus({preventScroll:!0}))},d=()=>{t?e?.(""):o(!1)},u=t?`${s} ${s===1?"match":"matches"}`:"";return a.createElement("div",{className:`ps-session-search${i?" is-open":""}`,"data-session-search":"true"},n?a.createElement("button",{type:"button",className:"ps-session-search-trigger","aria-label":"Search sessions",title:"Search sessions",onClick:c},a.createElement(Zl)):null,a.createElement("div",{className:"ps-session-search-fields"},a.createElement(Zl),a.createElement("input",{ref:l,type:"text",inputMode:"search","aria-label":"Find a session",placeholder:"Find a session…",value:t,onChange:p=>e?.(p.target.value),onKeyDown:p=>{if(p.key==="Escape"){p.preventDefault(),d();return}if(p.key!=="ArrowDown")return;const m=r?.current?.querySelector?.(".ps-session-list-button");m&&(p.preventDefault(),m.focus({preventScroll:!0}))}}),u?a.createElement("span",{className:"ps-session-search-count",role:"status","aria-live":"polite"},u):null,t||n?a.createElement("button",{type:"button",className:"ps-session-search-clear","aria-label":t?"Clear session search":"Close session search",title:t?"Clear":"Close",onClick:d},"×"):null))}function Oi({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1,showDetailBox:r=null,selection:i=null,actionsOnly:o=!1,actionsHost:l=null,onAction:c=null,onDialogChange:d=null}){const u=String(s).includes("ps-mobile-session-pane"),p=a.useRef(null),m=iw(),f=u||m;mw(p,f);const h=se(t,G=>G.ui.themeId),g=kt(h),b=se(t,G=>!!G.ui.sessionDetailCollapsed),y=a.useRef(new Map),S=se(t,G=>({branding:G.branding,activeSessionId:i?i.sessionId:G.sessions.activeSessionId,sessionsById:G.sessions.byId,sessionsFlat:G.sessions.flat,filterQuery:i?i.query||"":G.sessions.filterQuery||"",ownerFilter:G.sessions.ownerFilter,pinnedIds:G.sessions.pinnedIds,manualOrder:G.sessions.manualOrder,selectedIds:i?[]:G.sessions.selectedIds,selectMode:i?!1:G.sessions.selectMode,auth:G.auth,connectionMode:G.connection?.mode||"local",modalOpen:!!G.ui.modal,focused:i?!0:G.ui.focusRegion==="sessions",listDeselected:i?!i.sessionId:!!G.sessions.listDeselected,canvasBySessionId:G.canvas?.bySessionId,canvasPrefs:G.canvas?.prefs,budgetPaused:G.budget?.paused}),qe),v=a.useMemo(()=>ns({sessions:{activeSessionId:S.activeSessionId,byId:S.sessionsById,flat:S.sessionsFlat,filterQuery:S.filterQuery,ownerFilter:S.ownerFilter,pinnedIds:S.pinnedIds,manualOrder:S.manualOrder,selectedIds:S.selectedIds,selectMode:S.selectMode,listDeselected:S.listDeselected},auth:S.auth,connection:{mode:S.connectionMode},branding:S.branding,canvas:{bySessionId:S.canvasBySessionId,prefs:S.canvasPrefs},budget:{paused:S.budgetPaused}}),[S.activeSessionId,S.auth,S.branding,S.budgetPaused,S.canvasBySessionId,S.canvasPrefs,S.connectionMode,S.filterQuery,S.listDeselected,S.ownerFilter,S.pinnedIds,S.manualOrder,S.selectedIds,S.selectMode,S.sessionsById,S.sessionsFlat]),w=dw(v),E=a.useRef({top:0,left:0,restore:!1}),k=a.useRef(null);k.current={query:S.filterQuery,setQuery:i?i.onQuery:G=>t.setSessionFilterQuery(G)};const x=a.useCallback(G=>{const W=String(G||""),ie=String(k.current?.query||""),pe=p.current;!ie.trim()&&W.trim()&&pe?E.current={top:pe.scrollTop,left:pe.scrollLeft,restore:!1}:ie.trim()&&!W.trim()&&(E.current.restore=!0),k.current?.setQuery?.(W)},[]);a.useLayoutEffect(()=>{S.filterQuery||!E.current.restore||!p.current||(p.current.scrollTop=E.current.top,p.current.scrollLeft=E.current.left,E.current.restore=!1)},[w,S.filterQuery]);const T=S.filterQuery?w.reduce((G,W)=>G+(W.searchMatch?1:0),0):0,A=S.activeSessionId&&S.sessionsById[S.activeSessionId]||null,R=S.activeSessionId&&w.find(G=>G.sessionId===S.activeSessionId)||null,[N,$]=a.useState(!1),[F,I]=a.useState(null),O=a.useRef(!1),M=["modelPicker","reasoningEffortPicker","contextTierPicker"],B=se(t,G=>M.includes(G.ui.modal?.type));a.useEffect(()=>{!B&&O.current&&(O.current=!1,$(!0))},[B]),a.useEffect(()=>{d?.(N||!!F||B)},[N,F,B,d]);const D=()=>{O.current=!0,$(!1),t.openSwitchModelPicker(()=>{O.current=!1}).then(()=>{!M.includes(t.getState().ui.modal?.type)&&O.current&&(O.current=!1,$(!0))}).catch(G=>{O.current=!1,$(!0),t.dispatch({type:"ui/status",text:G?.message||String(G)||"Failed to switch model"})})},j=S.auth?.principal||null,V=S.auth?.authorization?.role,C=V==="admin"||V==="anonymous",U=C&&S.auth?.adminScope!=="cluster",H=!!(A?.owner&&j&&String(A.owner.provider)===String(j.provider)&&String(A.owner.subject)===String(j.subject)),Y=!!(A&&!A.isGroup&&(A.isSystem?C:U||H)),te=Array.isArray(S.selectedIds)?S.selectedIds.length:0,ee=te>1,J=!!(A?.isGroup&&!ee),ae=!!(A&&!A.isSystem&&(A.isGroup||!A.parentSessionId&&!A.groupId)),de=!!(A&&Array.isArray(S.pinnedIds)&&S.pinnedIds.includes(A.sessionId)),Z=!!(A?.isGroup&&Number(A.memberCount||0)===0),le=ee?Array.isArray(S.selectedIds)&&S.selectedIds.some(G=>{const W=S.sessionsById[G];return W&&!W.isSystem&&!W.isGroup}):A?.isGroup?!0:!!A,$e=te>0,be=!!(A&&!S.listDeselected&&!A.isSystem&&!A.isGroup&&!A.parentSessionId),Re=$e?S.selectedIds.filter(G=>{const W=S.sessionsById[G];return W&&!W.isSystem&&!W.isGroup&&!W.parentSessionId}):be?[A.sessionId]:[],Se=`ps-session-pane${s?` ${s}`:""}`,rt=a.useRef(null);rt.current={rows:w,viewState:S,controller:t,selection:i};const[ce,Ke]=a.useState({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),Ne=a.useRef(null),Xe=a.useRef(null),q=a.useCallback(()=>{Xe.current!=null&&(cancelAnimationFrame(Xe.current),Xe.current=null)},[]),he=a.useCallback(()=>{let G=p.current;for(;G&&G!==document.body;){const W=window.getComputedStyle(G).overflowY;if(/(auto|scroll|overlay)/.test(W)&&G.scrollHeight-G.clientHeight>1)return G;G=G.parentElement}return null},[]),Be=a.useCallback((G,W)=>{const X=he();if(!X){q();return}const me=X.getBoundingClientRect();let ye=0;if(W<me.top+48?ye=-14*Math.min(1,(me.top+48-W)/48):W>me.bottom-48&&(ye=14*Math.min(1,(W-(me.bottom-48))/48)),Ne.current&&(Ne.current.autoScrollStep=ye),!Ne.current){q();return}if(Xe.current!=null)return;const Oe=()=>{const re=Ne.current;if(!re||!re.autoScrollStep){q();return}X.scrollTop+=re.autoScrollStep,Xe.current=requestAnimationFrame(Oe)};Xe.current=requestAnimationFrame(Oe)},[he,q]),Ee=a.useCallback(G=>{const W=Ne.current;if(Ne.current=null,q(),Ke({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),!(!G||!W?.started||W.ids.length===0)){if(W.intent==="reorder"){t.dispatch({type:"sessions/reorder",sessionId:W.ids[0],beforeSessionId:W.beforeSessionId});return}W.intent!=="file"&&W.intent!=="unfile"||t.moveSessionsToGroup(W.overGroupId,W.ids).catch(ie=>{t.dispatch({type:"ui/status",text:`Move failed: ${ie?.message||ie}`})})}},[t,q]),Pe=a.useCallback((G,W)=>typeof G!="number"||typeof W!="number"?null:(document.elementFromPoint(G,W)?.closest?.("[data-drop-group]")||null)?.getAttribute("data-drop-group")||null,[]),Te=a.useCallback((G,W,ie,pe)=>{if(typeof G!="number"||typeof W!="number"||ie==null)return;const X=Array.from(document.querySelectorAll(`[data-order-container="${CSS.escape(ie)}"][data-orderable="1"]`));if(X.length===0)return;for(const Oe of X){const re=Oe.getBoundingClientRect();if(W<re.top+re.height/2)return{before:Oe.getAttribute("data-session-id")||null,after:null}}const ye=X[X.length-1]?.getAttribute("data-session-id")||null;return{before:null,after:ye&&ye!==pe?ye:null}},[]),Le=a.useCallback((G,W,ie)=>{const pe=Pe(G,W);if(ie?.isGroup){const Oe=ie.ids.length===1?Te(G,W,ie.container,ie.ids[0]):void 0;return Oe===void 0?{kind:"none",overGroupId:null,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:Oe.before,after:Oe.after}}const X=ie?.ownGroupId||null;if(pe&&pe!==X)return{kind:"file",overGroupId:pe,before:void 0,after:null};if(!pe&&X)return{kind:"unfile",overGroupId:null,before:void 0,after:null};const ye=ie?.orderable&&ie.ids.length===1?Te(G,W,ie.container,ie.ids[0]):void 0;return ye===void 0?{kind:pe?"file":"none",overGroupId:pe,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:ye.before,after:ye.after}},[Pe,Te]);a.useEffect(()=>{if(!ce.dragging)return;const G=X=>{const me=Ne.current;if(!me)return;const ye=Le(X.clientX,X.clientY,me);me.intent=ye.kind,me.overGroupId=ye.overGroupId,me.beforeSessionId=ye.before,Be(X.clientX,X.clientY),document.body.classList.toggle("ps-drop-ok",ye.kind==="file"),Ke(Oe=>({...Oe,intent:ye.kind,overGroupId:ye.overGroupId,insertBeforeId:ye.before,insertAfterId:ye.after,x:X.clientX,y:X.clientY}))},W=X=>{const me=Ne.current;if(me&&typeof X?.clientX=="number"){const ye=Le(X.clientX,X.clientY,me);me.intent=ye.kind,me.overGroupId=ye.overGroupId,me.beforeSessionId=ye.before}Ee(!0)},ie=()=>Ee(!1),pe=X=>{X.key==="Escape"&&Ee(!1)};return window.addEventListener("pointermove",G),window.addEventListener("pointerup",W),window.addEventListener("pointercancel",ie),window.addEventListener("keydown",pe),document.body.classList.add("ps-dragging-sessions"),()=>{window.removeEventListener("pointermove",G),window.removeEventListener("pointerup",W),window.removeEventListener("pointercancel",ie),window.removeEventListener("keydown",pe),document.body.classList.remove("ps-dragging-sessions"),document.body.classList.remove("ps-drop-ok")}},[ce.dragging,Ee,Le,Be]);const St=a.useMemo(()=>({dragging:ce.dragging,overGroupId:ce.overGroupId,insertBeforeId:ce.insertBeforeId,insertAfterId:ce.insertAfterId,onPointerDown:(G,W)=>{if(W.isSystem||!W.orderable&&!W.isGroup&&W.depth>0)return;const ie=G.clientX,pe=G.clientY,X={row:W,startX:ie,startY:pe,started:!1,ids:[],overGroupId:null,beforeSessionId:void 0,orderable:!!W.orderable,container:W.orderContainer??null,isGroup:!!W.isGroup,ownGroupId:W.groupId||null,intent:"none",autoScrollStep:0},me=Oe=>{if(X.started||Math.hypot(Oe.clientX-ie,Oe.clientY-pe)<5)return;X.started=!0;const re=rt.current.viewState,et=Array.isArray(re.selectedIds)?re.selectedIds:[],It=et.includes(W.sessionId)&&et.length>1?et:[W.sessionId],os=re.sessionsById||{};X.ids=It,Ne.current=X,Ke({dragging:!0,ids:It,titles:It.map(ls=>os[ls]?.title||String(ls).slice(0,8)).slice(0,3),overGroupId:null,x:Oe.clientX,y:Oe.clientY})},ye=()=>{window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",ye)};window.addEventListener("pointermove",me),window.addEventListener("pointerup",ye)}}),[ce.dragging,ce.overGroupId,ce.insertBeforeId,ce.insertAfterId]),K=a.useCallback((G,W)=>{const{rows:ie,viewState:pe,controller:X,selection:me}=rt.current;if(me){(W.isGroup||W.hasChildren&&W.active)&&X.dispatch({type:W.collapsed?"sessions/expand":"sessions/collapse",sessionId:W.sessionId}),W.isGroup||me.onSelect(W.sessionId);return}if(G.metaKey||G.ctrlKey){G.preventDefault(),pe.selectMode||X.dispatch({type:"sessions/selectMode",enabled:!0}),X.dispatch({type:"sessions/selectToggle",sessionId:W.sessionId}),X.setFocus("sessions");return}if(G.shiftKey&&pe.activeSessionId){G.preventDefault();const Oe=ie.map(It=>It.sessionId),re=Oe.indexOf(pe.activeSessionId),et=Oe.indexOf(W.sessionId);if(re>=0&&et>=0){const[It,os]=re<=et?[re,et]:[et,re],ls=Oe.slice(It,os+1),np=Array.from(new Set([...pe.selectedIds||[],...ls]));X.setSessionSelection(np),X.setFocus("sessions");return}}if(W.hasChildren&&W.active){X.dispatch({type:W.collapsed?"sessions/expand":"sessions/collapse",sessionId:W.sessionId}),X.setFocus("sessions");return}pe.selectMode&&X.dispatch({type:"sessions/selectClear"}),X.setFocus("sessions"),W.sessionId===pe.activeSessionId?X.dispatch({type:"sessions/listReselect"}):W.active||X.loadSession(W.sessionId).catch(()=>{})},[]),P=a.useCallback((G,W)=>{G&&(W?y.current.set(G,W):y.current.delete(G))},[]),z=a.useRef(null),oe=`${S.activeSessionId||""}${S.focused?1:0}${S.modalOpen?1:0}`;a.useEffect(()=>{if(S.modalOpen||!S.focused||!S.activeSessionId){z.current=null;return}const G=y.current.get(S.activeSessionId);if(!G||z.current===oe)return;z.current=oe;const W=document.activeElement,ie=!!(W&&(W.tagName==="INPUT"||W.tagName==="TEXTAREA"||W.tagName==="SELECT"||W.isContentEditable));S.focused&&W!==G&&!ie&&G.focus({preventScroll:!0})},[oe,S.activeSessionId,S.focused,S.modalOpen,S.sessionsFlat]);const ge=a.createElement(a.Fragment,null,!o&&ee?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."},`${te} selected`):null,!o&&(ee?a.createElement(ve,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(_.CLEAR_SESSION_SELECTION).catch(()=>{})}):a.createElement(ve,{className:"ps-mini-button ps-pin-icon",icon:a.createElement(Rw),onClick:()=>t.handleCommand(_.PIN_SESSION).catch(()=>{}),disabled:!ae,active:de,label:ae?de?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"})),!o&&a.createElement(ve,{className:"ps-mini-button",icon:Re.length>1?a.createElement("span",{className:"ps-icon-badge"},a.createElement(ec),a.createElement("span",{className:"ps-icon-badge__count"},String(Re.length))):a.createElement(ec),onClick:()=>t.handleCommand(_.OPEN_MOVE_TO_GROUP).catch(()=>{}),label:Re.length>1?`Move ${Re.length} selected sessions to a group`:Re.length===1?"Move this session to a group":"New group"}),a.createElement(ve,{className:"ps-mini-button",icon:a.createElement(Gu),onClick:()=>{if(A?.isGroup){t.handleCommand(_.OPEN_RENAME_SESSION).catch(()=>{});return}$(!0)},disabled:!Y&&!J||ee,label:ee?"Disabled while multiple sessions are selected":A?.isSystem?"System sessions are managed by administrators":A?.isGroup?"Rename folder":Y?o?"Manage session — rename and switch model":"Manage session — rename, switch model, and sharing":"Only this session's owner or an admin can manage it"}),!o&&a.createElement(ve,{className:"ps-mini-button",icon:a.createElement($w),onClick:()=>{const G=A?.sessionId;if(!G)return;const W=fu(G);W&&(Xn(W),I({url:W,warn:!1}),jS(t,G).then(ie=>{I(pe=>pe&&pe.url===W?{...pe,warn:ie}:pe)}).catch(()=>{}))},disabled:!A||A.isGroup||ee,label:"Copy link — copy a direct link to this session"}),a.createElement(ve,{className:"ps-mini-button",icon:a.createElement(A?.isSystem?ww:Fi),onClick:()=>t.handleCommand(A?.isGroup?_.DELETE_SESSION:_.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!le,label:ee?`Terminate ${te} selected sessions (Mark Completed, Cancel, or Delete)`:A?.isGroup?Z?"Delete this empty group":"This group cannot be deleted yet":A?.isSystem?"Restart this system session (complete, terminate, or hard delete)":"Terminate — mark completed, cancel, or delete this session"}),e),Me=ce.dragging?a.createElement("div",{className:"ps-drag-ghost",style:{left:`${ce.x}px`,top:`${ce.y}px`}},a.createElement("div",{className:`ps-drag-ghost__stack${ce.ids.length>1?" is-collection":""}`},ce.ids.length>1?a.createElement("span",{className:"ps-drag-ghost__count"},String(ce.ids.length)):null,a.createElement("span",{className:"ps-drag-ghost__title"},ce.ids.length>1?`${ce.ids.length} sessions`:ce.titles[0]||"session")),a.createElement("div",{className:"ps-drag-ghost__hint"},ce.intent==="file"?"Release to file here":ce.intent==="unfile"?"Release to remove from folder":ce.intent==="reorder"?"Release to move here":"Release to cancel")):null;return a.createElement(a.Fragment,null,Me,o?l?Rs.createPortal(a.createElement("div",{className:"ps-moa-control-actions",onClick:c},ge),l):null:a.createElement(Ut,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:S.focused,theme:g,actions:i?a.createElement(a.Fragment,null,i.onCreate?a.createElement(ve,{className:"ps-mini-button",icon:a.createElement(Wu),label:"Create New Session",onClick:i.onCreate}):null,e):ge,className:Se},a.createElement("div",{ref:p,onKeyDown:i?G=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(G.key)||G.altKey||G.ctrlKey||G.metaKey)return;const W=[...p.current.querySelectorAll(".ps-session-list-button")],ie=W.indexOf(G.target.closest(".ps-session-list-button")),pe=G.key==="Home"?0:G.key==="End"?W.length-1:Math.max(0,Math.min(W.length-1,ie+(G.key==="ArrowUp"?-1:1))),X=W[pe];X&&(G.preventDefault(),G.stopPropagation(),X.dataset.sessionId&&i.onSelect(X.dataset.sessionId),X.focus())}:void 0,className:`ps-action-list ps-session-list${ce.dragging?" is-dragging":""}`,onClick:G=>{G.target instanceof Element&&G.target.closest(".ps-session-list-button")||(i?i.onSelect(null):t.dispatch({type:"sessions/listDeselect"}))}},w.length===0?a.createElement("div",{className:"ps-empty-state"},S.filterQuery?`No sessions matched "${S.filterQuery}".`:"No sessions yet."):w.map(G=>a.createElement(lw,{key:G.sessionId,row:G,theme:g,structuredRows:n,mobile:u,onRowClick:K,setRef:P,drag:i||f?null:St}))),a.createElement(fw,{query:S.filterQuery,onQuery:x,matchCount:T,mobile:u,listRef:p}),(r===null?!u:r)?a.createElement(rw,{session:A,childCount:R?.childCount||0,pause:R?.pause||null,controller:t,collapsed:b,onToggle:()=>t.dispatch({type:"ui/sessionDetailCollapsed",collapsed:!b})}):null),N&&A&&!A.isGroup?a.createElement(Ow,{controller:t,sessionId:A.sessionId,initialTitle:A.title||"",allowSharing:!o,currentModel:A.model||"",currentReasoningEffort:A.reasoningEffort||"",principal:S.auth?.principal||null,onClose:()=>$(!1),onSwitchModel:D,onChanged:()=>{}}):null,F?a.createElement(hw,{url:F.url,warn:F.warn,onCopyAgain:()=>{Xn(F.url),t.dispatch({type:"ui/status",text:BS})},onClose:()=>I(null)}):null)}function hw({url:t,warn:e,onCopyAgain:s,onClose:n}){const[r,i]=a.useState(""),o=Ia(t,ur).length>1,l=a.useCallback((d,u)=>{d==="session"&&!o?s?.():navigator?.clipboard?.writeText&&navigator.clipboard.writeText(u).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(hu,{url:t,keyPrefix:"session",copied:r,onCopy:l}),e?a.createElement("div",{className:"ps-link-warn"},US):null))}const Ql={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function Ge({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 Gu(){return a.createElement(Ge,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 Ha(){return a.createElement(Ge,null,a.createElement("path",{d:"M21 4H3l7.2 8.5V19l3.6 2v-8.5L21 4z"}))}function Zl(){return a.createElement(Ge,null,a.createElement("circle",{cx:"11",cy:"11",r:"7"}),a.createElement("path",{d:"m20 20-4-4"}))}function Wu(){return a.createElement(Ge,null,a.createElement("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),a.createElement("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))}function gw(){return a.createElement(Ge,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 yw(){return a.createElement(Ge,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 qu(){return a.createElement(Ge,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 bw(){return a.createElement(Ge,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 Sw(){return a.createElement(Ge,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 vw(){return a.createElement(Ge,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 ww(){return a.createElement(Ge,null,a.createElement("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"}),a.createElement("path",{d:"M21 3v5h-5"}))}function Ew(){return a.createElement(Ge,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 zu(){return a.createElement(Ge,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 kw(){return a.createElement(Ge,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 Iw(){return a.createElement(Ge,null,a.createElement("rect",{x:3,y:4,width:7,height:16,rx:1}),a.createElement("rect",{x:13,y:4,width:8,height:6.5,rx:1}),a.createElement("rect",{x:13,y:13.5,width:8,height:6.5,rx:1}))}function Jl(){return a.createElement(Ge,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 xw(){return a.createElement(Ge,null,a.createElement("path",{d:"M4 17l6-6-6-6"}),a.createElement("line",{x1:"12",y1:"19",x2:"20",y2:"19"}))}function Aw(){return a.createElement(Ge,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 Nw="M12 2.3 20.4 7.15v9.7L12 21.7 3.6 16.85V7.15Z",Cw="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",Tw="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 Pw(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":"true"},a.createElement("path",{d:Nw,strokeWidth:"1.9",strokeLinejoin:"round"}),a.createElement("path",{d:Cw,fill:"currentColor",stroke:"none",fillRule:"evenodd"}),a.createElement("path",{d:Tw,fill:"currentColor",stroke:"none"}))}function Mw(){return a.createElement(Ge,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 _w(){return a.createElement(Ge,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 $w(){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 Fi(){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 ec(){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 Rw(){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 Lw(){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 Ku(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()},HS);return()=>{clearTimeout(l),typeof o=="function"&&o()}},[i]),{access:n.access,loading:n.loading,reload:i}}function Ow({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:r,principal:i,onClose:o,onSwitchModel:l,onChanged:c,allowSharing:d=!0}){const[u,p]=a.useState("general"),[m,f]=a.useState(null),[h,g]=a.useState(s||""),[b,y]=a.useState([]),[S,v]=a.useState([]),[w,E]=a.useState("private"),[k,x]=a.useState(""),[T,A]=a.useState("write"),[R,N]=a.useState([]),[$,F]=a.useState(!1),[I,O]=a.useState(null);a.useEffect(()=>{let q=!1;return t.transport.getSessionAccess(e).then(he=>{!q&&he&&(f(he),E(he.visibility||"private"))}).catch(()=>{}),d&&typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(he=>{q||N(Array.isArray(he)?he:[])}).catch(()=>{}),()=>{q=!0}},[t,e,d]);const M=a.useCallback(()=>{t.transport.listSessionShares(e).then(q=>{const he=Array.isArray(q)?q:[];y(he),v(he)}).catch(()=>{y([]),v([])})},[t,e]);a.useEffect(()=>{d&&M()},[M,d]);const B=async q=>{F(!0),O(null);try{await q(),c?.()}catch(he){O(he?.message||String(he))}finally{F(!1)}},D=()=>B(async()=>{await t.transport.renameSession(e,h.trim())}),j=q=>{const he=q.trim().toLowerCase();if(!he)return null;const Be=R.find(Ee=>Ee.displayName&&Ee.displayName.toLowerCase()===he||Ee.email&&Ee.email.toLowerCase()===he||Ee.subject&&Ee.subject.toLowerCase()===he);return Be||{provider:i?.provider||"dev",subject:q.trim(),email:null,displayName:null}},V=q=>`${q.provider}${q.subject}`,C=q=>{const he=V(q);v(Be=>[...Be.filter(Ee=>V(Ee)!==he),{provider:q.provider,subject:q.subject,email:q.email??null,displayName:q.displayName??null,access:T}]),x("")},U=()=>{const q=j(k);q&&C(q)},H=q=>{const he=V(q);v(Be=>Be.filter(Ee=>V(Ee)!==he))},Y=new Set(S.map(V)),te=m?.owner?`${m.owner.provider}${m.owner.subject}`:null,ee=k.trim().toLowerCase(),J=ee?R.filter(q=>{const he=V(q);return he===te||Y.has(he)?!1:q.displayName&&q.displayName.toLowerCase().includes(ee)||q.email&&q.email.toLowerCase().includes(ee)||q.subject&&q.subject.toLowerCase().includes(ee)}).slice(0,25):[],ae=!!m?.canManage,de=m?.visibility||"private",Z=new Set(S.map(q=>`${V(q)}:${q.access}`)),le=new Set(b.map(q=>`${V(q)}:${q.access}`)),$e=Z.size!==le.size||[...Z].some(q=>!le.has(q)),be=ae&&(w!==de||$e),Re=()=>B(async()=>{w!==de&&await t.transport.setSessionVisibility(e,w);const q=new Map(b.map(Pe=>[V(Pe),Pe])),he=new Map(S.map(Pe=>[V(Pe),Pe]));for(const[Pe,Te]of he){const Le=q.get(Pe);(!Le||Le.access!==Te.access)&&await t.transport.grantSessionShare(e,{provider:Te.provider,subject:Te.subject,email:Te.email??null,displayName:Te.displayName??null},Te.access)}for(const[Pe,Te]of q)he.has(Pe)||await t.transport.revokeSessionShare(e,{provider:Te.provider,subject:Te.subject});const Be=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(Be)&&(y(Be),v(Be));const Ee=await t.transport.getSessionAccess(e).catch(()=>null);Ee&&(f(Ee),E(Ee.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),Se=l||(()=>{o(),t.openSwitchModelPicker().catch(q=>{t.dispatch({type:"ui/status",text:q?.message||String(q)||"Failed to switch model"})})}),rt=n?r?`${n}:${r}`:n:"—",ce=[{id:"general",label:"General"},...d&&ae?[{id:"access",label:"Access"}]:[]],Ke=ce.some(q=>q.id===u)?u:"general",Ne=typeof t.transport?.regenerateSession=="function",Xe=q=>q.stopPropagation();return a.createElement("div",{className:"ps-share-overlay",onClick:o},a.createElement("div",{className:"ps-share-modal",onClick:Xe},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"},ce.map(q=>a.createElement("button",{key:q.id,type:"button",role:"tab","aria-selected":Ke===q.id?"true":"false",className:`ps-manage-tab${Ke===q.id?" is-active":""}`,onClick:()=>p(q.id)},q.label))),a.createElement("div",{className:"ps-share-modal-body"},Ke==="general"?a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-share-section-label"},"Name"),a.createElement("div",{className:"ps-share-add-row"},a.createElement("input",{className:"ps-share-add-input",placeholder:"Session title",value:h,disabled:$,onChange:q=>g(q.target.value),onKeyDown:q=>{q.key==="Enter"&&D()}}),a.createElement("button",{className:"ps-mini-button",disabled:$||!h.trim(),onClick:D},"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"},rt),a.createElement("button",{className:"ps-mini-button",disabled:$,onClick:Se},"Switch model…")),Ne?a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-share-section-label"},"Context"),a.createElement("div",{className:"ps-share-section-sub"},"Rebuild this session's working context from its summary. The transcript is archived and the session keeps running — it is not a terminal action."),a.createElement("div",{className:"ps-share-add-row"},a.createElement("button",{className:"ps-mini-button ps-manage-regenerate",disabled:$,onClick:()=>{o(),t.handleCommand(_.REGENERATE_SESSION).catch(()=>{})}},a.createElement(Lw),a.createElement("span",null,"Regenerate context…")))):null):null,Ke==="access"&&ae?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(q=>a.createElement("label",{key:q,className:`ps-share-radio${w===q?" is-active":""}`},a.createElement("input",{type:"radio",name:"visibility",checked:w===q,disabled:$,onChange:()=>E(q)}),a.createElement("span",{className:"ps-share-radio-glyph"},Ql[q].glyph),a.createElement("span",null,Ql[q].label),a.createElement("span",{className:"ps-share-radio-hint"},q==="private"?"only you and admins":q==="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 grant can only raise someone's access above it, never lower it — to restrict everyone, lower the general level."),S.length===0?a.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):S.map(q=>a.createElement("div",{key:`${q.provider}/${q.subject}`,className:"ps-share-grant-row"},a.createElement("span",{className:"ps-share-grant-name"},q.displayName||q.subject),a.createElement("span",{className:"ps-share-grant-access"},`can ${q.access}`),a.createElement("button",{className:"ps-mini-button",disabled:$,onClick:()=>H(q)},"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:k,disabled:$,autoComplete:"off",onChange:q=>x(q.target.value),onKeyDown:q=>{q.key==="Enter"&&U()}}),a.createElement("select",{className:"ps-share-add-select",value:T,disabled:$,onChange:q=>A(q.target.value)},a.createElement("option",{value:"read"},"can read"),a.createElement("option",{value:"write"},"can write")),a.createElement("button",{className:"ps-mini-button",disabled:$||!k.trim(),onClick:U},"Add")),J.length>0?a.createElement("div",{className:"ps-share-suggestions"},J.map(q=>a.createElement("button",{key:`${q.provider}/${q.subject}`,type:"button",className:"ps-share-suggestion",disabled:$,onClick:()=>C(q)},a.createElement("span",{className:"ps-share-suggestion-name"},q.displayName||q.subject),q.email?a.createElement("span",{className:"ps-share-suggestion-email"},q.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),Ke==="access"&&ae?a.createElement("div",{className:"ps-manage-apply-bar is-footer"},a.createElement("span",{className:"ps-share-section-sub"},be?"Unsaved access changes.":"No changes to apply."),a.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:$||!be,onClick:Re},"Apply")):null,I?a.createElement("div",{className:"ps-share-error"},I):null))}function W0({controller:t,onReadOnlyFocus:e=null,mobile:s=!1,compact:n=!1,autoFocus:r=!s}){const i=se(t,d=>d.ui.modal),o=se(t,d=>d.sessions.byId[d.sessions.activeSessionId]),{access:l}=Ku(t,o?.sessionId,o?.isGroup),c=o?.serviceKind||l?.canWrite===!1;return a.useLayoutEffect(()=>{c&&!i&&e?.()},[c,i,e]),!o||o.isGroup||i?null:a.createElement("div",{className:"ps-chat-composer"},c?a.createElement("div",{className:"ps-composer-readonly"},o.serviceKind?"⚗ Service session — runtime machinery. Its transcript is a read-only trace; it does not accept messages.":`You have view access to this session. Ask ${l.owner?.displayName||l.owner?.email||"the owner"} for write access to participate.`):a.createElement(Qu,{controller:t,mobile:s,compact:n,autoFocus:r,active:!0}))}function q0({controller:t}){const e=se(t,c=>c),s=e.sessions.byId[e.sessions.activeSessionId],n=ji(s?.status==="running"),i=ar(e,{spinnerFrame:n,maxWidth:120})[0]?.map(c=>c.text||"").join("")||(s?String(s.status||"idle").replace(/^./,c=>c.toUpperCase()):""),o=Rd(e),l=["pending","queued","cancelling","rejected"].map(c=>{const d=o.filter(u=>u.pendingPhase===c).length;return d?`${d} ${c}`:""}).filter(Boolean).join(" · ");return a.createElement("div",{className:"ps-mobile-session-status","aria-label":"Session status"},a.createElement("span",{className:"ps-mobile-activity",title:i},i),l?a.createElement("span",{className:"ps-mobile-queue",title:l},l):null)}function Di({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0,onEnterZen:r=null,activityInHeader:i=!1}){const o=se(t,B=>B.ui.themeId),l=kt(o),c=se(t,B=>{const D=B.sessions.activeSessionId,j=mr(B),V=s||e?j.totalWidth:j.leftWidth,C=Math.max(20,V-4);return{activeSessionId:D,activeHistory:D&&B.history.bySessionId.get(D)||null,activeOutbox:D&&B.outbox?.bySessionId?.[D]?B.outbox.bySessionId[D]:tr,branding:B.branding,connection:B.connection,sessionsById:B.sessions.byId,sessionsFlat:B.sessions.flat,inspectorTab:B.ui.inspectorTab,activeSessionIsGroup:!!(D&&B.sessions.byId[D]?.isGroup),activeSessionStatus:D?String(B.sessions.byId[D]?.status||"").toLowerCase():"",focused:B.ui.focusRegion==="chat",scroll:B.ui.scroll.chat,followBottom:B.ui.followBottom?.chat!==!1,authPrincipal:B.auth?.principal||null,contentWidth:C}},qe),d=a.useMemo(()=>({branding:c.branding,connection:c.connection,auth:{principal:c.authPrincipal},sessions:{activeSessionId:c.activeSessionId,byId:c.sessionsById,flat:c.sessionsFlat},history:{bySessionId:c.activeSessionId&&c.activeHistory?new Map([[c.activeSessionId,c.activeHistory]]):new Map},outbox:{bySessionId:c.activeSessionId?{[c.activeSessionId]:c.activeOutbox}:{}},ui:{inspectorTab:c.inspectorTab}}),[c.activeHistory,c.activeSessionId,c.activeOutbox,c.authPrincipal,c.branding,c.connection,c.inspectorTab,c.sessionsById,c.sessionsFlat]),[u,p]=yu(),m=u??c.contentWidth,f=a.useMemo(()=>Ld(d,{width:m}),[d,m]),h=hc(!!f.animateTitleRight),g=a.useMemo(()=>gc(f.titleRight,f.animateTitleRight?h:""),[h,f.animateTitleRight,f.titleRight]),[b,y]=a.useState(!1),S=!!(c.activeHistory?.hasOlderEvents&&Number(c.activeHistory?.loadedEventCount||0)>=Mi),v=a.useMemo(()=>ua(d,m,{tableMode:"sentinel"}),[d,m]),w=ji(c.activeSessionStatus==="running"),k=a.useMemo(()=>ar(d,{spinnerFrame:w,maxWidth:m}),[d,w,m]),x=a.useMemo(()=>fa(d,m,{tableMode:"sentinel"}),[d,m]),T=a.useMemo(()=>k.length>0?[...x,...k]:x,[x,k]),A=a.useMemo(()=>i&&x.length?[...v,...x]:v,[i,v,x]),{access:R}=Ku(t,c.activeSessionId,c.activeSessionIsGroup),N=se(t,oh,qe),$=n&&!c.activeSessionIsGroup,F=!!c.sessionsById?.[c.activeSessionId]?.serviceKind,I=F||!!R&&R.canWrite===!1,O=$?a.createElement("div",{className:"ps-chat-composer"},I?a.createElement("div",{className:"ps-composer-readonly"},F?"⚗ Service session — runtime machinery. Its transcript is a read-only trace; it does not accept messages.":`You have view access to this session. Ask ${R.owner?.displayName||R.owner?.email||"the owner"} for write access to participate.`):a.createElement(Qu,{controller:t,mobile:e,active:!0})):null,M=!!(c.activeSessionId&&c.sessionsById[c.activeSessionId]);return N&&!M?a.createElement(Ut,{title:f.title,color:f.color,focused:c.focused,theme:l,className:"ps-chat-panel"},a.createElement("div",{className:"ps-empty-state ps-nav-error-state"},a.createElement("div",{className:"ps-nav-error-message"},N.message),N.retryable?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(N.sessionId)},"Retry"):null)):a.createElement(fr,{controller:t,title:e?Ol(f.title,28):f.title,titleRight:e&&g?Ol(g,18):g,actions:e&&r?a.createElement(ve,{className:"ps-mini-button",icon:a.createElement(qu),label:"Enter mobile zen",onClick:r}):null,color:f.color,focused:c.focused,lines:A,bottomStickyLines:i?tr:T,reserveBottomSticky:!i,scrollOffset:c.scroll,scrollMode:c.followBottom?"bottom":"top",stickyBottom:!0,paneKey:"chat",ariaLive:"polite",className:"is-wrapped",panelClassName:"ps-chat-panel",panelRef:p,bottomContent:O,topContent:S?a.createElement("div",{className:"ps-load-older-bar"},a.createElement("button",{type:"button",className:"ps-load-older-button",disabled:b,onClick:()=>{y(!0),t.handleCommand(_.EXPAND_HISTORY).catch(()=>{}).finally(()=>y(!1))}},b?"Loading older messages…":"↑ Load older messages")):null,structuredBlocks:!0,renderBody:null})}function Fw({controller:t,onClose:e}){const s=se(t,g=>g.ui.themeId),n=kt(s),r=se(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)}},qe),i=Iu(r.filename),o=se(t,g=>g.files.htmlViewMode||"rendered"),l=se(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]),u=se(t,g=>Number(g.files.htmlZoom)||1),p=a.useCallback(g=>{t.dispatch({type:"files/htmlZoom",zoom:g})},[t]),m=a.useCallback(g=>{t.stepArtifactPreview(g).catch(()=>{})},[t]),f=a.useCallback(g=>{if(!(g.metaKey||g.ctrlKey||g.altKey)){if(g.key==="ArrowLeft"||g.key==="["){g.preventDefault(),m(-1);return}if(g.key==="ArrowRight"||g.key==="]"){g.preventDefault(),m(1);return}g.key==="Escape"&&(g.preventDefault(),e())}},[e,m]),h=dr(r.sessionId,r.filename);return a.createElement("section",{className:"ps-artifact-pane",onKeyDown:f,tabIndex:-1,role:"region","aria-label":`Artifact: ${r.filename||"none"}`},a.createElement("header",{className:"ps-artifact-pane-bar"},i.kind==="page"?a.createElement($u,{mode:o,setMode:d}):null,i.kind==="page"&&o==="rendered"?a.createElement(_u,{fitWidth:l,setFitWidth:c}):null,i.kind==="page"&&o==="rendered"?a.createElement(er,{zoom:u,setZoom:p}):null,a.createElement("span",{className:"ps-artifact-pane-heading"},a.createElement("span",{className:"ps-artifact-pane-name",title:r.filename},xu(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:()=>m(-1),title:"Previous artifact (←)","aria-label":"Previous artifact"},"‹"),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",disabled:!r.canNext,onClick:()=>m(1),title:"Next artifact (→)","aria-label":"Next artifact"},"›"),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>{h&&(Xn(h),t.dispatch({type:"ui/status",text:mu}))},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(_.DOWNLOAD_SELECTED_FILE).catch(()=>{}),title:"Download","aria-label":"Download"},a.createElement(zu)),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(hr,{controller:t,focused:!1,previewOnly:!0,chromeless:!0,theme:n})))}function Dw({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(Yu,{controller:t,mobile:!0,visible:e,focusOnPromote:!0,maximized:s,onToggleMaximized:r}))}function Bw({controller:t}){const e=se(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)}},qe),s=!!La(e.filename)||Oa(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(hr,{controller:t,focused:!0,mobile:!0,previewOnly:!0,nativeScroll:!0})))}const Hw=140;function Uw(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-Hw;return{baseline:r,takeover:i&&n}}function jw(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=Uw(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 Gw({controller:t,layout:e="split",onEnterZen:s}){const n=a.createElement(Oi,{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(Di,{controller:t,mobile:!0,fullWidth:!0,onEnterZen:s}))):e==="sessions"?a.createElement("div",{className:"ps-mobile-workspace is-sessions-only"},a.createElement(Oi,{controller:t,panelClassName:"ps-mobile-session-pane",showDetailBox:!0})):a.createElement("div",{className:"ps-mobile-workspace"},n,a.createElement("div",{className:"ps-mobile-chat-pane"},a.createElement(Di,{controller:t,mobile:!0,fullWidth:!0,onEnterZen:s})))}function Vu(){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 tc(){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 sc({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 nc(){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 Ww=[{id:"session",label:"Session access"},{id:"public",label:"Anyone with link"}];function qw({controller:t,sessionId:e,slot:s,onClose:n}){const[r,i]=a.useState(null),[o,l]=a.useState(null),[c,d]=a.useState(!1),[u,p]=a.useState(""),[m,f]=a.useState(""),[h,g]=a.useState("session"),[b,y]=a.useState(null),[S,v]=a.useState(null),[w,E]=a.useState(!1),k=t.transport,x=`${window.location.origin}/?session=${encodeURIComponent(e)}&view=canvas&slot=${s}&max=1${w?"&show_chrome=false":""}`,T=(M,B)=>a.createElement(hu,{url:M,keyPrefix:B,copied:m,onCopy:$}),A=a.useCallback(()=>{k.getCanvasShareLink?.(e,s).then(M=>i(M||{exists:!1})).catch(M=>{i({exists:!1}),p(M?.message||String(M))}),typeof k.readCanvasKv=="function"&&k.readCanvasKv(e,s,{limit:1}).then(M=>{y(M?.policy||"owner"),v(M?.me||null)}).catch(()=>{y(null),v(null)})},[k,e,s]);a.useEffect(()=>{A()},[A]);const R=S?.relation==="owner"||S?.relation==="admin",N=M=>{d(!0),p(""),k.setCanvasKvAccess(e,s,M).then(()=>y(M)).catch(B=>p(B?.message||String(B))).finally(()=>d(!1))},$=(M,B)=>{navigator.clipboard?.writeText(B).then(()=>{f(M),window.setTimeout(()=>f(""),1500)}).catch(()=>p("Could not reach the clipboard — copy the link manually."))},F=M=>{d(!0),p(""),k.resetCanvasShareLink(e,s).then(({token:B})=>{l(`${window.location.origin}/?canvasShare=${encodeURIComponent(B)}`),i({exists:!0})}).catch(B=>p(B?.message||String(B))).finally(()=>d(!1))},I=()=>{d(!0),p(""),k.removeCanvasShareLink(e,s).then(()=>{l(null),i({exists:!1})}).catch(M=>p(M?.message||String(M))).finally(()=>d(!1))},O=a.createElement("div",{className:"ps-canvas-share-overlay",onClick:n},a.createElement("div",{className:"ps-canvas-share-dialog",onClick:M=>M.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"},Ww.map(M=>a.createElement("button",{key:M.id,type:"button",role:"tab","aria-selected":h===M.id?"true":"false",className:`ps-manage-tab${h===M.id?" is-active":""}`,onClick:()=>g(M.id)},M.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."),T(x,"session"),a.createElement("label",{className:"ps-canvas-share-check"},a.createElement("input",{type:"checkbox",checked:w,onChange:M=>E(M.target.checked)}),"Hide page chrome"),b!==null?a.createElement("div",{className:"ps-canvas-share-policy"},a.createElement("label",{className:"ps-canvas-share-sub",htmlFor:"ps-canvas-kv-policy"},"Who can edit inside this app"),a.createElement("select",{id:"ps-canvas-kv-policy",className:"ps-canvas-slot-select",value:b,disabled:c||!R,onChange:M=>N(M.target.value)},a.createElement("option",{value:"owner"},"Only people who can edit the session"),a.createElement("option",{value:"readers"},"Anyone who can open the session"),a.createElement("option",{value:"link"},"Anyone who can open the session, plus link viewers")),a.createElement("div",{className:"ps-canvas-share-sub"},b==="owner"?"You, admins, and anyone you shared the session with as “write”. People with view-only access can watch the app but not change anything in it.":b==="link"?"Your view-only people can edit inside the app. Anyone holding the share link can watch it — link holders can never edit.":"Adds your view-only people: they can edit inside the app. It does not let them message the agent."),R?null:a.createElement("div",{className:"ps-canvas-share-sub"},"Only the session owner or an admin can change this.")):null),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,T(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:()=>F(r?.exists)},r?.exists?"Reset link":"Create link"),r?.exists?a.createElement("button",{type:"button",className:"ps-mini-button",disabled:c,onClick:I},"Remove link"):null))),u?a.createElement("div",{className:"ps-canvas-share-error"},u):null));return typeof document<"u"&&document.body?Rs.createPortal(O,document.body):O}function ti({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 rc(){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 ic(){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 ac(){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 zw({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,onPanelKey:u=null}){const p=a.useRef(u);p.current=u;const m=!!u,[f,h]=a.useState(null),[g,b]=a.useState(null),[y,S]=a.useState(null),[v,w]=a.useState(0),E=a.useRef({live:null,staging:null}),k=a.useRef({rev:0,used:!1}),x=a.useRef(null),T=a.useRef(null),A=a.useRef(null),R=Ru(x),N=a.useRef(null),$=a.useRef(r);$.current=r;const F=a.useRef(i);F.current=i,a.useEffect(()=>{if(!t||!e)return;const M=B=>{const D=T.current,j=B.data;if(!j||typeof j!="object"||!B.source)return;const V=!!(D&&B.source===D.contentWindow),C=!!(A.current&&B.source===A.current.contentWindow);if(!(!V&&!C)){if(j.type==="moa-panel-key"){V&&document.activeElement===D&&["Tab","Escape"].includes(j.key)&&p.current?.(j.key,j.backwards===!0);return}if(j.type==="canvas-action"){if(!V)return;t.submitCanvasAction(e,j,s).then(U=>{U&&U.ok===!1&&typeof console<"u"&&console.warn(`canvas action rejected: ${U.reason}`)}).catch(()=>{});return}if(j.type==="canvas-kv"){const U=j.id,H=t.transport,Y=B.source,te=ae=>{try{Y.postMessage(ae,"*")}catch{}},ee=(ae,de="ERROR")=>te({type:"canvas-kv-result",id:U,ok:!1,error:String(ae?.message||ae||"failed"),code:ae?.code||de});if(typeof H?.readCanvasKv!="function"){ee("the canvas KV store is not available on this deployment","UNAVAILABLE");return}const J=String(j.op||"");if(!V&&(J==="put"||J==="delete")){ee("the canvas is still loading; retry the write in a moment","NOT_READY");return}if(J==="ready"||J==="list"){H.readCanvasKv(e,s,{prefix:j.prefix??null,limit:j.limit??null,after:j.after??null}).then(ae=>te({type:J==="ready"?"canvas-kv-ready":"canvas-kv-result",id:U,ok:!0,entries:ae?.entries??[],nextAfter:ae?.nextAfter??null,me:ae?.me??null,canWrite:!!ae?.me?.canWrite,policy:ae?.policy??"owner"})).catch(ee);return}if(J==="get"){H.readCanvasKv(e,s,{key:j.key}).then(ae=>te({type:"canvas-kv-result",id:U,ok:!0,entry:ae?.entries?.[0]??null})).catch(ee);return}if(J==="put"||J==="delete"){const ae=J==="put"?{op:"put",key:j.key,value:j.value,...j.ifMatch!=null?{ifMatch:j.ifMatch}:{}}:{op:"delete",key:j.key,...j.ifMatch!=null?{ifMatch:j.ifMatch}:{}};H.writeCanvasKv(e,s,[ae]).then(de=>{const Z=de?.results?.[0]??{ok:!1,error:"no result"};te({type:"canvas-kv-result",id:U,ok:!!Z.ok,key:Z.key,rev:Z.rev,capped:Z.capped,error:Z.error,code:Z.code})}).catch(ee);return}ee(`unknown canvas-kv op ${J}`,"INVALID_REQUEST")}}};return window.addEventListener("message",M),()=>window.removeEventListener("message",M)},[t,e,s]),a.useEffect(()=>{if(!(!t||!e||typeof t.subscribeCanvasKv!="function"))return t.subscribeCanvasKv(e,M=>{if(!M||Number(M.slot)!==Number(s))return;const B=T.current?.contentWindow;if(!B)return;const D=j=>{try{B.postMessage({type:"canvas-kv-change",key:M.key,rev:M.rev,op:M.op,...j?{v:j.v,by:j.by,at:j.at}:{}},"*")}catch{}};if(M.op==="delete"){D(null);return}if(M.value&&typeof M.value=="object"){D({v:M.value.v,by:M.value.by,at:M.value.at});return}t.transport?.readCanvasKv?.(e,s,{key:M.key}).then(j=>D(j?.entries?.[0]??null)).catch(()=>{})})},[t,e,s]),a.useEffect(()=>{if(!t||!e||!n)return;let M=!1,B=null;return Lu(t,e,s<=1?"canvas.html":`canvas${s}.html`,m).then(D=>{if(M){URL.revokeObjectURL(D);return}E.current.staging&&E.current.staging!==E.current.live&&URL.revokeObjectURL(E.current.staging),E.current.staging=D,S(null),b({url:D,rev:n})}).catch(()=>{if(!M){if(k.current.rev!==n&&(k.current={rev:n,used:!1}),!k.current.used){k.current.used=!0,B=setTimeout(()=>{M||w(D=>D+1)},1500);return}S({rev:n})}}),()=>{M=!0,B&&clearTimeout(B)}},[t,e,s,n,v,m]),a.useEffect(()=>()=>{E.current.staging&&E.current.staging!==E.current.live&&URL.revokeObjectURL(E.current.staging),E.current.live&&URL.revokeObjectURL(E.current.live),E.current={live:null,staging:null},h(null),b(null),S(null)},[e]);const I=a.useCallback(M=>{if(!M||E.current.staging!==M.url)return;const B=E.current.live;E.current.live=M.url,E.current.staging=null,B&&B!==M.url&&URL.revokeObjectURL(B),h(M),b(j=>j&&j.url===M.url?null:j);const D=x.current;if(D){const j=D.getBoundingClientRect(),V=$.current||1;N.current={w:Math.round(j.width/V),h:Math.round(j.height/V)}}if(t&&e&&F.current&&t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,rev:M.rev}),o&&F.current)try{T.current?.focus({preventScroll:!0})}catch{}},[t,e,o]);a.useEffect(()=>{if(!(!f||!l||c===null)){try{T.current?.contentWindow?.postMessage({type:"canvas-data",data:c,dataRev:l},"*"),d&&T.current?.contentWindow?.postMessage({type:"canvas-patch",patch:d,dataRev:l},"*")}catch{}t&&e&&F.current&&t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,dataRev:l})}},[f,l,c,d,t,e]),a.useEffect(()=>{if(i&&f&&t&&e&&(t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,rev:f.rev,...l?{dataRev:l}:{}}),o))try{T.current?.focus({preventScroll:!0})}catch{}},[i,f,t,e,o,l]),a.useEffect(()=>{if(!f||!i)return;const M=r||1,B=Math.round((R.width||0)/M),D=Math.round((R.height||0)/M);if(!B||!D)return;const j=N.current;if(j){if(!(j.w<220||j.h<170))return;const U=Math.abs(j.w-B),H=Math.abs(j.h-D);if(U<=2&&H<=2||U<=2&&H/Math.max(1,j.h)<.15)return}const V=setTimeout(()=>{N.current={w:B,h:D},w(C=>C+1)},350);return()=>clearTimeout(V)},[R.width,R.height,r,f,i]);const O=r!==1&&R.width>0?{flex:"none",width:`${Math.max(1,Math.round(R.width/r))}px`,height:`${Math.max(1,Math.round(R.height/r))}px`,transform:`scale(${r})`,transformOrigin:"top left"}:void 0;return a.createElement("div",{ref:x,className:"ps-html-preview-host is-fitting"},[f,g].filter(Boolean).map(M=>a.createElement("iframe",{key:`canvas:${M.rev}:${M.url}`,ref:M===f?(B=>{T.current=B}):(B=>{A.current=B}),className:`ps-html-preview-frame${M===f?"":" is-staging"}`,style:O,src:M.url,title:"Session canvas",sandbox:"allow-scripts allow-popups allow-popups-to-escape-sandbox",allow:"autoplay *",referrerPolicy:"no-referrer",onLoad:M===g?()=>I(M):void 0})),y?a.createElement("div",{className:"ps-canvas-load-error"},a.createElement("span",null,f?`Couldn't load rev ${y.rev} — showing rev ${f.rev}.`:`Couldn't load rev ${y.rev}.`),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>{k.current={rev:0,used:!1},S(null),w(M=>M+1)}},"Retry")):null)}const Kw=160;function Yu({controller:t,mobile:e=!1,visible:s=!0,focusOnPromote:n=!1,maximized:r=!1,onToggleMaximized:i=null}){const o=se(t,pa,qe),l=se(t,b=>Number(b.files.htmlZoom)||1),c=a.useCallback(b=>{t.dispatch({type:"files/htmlZoom",zoom:b})},[t]);a.useEffect(()=>{if(!s||!o.sessionId)return;const b=setTimeout(()=>{t.ensureCanvasSnapshot(o.sessionId).catch(()=>{})},Kw);return()=>clearTimeout(b)},[t,o.sessionId,s]);const d=se(t,b=>b?.ui?.canvasZen===!0),[u,p]=a.useState(!1),[m,f]=a.useState(null);a.useEffect(()=>{if(!r){f(null);return}let b=0;const y=()=>{const S=document.getElementById("ps-toolbar-canvas-slot");S?f(S):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(ti,{controller:t,view:o,compact:!0}),o.exists?a.createElement("button",{type:"button",className:"ps-canvas-max-btn",onClick:()=>p(!0),title:"Share this canvas — copy a view link","aria-label":"Share canvas"},a.createElement(nc)):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?ac:ic)):null):null:r?m?Rs.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(ti,{controller:t,view:o,compact:!0}),o.exists?a.createElement(er,{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(rc)),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(ac))),m):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(Vu)),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(ti,{controller:t,view:o})),a.createElement("span",{className:"ps-artifact-pane-actions"},o.exists?a.createElement(er,{zoom:l,setZoom:c}):null,o.exists?a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>p(!0),title:"Share this canvas — copy a view link","aria-label":"Share canvas"},a.createElement(nc)):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(rc)),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(ic))));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(zw,{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."))),u&&o.exists?a.createElement(qw,{controller:t,sessionId:o.sessionId,slot:o.slot,onClose:()=>p(!1)}):null)}function Xu({activeTab:t,controller:e}){const s=a.useMemo(()=>Ta(e),[e]);return a.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>a.createElement(ve,{key:n,icon:_l[n]?a.createElement(_l[n]):"•",label:_S[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function hr({controller:t,focused:e,mobile:s=!1,previewOnly:n=!1,nativeScroll:r=!1,chromeless:i=!1}){const o=se(t,I=>I.ui.themeId),l=kt(o),c=a.useRef(null),d=se(t,I=>{const O=I.sessions.activeSessionId,M=mr(I),B=s||I.files.fullscreen?I.ui.layout?.viewportWidth??120:M.rightWidth;return{activeSessionId:O,sessionsById:I.sessions.byId,sessionsFlat:I.sessions.flat,filesBySessionId:I.files.bySessionId,filesFilter:I.files.filter,selectedArtifactId:I.files.selectedArtifactId,markedIds:I.files.markedIds||[],previewOrigin:I.files.previewOrigin||null,focused:e,previewScroll:I.ui.scroll.filePreview,fullscreen:!!I.files.fullscreen,contentWidth:Math.max(20,B-4),canBrowserUpload:RS(t),canPathUpload:LS(t),canDeleteArtifacts:FS(t),canOpenLocally:DS(t)}},qe),u=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]),p=a.useMemo(()=>ya(u,{listWidth:Math.max(18,d.contentWidth-4),previewWidth:Math.max(18,d.contentWidth-4),showHints:!1}),[u,d.contentWidth]),m=a.useMemo(()=>Xt(u),[u]),f=m.length>0,h=a.useCallback(I=>{const O=Array.isArray(I)?I.filter(Boolean):[];O.length!==0&&t.uploadArtifactFiles(O).catch(()=>{})},[t]),g=a.useCallback(()=>{if(d.canBrowserUpload&&c.current){c.current.click();return}d.canPathUpload&&t.handleCommand(_.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(ve,{icon:a.createElement(Fi),label:`Delete ${b.size} marked`,onClick:()=>t.deleteMarkedArtifacts().catch(()=>{})}):null,a.createElement(ve,{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:I=>{h(Array.from(I.currentTarget.files||[])),I.currentTarget.value=""}}),a.createElement(ve,{icon:a.createElement(Ew),label:"Upload",onClick:g,disabled:!d.canBrowserUpload&&!d.canPathUpload}),a.createElement(ve,{icon:a.createElement(zu),label:"Download",onClick:()=>t.handleCommand(_.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!f}),a.createElement(ve,{icon:"🔗",label:"Copy link to this artifact",onClick:()=>{const I=dr(p.selectedSessionId,p.selectedFilename);I&&(Xn(I),t.dispatch({type:"ui/status",text:mu}))},disabled:!f||!p.selectedFilename}),d.canDeleteArtifacts?a.createElement(ve,{icon:a.createElement(Fi),label:"Delete",onClick:()=>t.handleCommand(_.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,d.canOpenLocally?a.createElement(ve,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(_.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,a.createElement(ve,{icon:a.createElement(Ha),label:"Filter",onClick:()=>t.handleCommand(_.OPEN_FILES_FILTER).catch(()=>{})}),a.createElement(ve,{icon:a.createElement(d.fullscreen?bw:qu),label:d.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(_.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),S=a.useRef(null);a.useEffect(()=>{const I=S.current;I&&typeof I.scrollIntoView=="function"&&I.scrollIntoView({block:"nearest"})},[p.selectedIndex,d.selectedArtifactId]);const v=m.length===0?Je(p.listBodyLines||[]).map((I,O)=>a.createElement(st,{key:`empty:${O}`,line:I,theme:l})):m.map((I,O)=>a.createElement("button",{key:I.id,type:"button",ref:O===p.selectedIndex?S:null,className:`ps-list-button${O===p.selectedIndex?" is-selected":""}`+(b.has(I.id)?" is-marked":""),onClick:M=>{if(t.setFocus("inspector"),M.metaKey||M.ctrlKey){t.toggleArtifactMark(I);return}if(M.shiftKey){t.markArtifactRange(I);return}t.clearArtifactMarks(),t.selectFileBrowserItem(I).then(()=>{s&&t.handleCommand(_.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})}).catch(()=>{})}},a.createElement(st,{line:Je([p.listBodyLines?.[O]])[0],theme:l}))),w=!p.previewLoading&&!p.previewError,E=w&&Oa(p.selectedFilename,p.previewContentType)&&!p.previewIsBinary&&!!p.previewContent,k=w&&($a.test(String(p.previewContentType||""))||Ra.test(String(p.selectedFilename||""))),x=w&&!p.previewIsBinary&&!E&&p.previewRenderMode!=="markdown"&&p.previewContent?La(p.selectedFilename):null,T=n?"activity":null,A=r?null:"filePreview",R=w&&!p.previewIsBinary&&Eu(p.selectedFilename,p.previewContentType)&&!!p.previewContent,$=w&&!p.previewIsBinary&&wu(p.selectedFilename,p.previewContentType)?a.createElement(Fv,{controller:t,sessionId:p.selectedSessionId,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,theme:l,color:"cyan",focused:!1,title:null,chromeless:i}):R?a.createElement(Qr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:A,scrollOffset:d.previewScroll,className:"ps-csv-preview",focusRegion:T},a.createElement(yv,{content:p.previewContent,filename:p.selectedFilename})):k?a.createElement(Wl,{title:null,color:"cyan",focused:!1,theme:l,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,source:p.previewSource,uploadedAt:p.previewUploadedAt,controller:t,sessionId:p.selectedSessionId}):x?a.createElement(Qr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:A,scrollOffset:d.previewScroll,className:"ps-diff-preview",focusRegion:T},a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,$s(p.previewContent,x,l)))):E?a.createElement(Qr,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:A,scrollOffset:d.previewScroll,className:"ps-diff-preview",focusRegion:T},a.createElement("pre",{className:"ps-md-code-pre is-diff"},a.createElement("code",null,Fa(p.previewContent,l)))):p.previewRenderMode==="markdown"&&!p.previewLoading&&!p.previewError?a.createElement($v,{controller:t,title:null,color:"cyan",focused:!1,scrollOffset:d.previewScroll,paneKey:A,theme:l,focusRegion:T,content:mv(p.previewContent||"")}):p.previewIsBinary&&!p.previewLoading&&!p.previewError?a.createElement(Wl,{title:null,color:"cyan",focused:!1,theme:l,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,source:p.previewSource,uploadedAt:p.previewUploadedAt,controller:t,sessionId:p.selectedSessionId}):a.createElement(fr,{controller:t,title:null,color:"cyan",focused:!1,lines:p.previewLines,scrollOffset:d.previewScroll,scrollMode:"top",paneKey:A,focusRegion:T,className:"is-preview is-wrapped"}),F=d;return n?$:a.createElement(Ut,{title:F.fullscreen?p.fullscreenTitle:s&&p.panelTitleMobile?p.panelTitleMobile:p.panelTitle,color:"magenta",focused:F.focused,actions:y,theme:l},a.createElement(Xu,{activeTab:"files",controller:t}),F.fullscreen?$:a.createElement("div",{className:"ps-files-grid is-list-only"},a.createElement("div",{className:"ps-action-list ps-files-list"},v)))}function Gs({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const r=se(t,b=>{const y=mr(b),S=b.ui.inspectorTab,v=e?b.ui.layout?.viewportWidth??120:y.rightWidth;return{inspectorTab:S,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:YS(v,S,e)}},qe),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]=yu(),c=o??r.contentWidth,d=a.useMemo(()=>Ht(i,{width:c}),[i,c]),u=a.useMemo(()=>{const b=r.activeSessionId&&r.historyBySessionId?.get(r.activeSessionId)||null,y=new Map;for(const S of b?.events||[]){if(S?.eventType!=="session.turn_completed")continue;const v=Number(S?.data?.turnIndex??S?.data?.iteration);Number.isFinite(v)&&y.set(v,S)}return y},[r.activeSessionId,r.historyBySessionId]),p=a.useCallback((b,y)=>a.createElement(Qv,{lines:b,theme:y,completionByTurn:u}),[u]),m=a.useCallback((b,y)=>a.createElement(Xv,{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 f=a.useRef(null);if(a.useEffect(()=>{if(e)return f.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 S=window.getComputedStyle(y),v=document.createElement("span");v.style.cssText="position:absolute;visibility:hidden;white-space:pre;",v.style.fontFamily=S.fontFamily,v.style.fontSize=S.fontSize,v.style.fontWeight=S.fontWeight,v.style.letterSpacing=S.letterSpacing,v.textContent="0".repeat(100),y.parentElement.appendChild(v);const w=v.getBoundingClientRect().width/100||8;v.remove();const E=window.getComputedStyle(b),k=b.clientWidth-(parseFloat(E.paddingLeft)||0)-(parseFloat(E.paddingRight)||0);if(!(k>50))return;const T=Math.floor(k/w)+6,A=t.getState().ui.layout?.viewportWidth??120;if(Math.abs(T-A)<=2)return;t.dispatch({type:"ui/viewport",width:T,height:null})}catch{}}),()=>{f.current&&cancelAnimationFrame(f.current)}},[t,e,r.inspectorTab,r.activeSessionId]),r.inspectorTab==="files"&&!d.disabled)return a.createElement(hr,{controller:t,focused:r.focused,mobile:e});const h=[];if(r.inspectorTab==="logs")h.push(a.createElement(ve,{key:"tail",icon:r.logsTailing?"■":"⇣",label:r.logsTailing?"Stop tailing":"Tail (follow)",active:r.logsTailing,onClick:()=>t.handleCommand(_.TOGGLE_LOG_TAIL).catch(()=>{})})),h.push(a.createElement(ve,{key:"filter",icon:a.createElement(Ha),label:"Filter",onClick:()=>t.handleCommand(_.OPEN_LOG_FILTER).catch(()=>{})}));else if(r.inspectorTab==="history")h.push(a.createElement(ve,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(_.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),h.push(a.createElement(ve,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(_.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(ve,{key:`stats-view:${y}`,icon:b[y],label:`${y.replace(/^./u,S=>S.toUpperCase())} stats`,active:r.statsViewMode===y,onClick:()=>t.setStatsViewMode(y)}))}const g=n?h.concat(n):h;return a.createElement(fr,{controller:t,title:d.title,color:"magenta",focused:r.focused,actions:g,topContent:a.createElement(Xu,{activeTab:d.activeTab,controller:t}),stickyLines:d.stickyLines||[],lines:d.lines,renderBody:d.activeTab==="sequence"?p:d.activeTab==="nodes"?m: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 si({controller:t,panelClassName:e="",extraActions:s=null}){const n=se(t,l=>{const c=l.sessions.activeSessionId,d=mr(l),u=Math.max(3,d.activityPaneHeight-2);return{activeSessionId:c,activeSession:c&&l.sessions.byId[c]||null,activeHistory:c&&l.history.bySessionId.get(c)||null,focused:l.ui.focusRegion==="activity",scroll:l.ui.scroll.activity,followBottom:l.ui.followBottom?.activity!==!1,maxLines:u,nodeMapSelectedNode:l.ui.nodeMapSelectedNode,adminWorkers:l.admin?.workers,branding:l.branding,sessionsById:l.sessions.byId,sessionsFlat:l.sessions.flat,historyBySessionId:l.history.bySessionId,inspectorTab:l.ui.inspectorTab}},qe),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?Od(i):ga(i,n.maxLines),[r,i,n.maxLines]);return a.createElement(fr,{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 tr=Object.freeze([]);function oc(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 Qu({controller:t,mobile:e,compact:s=!1,active:n=!0,onAfterSend:r=null,autoFocus:i=!0}){const o=se(t,N=>{const $=N.sessions.activeSessionId,F=$&&N.sessions.byId[$]||null,I=$&&N.outbox?.bySessionId?.[$]?N.outbox.bySessionId[$]:[];return{value:N.ui.prompt,cursor:N.ui.promptCursor,focused:N.ui.focusRegion==="prompt",modalOpen:!!N.ui.modal,answerMode:!!F?.pendingQuestion?.question,canStopTurn:Nd(F),hasOutbox:I.length>0,hasPendingOutbox:I.some(O=>O?.phase==="pending"),pendingCount:I.filter(O=>O?.phase==="pending").length,editingPending:N.ui.promptEdit?.sessionId===$,selectedOutboxPhase:N.ui.promptEdit?.sessionId===$&&N.ui.promptEdit?.phase||null,promptAttachments:N.ui.promptAttachments||tr}},qe),l=a.useRef(null),c=a.useRef(null),[d,u]=a.useState(!1),p=o.selectedOutboxPhase==="queued",m=o.selectedOutboxPhase==="cancelling",f=p||m,h=e&&!o.editingPending?o.answerMode?"Answer…":"Message…":o.answerMode?"Type an answer and press Enter":o.editingPending?m?"Cancellation requested":p?"Queued message selected":"Edit the pending message, then send or cancel it":o.hasOutbox?"Type a message and press Enter to queue it behind the pending batch":"Type a message and press Enter",g=a.useRef(-1),b=a.useCallback((N=!1)=>{const $=l.current;$&&(!N&&$.scrollHeight<=$.clientHeight||($.style.height="0px",$.style.height=`${$.scrollHeight+2}px`))},[]);a.useLayoutEffect(()=>{const N=String(o.value||"").length,$=N<=g.current;g.current=N,b($||N===0)},[b,o.value,h]),a.useEffect(()=>{const N=()=>b(!0);window.addEventListener("resize",N);const $=l.current,F=$&&typeof ResizeObserver<"u"?new ResizeObserver(()=>b(!0)):null;return F&&$&&F.observe($),()=>{window.removeEventListener("resize",N),F?.disconnect()}},[b]);const y=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",S=y?o.promptAttachments.filter(N=>N?.kind==="image"):tr,v=a.useRef(new Map);a.useEffect(()=>{const N=v.current,$=new Set(S.map(F=>F.file));for(const[F,I]of N)$.has(F)||(URL.revokeObjectURL(I),N.delete(F));for(const F of S)if(F.file&&!N.has(F.file))try{N.set(F.file,URL.createObjectURL(F.file))}catch{}},[S]),a.useEffect(()=>()=>{for(const N of v.current.values())URL.revokeObjectURL(N);v.current.clear()},[]);const w=a.useCallback(N=>{if(!y)return 0;const $=Array.from(N||[]).filter(I=>I&&typeof I.type=="string"&&I.type.startsWith("image/"));return $.length===0?0:t.addPendingImageFiles($)?.accepted||0},[t,y]);a.useEffect(()=>{const N=l.current;if(!(!n||o.modalOpen||!o.focused||!N)){if(document.activeElement!==N){if(!i||typeof i=="function"&&!i()||e)return;try{N.focus({preventScroll:!0})}catch{N.focus()}}N.value===o.value&&N.selectionStart!==o.cursor&&N.setSelectionRange(o.cursor,o.cursor)}},[n,e,i,o.cursor,o.value,o.focused,o.modalOpen]);const E=a.useCallback(()=>{t.handleCommand(_.SEND_PROMPT).catch(()=>{}).finally(()=>{r?.()})},[t,r]),[k,x]=a.useState(!1),T=a.useCallback(()=>{x(!0),t.handleCommand(_.STOP_TURN).catch(()=>{}).finally(()=>x(!1))},[t]),A=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]),R=o.editingPending||o.hasPendingOutbox&&!o.value.trim()?"⇪":o.hasOutbox?"+":"❯";return a.createElement("div",{className:`ps-prompt-shell${s?" is-compact":""}${e?" is-mobile":""}${d?" is-drag-over":""}`,...y?{onDragOver:N=>{N.dataTransfer?.types?.includes?.("Files")&&(N.preventDefault(),u(!0))},onDragLeave:N=>{N.currentTarget.contains(N.relatedTarget)||u(!1)},onDrop:N=>{u(!1),N.dataTransfer?.files?.length&&(N.preventDefault(),w(N.dataTransfer.files))}}:{}},S.length>0?a.createElement("div",{className:"ps-prompt-attachments"},S.map((N,$)=>{const F=N.file?v.current.get(N.file):null;return a.createElement("div",{key:`attach:${$}:${N.filename}`,className:"ps-attach-chip",title:`${N.filename} · ${oc(N.sizeBytes)}`},F?a.createElement("img",{className:"ps-attach-thumb",src:F,alt:N.filename}):a.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),a.createElement("div",{className:"ps-attach-size"},oc(N.sizeBytes)),a.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${N.filename}`,"aria-label":`Remove attachment ${N.filename}`,onClick:()=>t.removePendingImageAttachment($)},"✕"))})):null,(()=>{const N=o.answerMode?"answer":m?"cancelling":p?"queued":o.editingPending?"pending":"you";return a.createElement("label",{className:`ps-prompt-label${N==="you"?" is-default":""}`},N)})(),a.createElement("textarea",{ref:l,className:"ps-prompt-input",rows:1,value:o.value,readOnly:f,placeholder:h,enterKeyHint:e?"enter":"send",onFocus:()=>t.setFocus("prompt"),onSelect:N=>t.setPromptCursor(N.currentTarget.selectionStart||0),onChange:N=>t.setPrompt(N.currentTarget.value,N.currentTarget.selectionStart||N.currentTarget.value.length),onPaste:y?N=>{const F=Array.from(N.clipboardData?.items||[]).filter(I=>I.kind==="file"&&I.type.startsWith("image/")).map(I=>I.getAsFile()).filter(Boolean);F.length>0&&w(F)>0&&N.preventDefault()}:void 0,onKeyDown:N=>{if(N.key==="Tab"&&!N.shiftKey&&t.acceptPromptReferenceAutocomplete()){N.preventDefault();return}if(N.key==="Escape"&&o.editingPending){if(N.preventDefault(),f){t.exitPendingPromptEdit({restoreDraft:!0});return}A();return}N.key==="Enter"&&!N.shiftKey&&!N.metaKey&&!e&&(N.preventDefault(),E())}}),a.createElement("div",{className:"ps-prompt-actions"},y&&!s?a.createElement(a.Fragment,null,a.createElement("input",{ref:c,type:"file",accept:"image/*",multiple:!0,className:"ps-hidden-file-input","aria-hidden":!0,tabIndex:-1,onChange:N=>{w(N.currentTarget.files),N.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:N=>N.preventDefault(),onClick:()=>c.current?.click()},"📎")):null,o.editingPending&&!m?a.createElement("button",{type:"button",className:"ps-mini-button",title:p?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":p?"Delete selected queued prompt":"Cancel selected pending prompt",onPointerDown:N=>N.preventDefault(),onClick:A},p?"Delete":"Cancel"):null,o.canStopTurn||k?a.createElement("button",{type:"button",className:`ps-stop-button${k?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:k,onPointerDown:N=>N.preventDefault(),onClick:T},"■"):null,a.createElement("button",{type:"button",className:`ps-send-button${e?" is-inline":""}`,title:o.editingPending||o.hasPendingOutbox&&!o.value.trim()?"Send all queued prompts":o.hasOutbox?"Queue prompt behind the pending batch":"Send prompt","aria-label":o.editingPending||o.hasPendingOutbox&&!o.value.trim()?"Send queued prompts":o.hasOutbox?"Queue prompt":"Send prompt",onPointerDown:N=>N.preventDefault(),onClick:E},R)))}const Vw=1e3;function ve({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),u=a.useRef(null),p=a.useRef(!1);a.useLayoutEffect(()=>{if(!o||!d.current||!c.current)return;const x=d.current,T=window.visualViewport,A=()=>{const R=T?.offsetLeft||0,N=T?.offsetTop||0,$=T?.width||window.innerWidth,F=T?.height||window.innerHeight,I=6,O=c.current.getBoundingClientRect();x.style.width="max-content",x.style.maxWidth=`${Math.min(220,$-2*I)}px`,x.style.maxHeight=`${F-2*I}px`;const M=x.getBoundingClientRect();let B=o.placement==="below";!B&&O.top-M.height-I<N&&(B=!0),B&&O.bottom+M.height+I>N+F&&O.top-M.height-I>=N&&(B=!1);const D=Math.max(R+I,Math.min(O.left+O.width/2-M.width/2,R+$-M.width-I)),j=Math.max(N+I,Math.min(B?O.bottom+I:O.top-M.height-I,N+F-M.height-I));x.style.transform="none",x.style.left=`${D}px`,x.style.top=`${j}px`};return A(),T?.addEventListener("resize",A),T?.addEventListener("scroll",A),window.addEventListener("resize",A),()=>{T?.removeEventListener("resize",A),T?.removeEventListener("scroll",A),window.removeEventListener("resize",A)}},[o]);const m=(x=!1)=>{const T=c.current;if(!T||typeof window>"u")return;const A=T.getBoundingClientRect(),R=x?A.top-44<0:A.bottom+44<window.innerHeight;l({x:A.left+A.width/2,y:R?A.bottom+6:A.top-6,placement:R?"below":"above"})},f=a.useRef(null),h=a.useRef(null),g=x=>{x.pointerType==="mouse"&&(clearTimeout(u.current),clearTimeout(f.current),u.current=setTimeout(m,Vw))},b=x=>{x.pointerType==="mouse"&&(clearTimeout(u.current),clearTimeout(f.current),l(null))},y=x=>{x.pointerType!=="mouse"&&(p.current=!1,h.current={x:x.clientX,y:x.clientY},clearTimeout(u.current),clearTimeout(f.current),u.current=setTimeout(()=>{p.current=!0,m(!0)},450))},S=x=>{if(x.pointerType==="mouse"||!h.current)return;const T=x.clientX-h.current.x,A=x.clientY-h.current.y;T*T+A*A>100&&(h.current=null,clearTimeout(u.current),l(null))},v=x=>{x.pointerType!=="mouse"&&(h.current=null,clearTimeout(u.current),p.current?(clearTimeout(f.current),f.current=setTimeout(()=>l(null),3e3),setTimeout(()=>{p.current=!1},250)):l(null))};a.useEffect(()=>()=>{clearTimeout(u.current),clearTimeout(f.current)},[]);const w=x=>{if(p.current){p.current=!1,x.preventDefault?.();return}n||s?.(x)},E=x=>{x.preventDefault?.()},k=o&&typeof document<"u"&&document.body?Rs.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:w,disabled:n,"aria-label":e,onPointerEnter:g,onPointerLeave:b,onPointerDown:y,onPointerMove:S,onPointerUp:v,onPointerCancel:v,onContextMenu:E},a.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),k)}function lc({controller:t,mobile:e,moa:s=null,canvasPaneOpen:n=!1,onToggleCanvasPane:r=null,mobilePane:i="workspace",onSelectMobilePane:o=null,mobileMainLayout:l="split"}){const[c,d]=a.useState(null);a.useEffect(()=>{typeof document>"u"||d(e?null:document.getElementById("ps-header-toolbar-slot"))},[e]);const u=se(t,I=>!!I.admin?.visible),p=se(t,I=>!!(I.admin?.profile?.isAdmin||I.auth?.authorization?.role==="admin")),m=p?"admin console":"settings",f=se(t,I=>!!I.ui?.budgetOpen),h=se(t,pa,qe),g=se(t,I=>I?.ui?.diagnosticsOpen===!0),b=se(t,I=>I?.ui?.canvasMaximized===!0),y=se(t,I=>!!(I?.files?.paneOpen&&I?.files?.selectedArtifactId)),S=[{key:"new",icon:a.createElement(Wu),label:"New session — choose model and agent",onClick:()=>t.handleCommand(_.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:a.createElement(Ha),label:"Filter sessions",onClick:()=>t.handleCommand(_.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:a.createElement(yw),label:"Theme",onClick:()=>t.handleCommand(_.OPEN_THEME_PICKER).catch(()=>{})},{key:"canvas",icon:a.createElement(Vu),label:(e?n:h.mode==="canvas"&&!y)?"Hide the canvas":"Show canvas",onClick:()=>{if(e){r&&r();return}t.dispatch({type:"ui/canvasOpen",open:h.mode!=="canvas",sessionId:h.sessionId,manual:!0})},active:e?n:h.mode==="canvas"&&!y,badge:e?h.exists&&(h.latestRev>(h.lastViewedRev||0)||(h.latestDataRev||0)>(h.lastViewedDataRev||0))&&!n:h.unseen,loadedDot:h.exists},{key:"budget",icon:a.createElement(vw),label:f?"Close budget":"Budget — providers, limits and usage",onClick:()=>{f?t.closeBudget():t.openBudget().catch(()=>{})},active:f},...e?[]:[{key:"diagnostics",icon:a.createElement(tc),label:g?"Hide diagnostics":"Show diagnostics (inspector and activity)",onClick:()=>t.dispatch({type:"ui/diagnosticsOpen"}),active:g}],...e?[]:[{key:"admin",icon:a.createElement(Sw),label:u?`Close ${m}`:p?"Admin console":"Settings",onClick:()=>t.handleCommand(u?_.CLOSE_ADMIN_CONSOLE:_.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:u}],...e?[]:[{key:"workspace",icon:a.createElement(Jl),label:"Workspace — sessions, chat and panels",onClick:()=>t.handleCommand(_.OPEN_WORKSPACE).catch(()=>{}),active:!s?.active&&!u&&!f}]];s&&S.push({key:"moa",icon:a.createElement(Iw),label:s.returnTo?"Back to MoA — Master of Agents":"Master of Agents",active:s.active,disabled:!s.loaded,onClick:()=>{t.dispatch({type:"ui/canvasMaximized",on:!1}),t.handleCommand(_.OPEN_WORKSPACE).catch(()=>{}),s.open()}});const v=I=>{const O=a.createElement(ve,{key:I.badge?void 0:I.key,icon:I.icon,label:I.label,onClick:I.onClick,disabled:!!I.disabled,active:!!I.active});return I.badge||I.loadedDot?a.createElement("span",{key:I.key,className:"ps-canvas-toggle"},O,I.loadedDot?a.createElement("span",{className:"ps-canvas-loaded-dot","aria-hidden":"true"}):null,I.badge?a.createElement("span",{className:"ps-canvas-badge","aria-hidden":"true"}):null):O};if(e){const I={split:"Main — sessions and chat (tap for chat only)",chat:"Main — chat only (tap for sessions only)",sessions:"Main — sessions only (tap for both)"},O=i==="inspector"||i==="activity",M=i==="inspector"?"activity":"inspector",B=[{id:"workspace",icon:Jl,label:I[l]||I.split,focus:"chat"},{id:M,icon:tc,active:O,label:O?i==="inspector"?"Diagnostics — inspector (tap for activity)":"Diagnostics — activity (tap for inspector)":"Diagnostics — inspector and activity",focus:M}];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"},S.filter(D=>D.key!=="moa").map(v)),a.createElement("div",{className:"ps-toolbar-row-actions is-panes"},...S.filter(D=>D.key==="moa").map(v),B.map(D=>a.createElement(ve,{key:D.id==="workspace"?"workspace":"diagnostics",icon:a.createElement(D.icon),label:D.label,active:D.active??i===D.id,onClick:()=>{o&&o(D.id,D.focus)}})))))}const w=s?.active?"moa":u?"admin":f?"budget":"workspace",E=["new","filter"],k=["canvas","diagnostics"],x=["workspace","moa","budget","admin"],T=I=>(!b||I.key==="canvas")&&!(s?.active&&["workspace","budget","admin"].includes(I.key))?I:{...I,onClick:(...O)=>(t.dispatch({type:"ui/canvasMaximized",on:!1}),s?.active&&["workspace","budget","admin"].includes(I.key)&&s.leave(),I.onClick?.(...O))},A=I=>I.map(O=>S.find(M=>M.key===O)).filter(Boolean).map(T).map(v),R=I=>a.createElement("span",{key:I,className:"ps-toolbar-divider","aria-hidden":"true"}),N=w==="workspace"?[...A(E),...A(k)]:[],$=[...A(x),R("mode-divider"),...A(["theme"])],F=a.createElement("div",{className:`ps-toolbar${s?.active?" is-moa":""}`},a.createElement("div",{className:"ps-toolbar-side is-left"},s?.active?a.createElement("div",{id:"ps-moa-status-slot"}):b?N:null),a.createElement("div",{className:"ps-toolbar-actions"},s?.active?a.createElement("div",{id:"ps-moa-header-slot"}):b?null:N),a.createElement("div",{className:"ps-toolbar-side is-right"},a.createElement("span",{className:"ps-toolbar-meta-slot",id:"ps-toolbar-meta-slot"}),b?a.createElement("span",{className:"ps-toolbar-canvas-slot",id:"ps-toolbar-canvas-slot"}):null,b?a.createElement("span",{className:"ps-toolbar-divider","aria-hidden":"true"}):null,a.createElement("div",{className:"ps-toolbar-actions is-tools"},$),a.createElement("span",{className:"ps-toolbar-signout-slot",id:"ps-toolbar-signout-slot"})));return c?Rs.createPortal(F,c):F}function Ds(t){try{t.currentTarget?.setPointerCapture?.(t.pointerId)}catch{}}function Yw({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 u=s.current;if(!u)return;const p=Math.round((l-u.startX)/cu),m=p-u.appliedCells;m&&(t.adjustPaneSplit(m),u.appliedCells=p)},d=u=>{s.current&&(l=u.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(),Ds(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(_.GROW_RIGHT_PANE).catch(()=>{});return}i.key==="ArrowRight"&&(i.preventDefault(),t.handleCommand(_.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 Xw({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=Ns(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(),Ds(i);const o=i.currentTarget.closest(".ps-workspace-main-grid"),l=$i(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=$i(o?.getBoundingClientRect?.().width),c=d=>{const u=Ns((Number(e)||0)+d,l.minAdjust,l.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:u})};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 Qw({controller:t,canvasPaneAdjust:e=0,diagnosticsPaneAdjust:s=0}){const n=a.useRef(null),[r,i]=a.useState(!1),o=(c,d)=>({canvas:Pa+(Number(c)||0),diag:Ma+(Number(d)||0)}),l=(c,d)=>{const u=o(c,d);if(u.canvas<Pn||u.diag<Pn){t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:0}),t.dispatch(u.canvas<Pn?{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=u=>{const p=n.current;if(!p)return;const m=u.clientX-p.startX;t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:p.startCanvas+m}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:p.startDiag-m})},d=()=>{const u=n.current;if(n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x"),u){const p=t.getState()?.ui?.layout||{};l(p.canvasPaneAdjust??0,p.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(),Ds(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 Zw({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(),Ds(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 Jw({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"?Pa:Ma,d=u=>{if(c+u<Pn){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]:u})};return a.useEffect(()=>{if(!r)return;const u=m=>{const f=n.current;if(!f)return;const h=f.startAdjust-(m.clientX-f.startX);t.dispatch({type:o,[l]:Math.min(h,f.maxAdjust)})},p=()=>{const m=n.current;n.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x"),m&&d((t.getState()?.ui?.layout||{})[l]??0)};return window.addEventListener("pointermove",u),window.addEventListener("pointerup",p),window.addEventListener("pointercancel",p),()=>{window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p)}},[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:u=>{if(u.button!==0)return;u.preventDefault(),Ds(u);const p=document.querySelector(".ps-workspace-main-grid > .ps-workspace-pane-slot:last-child"),m=p?p.getBoundingClientRect().width:Number.POSITIVE_INFINITY,f=Number(s)||0;n.current={startX:u.clientX,startAdjust:f,maxAdjust:f+Math.max(0,m-Ca)},i(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>t.dispatch({type:o,[l]:0}),onKeyDown:u=>{u.key!=="ArrowLeft"&&u.key!=="ArrowRight"||(u.preventDefault(),d((Number(s)||0)-(u.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 e0({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=Ns(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(),Ds(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:u}=lo(l,c);s.current={startY:i.clientY,start:Ns(Number(e)||0,d,u),minAdjust:d,maxAdjust:u},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:u}=lo(l,c);t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:Ns((Number(e)||0)+(i.key==="ArrowDown"?c:-c),d,u)})}},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 t0=[{value:"day",label:"Daily"},{value:"week",label:"Weekly"},{value:"month",label:"Monthly"}],cc={day:"Daily",week:"Weekly",month:"Monthly"},s0={plain:"",amber:" warn",red:" over",idle:""};function n0(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 r0(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 Bi(t){return t?`resets ${t}`:"no reset recorded"}function i0(t,e,s){return`${t} ${t===1?e:s}`}function a0(t,e,s=[]){if(!e?.name)return[];const n=new Map;for(const r of t){if(!(r.catalogKind==="runtime_provider"?r.providerId===e.name:r.catalogKind==="provider_type"?r.providerId===e.typeId:r.providerId===e.name||r.providerId===e.typeId))continue;const o=`${e.name}:${r.modelName}`;n.set(o,{qualifiedName:o,modelName:r.modelName})}for(const r of s)r.providerName!==e.name||r.rowKind!=="model"||!String(r.scope||"").startsWith(`${e.name}:`)||n.set(r.scope,{qualifiedName:r.scope,modelName:r.scope.slice(e.name.length+1)});return[...n.values()]}function o0(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,catalogKind:r.catalogKind||n.catalogKind})):[n]).filter(n=>n&&(n.modelName||n.qualifiedName)).map(n=>({modelName:n.modelName||String(n.qualifiedName).split(":").slice(1).join(":"),providerId:n.providerId||"",catalogKind:n.catalogKind||null}))}function Zu({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:u=null,cancelLabel:p="Cancel"}){const m=a.useRef(null);return a.useEffect(()=>{const f=m.current;if(!f)return;const h=()=>[...f.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')];f.contains(document.activeElement)||(h()[0]||f).focus();const g=b=>{if(b.key!=="Tab")return;const y=h();if(!y.length)return;const S=y[0],v=y[y.length-1];b.shiftKey&&document.activeElement===S?(b.preventDefault(),v.focus()):!b.shiftKey&&document.activeElement===v&&(b.preventDefault(),S.focus())};return f.addEventListener("keydown",g),()=>f.removeEventListener("keydown",g)},[]),a.useEffect(()=>{const f=h=>{h.key==="Escape"&&(h.preventDefault(),h.stopPropagation(),d())};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[d]),a.createElement("div",{className:"ps-budget-sheet-backdrop",onMouseDown:f=>{f.target===f.currentTarget&&(f.preventDefault(),d())}},a.createElement("div",{className:"ps-budget-sheet",role:"dialog","aria-modal":"true","aria-label":t,ref:m,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},p),u?a.createElement("button",{type:"button",className:`ps-mini-button ${i?"is-danger":"is-primary"}`,onClick:u,disabled:o||l},o?"…":r):null))))}function tt({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 Qt({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 l0(t){const e=t.known?s0[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 c0(t){if(!t.split)return a.createElement("span",{className:"ps-budget-split"},"—");const e="Parts of the input, not additions to it: the total is input + output.";return a.createElement("span",{className:"ps-budget-split"},a.createElement("span",null,"in ",ne(t.split.input)),a.createElement("span",null,"out ",ne(t.split.output)),a.createElement("span",{title:e},"cache r ",ne(t.split.cacheRead)),a.createElement("span",{title:e},"w ",ne(t.split.cacheWrite)))}function d0(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.":"",o=s.splitText?` Made of ${s.splitText}.`:"";return`${n} · ${e.label} — ${r}. It ${Bi(s.resetsLabel)}.${i}${o}`}function u0({controller:t,view:e,defaults:s=null}){const n=a.useCallback((l,c="*")=>{t.selectBudgetProvider(l,c).catch(()=>{})},[t]),r=l=>l.kind==="model"?a.createElement("td",{className:"ps-budget-grid-name is-model"},a.createElement("button",{type:"button",className:"ps-budget-grid-pick","aria-pressed":l.selected?"true":"false",onClick:()=>n(l.providerName,l.scope)},a.createElement("span",{className:"ps-budget-grid-mname"},l.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":l.selected?"true":"false","aria-expanded":l.modelRowCount>0?l.expanded?"true":"false":void 0,onClick:()=>n(l.providerName)},a.createElement("span",{className:"ps-budget-grid-pname"},l.label),l.ownerLabel?a.createElement("span",{className:"ps-budget-grid-owner"},`(${l.ownerLabel})`):null,l.classLabel?a.createElement("span",{className:`ps-budget-chip is-${l.class}`,title:l.class==="shared"?"Shared: anyone may spend from it. An administrator manages its limits.":l.ownedByMe===!1?"A user provider belonging to another user.":"Your own provider. Only you see it or spend from it."},l.classLabel):null,s?.mine?.provider===l.providerName?a.createElement("span",{className:"ps-budget-chip"},"my default"):null,s?.cluster?.provider===l.providerName?a.createElement("span",{className:"ps-budget-chip"},"cluster default"):null,s?.system?.provider===l.providerName?a.createElement("span",{className:"ps-budget-chip"},"system default"):null,l.hold?a.createElement("span",{className:"ps-budget-chip is-hold",title:`It ${l.hold.label}.`},"on hold"):null,l.allowanceLabel?a.createElement("span",{className:"ps-budget-grid-allow"},l.allowanceLabel):null,l.expandLabel?a.createElement("span",{className:"ps-budget-grid-teaser"},l.expandLabel):null)),i=l=>a.createElement("tr",{key:l.key,className:`ps-budget-grid-row${l.kind==="model"?" is-model":""}${l.selected?" is-on":""}`,onClick:c=>{c.target?.closest?.("button")||n(l.providerName,l.kind==="model"?l.scope:"*")}},r(l),e.columns.map(c=>a.createElement("td",{key:c.id,className:"ps-budget-grid-num","data-period":c.label,title:d0(l,c,l.cells[c.id])},l0(l.cells[c.id])))),o=l=>a.createElement("tr",{key:`${l.key}:split`,className:`ps-budget-grid-split${l.kind==="model"?" is-model":""}`,"aria-label":`What ${l.kind==="model"?l.label:l.providerName} spent, by kind of token`},a.createElement("td",{className:"ps-budget-grid-split-name"}),e.columns.map(c=>a.createElement("td",{key:c.id,className:"ps-budget-grid-num is-split","data-period":c.label},c0(l.cells[c.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(l=>a.createElement("th",{key:l.id,className:"ps-budget-grid-h is-num",scope:"col"},l.label)))),a.createElement("tbody",null,e.rows.flatMap(l=>l.selected?[i(l),o(l)]:[i(l)]))))}function p0({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 v=()=>{const E=Math.round(i.getBoundingClientRect().width);c(k=>Math.abs(E-k)<1?k:E)},w=new ResizeObserver(v);return w.observe(i),v(),()=>w.disconnect()},[i]);const d=s.days,u=d.length,p=a.useMemo(()=>{const E=l-(u-1)*5,k=l>0?Math.floor(E/30):7,x=Math.max(1,Math.min(7,k)),T=Math.max(1,Math.ceil(u/x)),A=new Set;for(let R=u-1;R>=0;R-=T)A.add(R);return A},[l,u]),m=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(Qt,{value:e.rangeDays,options:e.rangeOptions,label:"Chart range",onChange:v=>t.setBudgetRangeDays(v).catch(()=>{})}),a.createElement("span",{className:"ps-budget-sub"},s.rangeLabel)));if(s.failed)return a.createElement("div",r,m,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,m,a.createElement("div",{className:"ps-budget-empty"},"Reading the daily usage…"));const f=s.scaleMax,h=[1,.75,.5,.25,0],g=n0(f),b=d.filter(v=>v.tokens>0).length,y=s.quotaPct==null?null:Math.max(0,Math.min(96,100-s.quotaPct)),S=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((v,w)=>a.createElement("span",{key:v.dayUtc,className:p.has(w)?"is-tick":void 0},p.has(w)?v.label:""))));return a.createElement("div",r,m,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"},f>0?h.map(v=>a.createElement("div",{key:`t${v}`,className:"ps-budget-ytick",style:{top:`${(1-v)*100}%`}},g(f*v))):null),a.createElement("div",{className:"ps-budget-plot"},f>0?h.map(v=>a.createElement("div",{key:`g${v}`,className:"ps-budget-gridline",style:{top:`${(1-v)*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(v=>a.createElement("div",{key:v.dayUtc,className:`ps-budget-tl-col${v.tokens===0?" is-idle":""}${s.quotaTokens!=null&&v.tokens>s.quotaTokens?" is-over":""}`,title:`${v.label} · ${v.tokens?`${v.tokens.toLocaleString("en-US")} tokens · ${i0(v.turns,"turn","turns")}`:"no usage"}`},a.createElement("div",{className:"ps-budget-tl-bar",style:{height:v.tokens===0?"2px":`${Math.max(1,v.pct)}%`}})))),s.empty?a.createElement("div",{className:"ps-budget-noaxis"},`No token usage on ${n.subject} in this range.`):null)),S,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 ${u} 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 m0({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-stats"},a.createElement("div",{className:"ps-budget-system-stat"},a.createElement("strong",null,e.tokensLabel),a.createElement("span",null,"tokens")),a.createElement("div",{className:"ps-budget-system-stat"},a.createElement("strong",null,ne(e.turns)),a.createElement("span",null,e.turns===1?"turn":"turns")),e.turns>0?a.createElement("div",{className:"ps-budget-system-stat"},a.createElement("strong",null,ne(Math.round(e.tokens/e.turns))),a.createElement("span",null,"tokens / turn")):null),e.models.length?a.createElement("table",{className:"ps-budget-system-models"},a.createElement("thead",null,a.createElement("tr",null,a.createElement("th",{scope:"col"},"Model"),a.createElement("th",{scope:"col",className:"is-num"},"Tokens"),a.createElement("th",{scope:"col",className:"is-share"},"Share"),a.createElement("th",{scope:"col",className:"is-num"},"Turns"))),a.createElement("tbody",null,e.models.map(n=>{const r=e.tokens>0?n.tokens/e.tokens:0,i=Math.round(r*100);return a.createElement("tr",{key:n.key},a.createElement("td",{className:"ps-budget-system-model-name"},s(n.label)),a.createElement("td",{className:"is-num"},n.tokensLabel),a.createElement("td",{className:"is-share"},a.createElement("span",{className:"ps-budget-system-bar",role:"img","aria-label":`${i}% of system spend`},a.createElement("span",{className:"ps-budget-system-bar-fill",style:{width:`${Math.max(r>0?1:0,r*100)}%`}})),a.createElement("span",{className:"ps-budget-system-pct"},`${i}%`)),a.createElement("td",{className:"is-num"},ne(n.turns)))}))):a.createElement("div",{className:"ps-budget-sub"},"No system spend in this range.")):null)}function f0({row:t,rawRows:e,models:s,modelsLoading:n,modelsError:r,onRetryModels:i,isAdmin:o,busy:l,error:c,onCancel:d,onRun:u,initialPeriod:p="day",initialScope:m="*"}){const f=t.class==="shared",h=t.manageable===!0,g=[...h?[{value:"limit",label:"Limits"}]:[],...h&&o&&f?[{value:"allowance",label:"Allowance"}]:[],...h&&o?[{value:"hold",label:"Hold"}]:[]],[b,y]=a.useState("limit"),[S,v]=a.useState(p),[w,E]=a.useState(m==="*"?"all":"model"),[k,x]=a.useState(m==="*"?"":m),[T,A]=a.useState("");a.useEffect(()=>{!k&&s[0]&&x(s[0].qualifiedName)},[s,k]);const R=e.find(z=>z.providerName===t.providerName&&z.rowKind!=="model")||null,N=w==="model"?k||s[0]?.qualifiedName||"":null,$=w==="model"?e.find(z=>z.providerName===t.providerName&&z.rowKind==="model"&&z.scope===N)||null:R,F=$?.periods?.[S]||null,I=F?.quotaTokens??null,O=$?Number(F?.usedTokens)||0:null,M=O!=null,B=t.cells[S]?.resetsLabel||null,D=cc[S]||S,j=N||"all models";a.useEffect(()=>{A(I==null?"":Number(I).toLocaleString("en-US"))},[I,S,N]);const V=r0(T),C=!!V&&(w!=="model"||!!N),U=I!=null,H=Number.isFinite(t.allowancePct)?t.allowancePct:100,Y=V==null||H>=100?V:Math.max(1,Math.floor(V*H/100)),te=Number(F?.yourUsedTokens),ee=M&&V!==null&&O>=V,J=!ee&&V!==null&&Y!==V&&Number.isFinite(te)&&te>=Y,ae=Number.isFinite(t.allowancePct)?t.allowancePct:100,[de,Z]=a.useState(String(ae)),le=Number(String(de).trim()),$e=Number.isFinite(le)&&le>=1&&le<=100&&Math.floor(le)===le,be=["day","week","month"].map(z=>({id:z,label:cc[z],tokens:R?.periods?.[z]?.quotaTokens??null})).filter(z=>z.tokens!=null),Re=!!t.hold,[Se,rt]=a.useState(Re?"release":"forever"),[ce,Ke]=a.useState(""),Ne=(()=>{if(Se!=="until"||!ce)return null;const z=new Date(ce);return Number.isNaN(z.getTime())?null:z.toISOString()})(),Xe=!!Ne&&Date.parse(Ne)<=Date.now(),q=Se!=="until"||!!Ne&&!Xe,he=Se!=="until"?null:Xe?"That time has already passed. A hold has to end in the future.":ce&&!Ne?"That is not a time this can read.":null,Be={limit:"Limits",allowance:"Allowance",hold:"Hold"},Ee={limit:U?"Replace limit":"Save limit",allowance:"Save allowance",hold:Se==="release"?"Release hold":"Place hold"},Pe={limit:"Limits are enforced.",allowance:"Applies to everyone.",hold:"Stops new turns."},Te=b==="limit"?C:b==="allowance"?$e:b==="hold"?q:!0,Le=()=>{b==="limit"?C&&u("limit",{period:S,model:N,tokens:V}):b==="allowance"?$e&&u("allowance",{pct:le}):b==="hold"&&u("hold",Se==="release"?{release:!0,untilUtc:null}:{release:!1,untilUtc:Ne})},St=a.createElement(a.Fragment,null,a.createElement(tt,{label:"Time period",hint:"One limit per period and scope."},a.createElement(Qt,{value:S,onChange:v,options:t0,label:"Time period"})),a.createElement(tt,{label:"Applies to"},a.createElement(Qt,{value:w,onChange:E,label:"Applies to",options:[{value:"all",label:"all models"},{value:"model",label:"one model"}]}),w==="model"?a.createElement("select",{className:"ps-budget-input","aria-label":"Model this limit applies to",value:k,onChange:z=>x(z.target.value)},s.length===0?a.createElement("option",{value:""},n?"Loading models…":r?"Model catalog unavailable":"No models listed for this provider"):s.map(z=>a.createElement("option",{key:z.qualifiedName,value:z.qualifiedName},z.qualifiedName))):null,r?a.createElement("div",{className:"ps-budget-note is-warn",role:"status"},"Could not load the model catalog. Existing model limits remain editable. ",a.createElement("button",{type:"button",onClick:i,disabled:n},"Retry")):null),a.createElement(tt,{label:"Tokens",hint:V?`= ${V.toLocaleString("en-US")} tokens.`:T.trim()?"A whole number of tokens: 20,000,000 or 20M.":"Remove the limit to uncap."},a.createElement("input",{className:`ps-budget-input${T&&!V?" is-invalid":""}`,value:T,"aria-label":"Tokens",placeholder:"20,000,000 or 20M",onChange:z=>A(z.target.value),onKeyDown:z=>{z.key==="Enter"&&Le()}})),a.createElement("div",{className:"ps-budget-consequences"},a.createElement("div",null,`${D} · ${j} — `,M?a.createElement(a.Fragment,null,a.createElement("strong",null,`${O.toLocaleString("en-US")} tokens`),f?" spent by users this period.":" spent this period."):a.createElement(a.Fragment,null,a.createElement("strong",null,"not measured yet"),". Current spend will count.")),B?a.createElement("div",{className:"ps-budget-sub"},`Resets ${B}.`):null),U?a.createElement("div",{className:"ps-budget-note is-warn"},`Replaces the existing ${ne(I)} token limit.`):null,a.createElement("div",{className:`ps-budget-note${ee||J?" is-warn":""}`},"Current spend counts. Saving does not reset usage.",ee?` ${O.toLocaleString("en-US")} already meets ${V.toLocaleString("en-US")}, so sessions on ${t.providerName} pause on their next turn${B?` — until this period ${Bi(B)}`:""}.`:J?` At ${H}% each that is ${Y.toLocaleString("en-US")} per person, which you have already spent — so sessions pause on their next turn${B?` — until this period ${Bi(B)}`:""}.`:""),U?a.createElement("div",null,a.createElement("button",{type:"button",className:"ps-mini-button is-danger",disabled:l,onClick:()=>u("removeLimit",{period:S,model:N})},`Remove the ${D} · ${j} limit`),a.createElement("div",{className:"ps-budget-note"},"Usage history is kept.")):null),K=a.createElement(a.Fragment,null,a.createElement(tt,{label:"Share per person",hint:$e?le>=100?"100% removes the per-person ceiling.":`Each person may use up to ${le}% of each limit, per period.`:"A whole number from 1 to 100."},a.createElement("input",{className:`ps-budget-input${de&&!$e?" is-invalid":""}`,value:de,"aria-label":"Share per person, as a percentage",inputMode:"numeric",placeholder:"20",onChange:z=>Z(z.target.value),onKeyDown:z=>{z.key==="Enter"&&$e&&Le()}})),a.createElement("div",{className:"ps-budget-consequences"},be.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,be.map(z=>a.createElement("div",{key:z.id},`${z.label} · ${ne(z.tokens)} → `,a.createElement("strong",null,$e?`${ne(Math.floor(z.tokens*le/100))} per person`:"—"))),a.createElement("div",{className:"ps-budget-note"},"The provider limit still caps total spend.")),$e&&le<ae?a.createElement("div",{className:"ps-budget-note is-warn"},"Users already past the new ceiling pause on their next turn."):null)),P=a.createElement(a.Fragment,null,a.createElement(tt,{label:"What to do"},a.createElement(Qt,{value:Se,onChange:rt,label:"What to do",options:[...Re?[{value:"release",label:"release it"}]:[],{value:"forever",label:"hold until released"},{value:"until",label:"hold until a time"}]})),Se==="until"?a.createElement(tt,{label:"Ends at",hint:he||"Sessions resume at this time."},a.createElement("input",{className:`ps-budget-input${ce&&!q?" is-invalid":""}`,"aria-label":"The hold ends at",type:"datetime-local",value:ce,onChange:z=>Ke(z.target.value)})):null,Re?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${Se==="release"?"":" is-warn"}`},Se==="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(Zu,{title:Be[b],subtitle:`${t.providerName}${f?" · shared":""}`,confirmLabel:Ee[b]||"",danger:b==="hold"&&Se==="release",busy:l,disabled:!Te,error:c,onCancel:d,onConfirm:Ee[b]?Le:null,cancelLabel:Ee[b]?"Cancel":"Done",footNote:Pe[b]},g.length>1?a.createElement(tt,{label:"What to change"},a.createElement(Qt,{value:b,onChange:y,options:g,label:"What to change"})):null,b==="limit"?St:null,b==="allowance"?K:null,b==="hold"?P:null)}function h0({types:t,existingNames:e,isAdmin:s,busy:n,error:r,onDirty:i,onCancel:o,onConfirm:l,initialName:c="",initialShared:d=!1,initialType:u="",updateProvider:p=null}){const m=!!p,[f,h]=a.useState(c),[g,b]=a.useState(u||t[0]?.id||""),[y,S]=a.useState(""),[v,w]=a.useState(""),[E,k]=a.useState(s&&d),x=a.useRef(null);a.useEffect(()=>{x.current?.focus()},[]),a.useEffect(()=>{!g&&t[0]&&b(t[0].id)},[t,g]);const T=f.trim(),A=!m&&e.some(j=>j.toLowerCase()===T.toLowerCase()),R=T!==""&&!/^[A-Za-z0-9._-]+$/.test(T),N=T.length>64,$=t.find(j=>j.id===g)?.usesWorkloadIdentity===!0,F=$,I=F?!0:E,O=!!T&&!A&&!R&&!N&&!!g&&($||!!y.trim())&&(!F||s),M=/github/i.test(g),B=()=>{if(!O)return;const j={name:T,type:g,shared:I,credentials:$?{kind:"workloadIdentity"}:M?{githubToken:y.trim()}:{apiKey:y.trim()},baseUrl:v.trim()||null};S(""),l(j)},D=()=>{S(""),o()};return a.createElement(Zu,{title:m?`Update key for ${T}`:M?"Add GitHub Copilot provider":"Add model provider",subtitle:I?"Shared":"Personal",confirmLabel:m?"Update key":"Add provider",busy:n,disabled:!O,error:r,onCancel:D,onConfirm:B,footNote:m?"Only the key changes. The name, type, base URL, defaults, system-session routing and usage history all stay as they are.":""},a.createElement(tt,{label:"Name",hint:A?"A provider with that name already exists, and names are unique across the cluster.":N?`Too long: ${T.length} characters, and a name may be at most 64.`:R?'Letters, numbers, dot, dash and underscore only — no colon, no spaces, no accents: a session refers to it as "<provider>:<model>".':m?"Not changing. Sessions keep referring to it as provider:model.":"Permanent. Used in provider:model."},a.createElement("input",{ref:x,className:`ps-budget-input${m?" is-static":""}${(A||R||N)&&T?" is-invalid":""}`,"aria-label":"Provider name",value:f,placeholder:"azure-prod",disabled:m,onChange:j=>{i?.(),h(j.target.value)},onKeyDown:j=>{j.key==="Enter"&&O&&B()}})),a.createElement(tt,{label:"Type",hint:m?"Not changing.":"Backend and model catalog."},a.createElement("select",{className:`ps-budget-input${m?" is-static":""}`,"aria-label":"Provider type",value:g,disabled:m,onChange:j=>{i?.(),b(j.target.value)}},t.length===0?a.createElement("option",{value:""},"No provider types are listed on this deployment"):t.map(j=>a.createElement("option",{key:j.id,value:j.id},j.id)))),$?a.createElement(tt,{label:"Authentication",hint:"Nothing is stored. The worker mints a short-lived token for each request."},a.createElement("div",{className:"ps-budget-input is-static",role:"note"},"Use the Workload Identity configured in the worker")):a.createElement(tt,{label:m?M?"New GitHub Copilot token":"New API key":M?"GitHub Copilot token":"API key",hint:m?"Replaces the current one. The existing key is never shown.":"Paste the token value."},a.createElement("input",{className:"ps-budget-input",type:"password",autoComplete:"off","aria-label":m?M?"New GitHub Copilot token":"New API key":M?"GitHub Copilot token":"API key",value:y,placeholder:"Paste token",onChange:j=>{i?.(),S(j.target.value)},onKeyDown:j=>{j.key==="Enter"&&O&&B()}})),m?null:a.createElement(tt,{label:"Base URL",hint:"Optional."},a.createElement("input",{className:"ps-budget-input",value:v,placeholder:"https://…","aria-label":"Base URL",onChange:j=>w(j.target.value)})),F&&!m?a.createElement(tt,{label:"Access",hint:"It runs on the worker's own identity, which belongs to the organization, so it cannot be personal."},a.createElement("div",{className:"ps-budget-input is-static",role:"note"},"Shared")):s&&!m?a.createElement(tt,{label:"Access"},a.createElement(Qt,{value:E?"shared":"mine",onChange:j=>k(j==="shared"),label:"Access",options:[{value:"shared",label:"Shared"},{value:"mine",label:"Only me"}]})):null)}function g0(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,e.tab,e.summary,t.auth?.authorization?.role,t.admin?.profile]}const dc=["#5b8def","#e8833a","#3fb27f","#c95d63","#8f6fd8","#2fa8bf","#c9a227","#d1699e","#7a9a3b","#8a8a8a"],Hi=t=>dc[t%dc.length];function y0({view:t,included:e}){const l=t.agents.filter(b=>e.has(b.agent)).map(b=>b.agent),c=t.dayKeys.map(b=>{const y=t.daily.get(b)||new Map;return l.reduce((S,v)=>S+(y.get(v)||0),0)}),d=Math.max(0,...c)||1,u=180,p=b=>u-b/d*u,m=Math.max(1,t.dayKeys.length),f=662/m,h=Math.max(3,f*.66),g=m>40?10:m>20?5:1;return a.createElement("svg",{className:"ps-summary-chart",viewBox:"0 0 720 210",role:"img","aria-label":`Tokens per day by agent, ${m} days`},[0,.25,.5,.75,1].map(b=>a.createElement("g",{key:b},a.createElement("line",{x1:58,x2:720,y1:8+u-b*u,y2:8+u-b*u,className:"ps-summary-chart__grid"}),a.createElement("text",{x:52,y:8+u-b*u+3,className:"ps-summary-chart__tick",textAnchor:"end"},xe(b*d)))),t.dayKeys.map((b,y)=>{const S=t.daily.get(b)||new Map,v=58+y*f+(f-h)/2;let w=0;const E=l.map((x,T)=>{const A=S.get(x)||0;if(A<=0)return null;const R=8+p(w);w+=A;const N=8+p(w);return a.createElement("rect",{key:x,x:v,y:N,width:h,height:Math.max(.5,R-N-.5),fill:Hi(t.agents.findIndex($=>$.agent===x))})}),k=`${b}: ${xe(w)} tokens
|
|
107
|
-
`+l.map(x=>[x,S.get(x)||0]).filter(([,x])=>x>0).sort((x,T)=>T[1]-x[1]).map(([x,T])=>`${x}: ${xe(T)}`).join(`
|
|
108
|
-
`);return a.createElement("g",{key:b,className:"ps-summary-chart__bar"},a.createElement("title",null,k),E,y%g===0||y===m-1?a.createElement("text",{x:v+h/2,y:204,className:"ps-summary-chart__day",textAnchor:"middle"},b.slice(5)):null)}))}const uc={agent:(t,e)=>t.agent.localeCompare(e.agent),turns:(t,e)=>e.turns-t.turns,sessions:(t,e)=>e.sessions-t.sessions,total:(t,e)=>e.total-t.total,perTurn:(t,e)=>e.perTurn-t.perTurn,cacheRead:(t,e)=>e.cacheRead-t.cacheRead};function b0(t){const e=t.budget?.agents||{},s=t.budget?.summary||{};return[e.loading,e.error,e.fetchedAt,s.days,s.preset,(s.providers||[]).join(","),(t.budget?.grid||[]).length]}function S0({controller:t}){const e=se(t,b0,qe),s=a.useMemo(()=>dg(t.getState()),[t,e]),n=a.useMemo(()=>Bd(t.getState()),[t,e]);a.useEffect(()=>{!s.loaded&&!s.loading&&!s.error&&t.loadUsageAgents().catch(()=>{})},[t]);const[r,i]=a.useState(()=>new Set),[o,l]=a.useState("total"),c=a.useMemo(()=>new Set(s.agents.map(w=>w.agent).filter(w=>!r.has(w))),[s,r]),d=w=>i(E=>{const k=new Set(E);return k.has(w)?k.delete(w):k.add(w),k}),u=s.agents.map(w=>w.agent),p=u.filter(w=>c.has(w)).length,m=u.length>0&&p===u.length,f=p===0,h=()=>i(()=>f?new Set:new Set(u)),g=a.useCallback(w=>{w&&(w.indeterminate=!m&&!f)},[m,f]),b=a.useMemo(()=>[...s.agents].sort(uc[o]||uc.total),[s,o]),y=w=>t.setUsageSummaryFilter({days:w}).catch(()=>{}),S=({preset:w,providers:E})=>t.setUsageSummaryFilter({preset:w,providers:E}).catch(()=>{}),v=(w,E,k)=>a.createElement("th",{key:E,title:k||"Click to sort by this column",style:{cursor:"pointer"},onClick:()=>l(w)},E,o===w?" ▾":"");return a.createElement("div",{className:`ps-summary${s.loading?" is-loading":""}`},a.createElement("div",{className:"ps-summary__filters"},a.createElement(ep,{view:n,onChange:S}),a.createElement("div",{className:"ps-budget-seg",role:"group","aria-label":"Window"},Ju.map(w=>a.createElement("button",{key:w,type:"button",className:`ps-budget-seg__button${s.days===w?" is-on":""}`,"aria-pressed":s.days===w,onClick:()=>y(w)},`${w}d`))),a.createElement("span",{className:"ps-summary__scope"},s.scope==="cluster"?"Whole cluster, system sessions included":"Your own turns")),s.error?a.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},a.createElement("div",null,"The agent pivot could not be read. "),a.createElement("div",{className:"ps-budget-sub"},s.error)):null,a.createElement("div",{className:"ps-summary__card"},a.createElement("div",{className:"ps-summary__card-head"},a.createElement("b",null,"Tokens per day, by agent"),a.createElement("span",{className:"ps-summary__muted"},`last ${s.days} days · ${xe(s.windowTotal)} tokens · untick a row below to slice the chart`)),s.loaded||s.windowTotal>0?a.createElement(y0,{view:s,included:c}):null,a.createElement("div",{className:"ps-summary__legend",style:{flexWrap:"wrap",marginTop:"6px"}},s.agents.map((w,E)=>c.has(w.agent)?a.createElement("span",{key:w.agent},a.createElement("i",{className:"ps-summary-dot",style:{background:Hi(E)}}),w.agent):null))),a.createElement("div",{className:"ps-summary__card"},a.createElement("div",{className:"ps-summary__card-head"},a.createElement("b",null,"By agent"),a.createElement("span",{className:"ps-summary__muted"},"tokens/turn is the window average — a ledger row is one turn")),s.agents.length===0?a.createElement("div",{className:"ps-budget-empty"},s.loaded?"No token usage in this window.":s.loading?"Reading…":""):a.createElement("div",{className:"ps-summary__table-wrap"},a.createElement("table",{className:"ps-summary__table"},a.createElement("thead",null,a.createElement("tr",null,a.createElement("th",{title:f?"Put every agent back in the chart":"Clear every agent out of the chart"},a.createElement("input",{type:"checkbox",ref:g,checked:m,onChange:h,"aria-label":f?"Select all agents":"Clear all agents"})),v("agent","Agent"),a.createElement("th",{title:"Distinct model names this agent ran in the window"},"Models"),v("turns","Turns"),v("sessions","Sessions"),v("total","Total"),v("perTurn","Tok/turn","Window average: total tokens over ledger turns"),v("cacheRead","Cache read"),a.createElement("th",null,"Cache write"),a.createElement("th",null,"Share"),a.createElement("th",null,"Trend"))),a.createElement("tbody",null,b.map(w=>a.createElement("tr",{key:w.agent},a.createElement("td",null,a.createElement("input",{type:"checkbox",checked:!r.has(w.agent),onChange:()=>d(w.agent),"aria-label":`Include ${w.agent} in the chart`})),a.createElement("td",{className:"is-model"},a.createElement("i",{className:"ps-summary-dot",style:{background:Hi(s.agents.findIndex(E=>E.agent===w.agent))}})," ",w.agent),a.createElement("td",{title:w.models.join(", ")},w.models.length<=2?w.models.join(", "):`${w.models.slice(0,2).join(", ")} +${w.models.length-2}`),a.createElement("td",null,w.turns),a.createElement("td",null,w.sessions),a.createElement("td",{className:"is-total"},xe(w.total)),a.createElement("td",null,xe(Math.round(w.perTurn))),a.createElement("td",null,xe(w.cacheRead)),a.createElement("td",null,xe(w.cacheWrite)),a.createElement("td",{className:"is-share"},a.createElement("i",{className:"ps-summary-share",style:{width:`${Math.max(1,Math.round(w.share*100))}px`}}),`${(w.share*100).toFixed(w.share<.1?1:0)}%`),a.createElement("td",null,a.createElement(tp,{values:s.dayKeys.map(E=>{const k=w.daily.find(x=>x.day===E);return k&&Number(k.total)||0})})))))))))}const Ju=[14,30,90],v0=[{id:"all",label:"All providers"},{id:"shared",label:"Shared providers"},{id:"users",label:"User providers"}];function w0(t){if(t.preset==="all")return"All providers";if(t.preset==="shared")return"Shared providers";if(t.preset==="users")return"User providers";const e=t.selectedProviders.length;return e===0?"No providers":e===1?t.selectedProviders[0]:`${e} providers`}function ep({view:t,onChange:e}){const[s,n]=a.useState(!1),r=a.useRef(null);a.useEffect(()=>{if(!s)return;const d=p=>{r.current&&!r.current.contains(p.target)&&n(!1)},u=p=>{p.key==="Escape"&&n(!1)};return document.addEventListener("pointerdown",d),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",d),document.removeEventListener("keydown",u)}},[s]);const i=d=>d==="all"?[]:t.providers.filter(u=>d==="shared"?u.class==="shared":u.class!=="shared").map(u=>u.name),o=new Set(t.preset==="all"?t.providers.map(d=>d.name):t.preset==="custom"?t.selectedProviders:i(t.preset)),l=d=>{e({preset:d,providers:i(d)}),n(!1)},c=d=>{const u=new Set(o);u.has(d)?u.delete(d):u.add(d),e({preset:"custom",providers:Array.from(u)})};return a.createElement("div",{className:"ps-summary-picker",ref:r},a.createElement("button",{type:"button",className:`ps-mini-button ps-summary-picker__button${s?" is-open":""}`,"aria-haspopup":"listbox","aria-expanded":s,"aria-label":"Providers filter",onClick:()=>n(d=>!d)},w0(t)," ",a.createElement("span",{"aria-hidden":"true"},"▾")),s?a.createElement("div",{className:"ps-summary-picker__menu",role:"listbox","aria-label":"Providers"},v0.map(d=>a.createElement("button",{key:d.id,type:"button",role:"option","aria-selected":t.preset===d.id,className:`ps-summary-picker__preset${t.preset===d.id?" is-on":""}`,onClick:()=>l(d.id)},d.label)),a.createElement("div",{className:"ps-summary-picker__rule","aria-hidden":"true"}),a.createElement("button",{type:"button",className:"ps-summary-picker__preset is-clear",onClick:()=>e({preset:"custom",providers:[]})},"Clear all"),t.providers.length===0?a.createElement("div",{className:"ps-summary-picker__empty"},"No providers to choose from."):t.providers.map(d=>a.createElement("label",{key:d.name,className:"ps-summary-picker__row"},a.createElement("input",{type:"checkbox",checked:o.has(d.name),onChange:()=>c(d.name),"aria-label":`Include ${d.name}`}),a.createElement("span",{className:"ps-summary-picker__name"},d.name),a.createElement("span",{className:`ps-scope-badge is-${d.class}`},d.class==="shared"?"shared":"user")))):null)}function xe(t){return ne(Number(t)||0)}function E0({series:t}){const o=t.map(y=>y.total),l=Math.max(0,...o),c=y=>y,d=c(l)||1,u=160,p=y=>u-c(y)/d*u,m=Math.max(1,t.length),f=662/m,h=Math.max(3,f*.66),g=[0,.25,.5,.75,1].map(y=>({f:y,label:xe(y*l)})),b=m>40?10:m>20?5:1;return a.createElement("svg",{className:"ps-summary-chart",viewBox:"0 0 720 190",role:"img","aria-label":`Tokens per day, ${t.length} days`},g.map(y=>a.createElement("g",{key:y.label+y.f},a.createElement("line",{x1:58,x2:720,y1:8+u-y.f*u,y2:8+u-y.f*u,className:"ps-summary-chart__grid"}),a.createElement("text",{x:52,y:8+u-y.f*u+3,className:"ps-summary-chart__tick",textAnchor:"end"},y.label))),t.map((y,S)=>{const v=58+S*f+(f-h)/2,w=Math.min(y.input,y.cacheRead),E=Math.min(y.input-w,y.cacheWrite),k=y.input-w-E,x=k+w,T=y.input,A=T+y.output,R=8+u,N=8+p(k),$=8+p(x),F=8+p(T),I=8+p(A),O=`${y.day}: ${xe(y.total)} tokens · in ${xe(y.input)} (cache r ${xe(y.cacheRead)} · w ${xe(y.cacheWrite)}) · out ${xe(y.output)} · ${y.turns} turns`;return a.createElement("g",{key:y.day,className:"ps-summary-chart__bar"},a.createElement("title",null,O),a.createElement("rect",{x:v,y:N,width:h,height:Math.max(0,R-N),className:"is-in"}),a.createElement("rect",{x:v,y:$,width:h,height:Math.max(0,N-$),className:"is-cache"}),a.createElement("rect",{x:v,y:F,width:h,height:Math.max(0,$-F),className:"is-cache-w"}),a.createElement("rect",{x:v,y:I,width:h,height:Math.max(0,F-I),className:"is-out"}),S%b===0||S===m-1?a.createElement("text",{x:v+h/2,y:184,className:"ps-summary-chart__day",textAnchor:"middle"},y.day.slice(5)):null)}))}function tp({values:t}){const e=Math.max(0,...t);return a.createElement("span",{className:"ps-summary-spark","aria-hidden":"true",style:{gridAutoColumns:t.length>30?"2px":"4px"}},t.map((s,n)=>a.createElement("i",{key:n,style:{height:`${e>0?Math.max(s>0?8:0,s/e*100):0}%`}})))}function ni({label:t,w:e}){return a.createElement("div",{className:"ps-summary-kpi"},a.createElement("div",{className:"ps-summary-kpi__label"},t),a.createElement("div",{className:"ps-summary-kpi__value"},xe(e.total)),a.createElement("div",{className:"ps-summary-kpi__split",title:"Total is input + output. Cache read and write are parts of the input, not additions to it."},a.createElement("span",null,a.createElement("i",{className:"ps-summary-dot is-in"}),"in ",xe(e.input)),a.createElement("span",null,a.createElement("i",{className:"ps-summary-dot is-cache"}),"cache r ",xe(e.cacheRead)),a.createElement("span",null,a.createElement("i",{className:"ps-summary-dot is-cache-w"}),"w ",xe(e.cacheWrite)),a.createElement("span",null,a.createElement("i",{className:"ps-summary-dot is-out"}),"out ",xe(e.output)),a.createElement("span",null,`· ${e.turns} turns`)))}function k0(t){const e=t.budget?.summary||{};return[e.loading,e.error,e.fetchedAt,e.days,e.preset,(e.providers||[]).join(","),(t.budget?.grid||[]).length]}function I0({controller:t}){const e=se(t,k0,qe),s=a.useMemo(()=>Bd(t.getState()),[t,e]);a.useEffect(()=>{!s.loaded&&!s.loading&&!s.error&&t.loadUsageSummary().catch(()=>{})},[t]);const n=l=>t.setUsageSummaryFilter({days:l}).catch(()=>{}),r=({preset:l,providers:c})=>t.setUsageSummaryFilter({preset:l,providers:c}).catch(()=>{}),i=s.classes.filter(l=>l.total>0),o=`last ${s.days} days`;return a.createElement("div",{className:`ps-summary${s.loading?" is-loading":""}`},a.createElement("div",{className:"ps-summary__filters"},a.createElement(ep,{view:s,onChange:r}),a.createElement("div",{className:"ps-budget-seg",role:"group","aria-label":"Window"},Ju.map(l=>a.createElement("button",{key:l,type:"button",className:`ps-budget-seg__button${s.days===l?" is-on":""}`,"aria-pressed":s.days===l,"aria-label":`Last ${l} days`,onClick:()=>n(l)},`${l}d`))),a.createElement("span",{className:"ps-summary__scope"},s.scope==="cluster"?"Whole cluster, system sessions included":"Your own turns")),s.error?a.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},a.createElement("div",null,"The summary could not be read. "),a.createElement("div",{className:"ps-budget-sub"},s.error)):null,a.createElement("div",{className:"ps-summary__kpis"},a.createElement(ni,{label:"Today (UTC)",w:s.windows.day}),a.createElement(ni,{label:"Last 7 days",w:s.windows.week}),a.createElement(ni,{label:"Last 30 days",w:s.windows.month})),a.createElement("div",{className:"ps-summary__card"},a.createElement("div",{className:"ps-summary__card-head"},a.createElement("b",null,"Tokens per day"),a.createElement("span",{className:"ps-summary__legend"},a.createElement("span",{title:"Prompt tokens that were neither served from nor written to the cache"},a.createElement("i",{className:"ps-summary-dot is-in"}),"input"),a.createElement("span",{title:"The part of the input served from the cache"},a.createElement("i",{className:"ps-summary-dot is-cache"}),"cache read"),a.createElement("span",{title:"The part of the input written to the cache"},a.createElement("i",{className:"ps-summary-dot is-cache-w"}),"cache write"),a.createElement("span",null,a.createElement("i",{className:"ps-summary-dot is-out"}),"output")),a.createElement("span",{className:"ps-summary__muted"},`${o} · ${xe(s.windowTotal)} tokens`),null),s.windowTotal>0||s.loaded?a.createElement(E0,{series:s.series}):null,i.length>1?a.createElement("div",{className:"ps-summary__muted"},"By charge: ",i.map((l,c)=>`${c?" · ":""}${l.chargeClass} ${xe(l.total)}`).join("")):null),a.createElement("div",{className:"ps-summary__card"},a.createElement("div",{className:"ps-summary__card-head"},a.createElement("b",null,"By model"),a.createElement("span",{className:"ps-summary__muted"},`${o} · across providers, efforts and context tiers`)),s.models.length===0?a.createElement("div",{className:"ps-budget-empty"},s.loaded?"No token usage in this window.":s.loading?"Reading…":""):a.createElement("div",{className:"ps-summary__table-wrap"},a.createElement("table",{className:"ps-summary__table"},a.createElement("thead",null,a.createElement("tr",null,[["Model"],["Turns"],["Providers","Distinct provider names in the ledger for this window — including providers since deleted"],["Input","Prompt tokens, including what was served from and written to the cache"],["Output"],["Cache read","The part of Input served from the cache"],["Cache write","The part of Input written to the cache"],["Total","Input + Output"],["Share"],["Trend"]].map(([l,c])=>a.createElement("th",{key:l,title:c},l)))),a.createElement("tbody",null,s.models.map(l=>a.createElement("tr",{key:l.model},a.createElement("td",{className:"is-model"},l.model),a.createElement("td",null,l.turns),a.createElement("td",null,l.providers),a.createElement("td",null,xe(l.input)),a.createElement("td",null,xe(l.output)),a.createElement("td",null,xe(l.cacheRead)),a.createElement("td",null,xe(l.cacheWrite)),a.createElement("td",{className:"is-total"},xe(l.total)),a.createElement("td",{className:"is-share"},a.createElement("i",{className:"ps-summary-share",style:{width:`${Math.max(1,Math.round(l.share*100))}px`}}),`${(l.share*100).toFixed(l.share<.1?1:0)}%`),a.createElement("td",null,a.createElement(tp,{values:l.sparkline})))))))))}function x0({controller:t}){const e=se(t,g0,qe),s=a.useMemo(()=>ug(t.getState()),[t,e]),n=a.useMemo(()=>t.getState().budget?.grid||[],[t,e]),[r,i]=a.useState([]),[o,l]=a.useState(!0),[c,d]=a.useState(!1),[u,p]=a.useState(0),[m,f]=a.useState(new Map),[h,g]=a.useState(null),b=a.useCallback(()=>{typeof t.transport.getDefaults=="function"&&Promise.resolve(t.transport.getDefaults()).then(D=>g(D||null)).catch(()=>{})},[t]);a.useEffect(()=>{let D=!0;return l(!0),Promise.resolve().then(()=>{if(typeof t.transport.listModels!="function")throw new Error("Model catalog unavailable");return t.transport.listModels()}).then(j=>{D&&(i(o0(j)),d(!1))}).catch(()=>{D&&d(!0)}).finally(()=>{D&&l(!1)}),typeof t.transport.listProviders=="function"&&Promise.resolve(t.transport.listProviders()).then(j=>{if(!D)return;const V=new Map;for(const C of j?.providers||[])V.set(C.name,C.typeId||"");f(V)}).catch(()=>{}),b(),()=>{D=!1}},[t,b,u]),a.useEffect(()=>{const D=t.getState().budget||{};!D.loaded&&!D.loading&&!D.error&&t.loadProviderTable().catch(()=>{})},[t]),a.useEffect(()=>{const D=setInterval(()=>{t.refreshProviderTable().catch(()=>{})},6e4);return()=>clearInterval(D)},[t]),a.useEffect(()=>{const D=j=>{if(j.key!=="Escape")return;const V=j.target,C=V&&V.tagName;C==="SELECT"||C==="INPUT"||C==="TEXTAREA"||t.getState().ui.modal||document.querySelector(".ps-budget-sheet")||(j.preventDefault(),j.stopPropagation(),t.closeBudget())};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[t]);const[y,S]=a.useState(null),[v,w]=a.useState(!1),[E,k]=a.useState(null),x=a.useRef(null),T=D=>{x.current=typeof document<"u"?document.activeElement:null,k(null),w(!1),S(D)},A=a.useCallback(()=>{S(null),k(null),w(!1);const D=x.current;x.current=null,D&&typeof D.focus=="function"&&document.contains(D)&&D.focus()},[]),R=async(D,{keepOpen:j=!1,onDone:V=null}={})=>{w(!0),k(null);const C=await D();if(w(!1),!C||C.ok!==!0){k(C?.error||"The change was refused.");return}j||A(),V&&V(C.result||null)},N=D=>t.dispatch({type:"ui/status",text:D}),$=s.selected,F=s.selectedProviderRow,I=$?a0(r,{name:$.providerName,typeId:m.get($.providerName)||""},n):[];let O=null;y?.kind==="edit"&&F&&(O=a.createElement(f0,{row:F,rawRows:n,models:I,isAdmin:s.isAdmin,modelsLoading:o,modelsError:c,onRetryModels:()=>p(D=>D+1),initialPeriod:y.period||"day",initialScope:y.scope||"*",busy:v,error:E,onCancel:A,onRun:(D,j)=>{const V=$.providerName;if(D==="limit")return R(()=>t.setProviderLimit({provider:V,...j}),{onDone:C=>{const U=Number(C?.seededTokens)||0;N(U>0?`Limit saved. This period had already spent ${ne(U)} tokens, and they count against it.`:"Limit saved. This period has spent nothing against it yet.")}});if(D==="removeLimit")return R(()=>t.removeProviderLimit({provider:V,...j}),{onDone:()=>N(`That period no longer caps ${V}.`)});if(D==="allowance")return R(()=>t.setProviderAllowance({provider:V,pct:j.pct}),{onDone:()=>N(j.pct>=100?`Everyone shares the whole of ${V} again.`:`Each person may now use up to ${j.pct}% of each of ${V}'s limits.`)});if(D==="hold")return R(()=>t.setProviderHold({provider:V,...j}),{onDone:()=>{if(j.release){N(`The hold on ${V} is released. Sessions waiting on it wake up.`);return}const C=(t.getState().budget?.grid||[]).find(H=>H.providerName===V&&H.rowKind!=="model"),U=C?.holdIndefinite===!0||(C?.holdUntilUtc?Date.parse(C.holdUntilUtc)>Date.now():!1);N(U?`${V} is on hold. No new turn runs against it until it is released.`:`${V} is NOT on hold: the time given has already passed.`)}})}}));const M=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(ve,{icon:"↻",label:"Refresh providers and budgets",className:"ps-mini-button",disabled:s.loading||s.refreshing,onClick:()=>t.refreshProviderTable().catch(()=>{})})));let B;return s.failed?B=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?B=a.createElement("div",{className:"ps-budget-empty"},"Reading providers and budgets…"):B=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(u0,{controller:t,view:s,defaults:h}),a.createElement("div",{className:"ps-budget-actions"},a.createElement(ve,{icon:a.createElement(Gu),label:"Edit usage policy",className:"ps-mini-button",disabled:!F||!F.manageable,onClick:()=>T({kind:"edit",scope:$?.kind==="model"?$.scope:"*"})}),a.createElement("span",{className:"ps-budget-sub"},$?$.providerName:"No provider selected")),a.createElement("div",{className:"ps-budget-foot ps-budget-sub"},"Manage providers and defaults in Admin Console."),$?a.createElement(p0,{controller:t,view:s}):null,$?a.createElement(m0,{view:s}):null)),a.createElement("div",{className:"ps-budget-surface"},M,a.createElement("div",{className:"ps-budget-tabs",role:"tablist"},[["providers","Providers"],["summary","Cluster summary"],["agents","Agents"]].map(([D,j])=>a.createElement("button",{key:D,type:"button",role:"tab","aria-selected":(t.getState().budget?.tab||"providers")===D,className:`ps-budget-tab${(t.getState().budget?.tab||"providers")===D?" is-on":""}`,onClick:()=>t.setBudgetTab(D)},j))),(t.getState().budget?.tab||"providers")==="summary"?a.createElement("div",{className:"ps-budget"},a.createElement(I0,{controller:t})):t.getState().budget?.tab==="agents"?a.createElement("div",{className:"ps-budget"},a.createElement(S0,{controller:t})):a.createElement("div",{className:"ps-budget"},B),O)}function Ui({controller:t}){const e=se(t,y=>y.ui.themeId),s=se(t,y=>!!y.ui.touchScale),n=kt(e),r=se(t,y=>({rawModal:y.ui.modal,themePicker:gy(y),modelPicker:jg(y),reasoningEffortPicker:Wg(y),contextTierPicker:qg(y),sessionAgentPicker:Gg(y),sessionGroupPicker:zg(y),sessionGroupName:Vg(y),artifactPicker:Jg(y),logFilter:Qg(y),filesFilter:Zg(y),historyFormat:hy(y),renameSession:Kg(y),sessionOwnerFilter:Xg(y),artifactUpload:Yg(y),confirm:yy(y),logsFilter:y.logs.filter,filesFilterState:y.files.filter,historyFormatState:y.executionHistory?.format||"pretty"}),qe),i=r.rawModal,o=a.useRef(null),l=a.useRef(null),c=a.useRef(null),[d,u]=a.useState(""),p=i?.type==="sessionOwnerFilter";if(a.useEffect(()=>{p||u("")},[p]),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 S=y.querySelector(".ps-list-button.is-selected");S&&typeof S.scrollIntoView=="function"&&S.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 m=()=>t.handleCommand(_.CLOSE_MODAL).catch(()=>{}),f=()=>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,S="Apply",v=null,w=null)=>{const E=Array.isArray(y.rows)?y.rows:[],k=Array.isArray(y.rowItemIndexes)?y.rowItemIndexes:null,x=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",T=k&&k.length===E.length?E.map((A,R)=>{const N=k[R],$=Array.isArray(A)?A:Je([A])[0]?.runs||[{text:A?.text||"",color:A?.color}];if(N==null||N<0)return a.createElement("div",{key:`row:${R}`,className:"ps-line ps-modal-list-heading-line"},a.createElement(Ye,{runs:$,theme:n}));const F=i.items?.[N];return a.createElement("button",{key:F?.id||`row:${R}`,type:"button",className:`ps-list-button ps-modal-list-button${N===i.selectedIndex?" is-selected":""}${x?" is-hanging":""}${F?.disabled?" is-disabled":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:N})}},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Ye,{runs:$,theme:n})))}):(i.items||[]).flatMap((A,R,N)=>{const $=a.createElement("button",{key:A.id||R,type:"button",className:`ps-list-button ps-modal-list-button${R===i.selectedIndex?" is-selected":""}${x?" is-hanging":""}${A?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:R})},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Ye,{runs:Array.isArray(E?.[R])?E[R]:Je([E?.[R]])[0]?.runs||[{text:E?.[R]?.text||"",color:E?.[R]?.color}],theme:n})));return A?.group&&A.group!==N[R-1]?.group?[a.createElement("div",{key:`group:${A.group}`,className:"ps-modal-list-group","aria-hidden":"true"},A.group),$]:[$]});return a.createElement("div",{className:"ps-modal-backdrop",onClick:m},a.createElement("div",{className:`ps-modal is-list${i.type==="themePicker"?" is-theme-picker":""}`,onClick:A=>A.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:m,"aria-label":"Close",title:"Close"},"✕")),w,a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:c,className:"ps-modal-list"},T),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),Je(y.detailsLines||[]).map((A,R)=>a.createElement(st,{key:`detail:${R}`,line:A,theme:n,className:"ps-modal-detail-line"})))),a.createElement("div",{className:"ps-modal-footer"},v,a.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(_.MODAL_CONFIRM).catch(()=>{})},S))))};if(i.type==="confirm"&&r.confirm){const y=!!i.alert,S=!y&&i.action==="deleteSession",v=i.action==="regenerateSession",w=i.extras||{};return a.createElement("div",{className:"ps-modal-backdrop",onClick:m},a.createElement("div",{className:"ps-modal is-narrow",onClick:E=>E.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},r.confirm.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"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)),v?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:w.distillMode||"llm",onChange:E=>t.updateConfirmExtras({distillMode:E.currentTarget.value})},a.createElement("option",{value:"llm"},"Intelligent (LLM reads the whole transcript)"),a.createElement("option",{value:"deterministic"},"Fast (no LLM — tail + pointers)"))),(w.distillMode||"llm")==="llm"?a.createElement(A0,{controller:t,extras:w}):null,(w.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:w.instructions||"",maxLength:4e3,onChange:E=>t.updateConfirmExtras({instructions:E.currentTarget.value})}):null):null,a.createElement("div",{className:"ps-modal-footer"},y?null:a.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),a.createElement("button",{type:"button",className:`ps-modal-button ${S?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(_.MODAL_CONFIRM).catch(()=>{})},r.confirm.confirmLabel))))}if(i.type==="themePicker"&&r.themePicker)return h(r.themePicker,"Apply Theme",f());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=[["used","Most used","Ordered by how often YOU have started each agent"],["name","Name","Alphabetical by agent name"],["package","Package","Grouped by package name, then agent name"]],S=a.createElement("div",{className:"ps-agent-picker-toolbar"},a.createElement("input",{type:"search",className:"ps-agent-picker-search","data-modal-search":"true",placeholder:"Search agents, packages, tools…",value:i.query||"",autoFocus:!0,"aria-label":"Search agents",onChange:v=>t.setAgentPickerQuery(v.target.value),onKeyDown:v=>{["ArrowUp","ArrowDown","Enter","Escape","Tab"].includes(v.key)||v.stopPropagation()}}),a.createElement("div",{className:"ps-agent-picker-sorts",role:"group","aria-label":"Sort agents"},y.map(([v,w,E])=>a.createElement("button",{key:v,type:"button",className:`ps-agent-picker-sort${(i.sort||"used")===v?" is-on":""}`,title:E,"aria-pressed":(i.sort||"used")===v?"true":"false",onClick:()=>t.setAgentPickerSort(v)},w))));return h(r.sessionAgentPicker,"Create Session",null,S)}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,S=Array.isArray(y.rows)?y.rows:[],v=d.trim().toLowerCase(),w=k=>{const x=S?.[k];return(Array.isArray(x)?x:Je([x])[0]?.runs||[]).map(A=>A?.text||"").join("")||String(x?.text||"")},E=(i.items||[]).map((k,x)=>x).filter(k=>{if(!v)return!0;const x=(i.items||[])[k]||{};return`${w(k)} ${x.label||""} ${x.description||""}`.toLowerCase().includes(v)});return a.createElement("div",{className:"ps-modal-backdrop",onClick:m},a.createElement("div",{className:"ps-modal is-list",onClick:k=>k.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:m,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{className:"ps-modal-input ps-modal-search","data-modal-search":"true",value:d,placeholder:"Search people…",autoFocus:!0,onChange:k=>u(k.currentTarget.value),onKeyDown:k=>{k.key==="Escape"&&d&&(k.stopPropagation(),u(""))}}),a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:c,className:"ps-modal-list"},E.length===0?a.createElement("div",{className:"ps-empty-state"},`No one matches "${d}".`):null,E.map(k=>(x=>a.createElement("button",{key:x.id||k,type:"button",className:`ps-list-button ps-modal-list-button${k===i.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(k)},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Ye,{runs:Array.isArray(S?.[k])?S[k]:Je([S?.[k]])[0]?.runs||[{text:S?.[k]?.text||"",color:S?.[k]?.color}],theme:n}))))((i.items||[])[k]||{}))),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),Je(y.detailsLines||[]).map((k,x)=>a.createElement(st,{key:`detail:${x}`,line:k,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:m},"Done"))))}if(i.type==="renameSession"&&r.renameSession)return a.createElement("div",{className:"ps-modal-backdrop",onClick:m},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:m,"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(_.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Je(r.renameSession.helpLines||[]).map((y,S)=>a.createElement(st,{key:`help:${S}`,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:m},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(_.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(i.type==="sessionGroupName"&&r.sessionGroupName)return a.createElement("div",{className:"ps-modal-backdrop",onClick:m},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:m,"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(_.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},Je(r.sessionGroupName.helpLines||[]).map((y,S)=>a.createElement(st,{key:`help:${S}`,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:m},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(_.MODAL_CONFIRM).catch(()=>{})},r.sessionGroupName.mode==="rename"?"Rename":"Create and Move"))));if(i.type==="terminatePicker"){const y=Number(i.bulkCount)>1,S=!!i.systemRestart,v=String(i.sessionTitle||"").trim()||"this session",w=Number(i.bulkCount)||0,E=y?`What should happen to the ${w} selected sessions? Choose an action; you'll be asked to confirm.`:S?`How should "${v}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${v}"? Choose an action; you'll be asked to confirm.`,k=x=>()=>{t.pickTerminateAction(x).catch(()=>{})};return a.createElement("div",{className:"ps-modal-backdrop",onClick:m},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"},i.title||"Session Lifecycle"),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:m,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},a.createElement("p",{style:{color:"#94a3b8",margin:0}},E)),a.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},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:k("regenerate")},"Regenerate Context"):null,a.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:k("complete")},y?`Mark ${w} Completed`:S?"Complete & Restart":"Mark Completed"),a.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:k("cancel")},y?`Cancel ${w} Sessions`:S?"Terminate & Restart":"Cancel Session"),a.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:k("delete")},y?`Hard Delete ${w} Sessions`:S?"Hard Delete & Restart":"Delete Session")),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Close"))))}if(i.type==="artifactUpload"&&r.artifactUpload)return a.createElement("div",{className:"ps-modal-backdrop",onClick:m},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:m,"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"},Je(r.artifactUpload.helpLines||[]).map((y,S)=>a.createElement(st,{key:`help:${S}`,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:m},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(_.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:m},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:m,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-filter-grid"},(i.items||[]).map((y,S)=>{const v=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||S,className:"ps-filter-column"},a.createElement("div",{className:"ps-filter-title"},y.label),(y.options||[]).map(w=>a.createElement("button",{key:w.id,type:"button",className:`ps-filter-option${w.id===v?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:S}),i.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:w.id}):i.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[y.id]:w.id}}),t.ensureFilesForScope(w.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[y.id]:w.id}})}},w.label)))})),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:m},"Done")))):null}function A0({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 z0({controller:t}){const e=se(t,s=>s.ui.modal);return sp(t,!1,!e),a.createElement(Ui,{controller:t})}function sp(t,e,s=!1){a.useEffect(()=>{if(s)return;const n=r=>{if(r.defaultPrevented)return;const i=r.target,o=i instanceof HTMLElement&&(i.tagName==="TEXTAREA"||i.tagName==="INPUT"||i.tagName==="SELECT"||i.isContentEditable),l=t.getState().ui.modal,c=Ta(t),d=t.getState().ui.inspectorTab,u=t.getState().ui.focusRegion,p=!r.metaKey&&!r.ctrlKey&&!r.altKey,m=!r.metaKey&&!r.ctrlKey&&!r.altKey&&r.key==="T"&&r.shiftKey,f=!r.metaKey&&!r.ctrlKey&&!r.altKey&&r.key==="N"&&r.shiftKey,h=g=>{const b=$S(c,d,g);t.selectInspectorTab(b).catch(()=>{})};if(!o&&m){r.preventDefault(),t.handleCommand(_.OPEN_THEME_PICKER).catch(()=>{});return}if(!o&&f){r.preventDefault(),t.handleCommand(_.OPEN_MODEL_PICKER).catch(()=>{});return}if(l&&!o){if(r.key==="Escape"||l.type==="confirm"&&r.key==="n"){r.preventDefault(),t.handleCommand(_.CLOSE_MODAL).catch(()=>{});return}if(r.key==="Enter"||l.type==="confirm"&&r.key==="y"){r.preventDefault(),t.handleCommand(_.MODAL_CONFIRM).catch(()=>{});return}if(r.key==="Tab"&&r.shiftKey){r.preventDefault(),t.handleCommand(_.MODAL_PANE_PREV).catch(()=>{});return}if(r.key==="Tab"){r.preventDefault(),t.handleCommand(_.MODAL_PANE_NEXT).catch(()=>{});return}if(r.key==="ArrowUp"||r.key==="k"){r.preventDefault(),t.handleCommand(_.MODAL_PREV).catch(()=>{});return}(r.key==="ArrowDown"||r.key==="j")&&(r.preventDefault(),t.handleCommand(_.MODAL_NEXT).catch(()=>{}));return}if(l&&o&&i instanceof HTMLElement&&i.dataset.modalSearch==="true"){if(r.key==="Escape"){r.preventDefault(),t.handleCommand(_.CLOSE_MODAL).catch(()=>{});return}if(r.key==="Enter"){r.preventDefault(),t.handleCommand(_.MODAL_CONFIRM).catch(()=>{});return}if(r.key==="ArrowUp"){r.preventDefault(),t.handleCommand(_.MODAL_PREV).catch(()=>{});return}if(r.key==="ArrowDown"){r.preventDefault(),t.handleCommand(_.MODAL_NEXT).catch(()=>{});return}return}if(!o){if(r.key==="r"&&p&&u!=="prompt"){r.preventDefault(),t.handleCommand(_.REFRESH).catch(()=>{});return}if(r.key==="n"&&p){r.preventDefault(),t.handleCommand(_.NEW_SESSION).catch(()=>{});return}if(u==="inspector"&&d==="files"&&(r.key==="u"&&p||(r.ctrlKey||r.metaKey)&&r.key.toLowerCase()==="a")){r.preventDefault(),t.handleCommand(_.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(u==="inspector"&&d==="files"&&r.key==="a"&&p){r.preventDefault(),t.handleCommand(_.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&d==="files"&&r.key==="x"&&p){r.preventDefault(),t.handleCommand(_.DELETE_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&d==="files"&&r.key==="o"&&p){r.preventDefault(),t.handleCommand(_.OPEN_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&d==="files"&&r.key==="f"&&p){r.preventDefault(),t.handleCommand(_.OPEN_FILES_FILTER).catch(()=>{});return}if(u==="inspector"&&d==="stats"&&r.key==="f"&&p){r.preventDefault(),t.handleCommand(_.TOGGLE_STATS_VIEW).catch(()=>{});return}if(u==="inspector"&&d==="files"&&r.key==="v"&&p){r.preventDefault(),t.handleCommand(_.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(u==="inspector"&&d==="logs"&&r.key==="t"&&p){r.preventDefault(),t.handleCommand(_.TOGGLE_LOG_TAIL).catch(()=>{});return}if(u==="inspector"&&d==="logs"&&r.key==="f"&&p){r.preventDefault(),t.handleCommand(_.OPEN_LOG_FILTER).catch(()=>{});return}if(u==="inspector"&&d==="history"&&r.key==="f"&&p){r.preventDefault(),t.handleCommand(_.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(u==="inspector"&&d==="history"&&r.key==="r"&&p){r.preventDefault(),t.handleCommand(_.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(u==="inspector"&&d==="history"&&r.key==="a"&&p){r.preventDefault(),t.handleCommand(_.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(r.key==="a"&&p){r.preventDefault(),t.handleCommand(_.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(r.key==="p"&&p){r.preventDefault(),t.handleCommand(_.FOCUS_PROMPT).catch(()=>{});return}if(r.key==="c"&&p){r.preventDefault(),t.handleCommand(_.CANCEL_SESSION).catch(()=>{});return}if(r.key==="d"&&p){r.preventDefault(),t.handleCommand(_.DONE_SESSION).catch(()=>{});return}if(r.key==="D"&&r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey){r.preventDefault(),t.handleCommand(_.DELETE_SESSION).catch(()=>{});return}if(r.key==="m"&&p&&u==="inspector"){r.preventDefault(),h(1);return}if(r.key==="["&&p){r.preventDefault(),t.handleCommand(_.GROW_LEFT_PANE).catch(()=>{});return}if(r.key==="]"&&p){r.preventDefault(),t.handleCommand(_.GROW_RIGHT_PANE).catch(()=>{});return}if(r.key==="{"&&p){r.preventDefault(),t.handleCommand(_.SHRINK_SESSION_PANE).catch(()=>{});return}if(r.key==="}"&&p){r.preventDefault(),t.handleCommand(_.GROW_SESSION_PANE).catch(()=>{});return}if(u==="inspector"&&r.key==="ArrowLeft"){r.preventDefault(),h(-1);return}if(u==="inspector"&&r.key==="ArrowRight"){r.preventDefault(),h(1);return}if(u==="sessions"&&(r.key==="ArrowUp"||r.key==="k")){r.preventDefault(),t.handleCommand(_.MOVE_SESSION_UP).catch(()=>{});return}if(u==="sessions"&&(r.key==="ArrowDown"||r.key==="j")){r.preventDefault(),t.handleCommand(_.MOVE_SESSION_DOWN).catch(()=>{});return}if(u==="sessions"&&r.ctrlKey&&r.key.toLowerCase()==="g"&&!r.metaKey&&!r.altKey){r.preventDefault(),t.handleCommand(_.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(u==="sessions"&&(r.key==="PageUp"||r.ctrlKey&&r.key.toLowerCase()==="u")){r.preventDefault(),t.handleCommand(_.PAGE_UP).catch(()=>{});return}if(u==="sessions"&&(r.key==="PageDown"||r.ctrlKey&&r.key.toLowerCase()==="d")){r.preventDefault(),t.handleCommand(_.PAGE_DOWN).catch(()=>{});return}if(u==="sessions"&&r.key==="t"&&p){r.preventDefault(),t.handleCommand(_.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(r.key==="PageUp"||r.ctrlKey&&r.key.toLowerCase()==="u")){r.preventDefault(),t.handleCommand(_.PAGE_UP).catch(()=>{});return}if(!e&&(r.key==="PageDown"||r.ctrlKey&&r.key.toLowerCase()==="d")){r.preventDefault(),t.handleCommand(_.PAGE_DOWN).catch(()=>{});return}if(!e&&r.key==="g"&&p){r.preventDefault(),t.handleCommand(_.SCROLL_TOP).catch(()=>{});return}if(!e&&r.key==="G"&&r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey){r.preventDefault(),t.handleCommand(_.SCROLL_BOTTOM).catch(()=>{});return}if(u!=="prompt"&&r.key==="h"&&p){r.preventDefault(),t.handleCommand(_.FOCUS_LEFT).catch(()=>{});return}if(u!=="prompt"&&r.key==="l"&&p){r.preventDefault(),t.handleCommand(_.FOCUS_RIGHT).catch(()=>{});return}if(!e&&u==="inspector"&&d==="files"&&(r.key==="ArrowUp"||r.key==="k")){r.preventDefault(),t.handleCommand(_.MOVE_FILE_UP).catch(()=>{});return}if(!e&&u==="inspector"&&d==="files"&&(r.key==="ArrowDown"||r.key==="j")){r.preventDefault(),t.handleCommand(_.MOVE_FILE_DOWN).catch(()=>{});return}if(!e&&(r.key==="ArrowUp"||r.key==="k")){r.preventDefault(),t.handleCommand(_.SCROLL_UP).catch(()=>{});return}if(!e&&(r.key==="ArrowDown"||r.key==="j")){r.preventDefault(),t.handleCommand(_.SCROLL_DOWN).catch(()=>{});return}!e&&r.key==="Escape"&&(r.preventDefault(),t.handleCommand(_.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[t,e,s])}function N0(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 C0({controller:t,mobile:e=!1}){const s=se(t,At,qe),n=se(t,I=>I.admin.features),r=se(t,I=>I.admin.workers),i=se(t,I=>I.auth?.authorization?.role),o=s.packages||{},l=s.section==="packages",c=s.section==="workers",d=s.section==="features",u=a.createElement(yS,{controller:t,features:n,workers:r?.list||[],workersError:r?.error,isAdmin:s.isAdmin&&(!i||i==="admin"||i==="anonymous")}),[p,m]=a.useState(null),[f,h]=a.useState(!1),[g,b]=a.useState(null),[y,S]=a.useState(()=>{const I={wsWidth:440,treePct:44,navWidth:240};try{return{...I,...JSON.parse(window.localStorage.getItem("ps-admin-ws-layout")||"{}")}}catch{return I}}),v=a.useCallback(I=>{S(O=>{const M={...O,...I};M.wsWidth=Math.min(900,Math.max(300,Math.round(M.wsWidth))),M.treePct=Math.min(85,Math.max(15,M.treePct)),M.navWidth=Math.min(420,Math.max(170,Math.round(M.navWidth??240)));try{window.localStorage.setItem("ps-admin-ws-layout",JSON.stringify(M))}catch{}return M})},[]),w=a.useCallback(I=>{I.preventDefault(),document.body.style.cursor="col-resize";const O=I.clientX,M=y.navWidth??240,B=j=>v({navWidth:M+(j.clientX-O)}),D=()=>{window.removeEventListener("pointermove",B),window.removeEventListener("pointerup",D),window.removeEventListener("pointercancel",D),document.body.style.cursor=""};window.addEventListener("pointermove",B),window.addEventListener("pointerup",D),window.addEventListener("pointercancel",D)},[y.navWidth,v]);a.useCallback(()=>{t.closeAdminConsole()},[t]);const E=a.useCallback(()=>{m(null),h(!1),b(null),t.dismissAdminModelProviderMutationError()},[t]),k=a.useCallback(async I=>{h(!0),b(null);const O=p?.update?await t.updateAdminProviderCredential({name:I.name,credentials:I.credentials,shared:I.shared===!0}):await t.createAdminProvider(I);if(h(!1),!O?.ok){b(O?.error||`The provider key could not be ${p?.update?"updated":"created"}.`);return}E()},[E,t,p]),x=a.createElement("header",{className:"ps-admin-console__header"},a.createElement("h2",null,s.isAdmin?"Admin Console":"Settings"),s.isAdmin?a.createElement("small",null,s.adminPolicyLabel):null),T=a.createElement(O0,{controller:t,view:s,sheetOpen:!!p,onAddPersonal:()=>{t.dismissAdminModelProviderMutationError(),m({shared:!1,github:!0})},onAddShared:()=>{t.dismissAdminModelProviderMutationError(),m({shared:!0,github:!1})},onUpdatePersonal:I=>{t.dismissAdminModelProviderMutationError(),m({update:I,shared:I.class==="shared"})}}),A=a.createElement(T0,{controller:t,view:s}),R=a.createElement(P0,{controller:t,view:s}),N=l&&o.selectedName?a.createElement(_0,{controller:t,view:s,layout:y,onLayout:v}):null,$=o.addDialog?.open?a.createElement(L0,{controller:t,dialog:o.addDialog}):null,F=p?a.createElement(h0,{types:s.modelProviders?.providerTypes||[],existingNames:[...s.modelProviders?.sharedProviders||[],...s.modelProviders?.myProviders||[]].map(I=>I.name),isAdmin:s.isAdmin,initialShared:p.shared,updateProvider:p.update||null,initialType:p.github?(s.modelProviders?.providerTypes||[]).find(I=>/github/i.test(I.id))?.id||"":p.update?.typeId||"",initialName:p.update?.name||"",busy:f,error:g,onDirty:()=>b(null),onCancel:E,onConfirm:k}):null;if(e){let I;return l&&o.selectedName?I=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"),R,N):l?I=A:c?I=a.createElement("div",{className:"ps-admin-mobile-stack"},A,a.createElement(pc,{controller:t,view:s})):I=a.createElement("div",{className:"ps-admin-mobile-stack"},A,d?u:T),a.createElement("div",{className:"ps-admin-console is-mobile"},x,s.loadError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,I,$,F)}return a.createElement("div",{className:"ps-admin-console is-workspace"},x,s.loadError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,a.createElement("div",{className:"ps-admin-workspace",style:N?{gridTemplateColumns:`${y.navWidth}px minmax(0, 1fr) minmax(0, ${y.wsWidth}px)`}:{gridTemplateColumns:`${y.navWidth}px minmax(0, 1fr)`}},a.createElement("div",{className:"ps-admin-nav"},A,a.createElement("div",{className:"ps-admin-nav__resize",onPointerDown:w,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings column"})),a.createElement("div",{className:"ps-admin-main"},l?R:c?a.createElement(pc,{controller:t,view:s}):d?u:T),N),$,F)}function pc({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 T0({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")):n.id==="features"?t.setAdminSection("features"):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(Li,{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 P0({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=(c,d)=>()=>t.runAdminPackageAction(c,d),o=n.actionPending,l=async()=>{try{await t.transport.saveAgentPackageDownload(n.name,n.activeSemver??null,{scope:n.scope,owner:n.owner??null})}catch(c){window.alert(`Could not download ${n.name}: ${c?.message||c}`)}};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(c=>a.createElement("span",{key:c.name,className:"ps-agent-chip",title:c.description},c.name,c.toolCount?a.createElement("i",null,` · ${c.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(c=>a.createElement("div",{key:c.semver,className:`ps-admin-version${c.active?" is-active":""}`},a.createElement("b",null,c.semver),a.createElement("span",null,c.sha12),a.createElement("span",null,c.dateText),c.active?a.createElement("span",{className:"is-ok"},"● active"):n.canEdit?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:i("pin",c.semver),disabled:!!o},"Pin"):null)))):null,n.scope==="shared"?a.createElement(M0,{controller:t,detail:n,pending:o}):null,n.canEdit?a.createElement("div",{className:"ps-admin-detail__actions"},n.source&&n.canManage?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`):n.canManage?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:i(n.scope==="shared"?"demote":"promote"),disabled:!!o,title:n.scope==="shared"&&n.editors.length?"Demoting revokes every editor grant":void 0},n.scope==="shared"?"Demote to user":"Promote to shared"):null,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,typeof t.transport.saveAgentPackageDownload=="function"?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>l(),disabled:!!o||!n.activeSemver,title:`Download ${n.name}@${n.activeSemver??"?"} as the .tgz the CLI would push`},o==="download"?"Downloading…":"Download"):null,a.createElement("button",{type:"button",className:"ps-mini-button",onClick:i(n.enabled?"disable":"enable"),disabled:!!o},n.enabled?"Disable":"Enable"),n.canManage?a.createElement("button",{type:"button",className:"ps-mini-button is-danger",onClick:r,disabled:!!o},"Delete"):null):a.createElement("p",{className:"ps-admin-console__hint"},"Read-only: only the package creator, a granted editor, or an admin can modify it."),n.actionError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},n.actionError):null)}function M0({controller:t,detail:e,pending:s}){const[n,r]=a.useState(""),[i,o]=a.useState([]);a.useEffect(()=>{if(!e.canManage||typeof t.transport.listKnownUsers!="function")return;let m=!1;return t.transport.listKnownUsers({limit:500}).then(f=>{m||o(Array.isArray(f)?f:[])}).catch(()=>{}),()=>{m=!0}},[t,e.canManage]);const l=new Set(e.editors.map(m=>`${m.provider}${m.subject}`)),c=n.trim().toLowerCase(),d=c?i.filter(m=>!l.has(`${m.provider}${m.subject}`)&&(m.displayName&&m.displayName.toLowerCase().includes(c)||m.email&&m.email.toLowerCase().includes(c)||m.subject&&m.subject.toLowerCase().includes(c))).slice(0,8):[],u=m=>{!m?.provider||!m?.subject||(r(""),t.runAdminPackageAction("grantEditor",{provider:m.provider,subject:m.subject}))},p=()=>{const m=n.trim();if(!m)return;const f=i.find(h=>h.displayName&&h.displayName.toLowerCase()===m.toLowerCase()||h.email&&h.email.toLowerCase()===m.toLowerCase()||h.subject&&h.subject.toLowerCase()===m.toLowerCase());if(f)return u(f);if(d.length===1)return u(d[0])};return a.createElement("div",{className:"ps-admin-editors"},a.createElement("div",{className:"ps-admin-detail__label"},"Editors"),e.editors.length?a.createElement("div",{className:"ps-admin-detail__chips"},e.editors.map(m=>a.createElement("span",{key:`${m.provider}${m.subject}`,className:"ps-agent-chip",title:`${m.provider}:${m.subject}${m.grantedByDisplay?` · granted by ${m.grantedByDisplay}`:""}`},m.label,e.canManage?a.createElement("button",{type:"button",className:"ps-chip-remove","aria-label":`Remove editor ${m.label}`,disabled:!!s,onClick:()=>t.runAdminPackageAction("revokeEditor",{provider:m.provider,subject:m.subject})},"×"):null))):a.createElement("p",{className:"ps-admin-console__hint"},e.canManage?"No editors yet. Add a person to let them publish, pin and enable this package. Grants are revoked if the package is demoted.":"Only the owner and admins can change this package."),e.canManage?a.createElement("div",{className:"ps-admin-editors__add"},a.createElement("input",{type:"text",className:"ps-input",placeholder:"Add editor by name, email, or id…",value:n,disabled:!!s,onChange:m=>r(m.target.value),onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),p())},"aria-label":"Add editor"}),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:p,disabled:!!s||!n.trim()},"Add"),d.length?a.createElement("div",{className:"ps-admin-editors__suggestions",role:"listbox"},d.map(m=>a.createElement("button",{key:`${m.provider}${m.subject}`,type:"button",role:"option",className:"ps-admin-editors__suggestion",onClick:()=>u(m)},m.displayName||m.email||m.subject,m.email&&m.displayName?a.createElement("i",null,` ${m.email}`):null))):null):null)}function _0({controller:t,view:e,layout:s=null,onLayout:n=null}){const r=se(t,p=>p.ui.themeId),i=kt(r),o=e.packages?.workspace,l=a.useRef(null),c=a.useCallback((p,m)=>{if(!n)return;p.preventDefault();const f=p.clientX,h=p.clientY,g={...s},b=S=>m(g,S.clientX-f,S.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(p=>{document.body.style.cursor="col-resize",c(p,(m,f)=>n({wsWidth:m.wsWidth-f}))},[c,n]),u=a.useCallback(p=>{document.body.style.cursor="row-resize";const m=l.current?.getBoundingClientRect().height||600;c(p,(f,h,g)=>n({treePct:f.treePct+g/m*100}))},[c,n]);return o?a.createElement("div",{className:"ps-admin-ws",ref:l,style:s?{gridTemplateRows:`auto minmax(80px, ${s.treePct}%) auto minmax(0, 1fr)`}:void 0},n?a.createElement("div",{className:"ps-admin-ws__vdivider",title:"Drag to resize the workspace",onPointerDown:d}):null,a.createElement("div",{className:"ps-admin-ws__head"},`Package workspace${o.semver?` · ${e.packages.selectedName}@${o.semver}`:""}`),a.createElement("div",{className:"ps-admin-ws__tree"},o.loading?a.createElement("div",{className:"ps-admin-tree__hint"},"Loading files…"):null,o.error?a.createElement("div",{className:"ps-admin-tree__hint is-error"},o.error):null,o.treeRows.map(p=>a.createElement("button",{key:`${p.type}:${p.path}`,type:"button",style:{paddingLeft:`${8+(p.depth||0)*16}px`},className:`ps-admin-ws__row is-${p.type}${p.selected?" is-selected":""}`,onClick:p.type==="dir"?()=>t.toggleAdminPackageDir(p.path):()=>t.selectAdminPackageFile(p.path)},a.createElement("span",{className:"ps-admin-ws__caret"},p.type==="dir"?p.expanded?"▾":"▸":""),a.createElement("span",{className:"ps-admin-ws__name"},p.label),p.sizeText?a.createElement("span",{className:"ps-admin-ws__size"},p.sizeText):null))),a.createElement("div",{className:`ps-admin-ws__preview-head${n?" is-resizable":""}`,title:n?"Drag to resize file list vs preview":void 0,onPointerDown:n?u:void 0},o.selectedPath?`Preview · ${o.selectedPath}`:"Preview"),a.createElement("div",{className:"ps-admin-ws__preview"},o.fileLoading?a.createElement("div",{className:"ps-admin-tree__hint"},"Loading…"):null,o.fileError?a.createElement("div",{className:"ps-admin-tree__hint is-error"},o.fileError):null,o.file?o.file.isBinary?a.createElement("div",{className:"ps-admin-tree__hint"},`Binary file · ${o.file.sizeText}`):a.createElement(R0,{file:o.file,theme:i}):null)):null}function $0(t){const e=/^---\n([\s\S]*?)\n---\n?/.exec(t||"");if(!e)return{meta:null,body:t||""};const s=e[1].split(`
|
|
109
|
-
`).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 R0({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}=$0(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(Da,{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,$s(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,$s(t.text||"",s,e))),n)}function L0({controller:t,dialog:e}){const s=se(t,p=>p.docs?.agentPackageGuideUrl||null),n=p=>m=>t.setAdminAddPackageField(p,m.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,u=p=>{if(p.preventDefault(),!(l||e.submitting)){if(e.kind==="upload"){const m=o.current;if(!m?.files?.length){t.failAdminAddPackage("Choose a package folder first.");return}const f=[...m.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=f.reduce((g,{file:b})=>g+b.size,0);if(f.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(f.map(({file:g,path:b})=>new Promise((y,S)=>{const v=new FileReader;v.onerror=()=>S(new Error(`could not read ${b}`)),v.onload=()=>y({path:b,contentBase64:String(v.result).split(",",2)[1]||""}),v.readAsDataURL(g)}))).then(g=>t.submitAdminUploadPackage(g,e.scope)).catch(g=>t.failAdminAddPackage(g?.message||"Could not read the chosen folder.")).finally(()=>c(!1));return}t.submitAdminAddPackage().catch(()=>{})}};return a.createElement("div",{className:"ps-modal-backdrop",onClick:()=>t.closeAdminAddPackage()},a.createElement("form",{className:"ps-modal ps-admin-add",onClick:p=>p.stopPropagation(),autoComplete:"off",onSubmit:u},a.createElement("div",{className:"ps-modal-header"},a.createElement("span",null,e.updateName?`Update ${e.updateName}`:"Add agent package"),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage()},"✕")),a.createElement("div",{className:"ps-admin-add__body"},a.createElement("div",{className:"ps-admin-add__tabs"},r.map(([p,m])=>a.createElement("button",{key:p,type:"button",className:`ps-admin-add__tab${e.kind===p?" is-on":""}`,onClick:()=>t.setAdminAddPackageField("kind",p)},m))),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 ri(t){return t?.configured?.model||""}function ii({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 mc({providers:t,isAdmin:e,personal:s,busy:n,onSystemUse:r,onUpdate:i,onDelete:o}){return t.length?a.createElement("div",{className:"ps-admin-provider-list"},t.map(l=>a.createElement("div",{key:l.name,className:"ps-admin-provider-row"},a.createElement("div",{className:"ps-admin-provider-row__identity"},a.createElement("strong",{title:l.name},l.name),a.createElement("span",{className:`ps-scope-badge is-${l.class==="shared"?"shared":"user"}`},l.class),l.isMyDefault?a.createElement("span",{className:"ps-scope-badge is-off"},"my default"):null,l.isClusterDefault?a.createElement("span",{className:"ps-scope-badge is-off"},"cluster default"):null,l.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:l.systemUseEnabled,disabled:n,onChange:c=>r(l.name,c.target.checked)}),"Allow system sessions"):null,(s||e)&&!l.usesWorkloadIdentity?a.createElement("button",{type:"button",className:"ps-mini-button","aria-label":`Update key for ${l.name}`,title:`Update key for ${l.name}`,disabled:n,onClick:()=>i(l)},"Update key"):null,a.createElement(ve,{icon:a.createElement(gw),label:`Delete ${l.name}`,className:"ps-mini-button is-danger",disabled:n,onClick:()=>o(l)}))))):a.createElement("p",{className:"ps-admin-console__hint"},s?"No personal providers yet.":"No shared providers are configured.")}function O0({controller:t,view:e,onAddPersonal:s,onAddShared:n,onUpdatePersonal:r,sheetOpen:i=!1}){const o=e.modelProviders||{},l=!!o.mutation?.pending,c=ri(o.systemSessionDefault),[d,u]=a.useState(c),[p,m]=a.useState(""),[f,h]=a.useState(null);a.useEffect(()=>{u(c)},[c]);const g=(T,A)=>T.find(R=>R.qualifiedName===A)||null,b=(T,A,R)=>{t.setAdminModelDefault(T,g(A,R))},y=T=>{window.confirm(`Delete ${T.name}? Sessions using it will wait until that provider name exists again.`)&&t.deleteAdminProvider(T.name,{shared:T.class==="shared"})},S=async()=>{h(null);const T=await t.setAdminSystemModelDefault(g(o.systemChoices||[],d),{restartDisposition:p||null});T?.ok&&h(T.result?.restart||{requested:!1})},v=(o.systemAgentRoutes||[]).filter(T=>!T.override),w=o.page==="shared"&&e.isAdmin,E=a.createElement("div",{className:"ps-admin-provider-heading"},a.createElement("h3",null,"Model Providers"),a.createElement(ve,{icon:"↻",label:"Refresh model providers",className:"ps-mini-button",disabled:o.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:l},"Add provider")),a.createElement(mc,{providers:o.myProviders||[],isAdmin:e.isAdmin,personal:!0,busy:l,onSystemUse:(T,A)=>t.setAdminProviderSystemUse(T,A),onUpdate:r,onDelete:y})),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement(ii,{label:"My Session Default",hint:`Effective: ${o.mySessionDefault?.effective?.model||"none"}.`,value:ri(o.mySessionDefault),choices:o.userChoices||[],disabled:l,emptyLabel:"Use cluster default",onChange:T=>b("user",o.userChoices||[],T)}))),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:l},"Add provider")),a.createElement(mc,{providers:o.sharedProviders||[],isAdmin:!0,personal:!1,busy:l,onSystemUse:()=>{},onDelete:y,onUpdate:r})),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement(ii,{label:"Cluster Session Default",hint:`Effective: ${o.clusterSessionDefault?.effective?.model||"none"}.`,value:ri(o.clusterSessionDefault),choices:o.clusterChoices||[],disabled:l,emptyLabel:"Use first shared provider",onChange:T=>b("cluster",o.clusterChoices||[],T)})),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement("h4",null,"System Session Default"),a.createElement(ii,{label:"Model",hint:"Shared and system-enabled personal providers.",value:d,choices:o.systemChoices||[],disabled:l,emptyLabel:"Use first eligible provider",onChange:u}),a.createElement("div",{className:"ps-admin-detail__label"},"Existing system sessions"),a.createElement(Qt,{value:p,onChange:m,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"},`${v.length} agent${v.length===1?"":"s"} inherit this default.`),a.createElement("button",{type:"button",className:"ps-primary-button",disabled:l,onClick:S},l&&o.mutation?.pending==="systemDefault"?"Applying…":"Apply")),f?.requested?a.createElement("p",{className:"ps-admin-console__status"},`${f.restarted}/${f.affected} restarted${f.failures?.length?` · ${f.failures.length} failed`:""}.`):null),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement("h4",null,"System Agent Overrides"),(o.systemAgentRoutes||[]).length===0?a.createElement("p",{className:"ps-admin-console__hint"},"No system agents."):a.createElement("div",{className:"ps-admin-override-table"},(o.systemAgentRoutes||[]).map(T=>a.createElement("div",{key:T.agentId,className:"ps-admin-override-row"},a.createElement("div",{className:"ps-admin-override-row__agent"},a.createElement("strong",null,T.title),a.createElement("span",null,T.effectiveModel||"blocked"),a.createElement("small",null,T.override?"override":"system default")),a.createElement("select",{className:"ps-budget-input",value:T.override?.model||"",disabled:l,"aria-label":`Model override for ${T.title}`,onChange:A=>{const R=g(o.systemChoices||[],A.target.value);R?t.setAdminSystemAgentModel(T.agentId,R):t.clearAdminSystemAgentModel(T.agentId)}},a.createElement("option",{value:""},"Inherit system default"),(o.systemChoices||[]).map(A=>a.createElement("option",{key:A.qualifiedName,value:A.qualifiedName},`${A.provider} · ${A.model}`))))))));return a.createElement("section",{className:"ps-admin-detail ps-admin-model-providers"},E,o.error||o.mutation?.error&&!i?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},!i&&o.mutation?.error||o.error):null,w?x:k)}function K0({transport:t,mode:e="remote",branding:s=null,docs:n=null}={}){GS();const r=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches,i=Wy(Hy,hi({mode:e,branding:s,docs:n}));return i.dispatch({type:"ui/touchScale",enabled:r}),new Kb({store:i,transport:t})}function V0({controller:t,suspended:e=!1,moa:s=null}){const n=a.useRef(null),r=a.useRef(null),i=Fl(n,e),o=Fl(r,e),l=ZS(i);a.useEffect(()=>{const K=()=>{try{const oe=document.createElement("span");oe.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const ge=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");if(ge){const ie=window.getComputedStyle(ge);oe.style.fontFamily=ie.fontFamily,oe.style.fontSize=ie.fontSize,oe.style.fontWeight=ie.fontWeight,oe.style.letterSpacing=ie.letterSpacing}oe.textContent="0".repeat(100),(ge?.parentElement||document.body).appendChild(oe);const Me=oe.getBoundingClientRect().width/100||8;oe.remove();const G=document.documentElement.clientWidth||window.innerWidth,W=document.documentElement.clientHeight||window.innerHeight;t.dispatch({type:"ui/viewport",width:Math.floor(G/Me),height:Math.floor(W/wt)})}catch{}};K();let P;const z=()=>{clearTimeout(P),P=setTimeout(K,150)};return window.addEventListener("resize",z),window.addEventListener("orientationchange",z),()=>{clearTimeout(P),window.removeEventListener("resize",z),window.removeEventListener("orientationchange",z)}},[t]);const[c,d]=a.useState("split"),u=se(t,K=>({moa:K.ui.moa,themeId:K.ui.themeId,touchScale:!!K.ui.touchScale,sessionDetailCollapsed:!!K.ui.sessionDetailCollapsed,agentPickerUsage:K.ui.agentPickerUsage,ownerFilter:K.sessions.ownerFilter,pinnedIds:K.sessions.pinnedIds,manualOrder:K.sessions.manualOrder,collapsedSessionIds:K.sessions.collapsedIds,activeSessionId:K.sessions.activeSessionId||null,revealedCreatedSessionId:K.ui.revealedCreatedSessionId||null,promptRows:gu(K),rightPaneMode:K.ui.rightPaneMode||"panes",canvasOpen:K.ui.canvasOpen===!0,diagnosticsOpen:K.ui.diagnosticsOpen===!0,canvasMaximized:K.ui.canvasMaximized===!0,canvasZen:K.ui.canvasZen===!0,canvasPrefs:K.canvas?.prefs,activeSessionIsGroup:!!(K.sessions.activeSessionId&&K.sessions.byId[K.sessions.activeSessionId]?.isGroup),paneAdjust:K.ui.layout?.paneAdjust??0,sessionPaneAdjust:K.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:K.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:K.ui.layout?.activityPaneAdjust??0,canvasPaneAdjust:K.ui.layout?.canvasPaneAdjust??0,diagnosticsPaneAdjust:K.ui.layout?.diagnosticsPaneAdjust??0,diagnosticsSplitAdjust:K.ui.layout?.diagnosticsSplitAdjust??0,sessionViews:K.ui.sessionViews,focusRegion:K.ui.focusRegion,requestedFocusRegion:K.ui.requestedFocusRegion,inspectorTab:K.ui.inspectorTab,filesFullscreen:!!K.files.fullscreen,selectedArtifactId:K.files.selectedArtifactId||null,artifactPaneOpen:!!K.files.paneOpen,adminVisible:!!K.admin?.visible,budgetOpen:!!K.ui?.budgetOpen}),qe),p=a.useRef(!1),m=a.useRef(null),f=a.useRef(null),h=a.useRef(null),g=a.useRef(null),b=a.useRef(null),y=a.useRef(null),S=a.useRef(!1),v=a.useRef(0),w=a.useRef(0),E=a.useRef(null),k=a.useRef(null),[x,T]=a.useState("workspace"),A=(i.width||window.innerWidth||0)<ES,N=u.activeSessionIsGroup?0:u.promptRows;sp(t,A,e);const $=a.useRef(u.revealedCreatedSessionId);a.useEffect(()=>{$.current!==u.revealedCreatedSessionId&&($.current=u.revealedCreatedSessionId,!(!u.revealedCreatedSessionId||u.activeSessionId!==u.revealedCreatedSessionId)&&(A&&(T("workspace"),d("chat")),s?.active&&s.leave()))},[u.revealedCreatedSessionId,u.activeSessionId,A,s]),a.useEffect(()=>{t.dispatch({type:"ui/sessionViewDevice",device:A?"mobile":"desktop"})},[t,A]);const F=jw(A&&x==="workspace"&&!u.adminVisible);a.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-kb-takeover",F),()=>document.body.classList.remove("ps-kb-takeover")},[F]),a.useEffect(()=>{F&&t.applyPaneVisualScrollOffset?.("chat",0,{followBottom:!0})},[F,t]);const I=se(t,pa,qe),O=x==="canvas",M=a.useRef("workspace"),[B,D]=a.useState(!1),[j,V]=a.useState(!1);a.useEffect(()=>{T(K=>K==="canvas"?M.current||"workspace":K),D(!1),V(!1)},[I.sessionId]),a.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-canvas-lock",!!(A&&O)),()=>document.body.classList.remove("ps-canvas-lock")},[A,O]);const C=a.useCallback(()=>{x!=="canvas"&&(M.current=x),T("canvas"),D(!0),t.dispatch({type:"ui/rightPaneMode",mode:"canvas",sessionId:I.sessionId})},[t,x,I.sessionId]),U=a.useCallback(()=>{T(M.current||"workspace"),t.dispatch({type:"ui/rightPaneMode",mode:"panes",sessionId:I.sessionId,manual:!0})},[t,I.sessionId]),H=a.useRef(I.flipSeq);a.useEffect(()=>{I.flipSeq!==H.current&&(H.current=I.flipSeq,A&&C())},[I.flipSeq,A,C]);const Y=a.useCallback(()=>{if(O){U();return}C()},[O,U,C]);a.useEffect(()=>{let K=!0;p.current=!1,m.current=null,E.current=null,k.current=Rl(t.getState()),b.current&&(clearTimeout(b.current),b.current=null),y.current&&(clearInterval(y.current),y.current=null),S.current=!1,v.current=0;const P=t.transport;if(typeof P?.getCurrentUserProfile!="function"||typeof P?.setCurrentUserProfileSettings!="function")return p.current=!0,()=>{K=!1};const z=async()=>{if(!K||S.current)return;S.current=!0;const oe=w.current;try{const ge=await P.getCurrentUserProfile();if(!K)return;ge&&typeof ge.isAdmin=="boolean"&&!t.getState().admin?.profile&&t.dispatch({type:"admin/profile/loaded",profile:ge});const Me=ts(ge?.profileSettings);typeof Me[Zn()]=="boolean"&&(f.current=Me[Zn()]),(Me.rightPaneMode==="canvas"||Me.rightPaneMode==="panes")&&(h.current=Me.rightPaneMode),Me.desktopPanes&&(g.current=Me.desktopPanes),k.current=Rl(t.getState(),f.current,h.current,g.current);const G=qS(ge?.profileSettings,k.current),W=JSON.stringify(G),ie=Yr($l(t.getState()),f.current,h.current,g.current),pe=JSON.stringify(ie),X=p.current&&m.current!=null&&pe!==m.current,me=oe!==w.current||!!b.current||v.current||X||t.getState().ui.moaDirty===!0;if(!me&&E.current!==W&&(t.dispatch({type:"profileSettings/apply",settings:G}),E.current=W),!p.current||!me){const ye=Yr($l(t.getState()),f.current,h.current,g.current);m.current=JSON.stringify(ye)}p.current=!0}catch{if(!K)return;p.current=!0}finally{S.current=!1}};return z().catch(()=>{}),y.current=setInterval(()=>{z().catch(()=>{})},CS),()=>{K=!1,b.current&&(clearTimeout(b.current),b.current=null),y.current&&(clearInterval(y.current),y.current=null),S.current=!1}},[t]),a.useEffect(()=>{if(!p.current)return;const K=Yr(u,f.current,h.current,g.current),P=JSON.stringify(K);m.current!==P&&(m.current=P,w.current+=1,b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{b.current=null,v.current+=1;const z=t.getState().ui.moaRevision;t.dispatch({type:"ui/moaSaveStatus",status:"saving"}),zS(t,K).then(()=>t.dispatch({type:"ui/moaSaveStatus",status:"saved",revision:z})).catch(()=>{m.current=null,t.dispatch({type:"ui/moaSaveStatus",status:"error"})}).finally(()=>{v.current=Math.max(0,v.current-1)})},400))},[t,u.moa,u.activeSessionId,u.activityPaneAdjust,u.agentPickerUsage,u.canvasOpen,u.canvasPaneAdjust,u.canvasPrefs,u.canvasZen,u.collapsedSessionIds,u.diagnosticsOpen,u.diagnosticsPaneAdjust,u.diagnosticsSplitAdjust,u.ownerFilter,u.paneAdjust,u.manualOrder,u.pinnedIds,u.portalSessionColumnAdjust,u.rightPaneMode,u.sessionDetailCollapsed,u.sessionPaneAdjust,u.sessionViews,u.themeId,u.touchScale]),a.useEffect(()=>{QS(u.themeId),XS(u.touchScale)},[u.themeId,u.touchScale]);const te=a.useRef(null);a.useEffect(()=>{const K=te.current;if(te.current=u.focusRegion,K===null||K===u.focusRegion)return;const P=u.requestedFocusRegion;A&&(u.focusRegion==="inspector"||u.focusRegion==="activity")&&(P==="inspector"||P==="activity")&&T(u.focusRegion)},[A,u.focusRegion,u.requestedFocusRegion]),a.useEffect(()=>{const K=Ta(t);!K.includes(u.inspectorTab)&&K.length>0&&t.selectInspectorTab(K[0]).catch(()=>{})},[t,u.inspectorTab]);const ee=a.useMemo(()=>Ks(l,u.paneAdjust,N,u.sessionPaneAdjust,u.activityPaneAdjust),[l,u.activityPaneAdjust,u.paneAdjust,N,u.sessionPaneAdjust]),J=u.filesFullscreen&&u.inspectorTab==="files",ae=u.inspectorTab==="files"&&!!u.selectedArtifactId&&!J,de=!A&&u.artifactPaneOpen&&!!u.selectedArtifactId&&!J,Z=!A&&u.canvasOpen&&!J;a.useEffect(()=>{Z&&V(!0)},[Z,I.sessionId]);const le=!A&&u.diagnosticsOpen&&!J&&!de&&!(u.canvasZen&&u.canvasOpen),$e=de||Z||le,be=u.canvasMaximized&&Z,Re=u.canvasZen&&Z&&!de,Se=Math.max(260,Math.min(720,Number(u.canvasPrefs?.[u.activeSessionId]?.zenRailPx)||380));a.useEffect(()=>{if(e||!be&&!Re)return;const K=P=>{P.key==="Escape"&&t.dispatch(be?{type:"ui/canvasMaximized",on:!1}:{type:"ui/canvasZen",on:!1})};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[t,be,Re,e]);const rt=Math.max(0,Pa+(Number(u.canvasPaneAdjust)||0)),ce=Math.max(0,Ma+(Number(u.diagnosticsPaneAdjust)||0)),Ke=(Z?rt:0)+(Z&&le?1:0)+(le?ce:0),Ne=a.useCallback(()=>{t.closeArtifactPane().catch(()=>{})},[t]),Xe=Math.max(0,(i.width||0)*.68),q=o.width||Xe,he=KS(q,u.portalSessionColumnAdjust),Be=Re?"hidden":VS(he),Ee=Be==="hidden"?"0px":`clamp(0px, calc(${Na*100}% + ${Number(u.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,Pe=a.createElement("div",{className:`ps-workspace-grid${$e?"":" is-right-hidden"}`,style:{gridTemplateColumns:de?`minmax(0, ${ee.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${ee.rightWidth}fr)`:Re?`${Se}px var(--ps-resizer-track, 16px) minmax(0, 1fr)`:$e?`minmax(0, 1fr) var(--ps-resizer-track, 16px) min(${Ke}px, calc(100% - var(--ps-resizer-track, 16px) - ${Ca}px))`:"minmax(0, 1fr)"}},a.createElement("div",{ref:r,className:`ps-workspace-main-grid is-session-${Be}`,style:{gridTemplateColumns:`${Ee} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},Be!=="hidden"?a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},a.createElement(Oi,{controller:t,structuredRows:!0})):null,a.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},a.createElement(Xw,{controller:t,portalSessionColumnAdjust:u.portalSessionColumnAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},a.createElement(Di,{controller:t}))),$e?de?a.createElement(Yw,{controller:t,paneAdjust:u.paneAdjust}):Re?a.createElement(Zw,{controller:t,sessionId:u.activeSessionId,railPx:Se}):a.createElement(Jw,{controller:t,target:Z?"canvas":"diagnostics",adjust:Z?u.canvasPaneAdjust:u.diagnosticsPaneAdjust}):null,a.createElement("div",{className:`ps-workspace-column-host is-split${be?" has-maximized":""}`},de?a.createElement("div",{className:"ps-workspace-column is-artifact"},a.createElement(Fw,{controller:t,onClose:Ne})):null,j?a.createElement("div",{key:`canvas:${u.activeSessionId||""}`,className:`ps-workspace-column is-artifact ps-canvas-layer${Z&&!de?"":" is-hidden"}${be&&Z&&!de?" is-maximized":""}`,style:Z&&!de&&le&&!be?{flex:`0 0 ${rt}px`,minWidth:0}:void 0,...Z&&!de?{}:{inert:!0,"aria-hidden":"true"}},a.createElement(Yu,{controller:t,visible:Z&&!de,maximized:be})):null,Z&&le?a.createElement(Qw,{controller:t,canvasPaneAdjust:u.canvasPaneAdjust,diagnosticsPaneAdjust:u.diagnosticsPaneAdjust}):null,le?a.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`minmax(0px, calc(50% + ${Math.round(Number(u.diagnosticsSplitAdjust)||0)}px)) var(--ps-resizer-track, 16px) minmax(0px, 1fr)`,...Z?{flex:"1 1 0%",minWidth:0}:null}},a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},a.createElement(Gs,{controller:t,mobile:!1})),a.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},a.createElement(e0,{controller:t,splitAdjust:u.diagnosticsSplitAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},ae?a.createElement(hr,{controller:t,focused:!1,previewOnly:!0}):a.createElement(si,{controller:t}))):null)),Te=a.createElement("div",{className:"ps-workspace-full"},a.createElement(Gs,{controller:t,mobile:!1}));let Le=null;J&&!A?Le=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(Gs,{controller:t,mobile:!0})):x==="inspector"?Le=u.inspectorTab==="nodes"?a.createElement("div",{className:"ps-mobile-pane-fill ps-mobile-node-split"},a.createElement(Gs,{controller:t,mobile:!0}),a.createElement(si,{controller:t,panelClassName:"ps-mobile-node-detail"})):a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(Gs,{controller:t,mobile:!0})):x==="activity"?Le=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(si,{controller:t})):x==="canvas"?Le=null:Le=a.createElement(Gw,{controller:t,layout:c,onEnterZen:s?.openMobileZen});const St=A&&B?a.createElement(Dw,{key:`canvas:${I.sessionId||""}`,controller:t,visible:O}):null;return e?a.createElement(Ri.Provider,{value:t},a.createElement(lc,{controller:t,mobile:!1,moa:s}),a.createElement(Ui,{controller:t})):a.createElement(Ri.Provider,{value:t},a.createElement("div",{ref:n,className:"ps-web-shell"},a.createElement(lc,{controller:t,moa:s,mobile:A,canvasPaneOpen:O,onToggleCanvasPane:Y,mobilePane:x,mobileMainLayout:c,onSelectMobilePane:(K,P)=>{K==="workspace"&&x==="workspace"&&d(z=>z==="split"?"chat":z==="chat"?"sessions":"split"),t.closeBudget(),T(K),P&&t.setFocus(P)}}),a.createElement("div",{className:"ps-workspace"},u.adminVisible?a.createElement(C0,{controller:t,mobile:A}):u.budgetOpen?a.createElement(x0,{controller:t}):J?Te:A?Le:Pe,St),A&&J?a.createElement(Bw,{controller:t}):null,a.createElement(Ui,{controller:t})))}export{pg as A,Ri as C,F0 as M,V0 as P,a as R,q0 as S,lu as _,lp as a,Di as b,W0 as c,z0 as d,B0 as e,it as f,rp as g,Oi as h,K0 as i,H0 as j,Rs as k,Tf as l,bi as m,Js as n,yo as o,rw as p,U0 as q,fc as r,ns as s,bo as t,se as u,D0 as v,zw as w,G0 as x,kt as y,j0 as z};
|