pilotswarm 0.5.77 → 0.5.78

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.
Files changed (71) hide show
  1. package/package.json +2 -2
  2. package/tui/src/embedded-workers.js +3 -0
  3. package/ui/react/src/web-app.js +73 -56
  4. package/web/dist/assets/{abnfDiagram-VRR7QNED-CKO_DwJV.js → abnfDiagram-VRR7QNED-C2HGSvvf.js} +1 -1
  5. package/web/dist/assets/{arc-DNYWrpvl.js → arc-C3faoYvN.js} +1 -1
  6. package/web/dist/assets/{architectureDiagram-ZJ3FMSHR-BuYVWnLH.js → architectureDiagram-ZJ3FMSHR-CQhrAa5t.js} +1 -1
  7. package/web/dist/assets/{blockDiagram-677ZJIJ3-Cl_IMZqi.js → blockDiagram-677ZJIJ3-CVGwBieB.js} +1 -1
  8. package/web/dist/assets/{c4Diagram-LMCZKHZV-Dp8EWK6S.js → c4Diagram-LMCZKHZV-CmdrEA77.js} +1 -1
  9. package/web/dist/assets/channel-CTmDTaW4.js +1 -0
  10. package/web/dist/assets/{chunk-2Q5K7J3B-Dja0nryh.js → chunk-2Q5K7J3B-Bm1hu4Hq.js} +1 -1
  11. package/web/dist/assets/{chunk-32BRIVSS-BfmHxlTO.js → chunk-32BRIVSS--_hODe_V.js} +1 -1
  12. package/web/dist/assets/{chunk-5VM5RSS4-DJ3zmwrq.js → chunk-5VM5RSS4-COI5t4m6.js} +1 -1
  13. package/web/dist/assets/{chunk-EX3LRPZG-B6SN8xEo.js → chunk-EX3LRPZG-BCFKy6tL.js} +1 -1
  14. package/web/dist/assets/{chunk-JWPE2WC7-Dlgqhr3G.js → chunk-JWPE2WC7-Ddh7J2Rp.js} +1 -1
  15. package/web/dist/assets/{chunk-MOJQB5TN-Dn-J2ayj.js → chunk-MOJQB5TN-DuIGV22R.js} +1 -1
  16. package/web/dist/assets/{chunk-RYQCIY6F-Af9a3V0M.js → chunk-RYQCIY6F-BNQbAlZV.js} +1 -1
  17. package/web/dist/assets/{chunk-V7JOEXUC-M3md4NxL.js → chunk-V7JOEXUC-DmoLjQx9.js} +1 -1
  18. package/web/dist/assets/{chunk-VR4S4FIN-ee4UcZX-.js → chunk-VR4S4FIN-BTOlqom4.js} +1 -1
  19. package/web/dist/assets/{chunk-XXDRQBXY-C1o9OH3_.js → chunk-XXDRQBXY-DTsc-Dgs.js} +1 -1
  20. package/web/dist/assets/classDiagram-OUVF2IWQ-0JetCpCm.js +1 -0
  21. package/web/dist/assets/classDiagram-v2-EOCWNBFH-0JetCpCm.js +1 -0
  22. package/web/dist/assets/{cose-bilkent-JH36ORCC-CRxjVQDN.js → cose-bilkent-JH36ORCC-QEqZLCny.js} +1 -1
  23. package/web/dist/assets/{cynefin-VYW2F7L2-MSAXYGkZ.js → cynefin-VYW2F7L2-Deleul8f.js} +1 -1
  24. package/web/dist/assets/{cynefinDiagram-TSTJHNR4-BPutBNN1.js → cynefinDiagram-TSTJHNR4-D0HrNQd4.js} +1 -1
  25. package/web/dist/assets/{dagre-VKFMJZFB-_W1WeW3E.js → dagre-VKFMJZFB-CLdKXtyZ.js} +1 -1
  26. package/web/dist/assets/{diagram-FQU43EPY-DT_0zQl9.js → diagram-FQU43EPY-C0DnCIiG.js} +1 -1
  27. package/web/dist/assets/{diagram-G47NLZAW-HBy_Ck1W.js → diagram-G47NLZAW-DzQa8iDK.js} +1 -1
  28. package/web/dist/assets/{diagram-NH7WQ7WH-DyQQlTUp.js → diagram-NH7WQ7WH-CazRIZg4.js} +1 -1
  29. package/web/dist/assets/{diagram-OA4YK3LP-LJ7WYOVk.js → diagram-OA4YK3LP-gZanfxjg.js} +1 -1
  30. package/web/dist/assets/{diagram-WEI45ONY-B83fa0oq.js → diagram-WEI45ONY-CHoHyTz-.js} +1 -1
  31. package/web/dist/assets/{ebnfDiagram-CCIWWBDH-ZbAvBv6c.js → ebnfDiagram-CCIWWBDH-CeHz2Jh9.js} +1 -1
  32. package/web/dist/assets/{erDiagram-Q63AITRT-BNe1kdom.js → erDiagram-Q63AITRT-C95MErio.js} +1 -1
  33. package/web/dist/assets/{flowDiagram-23GEKE2U-DDlbRR4H.js → flowDiagram-23GEKE2U-AdgXiTao.js} +1 -1
  34. package/web/dist/assets/{ganttDiagram-NO4QXBWP-DRvGvhmv.js → ganttDiagram-NO4QXBWP-D7Ltt8Pp.js} +1 -1
  35. package/web/dist/assets/{gitGraphDiagram-IHSO6WYX-Bj5CkOw6.js → gitGraphDiagram-IHSO6WYX-9Xi-xmei.js} +1 -1
  36. package/web/dist/assets/index-C7_15DMS.css +1 -0
  37. package/web/dist/assets/index-IxnOJbWb.js +24 -0
  38. package/web/dist/assets/{infoDiagram-FWYZ7A6U-BB-pO5BG.js → infoDiagram-FWYZ7A6U-fRlxZHtD.js} +1 -1
  39. package/web/dist/assets/{ishikawaDiagram-FXEZZL3T-fplKz6J9.js → ishikawaDiagram-FXEZZL3T-CEVSVKfj.js} +1 -1
  40. package/web/dist/assets/{journeyDiagram-5HDEW3XC-CZXJ9si6.js → journeyDiagram-5HDEW3XC-CJhad1Ay.js} +1 -1
  41. package/web/dist/assets/{kanban-definition-HUTT4EX6-CL9u5Pmv.js → kanban-definition-HUTT4EX6-CE6OFSTa.js} +1 -1
  42. package/web/dist/assets/{linear-WwQWwN2U.js → linear-BuexMwfW.js} +1 -1
  43. package/web/dist/assets/{mermaid.core-1gBc6FeB.js → mermaid.core-DWYsDHXh.js} +4 -4
  44. package/web/dist/assets/{mindmap-definition-LN4V7U3C-CtKgb3BP.js → mindmap-definition-LN4V7U3C-6_lFebqE.js} +1 -1
  45. package/web/dist/assets/{papaparse.min-Dk5F4KnO.js → papaparse.min-DjlrGi59.js} +1 -1
  46. package/web/dist/assets/{pegDiagram-2B236MQR-rkKhqRQO.js → pegDiagram-2B236MQR-B1fuWjDp.js} +1 -1
  47. package/web/dist/assets/{pieDiagram-ENE6RG2P-VfaXje3o.js → pieDiagram-ENE6RG2P-BWsDDxls.js} +1 -1
  48. package/web/dist/assets/pilotswarm-3GsGwA3r.js +109 -0
  49. package/web/dist/assets/{quadrantDiagram-ABIIQ3AL-Cw6aMTCy.js → quadrantDiagram-ABIIQ3AL-CxzBQxBX.js} +1 -1
  50. package/web/dist/assets/{railroadDiagram-RFXS5EU6-Dju0kwmP.js → railroadDiagram-RFXS5EU6-Coqs5FXi.js} +1 -1
  51. package/web/dist/assets/{requirementDiagram-TGXJPOKE-BbyvxgRb.js → requirementDiagram-TGXJPOKE-v1GaofBK.js} +1 -1
  52. package/web/dist/assets/{sankeyDiagram-HTMAVEWB-Do_VdVhS.js → sankeyDiagram-HTMAVEWB-DGaKjdrZ.js} +1 -1
  53. package/web/dist/assets/{sequenceDiagram-DBY2YBRQ-CKqDjXwf.js → sequenceDiagram-DBY2YBRQ-UD5oqT-Q.js} +1 -1
  54. package/web/dist/assets/{sizeCapture-X5ZJPWSS-sVG1J5D7.js → sizeCapture-X5ZJPWSS-ClCMN9Ry.js} +1 -1
  55. package/web/dist/assets/{stateDiagram-2N3HPSRC-CfjQilyb.js → stateDiagram-2N3HPSRC-CU96VzpK.js} +1 -1
  56. package/web/dist/assets/stateDiagram-v2-6OUMAXLB-TNMXnnTc.js +1 -0
  57. package/web/dist/assets/{swimlanes-5IMT3BWC-Csum4YeF.js → swimlanes-5IMT3BWC-5pw00Cr8.js} +2 -2
  58. package/web/dist/assets/swimlanesDiagram-G3AALYLV-BOvR3DN_.js +8 -0
  59. package/web/dist/assets/{timeline-definition-FHXFAJF6-Cw6UCQjz.js → timeline-definition-FHXFAJF6-Dfd6fPWH.js} +1 -1
  60. package/web/dist/assets/{vennDiagram-L72KCM5P-b_571af9.js → vennDiagram-L72KCM5P-CaJB0ZOh.js} +1 -1
  61. package/web/dist/assets/{wardleyDiagram-EHGQE667-DL_0-lVh.js → wardleyDiagram-EHGQE667-Cau_Q6Bk.js} +1 -1
  62. package/web/dist/assets/{xychartDiagram-FW5EYKEG-BqKYzu8y.js → xychartDiagram-FW5EYKEG-DTUEy024.js} +1 -1
  63. package/web/dist/index.html +3 -3
  64. package/web/dist/assets/channel-DTKy7mHi.js +0 -1
  65. package/web/dist/assets/classDiagram-OUVF2IWQ-MfqAYpCn.js +0 -1
  66. package/web/dist/assets/classDiagram-v2-EOCWNBFH-MfqAYpCn.js +0 -1
  67. package/web/dist/assets/index-CVQyeZNA.js +0 -24
  68. package/web/dist/assets/index-mtWlthKI.css +0 -1
  69. package/web/dist/assets/pilotswarm-BvFGjArK.js +0 -109
  70. package/web/dist/assets/stateDiagram-v2-6OUMAXLB-CYw2jLW6.js +0 -1
  71. package/web/dist/assets/swimlanesDiagram-G3AALYLV-CbG-9P20.js +0 -8
@@ -1,109 +0,0 @@
1
- function Np(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Pr={exports:{}},ue={};var to;function Cp(){if(to)return ue;to=1;var e=Symbol.for("react.transitional.element"),t=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(A){return A===null||typeof A!="object"?null:(A=m&&A[m]||A["@@iterator"],typeof A=="function"?A:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,b={};function y(A,G,D){this.props=A,this.context=G,this.refs=b,this.updater=D||h}y.prototype.isReactComponent={},y.prototype.setState=function(A,G){if(typeof A!="object"&&typeof A!="function"&&A!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,A,G,"setState")},y.prototype.forceUpdate=function(A){this.updater.enqueueForceUpdate(this,A,"forceUpdate")};function v(){}v.prototype=y.prototype;function S(A,G,D){this.props=A,this.context=G,this.refs=b,this.updater=D||h}var w=S.prototype=new v;w.constructor=S,g(w,y.prototype),w.isPureReactComponent=!0;var E=Array.isArray;function I(){}var T={H:null,A:null,T:null,S:null},C=Object.prototype.hasOwnProperty;function k(A,G,D){var Y=D.ref;return{$$typeof:e,type:A,key:G,ref:Y!==void 0?Y:null,props:D}}function O(A,G){return k(A.type,G,A.props)}function N(A){return typeof A=="object"&&A!==null&&A.$$typeof===e}function R(A){var G={"=":"=0",":":"=2"};return"$"+A.replace(/[=:]/g,function(D){return G[D]})}var H=/\/+/g;function x(A,G){return typeof A=="object"&&A!==null&&A.key!=null?R(""+A.key):G.toString(36)}function P(A){switch(A.status){case"fulfilled":return A.value;case"rejected":throw A.reason;default:switch(typeof A.status=="string"?A.then(I,I):(A.status="pending",A.then(function(G){A.status==="pending"&&(A.status="fulfilled",A.value=G)},function(G){A.status==="pending"&&(A.status="rejected",A.reason=G)})),A.status){case"fulfilled":return A.value;case"rejected":throw A.reason}}throw A}function _(A,G,D,Y,J){var te=typeof A;(te==="undefined"||te==="boolean")&&(A=null);var Z=!1;if(A===null)Z=!0;else switch(te){case"bigint":case"string":case"number":Z=!0;break;case"object":switch(A.$$typeof){case e:case t:Z=!0;break;case u:return Z=A._init,_(Z(A._payload),G,D,Y,J)}}if(Z)return J=J(A),Z=Y===""?"."+x(A,0):Y,E(J)?(D="",Z!=null&&(D=Z.replace(H,"$&/")+"/"),_(J,G,D,"",function(oe){return oe})):J!=null&&(N(J)&&(J=O(J,D+(J.key==null||A&&A.key===J.key?"":(""+J.key).replace(H,"$&/")+"/")+Z)),G.push(J)),1;Z=0;var ne=Y===""?".":Y+":";if(E(A))for(var ae=0;ae<A.length;ae++)Y=A[ae],te=ne+x(Y,ae),Z+=_(Y,G,D,te,J);else if(ae=f(A),typeof ae=="function")for(A=ae.call(A),ae=0;!(Y=A.next()).done;)Y=Y.value,te=ne+x(Y,ae++),Z+=_(Y,G,D,te,J);else if(te==="object"){if(typeof A.then=="function")return _(P(A),G,D,Y,J);throw G=String(A),Error("Objects are not valid as a React child (found: "+(G==="[object Object]"?"object with keys {"+Object.keys(A).join(", ")+"}":G)+"). If you meant to render a collection of children, use an array instead.")}return Z}function $(A,G,D){if(A==null)return A;var Y=[],J=0;return _(A,Y,"","",function(te){return G.call(D,te,J++)}),Y}function B(A){if(A._status===-1){var G=A._result;G=G(),G.then(function(D){(A._status===0||A._status===-1)&&(A._status=1,A._result=D)},function(D){(A._status===0||A._status===-1)&&(A._status=2,A._result=D)}),A._status===-1&&(A._status=0,A._result=G)}if(A._status===1)return A._result.default;throw A._result}var j=typeof reportError=="function"?reportError:function(A){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var G=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof A=="object"&&A!==null&&typeof A.message=="string"?String(A.message):String(A),error:A});if(!window.dispatchEvent(G))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",A);return}console.error(A)},W={map:$,forEach:function(A,G,D){$(A,function(){G.apply(this,arguments)},D)},count:function(A){var G=0;return $(A,function(){G++}),G},toArray:function(A){return $(A,function(G){return G})||[]},only:function(A){if(!N(A))throw Error("React.Children.only expected to receive a single React element child.");return A}};return ue.Activity=p,ue.Children=W,ue.Component=y,ue.Fragment=s,ue.Profiler=r,ue.PureComponent=S,ue.StrictMode=n,ue.Suspense=c,ue.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,ue.__COMPILER_RUNTIME={__proto__:null,c:function(A){return T.H.useMemoCache(A)}},ue.cache=function(A){return function(){return A.apply(null,arguments)}},ue.cacheSignal=function(){return null},ue.cloneElement=function(A,G,D){if(A==null)throw Error("The argument must be a React element, but you passed "+A+".");var Y=g({},A.props),J=A.key;if(G!=null)for(te in G.key!==void 0&&(J=""+G.key),G)!C.call(G,te)||te==="key"||te==="__self"||te==="__source"||te==="ref"&&G.ref===void 0||(Y[te]=G[te]);var te=arguments.length-2;if(te===1)Y.children=D;else if(1<te){for(var Z=Array(te),ne=0;ne<te;ne++)Z[ne]=arguments[ne+2];Y.children=Z}return k(A.type,J,Y)},ue.createContext=function(A){return A={$$typeof:o,_currentValue:A,_currentValue2:A,_threadCount:0,Provider:null,Consumer:null},A.Provider=A,A.Consumer={$$typeof:i,_context:A},A},ue.createElement=function(A,G,D){var Y,J={},te=null;if(G!=null)for(Y in G.key!==void 0&&(te=""+G.key),G)C.call(G,Y)&&Y!=="key"&&Y!=="__self"&&Y!=="__source"&&(J[Y]=G[Y]);var Z=arguments.length-2;if(Z===1)J.children=D;else if(1<Z){for(var ne=Array(Z),ae=0;ae<Z;ae++)ne[ae]=arguments[ae+2];J.children=ne}if(A&&A.defaultProps)for(Y in Z=A.defaultProps,Z)J[Y]===void 0&&(J[Y]=Z[Y]);return k(A,te,J)},ue.createRef=function(){return{current:null}},ue.forwardRef=function(A){return{$$typeof:l,render:A}},ue.isValidElement=N,ue.lazy=function(A){return{$$typeof:u,_payload:{_status:-1,_result:A},_init:B}},ue.memo=function(A,G){return{$$typeof:d,type:A,compare:G===void 0?null:G}},ue.startTransition=function(A){var G=T.T,D={};T.T=D;try{var Y=A(),J=T.S;J!==null&&J(D,Y),typeof Y=="object"&&Y!==null&&typeof Y.then=="function"&&Y.then(I,j)}catch(te){j(te)}finally{G!==null&&D.types!==null&&(G.types=D.types),T.T=G}},ue.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},ue.use=function(A){return T.H.use(A)},ue.useActionState=function(A,G,D){return T.H.useActionState(A,G,D)},ue.useCallback=function(A,G){return T.H.useCallback(A,G)},ue.useContext=function(A){return T.H.useContext(A)},ue.useDebugValue=function(){},ue.useDeferredValue=function(A,G){return T.H.useDeferredValue(A,G)},ue.useEffect=function(A,G){return T.H.useEffect(A,G)},ue.useEffectEvent=function(A){return T.H.useEffectEvent(A)},ue.useId=function(){return T.H.useId()},ue.useImperativeHandle=function(A,G,D){return T.H.useImperativeHandle(A,G,D)},ue.useInsertionEffect=function(A,G){return T.H.useInsertionEffect(A,G)},ue.useLayoutEffect=function(A,G){return T.H.useLayoutEffect(A,G)},ue.useMemo=function(A,G){return T.H.useMemo(A,G)},ue.useOptimistic=function(A,G){return T.H.useOptimistic(A,G)},ue.useReducer=function(A,G,D){return T.H.useReducer(A,G,D)},ue.useRef=function(A){return T.H.useRef(A)},ue.useState=function(A){return T.H.useState(A)},ue.useSyncExternalStore=function(A,G,D){return T.H.useSyncExternalStore(A,G,D)},ue.useTransition=function(){return T.H.useTransition()},ue.version="19.2.4",ue}var so;function Mc(){return so||(so=1,Pr.exports=Cp()),Pr.exports}var Tp=Mc();const a=Np(Tp);var Mr={exports:{}},Ze={};var no;function Pp(){if(no)return Ze;no=1;var e=Mc();function t(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(t(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=e.__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 Ze.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,Ze.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(t(299));return i(c,d,null,u)},Ze.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()}},Ze.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))},Ze.prefetchDNS=function(c){typeof c=="string"&&n.d.D(c)},Ze.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})}},Ze.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)},Ze.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})}},Ze.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)},Ze.requestFormReset=function(c){n.d.r(c)},Ze.unstable_batchedUpdates=function(c,d){return c(d)},Ze.useFormState=function(c,d,u){return o.H.useFormState(c,d,u)},Ze.useFormStatus=function(){return o.H.useHostTransitionStatus()},Ze.version="19.2.4",Ze}var ro;function Mp(){if(ro)return Mr.exports;ro=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),Mr.exports=Pp(),Mr.exports}var Hs=Mp();const _p=a.createContext(null);function yt(){const e=a.useContext(_p);if(!e)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return e}function ee(e,t,s=Object.is){const n=a.useRef(t),r=a.useRef(s);n.current=t,r.current=s;const[i,o]=a.useState(()=>t(e.getState())),l=a.useRef(i);return a.useEffect(()=>{l.current=i},[i]),a.useEffect(()=>e.subscribe(c=>{const d=n.current(c);r.current(l.current,d)||(l.current=d,o(d))}),[e]),i}const io=[".  ",".. ","..."],ao=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function sa(e,t=120){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!e){n(0);return}const r=setInterval(()=>{n(i=>(i+1)%ao.length)},t);return()=>clearInterval(r)},[e,t]),e?ao[s]:""}function _c(e,t=360){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!e){n(0);return}const r=setInterval(()=>{n(i=>(i+1)%io.length)},t);return()=>clearInterval(r)},[e,t]),e?io[s]:""}function $c(e,t=""){if(!Array.isArray(e)||e.length===0)return null;if(!t)return e;const s=e[e.length-1]||{};return[...e,{text:t,color:s.color||"gray",bold:!!s.bold,underline:!!s.underline,backgroundColor:s.backgroundColor}]}const F={SESSIONS:"sessions",CHAT:"chat",INSPECTOR:"inspector",ACTIVITY:"activity",PROMPT:"prompt",ADMIN:"admin"},wt=["sequence","logs","nodes","history","files","stats"],L={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 hs(e,t,s){const n=e.indexOf(t),i=((n===-1?0:n)+s+e.length)%e.length;return e[i]}function na(e){const t=typeof e?.utilization=="number"?e.utilization:typeof e?.tokenLimit=="number"&&e.tokenLimit>0&&typeof e?.currentTokens=="number"?e.currentTokens/e.tokenLimit:null;return typeof t!="number"||!Number.isFinite(t)?null:Math.max(0,Math.min(100,Math.round(t*100)))}function vi(e){return typeof e!="number"||!Number.isFinite(e)||e<0?"?":e>=1e6?`${e>=1e7?Math.round(e/1e6):Math.round(e/1e5)/10}`.replace(/\.0$/,"")+"m":e>=1e3?`${e>=1e5?Math.round(e/1e3):Math.round(e/100)/10}`.replace(/\.0$/,"")+"k":String(Math.round(e))}function $p(e){const t=na(e);return t==null?"gray":t>=85?"red":t>=70?"yellow":"gray"}function Rp(e){if(!e||!(typeof e.tokenLimit=="number"&&e.tokenLimit>0&&typeof e.currentTokens=="number"&&e.currentTokens>=0))return null;const t=na(e);return t==null?null:{text:`ctx ${vi(e.currentTokens)}/${vi(e.tokenLimit)} ${t}%`,color:$p(e)}}function Lp(e){const t=e?.compaction;return!t||typeof t!="object"?null:t.state==="running"?{text:"[compacting]",color:"magenta"}:t.state==="failed"?{text:"[compact failed]",color:"red"}:null}function Rc(e){return!e||typeof e!="object"?null:{...e,...e.compaction&&typeof e.compaction=="object"?{compaction:{...e.compaction}}:{}}}function Op(e){if(e instanceof Date)return e.getTime();const t=new Date(e).getTime();return Number.isFinite(t)?t:Date.now()}function Lc(e,t,s={},n={}){if(!t)return null;const r=Rc(e)||{},i=Op(n.timestamp);return t==="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):t==="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):t==="session.compaction_start"?(r.compaction={...r.compaction||{},state:"running",startedAt:i,completedAt:void 0,error:void 0},r):t==="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(e,t,s={}){const n=e?[{text:`[${e}] `,color:"white"}]:[];return t==="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 ${vi(s.tokensRemoved)}`,color:"gray"}]:[]]}const wi=/\{(\/?)([a-z-]+)\}/g,Dp={color:null,bold:!1,underline:!1},jn=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,oo=/session:\/\/([A-Za-z0-9-]+)/g,Mn=" (press a to download)",Bp={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function _n(e){return{color:e.color,bold:e.bold,underline:e.underline}}function Hp(e,t,s){const n=_n(e);if(t==="bold")return n.bold=!s,n;if(t==="underline")return n.underline=!s,n;if(t.endsWith("-fg")){const r=t.slice(0,-3);return n.color=s?null:Bp[r]||null,n}return n}function ra(e){return String(e||"").replace(wi,"")}function Oc(e){const t=[],n=String(e||"").split(`
2
- `);for(const r of n){const i=[];let o=_n(Dp),l=0,c;for(;(c=wi.exec(r))!==null;){const[d,u,p]=c;c.index>l&&i.push({text:r.slice(l,c.index),..._n(o)}),o=Hp(o,p,u==="/"),l=c.index+d.length}(l<r.length||i.length===0)&&i.push({text:r.slice(l),..._n(o)}),t.push(i),wi.lastIndex=0}return t}function Le(e){return String(e||"").slice(0,8)}function Rs(e){const t=String(e||"");return t?t.includes(":")?t.split(":").slice(1).join(":"):t:""}let _r=null,$r=null,Rr=null,Lr=null;function Up(){return _r||(_r=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})),_r}function Fc(){return $r||($r=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})),$r}function jp(){return Rr||(Rr=new Intl.DateTimeFormat("en-GB",{month:"short"})),Rr}function Gp(){return Lr||(Lr=new Intl.DateTimeFormat("en-GB",{month:"short",day:"numeric"})),Lr}function Dc(e,t=new Date){if(!e)return"";try{const s=e instanceof Date?e:new Date(e);if(Number.isNaN(s.getTime()))return"";if(s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate())return Fc().format(s);const r=Up().format(s),i=String(s.getDate()),o=jp().format(s),l=s.getFullYear()===t.getFullYear()?"":String(s.getFullYear()).slice(-2);return`${i}${o}${l} ${r}`}catch{return""}}function Ke(e,t=new Date){if(!e)return"";try{const s=e instanceof Date?e:new Date(e),n=Fc().format(s);if(s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate())return n;const i=Gp().format(s),o=s.getFullYear()===t.getFullYear()?"":` ${s.getFullYear()}`;return`${i}${o} ${n}`}catch{return""}}function as(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"?";const t=Math.round(e),s=Math.floor(t/3600),n=Math.floor(t%3600/60),r=t%60;return s>0?`${s}h ${n}m`:n>0?`${n}m ${r}s`:`${r}s`}function Bc(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Wp(e,t,s){const n=e.indexOf(t,s);return n>=0?n:-1}function Gn(e){return/[A-Za-z0-9_]/u.test(String(e||""))}function lo(e,t,s){const n=e[t+s.length]||"";if(!n||/\s/u.test(n))return!1;if(!s.includes("_"))return!0;const r=e[t-1]||"";return!(Gn(r)&&Gn(n))}function qp(e,t,s){const n=e[t-1]||"";if(!n||/\s/u.test(n))return!1;if(!s.includes("_"))return!0;const r=e[t+s.length]||"";return!(Gn(n)&&Gn(r))}function co(e,t,s){let n=s;for(;n<e.length;){const r=e.indexOf(t,n);if(r<0)return-1;if(qp(e,r,t))return r;n=r+t.length}return-1}function zp(e){let t=String(e||""),s="";for(;t&&/[.,!?;:]/u.test(t[t.length-1]||"");)s=`${t[t.length-1]}${s}`,t=t.slice(0,-1);return{url:t,trailing:s}}function Kp(e,t,s){let n=0;for(;e.slice(s+n,s+n+t.length)===t;)n+=t.length;return n}function bn(e,t,s={}){if(!t)return;const n=e[e.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+=t;return}e.push({text:t,color:s.color||null,bold:!!s.bold,underline:!!s.underline,backgroundColor:s.backgroundColor||void 0,href:s.href||void 0})}function Ht(e,t){if(t){if(t.type==="text"){const s=e[e.length-1];if(s?.type==="text"){s.text+=t.text||"";return}}e.push(t)}}function Hc(e){return(e||[]).map(t=>t?.text||"").join("")}function $n(e){return ht(Hc(e))}function Vp(e,t){const s=Math.max(0,Number(t)||0);if(s<=0)return[];const n=[];let r=s;for(const i of e||[]){if(r<=0)break;const o=String(i?.text||"");if(!o)continue;const l=un(o,r);l&&(n.push({...i,text:l}),r-=ht(l))}return n}function Uc(e,t){const s=Math.max(0,Number(t)||0),n=Vp(e,s),r=$n(n),i=Math.max(0,s-r);return i>0&&n.push({text:" ".repeat(i),color:null,bold:!1,underline:!1}),n}function jc(e,t){const s=Math.max(1,Number(t)||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 e||[]){let c=String(l?.text||"");if(c)for(;c.length>0;){const d=Math.max(1,s-i),u=un(c,d);if(!u)break;if(u.length===c.length||ht(u)<d){r.push({...l,text:u}),i+=ht(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+=ht(m),c=c.slice(m.length),o()}else r.push({...l,text:u}),i+=ht(u),c=c.slice(u.length),i>=s&&o()}}return(r.length>0||n.length===0)&&o(),n}function uo(e,t){return t?(e||[]).map(s=>String(s?.text||"").trim()?{...s,color:t}:{...s}):e}function Gc(e){if(!e)return e;let t=String(e);for(;;){const s=t.replace(/[*_`]+$/g,"").replace(/[)\]}>!,;:?]+$/g,"").replace(/(\.[A-Za-z0-9]{1,16})\.+$/g,"$1");if(s===t)return t;t=s}}function Yp(e){const t=String(e||"");return jn.lastIndex=0,[...t.matchAll(jn)].map(s=>{const n=s[1],r=Gc(s[2]);return!n||!r?null:{sessionId:n,filename:r,uri:`artifact://${n}/${r}`}}).filter(Boolean)}function ss(e){const t=String(e||"");if(!t)return t;jn.lastIndex=0;const s=t.replace(jn,(n,r,i,o,l)=>{if(l.slice(Math.max(0,o-2),o)==="](")return n;const c=Gc(i);return!r||!c?n:`[artifact: ${c}](artifact://${r}/${c})${Mn}`});return oo.lastIndex=0,s.replace(oo,(n,r)=>r?`[session: ${Le(r)}](session://${r})`:n)}function ia(e=""){const t=String(e||""),s=[];let n=0;for(;n<t.length;){if(t[n]==="`"){const i=Kp(t,"`",n),o="`".repeat(i),l=Wp(t,o,n+i);if(l>n+i-1){Ht(s,{type:"code",text:t.slice(n+i,l)}),n=l+i;continue}}if(t.startsWith("**",n)||t.startsWith("__",n)){const i=t.slice(n,n+2),o=lo(t,n,i)?co(t,i,n+2):-1;if(o>n+2){Ht(s,{type:"strong",text:t.slice(n+2,o)}),n=o+2;continue}}if(t[n]==="["){const i=/^\[([^\]]+)\]\(([^)]+)\)/.exec(t.slice(n));if(i){Ht(s,{type:"link",text:i[1],href:i[2]}),n+=i[0].length;continue}}if(t.startsWith("<http://",n)||t.startsWith("<https://",n)){const i=t.indexOf(">",n+1);if(i>n+1){const o=t.slice(n+1,i);Ht(s,{type:"link",text:o,href:o}),n=i+1;continue}}if(t.startsWith("http://",n)||t.startsWith("https://",n)){let i=n;for(;i<t.length&&!/\s/u.test(t[i]||"");)i+=1;const{url:o,trailing:l}=zp(t.slice(n,i));if(o){Ht(s,{type:"link",text:o,href:o}),l&&Ht(s,{type:"text",text:l}),n=i;continue}}if((t[n]==="*"||t[n]==="_")&&t[n+1]!==" "&&t[n-1]!==t[n]&&lo(t,n,t[n])){const i=t[n],o=co(t,i,n+1);if(o>n+1){Ht(s,{type:"em",text:t.slice(n+1,o)}),n=o+1;continue}}let r=t.length;for(const i of["<https://","<http://","https://","http://","**","__","`","[","*","_"]){const o=t.indexOf(i,n+1);o!==-1&&o<r&&(r=o)}Ht(s,{type:"text",text:t.slice(n,r)}),n=r}return s.length>0?s:[{type:"text",text:""}]}function Xp(e=""){return ia(e).filter(t=>t?.type==="link"&&/^https?:\/\//i.test(String(t?.href||""))).map(t=>({href:String(t.href||"").trim(),text:String(t.text||t.href||"").trim()})).filter(t=>t.href)}function ts(e,t=0){if(t>=32)return[{text:String(e||""),color:null,bold:!1,underline:!1}];const s=ia(e),n=[];for(const r of s){if(r.type==="code"){bn(n,r.text,{color:"cyan"});continue}if(r.type==="strong"||r.type==="em"){for(const i of ts(r.text,t+1))bn(n,i.text,{...i,...r.type==="strong"?{bold:!0}:{underline:!0}});continue}if(r.type==="link"){bn(n,r.text,{color:"cyan",underline:!0,href:r.href});continue}bn(n,r.text)}return n.length>0?n:[{text:"",color:null,bold:!1,underline:!1}]}function ks(e){return/^\s*\|.*\|\s*$/.test(e)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(e)}function Is(e){const t=String(e||"").trim().replace(/^\|/,"").replace(/\|$/,""),s=[];let n="",r=!1;for(const i of t){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 Wn(e){return e.length>0&&e.every(t=>/^:?-+:?$/.test(String(t||"").replace(/\s+/g,"")))}function ht(e){return Array.from(String(e||"")).length}function un(e,t){if(t<=0)return"";let s="",n=0;for(const r of Array.from(String(e||""))){if(n+1>t)break;s+=r,n+=1}return s}function Wc(e,t){const s=String(e||""),n=Math.max(0,t-ht(s));return s+" ".repeat(n)}function qc(e){return Hc(ts(e))}function Qp(e,t){const s=qc(e).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),r=[];let i="";const o=l=>{let c=l;for(;ht(c)>t;){const d=un(c,t);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}`;ht(d)<=t?i=d:(r.push(i),i=c)}return i&&r.push(i),r.length>0?r:[""]}function Zp(e,t){const s=Math.max(1,...e.map(u=>u.length)),n=Math.max(s*3,t-(s*3+1)),r=Array.from({length:s},(u,p)=>Math.max(3,...e.map(m=>ht(m[p]||"")))),i=Array.from({length:s},(u,p)=>Math.max(3,...e.map(m=>Math.max(0,...String(m[p]||"").split(/\s+/).filter(Boolean).map(f=>ht(f)))))),o=Array.from({length:s},(u,p)=>Math.max(3,Math.min(Math.max(ht(e[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 Jp(e,t){if(!e||e.length===0)return"";const s=Math.max(1,...e.map(m=>m.length)),r=e.map(m=>Array.from({length:s},(f,h)=>m[h]||"")).map(m=>m.map(f=>qc(f))),i=Zp(r,t),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)=>Qp(g,i[b])),h=Math.max(...f.map(g=>g.length));for(let g=0;g<h;g++){const b=f.map((y,v)=>Wc(y[g]||"",i[v]));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 em(e,t){const s=String(e||"").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(!ks(o)||!ks(c)){n.push(o);continue}const d=Is(o),u=Is(c);if(!Wn(u)||d.length!==u.length){n.push(o);continue}const p=[d];for(i+=1;i+1<s.length&&ks(s[i+1]);){i+=1;const m=Is(s[i]);Wn(m)||p.push(m)}n.push(Jp(p,t))}return n.join(`
5
- `)}function tm(e,t){const s=String(e||"");if(!s)return[""];const n=[];let r=s;for(;r.length>0;){const i=un(r,t);if(!i)break;n.push(i),r=r.slice(i.length)}return n.length>0?n:[""]}function po(e,t){const s=Math.max(12,t),n=e?` ${String(e).trim()} `:" code ",r=un(n,Math.max(1,s-4)),i=Math.max(0,s-r.length-2);return[{text:`┌${r}${"─".repeat(i)}┐`,color:"gray"}]}function mo(e){return[{text:`└${"─".repeat(Math.max(1,e-2))}┘`,color:"gray"}]}function fo(e,t){const s=Math.max(8,t),n=Math.max(1,s-2),r=[];for(const i of e){const o=tm(i,n);for(const l of o)r.push([{text:"│",color:"gray"},{text:Wc(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 ds(e,t={}){const s=[],n=Math.max(20,Number(t?.width)||80),r=t.tableMode==="sentinel"?"sentinel":"boxArt",o=(r==="boxArt"?em(String(e||""),n):String(e||"")).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(po(c,Math.max(8,n))),s.push(...fo(d,Math.max(8,n))),s.push(mo(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&&ks(p)){const y=o[u+1]||"";if(ks(y)){const v=Is(p),S=Is(y);if(Wn(S)&&v.length===S.length){const w=[];let E=u+2;for(;E<o.length&&ks(o[E]);){const I=Is(o[E]);Wn(I)||w.push(I),E+=1}s.push({kind:"markdownTable",header:v,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(ts(f[2]).map(y=>({...y,color:y.color||"white",bold:!0})));continue}const h=/^>\s?(.*)$/.exec(p);if(h){s.push([{text:"> ",color:"gray"},...ts(h[1]).map(y=>({...y,color:y.color||"gray"}))]);continue}const g=/^\s*[-*]\s+(.*)$/.exec(p);if(g){s.push([{text:"• ",color:"gray"},...ts(g[1])]);continue}const b=/^\s*(\d+)\.\s+(.*)$/.exec(p);if(b){s.push([{text:`${b[1]}. `,color:"gray"},...ts(b[2])]);continue}s.push(ts(p))}return l&&(s.push(po(c,Math.max(8,n))),s.push(...fo(d,Math.max(8,n))),s.push(mo(Math.max(8,n)))),s}function Ue({title:e="SYSTEM",timestamp:t="",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(e||"SYSTEM").toUpperCase()} `,color:r,bold:!0},...t?[{text:` ${String(t)} `,color:"gray"}]:[]];if(c==="sentinel"){const w=ds(String(s||""),{width:p,tableMode:c}),E=o?w.map(I=>Array.isArray(I)?uo(I,o):I):w;return[{kind:"cardStart",runs:m,borderColor:i,...d?{cardKey:d}:{}},...E,{kind:"cardEnd"},[{text:"",color:null}]]}const f=ds(String(s||""),{width:p}),h=f.length>0?f.flatMap(w=>jc(w,p)):[[{text:"",color:null}]],g=o?h.map(w=>uo(w,o)):h,b=g.reduce((w,E)=>Math.max(w,$n(E)),0),y=l?Math.min(u,Math.max(12,$n(m)+3,b+4)):u,v=Math.max(1,y-4),S=Math.max(0,y-$n(m)-3);return[[{text:"┌─",color:i},...m,{text:`${"─".repeat(S)}┐`,color:i}],...g.map(w=>[{text:"│ ",color:i},...Uc(w,v),{text:" │",color:i}]),[{text:`└${"─".repeat(Math.max(1,y-2))}┘`,color:i}],[{text:"",color:null}]]}const aa="[canvas-action] ",ho=2048,go=8192;function sm(e){let t;try{t=JSON.stringify(e)||""}catch{return 1/0}return typeof TextEncoder<"u"?new TextEncoder().encode(t).length:t.length}function nm(e,t){const s=e?.actions;if(!s||typeof s!="object")return{ok:!1,reason:"the current canvas declares no response contract"};if(!t||typeof t!="object"||t.type!=="canvas-action")return{ok:!1,reason:"not a canvas-action message"};const n=typeof t.action=="string"?t.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=t.data===void 0?{}:t.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>ho)return{ok:!1,reason:`field ${JSON.stringify(l)} exceeds ${ho} characters`};if(p==="number"&&!Number.isFinite(m))return{ok:!1,reason:`field ${JSON.stringify(l)} must be a finite number`};o[l]=m}return sm(o)>go?{ok:!1,reason:`action payload exceeds ${go} bytes`}:{ok:!0,action:n,data:o}}function rm(e,t){return`${aa}${JSON.stringify({action:e,data:t})}`}function zc(e){return typeof e=="string"&&e.startsWith(aa)}function im(e){if(!zc(e))return null;try{const t=JSON.parse(e.slice(aa.length));return!t||typeof t!="object"||typeof t.action!="string"?null:{action:t.action,data:t.data&&typeof t.data=="object"?t.data:{}}}catch{return null}}function am({burst:e=3,windowMs:t=3e3}={}){const s=[];return function(r=Date.now()){for(;s.length&&r-s[0]>t;)s.shift();return s.length>=e?!1:(s.push(r),!0)}}function ps(e,t="PilotSwarm"){const s=t||"PilotSwarm",n=String(e?.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(e?.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 Kc(e){const t=ps(e,"PilotSwarm");return t==="PilotSwarm"?0:t==="Sweeper Agent"?1:t==="Resource Manager Agent"?2:t==="Facts Manager"?3:10}function yo(e){return String(e||"").trim().replace(/^Execution failed:\s*/,"")}function mr(e,t){const s=yo(e),n=yo(t);return!!s&&(n===s||n.startsWith(`${s} (`))}const an=["tool.execution_start","tool.execution_complete","tool.execution_partial_result","tool.execution_progress","external_tool.requested","external_tool.completed","session.agent_spawned"],om=new Set(an),lm=/(?:^|[.:/])(?: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 Rn(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Ls(e){return Rn(e).split(/\r?\n/).find(t=>t.trim())?.trim()||""}function cm(e){if(!e||typeof e!="object")return Ls(e);for(const t of["command","cmd","task","message","prompt","subject","body","query","path","reason","agent_ids","agent_id"])if(e[t]!=null)return Ls(typeof e[t]=="object"?JSON.stringify(e[t]):e[t]);return Object.entries(e).map(([t,s])=>`${t}: ${typeof s=="object"?JSON.stringify(s):s}`).join(" · ").split(/\r?\n/)[0]}function Vc(e,t){if(!om.has(t?.eventType))return!1;const s=t.data||{},n=`${t.sessionId}:${s.durableSessionId||""}`,r=[s.toolCallId&&`call:${s.toolCallId}`,s.requestId&&`request:${s.requestId}`].filter(Boolean),i=t.eventType==="session.agent_spawned";i&&r.push(`spawn:${t.seq}`);const o=r.length?e.findIndex(f=>f.kind==="chat-call"&&f.namespace===n&&f.callKeys.some(h=>r.includes(h))):-1,l=o>=0?e[o]:null;if(!l&&t.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=t.eventType==="tool.execution_complete",p=u&&(s.success===!1||!!s.error),m={...l,id:l?.id||`${n}:tool:${r[0]||`event:${t.seq}`}`,kind:"chat-call",role:"tool",namespace:n,callKeys:[...new Set([...l?.callKeys||[],...r])],name:c,arguments:d,category:i||lm.test(c)?"Agent":"Tool",text:i?Ls(s.task):cm(d)||l?.text||"",time:l?.time||Ke(t.createdAt),createdAt:l?.createdAt||new Date(t.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"&&(t.eventType==="tool.execution_partial_result"&&l?.lastPartialSeq!==t.seq&&(m.partial=`${l?.partial||""}${s.partialOutput||""}`,m.lastPartialSeq=t.seq),s.progressMessage&&(m.progress=s.progressMessage)),i&&(m.result={childSessionId:s.childSessionId,agentId:s.agentId,task:s.task}),o>=0?e[o]=m:e.push(m),!0}function Yc(e){const t=[e.arguments!==void 0?`Arguments
7
- ${Rn(e.arguments)}`:"",e.progress?`Progress
8
- ${e.progress}`:"",e.partial?`Output
9
- ${e.partial}`:"",e.result!==void 0?`Result
10
- ${Rn(e.result)}`:"",e.error?`Error
11
- ${Rn(e.error)}`:""].filter(Boolean);return{kind:"chatCall",callKey:e.id,category:e.category,text:`${e.name}${e.text?` — ${e.text}`:""}`,body:t.join(`
12
-
13
- `)||"Call recorded; no output has been recorded yet.",status:e.status,time:e.time}}const Wt=new Set(["completed","failed","cancelled","interrupted"]),Ot=(e,t=240)=>typeof e=="string"?e.trim().slice(0,t):"",Gt=e=>{const t=typeof e=="number"?e:new Date(e).getTime();return Number.isFinite(t)&&t>0?t:null},Or=e=>typeof e=="string"?e:e?.detailedContent||e?.content||e?.textResultForLlm||e?.message||e?.error?.message||"",fr={starting:"Starting",running:"Running",waiting:"Waiting",completed:"Done",failed:"Failed",cancelled:"Cancelled",interrupted:"Interrupted"};function qn(e,t){for(let s=e.length-1;s>=0;s--){const n=e[s];if(n.kind!=="native-task-group")continue;const r=n.tasks.findLastIndex(i=>t.toolCallId&&i.toolCallId===t.toolCallId||t.agentId&&i.agentId===t.agentId&&(!t.toolCallId||!i.toolCallId)||t.id&&i.id===t.id);if(r>=0)return{groupIndex:s,taskIndex:r}}return null}function zn(e,t,s,{authoritative:n=!1}={}){const r=qn(e,t),i=r?e[r.groupIndex].tasks[r.taskIndex]:null;if(i?.ownerId&&t.ownerId&&i.ownerId!==t.ownerId||t.revision!=null&&i?.revision!=null&&t.revision<i.revision)return;const o={id:t.toolCallId||t.agentId||t.id,title:"Native task",status:"starting",toolCalls:0,startedAt:Gt(t.startedAt)||Gt(s.createdAt),...i,...Object.fromEntries(Object.entries(t).filter(([,u])=>u!==void 0)),telemetryStale:!1};if(!o.id)return;if(o.id=i?.id||o.id,o.startedAt=i?.startedAt||Gt(t.startedAt)||Gt(s.createdAt),o.completedAt=Gt(o.completedAt),i&&Wt.has(i.status)&&(!i.inferredTerminal||!Wt.has(t.status))?(o.status=i.status,o.error=i.error,o.completedAt=i.completedAt,o.durationMs=i.durationMs,(!Wt.has(t.status)||t.status==="cancelled")&&(o.toolCalls=i.toolCalls),!t.result&&!t.error&&(o.preview=i.preview)):Wt.has(t.status)&&!t.inferredTerminal&&(o.inferredTerminal=!1,i?.inferredTerminal&&(o.error=t.error||"")),o.title=Ot(o.title,160)||"Native task",o.title==="Native task"&&i?.title&&(o.title=i.title),o.preview=Ot(o.preview),o.result=Ot(o.result,4e3),o.error=Ot(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:Ot(u.message),timestamp:u.timestamp})):[],r){const u=e[r.groupIndex],p=[...u.tasks];p[r.taskIndex]=o,e[r.groupIndex]={...u,tasks:p};return}const l=o.startedAt?e.findIndex(u=>Number(u.createdAt)>o.startedAt):-1,c=l<0?e.length:l,d=e[c-1];d?.kind==="native-task-group"&&d.tasks.length<32?e[c-1]={...d,tasks:[...d.tasks,o]}:e.splice(c,0,{id:`native-tasks:${s.sessionId}:${o.id}`,kind:"native-task-group",role:"system",createdAt:o.startedAt,tasks:[o]})}function dm(e,t){const s=(t?.eventType||"").replace(/^native\./,"");if(!an.includes(s)||s==="session.agent_spawned")return!1;const n=t.data||{},r=!!(n.nativeAgentId||n.parentToolCallId||t.eventType.startsWith("native.")),i=[n.toolCallId&&`call:${n.toolCallId}`,n.requestId&&`request:${n.requestId}`].filter(Boolean);let o=r?qn(e,{toolCallId:n.parentToolCallId,agentId:n.nativeAgentId}):null;const l=`${t.sessionId}:${n.durableSessionId||""}`;if(!o&&!r)for(let m=e.length-1;m>=0&&!o;m--){if(e[m].kind!=="native-task-group")continue;const f=e[m].tasks.findIndex(h=>h.calls?.some(g=>g.namespace===l&&g.callKeys.some(b=>i.includes(b))));f>=0&&(o={groupIndex:m,taskIndex:f})}if(!o&&r&&(n.parentToolCallId||n.nativeAgentId)&&(zn(e,{toolCallId:n.parentToolCallId,agentId:n.nativeAgentId,status:"running"},t),o=qn(e,{toolCallId:n.parentToolCallId,agentId:n.nativeAgentId})),!o)return r;const c=e[o.groupIndex],d=c.tasks[o.taskIndex],u=[...d.calls||[]];for(let m=e.length-1;m>=0;m--){const f=e[m];f.kind!=="chat-call"||f.namespace!==l||!f.callKeys.some(h=>i.includes(h))||(u.some(h=>h.callKeys.some(g=>f.callKeys.includes(g)))||u.push(f),e.splice(m,1))}Vc(u,{...t,eventType:s});const p=[...c.tasks];return p[o.taskIndex]={...d,calls:u,toolCalls:Math.max(d.toolCalls||0,u.length)},e[e.indexOf(c)]={...c,tasks:p},!0}function Xc(e,t){const s=t?.eventType||"",n=t?.data||{};if(s==="native.task_updated"){n.id&&fr[n.status]&&zn(e,n,t,{authoritative:!0});return}if(s==="session.turn_completed"||s==="session.turn_stopped"){for(let f=0;f<e.length;f++)e[f].kind==="native-task-group"&&(e[f]={...e[f],tasks:e[f].tasks.map(h=>Wt.has(h.status)?h:{...h,status:"interrupted",inferredTerminal:!0,completedAt:Gt(t.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=qn(e,u),m=p?e[p.groupIndex].tasks[p.taskIndex]:null;if(!(!m&&!r&&!o)){if((!m||o||s==="subagent.started")&&Object.assign(u,{title:l.description||l.name||(m?.title!=="Native task"?m?.title:null)||n.agentDisplayName||"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:t.createdAt,durationMs:n.durationMs,toolCalls:n.totalToolCalls,...n.cancelled?{error:"Task was cancelled before returning a result."}:s==="subagent.failed"?{error:Ot(Or(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=Or(n.result)||Or(n.error);Object.assign(u,{status:f?"failed":"completed",completedAt:t.createdAt,...f?{error:Ot(h,1e3)||"Native task request failed."}:{result:Ot(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=Math.max(m.toolCalls||0,u.toolCallIds.length),u.preview=l.description||(n.toolName?`Using ${n.toolName}`:"Working")}else if(s==="native.assistant.message")u.preview=Ot(n.content);else return;zn(e,u,t)}}function Qc(e,t,s={}){if(t?.phase==="unavailable"&&e)return{...e,nativeTaskSnapshot:e.nativeTaskSnapshot?{...e.nativeTaskSnapshot,liveSeq:void 0}:void 0,chat:e.chat.map(l=>l.kind!=="native-task-group"?l:{...l,tasks:l.tasks.map(c=>Wt.has(c.status)?c:{...c,telemetryStale:!0})})};if(t?.version!==1||!Array.isArray(t.tasks)||!t.ownerId)return e;const n=e||{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(t.ownerStartedAt)&&t.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=>!Wt.has(c.status)&&c.ownerStartedAt===i?{...c,telemetryStale:!0}:c)})};if(Number.isFinite(r?.ownerStartedAt)&&Number.isFinite(t.ownerStartedAt)&&t.ownerStartedAt<r.ownerStartedAt||r?.ownerId===t.ownerId&&r.revision>=t.revision||r?.ownerId===t.ownerId&&Number.isFinite(s.seq)&&Number.isFinite(r?.liveSeq)&&s.seq<=r.liveSeq)return n;const o=[...n.chat];for(const l of t.tasks.slice(0,32)){if(!l?.id||!fr[l.status])continue;const c=n.events?.some(u=>["session.turn_completed","session.turn_stopped"].includes(u.eventType)&&Gt(u.createdAt)>Gt(l.startedAt)),d={...l,ownerId:t.ownerId,ownerStartedAt:t.ownerStartedAt,revision:t.revision};c&&!Wt.has(d.status)&&(d.status="interrupted",d.inferredTerminal=!0,d.error="The parent turn ended before a task result was confirmed."),zn(o,d,{sessionId:s.sessionId,createdAt:l.startedAt},{authoritative:!0})}return{...n,chat:o,nativeTaskSnapshot:{ownerId:t.ownerId,ownerStartedAt:t.ownerStartedAt,revision:t.revision,liveSeq:s.seq}}}function Kn(e){return/^(?:Execution failed:\s*)?No response was returned\. Send your message again to retry\.(?: \(retry \d+\/\d+ in \d+s\))?$/.test(String(e||"").trim())}function um(e,t){if(!String(e?.error||"").trim()||t?.error!==void 0||["Completed","Failed","Terminated"].includes(String(t?.orchestrationStatus||""))||["completed","failed","cancelled","terminated"].includes(e?.status))return!1;const s=String(t?.status||"");if(["running","error"].includes(s))return!0;if(!["idle","waiting","unknown","pending",""].includes(s))return!1;const n=Number(e?.statusVersion),r=Number(t?.statusVersion);if(n>0&&r>0)return r<=n;const i=c=>typeof c=="number"?c:Date.parse(c||""),o=i(e?.updatedAt),l=i(t?.updatedAt);return o>0&&l>0&&l<=o}const qt=e=>e instanceof Date?e.getTime():typeof e=="number"?e:Date.parse(e||""),Ei=e=>e?.eventType==="session.error"||e?.eventType==="session.turn_completed"&&e.data?.resultType==="error",oa=e=>e?.eventType==="session.turn_completed"?String(e.data?.resultType==="error"&&e.data.errorMessage||"").trim():typeof e?.data=="string"?e.data:String(e?.data?.message||e?.data?.error||e?.data?.text||"").trim(),ki=(e,t)=>mr(t,e);function pm(e){const t=oa(e);if(!t||Kn(t))return null;const s=e?.data?.fatal===!0;return{id:`${e.sessionId}:${e.seq}:warning`,kind:"session-warning",role:"system",text:t,warningSeq:Number(e.seq),createdAt:qt(e.createdAt)||null,cardTitle:s?"Error":"Warning",cardTitleColor:s?"red":"yellow",cardBorderColor:s?"red":"yellow"}}function bo(e,t,s=[],n=Date.now()){const r=e?.chatWarnings||[],i=r.at(-1),o=String(t?.error||"").trim(),l=t?.status==="failed"||t?.orchestrationStatus==="Failed";if(!(!!o&&(l||!["completed","cancelled","terminated","input_required"].includes(t?.status))&&!["Completed","Terminated"].includes(t?.orchestrationStatus)))return i?.active?{...t,chatWarnings:[...r.slice(0,-1),{...i,active:!1}]}:t;const d=i?.createdAt||0,u=s.findLast(h=>Ei(h)&&qt(h.createdAt)>d&&ki(o,oa(h)));if(i&&!i.active&&o===i.text&&o===String(e?.error||"").trim()&&!u)return t;const p=i&&o!==i.text&&s.some(h=>Number(h.seq)>i.afterSeq&&qt(h.createdAt)>i.createdAt&&["user.message","assistant.message"].includes(h.eventType));if(i?.active&&!p)return i.text===o&&i.failed===l?t:{...t,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{...t,chatWarnings:[...f,{id:`session-error:${t.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:qt(u?.createdAt)||qt(t.updatedAt)||n}].slice(-300)}}function mm(e,t,s=[]){const n=e.filter(r=>r.kind!=="session-warning"||!Kn(r.text));for(const r of t?.chatWarnings||[]){if(Kn(r.text))continue;const o=s.filter(p=>Number(p.seq)>r.afterSeq).find(p=>Ei(p)||["user.message","assistant.message"].includes(p.eventType)),l=e.findLast(p=>p.kind==="session-warning"&&qt(p.createdAt)>(r.since||0)&&qt(p.createdAt)<=r.createdAt&&ki(r.text,p.text)),c=r.eventSeq??l?.warningSeq??(Ei(o)&&ki(r.text,oa(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=>qt(m.createdAt)>r.createdAt);n.splice(p<0?n.length:p,0,u)}}return n}const Ne=300,fm=[Ne,1e3,3e3,1e4],hm=[...an,...an.filter(e=>e!=="session.agent_spawned").map(e=>`native.${e}`),"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 Zc(e){const t=e?.data&&typeof e.data=="object"?e.data:{},s=Number.isFinite(t.toEpoch)?t.toEpoch:Number(t.epoch)||0,n=Number.isFinite(t.turnsArchived)?t.turnsArchived:null;return{id:`${e.sessionId}:${e.seq}:epoch`,kind:"epoch-divider",role:"epoch-divider",epoch:s,turnsArchived:n,time:Ke(e.createdAt),createdAt:e.createdAt instanceof Date?e.createdAt.getTime():new Date(e.createdAt).getTime()}}function Jc(e){const t=e?.data&&typeof e.data=="object"?e.data:{};return{id:`${e.sessionId}:${e.seq}:regen-refused`,kind:"regen-refused",role:"regen-refused",reason:typeof t.reason=="string"?t.reason:"unknown",time:Ke(e.createdAt),createdAt:e.createdAt instanceof Date?e.createdAt.getTime():new Date(e.createdAt).getTime()}}function ed(e){const t=e?.data&&typeof e.data=="object"?e.data:{},s=typeof t.error=="string"?t.error:"";return{id:`${e.sessionId}:${e.seq}:regen-failed`,kind:"regen-failed",role:"regen-failed",stage:typeof t.stage=="string"?t.stage:"unknown",error:s,time:Ke(e.createdAt),createdAt:e.createdAt instanceof Date?e.createdAt.getTime():new Date(e.createdAt).getTime()}}function gm(e){const t=e.eventType==="session.turn_completed"&&e.data?.resultType==="error";if(e.eventType!=="session.error"&&!t)return null;const s=pm(e);return s?{...s,errorText:s.text,sourceEventType:e.eventType,...t?{turnCompletedSeq:e.seq}:{},time:Ke(e.createdAt)}:null}function td(e,t){const s=gm(t);if(!s||e.some(i=>i.id===s.id||i.turnCompletedSeq!=null&&i.turnCompletedSeq===t.seq))return;const n=e.findLastIndex(i=>i.kind!=="chat-call"&&i.kind!=="native-task-group"),r=e[n];if(r?.kind==="session-warning"&&r.sourceEventType==="session.error"&&r.turnCompletedSeq==null&&t.eventType==="session.turn_completed"&&mr(r.errorText,s.errorText)){e[n]={...r,turnCompletedSeq:t.seq};return}e.push(s)}const ym=new Set(an);function sd(e,t){if(dm(e,t)||!ym.has(t?.eventType))return;const s=t?.data||{},n=s.toolName||s.name,r=`${t.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&&e.some(d=>d.kind==="chat-call"&&d.namespace===r&&d.callKeys.some(u=>i.includes(u)));n==="task"||!n&&!l&&s.toolCallId&&e.some(d=>d.kind==="native-task-group"&&d.tasks.some(u=>u.toolCallId===s.toolCallId))||Vc(e,t)}function st(e,t){const s=Array.isArray(e)?e.filter(Boolean):[],n=Math.max(Ne,Number(t)||Ne);return s.length>n?s.slice(-n):s}function Ft(e){return String(e||"").replace(/\r\n/g,`
14
- `).trim()}function So(e){if(!e)return"";const t=e instanceof Date?e:new Date(e);if(Number.isNaN(t.getTime()))return"";try{return t.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 t.toISOString().replace(/\.000Z$/,"Z")}}const nd=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,bm=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function la(e){return nd.test(Ft(e))}function zt(e){const t=String(e||"").replace(/\r\n/g,`
15
- `).trim();if(!t)return"";const s=t.replace(bm,"").trimStart();return s!==t?s.trim():la(t)?t.replace(nd,"").trim():t}const ca="[\\u200b-\\u200f\\u2060-\\u2064\\ufeff]*",rd=new RegExp(`^\\s*\\[${ca}SYSTEM:`,"i"),Sm=new RegExp(`^\\s*\\[${ca}SYSTEM:\\s*(.*?)\\]\\s*$`,"i"),vm=new RegExp(`^\\s*\\[${ca}SYSTEM:\\s*`,"i");function id(e){const t=String(e||"").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<t.length;){const o=t[i];if(!rd.test(o)){n.push(o),i+=1;continue}const l=Sm.exec(o);if(l){r(),s.push({kind:"system",text:l[1].trim()}),i+=1;continue}const c=[o.replace(vm,"")];let d=-1;for(let u=i+1;u<t.length;u+=1){const p=t[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 ad(e,t){const s=String(e||"").replace(/\r\n/g,`
20
- `);return t==="user"||t==="assistant"?id(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
21
- `).trim():s.trim()}function wm(e,t){return t!=="user"&&t!=="assistant"?[]:id(e).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function vo(e){const t=Ft(e?.text||"");if(!t)return"";if(e?.role==="user"||e?.role==="assistant"){const s=ad(t,e.role);if(s)return s}return zt(t)}function hr(e){const t=String(e||"").replace(/\r\n/g,`
22
- `).trim(),s='The user was asked: "';if(!t.startsWith(s)||!t.endsWith('"'))return null;const n=/"\nThe user responded(?: \(answered by [^\r\n]+?\))?: "/g;n.lastIndex=s.length;const r=n.exec(t);if(!r)return null;const i=t.slice(s.length,r.index),o=t.slice(n.lastIndex,-1);return!i.trim()||!o.trim()?null:{question:i,answer:o}}function Em(e){return Ft(ra(e)).length>0}function km(e){const t=Ft(e);return t?rd.test(t)||/^\[CHILD_UPDATE\b/i.test(t)||/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(t)||/^Buffered child updates arrived /i.test(t)||/^There is an active recurring schedule every /i.test(t)||/^It remains active automatically after this turn completes/i.test(t)||/^Sub-agent spawned successfully\./i.test(t)||/^Message sent to sub-agent /i.test(t)||/^No sub-agents have been spawned yet\./i.test(t)||/^Sub-agent status report \(/i.test(t)||/^Active sessions \(/i.test(t)||/^Sub-agents completed:/i.test(t)||/^Sub-agent .* has been (completed gracefully|cancelled|deleted)\./i.test(t)||/^The runtime recovered this session after the worker lost the live Copilot session\./i.test(t)||/^The runtime recovered this session after the live Copilot session was lost on a worker\./i.test(t)||/^The runtime is replaying this turn after a worker restart/i.test(t)||/^The runtime detected missing Copilot session state for /i.test(t)||/^(spawn_agent|message_agent|check_agents|wait_for_agents|complete_agent|cancel_agent|delete_agent) failed/i.test(t):!1}function Im(e){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(Ft(e))}function gs(e,t){const s=String(e||""),n=`${t}=`,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 xm(e,t){const s=Ft(t);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=gs(i,"request_id"),u=gs(i,"from"),p=gs(i,"subject"),m=/\bexpects_response=true\b/i.test(i),f=[u?`From: session-${Le(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:`${e.sessionId}:${e.seq}`,role:"system",text:f.join(`
25
- `),time:Ke(e.createdAt),createdAt:e.createdAt instanceof Date?e.createdAt.getTime():new Date(e.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=gs(i,"request_id"),d=gs(i,"from"),u=gs(i,"verdict")||"answered",p=[d?`From: session-${Le(d)}`:"",c?`Request ID: ${c}`:"",`Verdict: ${u}`,"",l].filter((m,f)=>f===3||String(m||"").trim());return{id:`${e.sessionId}:${e.seq}`,role:"system",text:p.join(`
26
- `),time:Ke(e.createdAt),createdAt:e.createdAt instanceof Date?e.createdAt.getTime():new Date(e.createdAt).getTime(),cardTitle:"Session Reply",agentCallPreview:l,cardTitleColor:"green",cardBorderColor:"green"}}return null}function Am(e,t,s){return e?.eventType==="system.message"||(t==="user"||t==="assistant")&&km(s)?"system":t}function wo(e,t){const s=Array.isArray(e?.clientMessageIds)?e.clientMessageIds:[],n=Array.isArray(t?.clientMessageIds)?t.clientMessageIds:[];return s.length===0||n.length===0?null:s.some(r=>n.includes(r))}function Nm(e,t){if(!e||!t||e.role!==t.role)return!1;if(e.sender?.kind==="agent"||t.sender?.kind==="agent")return e.sender?.kind===t.sender?.kind&&e.sender?.sessionId===t.sender?.sessionId&&(e.id===t.id||wo(e,t)===!0);if(e.role==="assistant"&&e.messageId&&t.messageId)return e.messageId===t.messageId;if(e.kind==="canvas-update"||t.kind==="canvas-update"||e.kind==="chat-call"||t.kind==="chat-call"||e.kind==="session-warning"||t.kind==="session-warning")return e.kind===t.kind&&e.id===t.id;const s=vo(e),n=vo(t);if(!s||!n||s!==n)return!1;const r=wo(e,t);if(r!=null)return r;const i=Number(e.createdAt||0),o=Number(t.createdAt||0);return e.optimistic||t.optimistic?!0:!i||!o?!1:Math.abs(i-o)<=1e4}function xs(e=[]){const t=[];for(const s of e){if(!s)continue;const n=t[t.length-1];if(!Nm(n,s)){t.push(s);continue}if(n?.optimistic&&!s?.optimistic){t[t.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));t[t.length-1]={...o,redelivered:!0,...Number.isFinite(l)?{firstDeliveredAt:l}:{}};continue}t[t.length-1]=o}return t}function Cm(e){return typeof e=="string"?e.replace(/^\[FROM:[^\]\n]*\]\n?/,""):e}function As(e,t){const s=Us(e),n=xm(e,s);if(n)return n;const r=Cm(ad(s,t));if(t==="user"&&zc(r)){const f=im(r);if(f)return{id:`${e.sessionId}:${e.seq}`,kind:"canvas-action",role:"user",action:f.action,data:f.data,text:r,time:Ke(e.createdAt),createdAt:e.createdAt instanceof Date?e.createdAt.getTime():new Date(e.createdAt).getTime(),...Array.isArray(e?.data?.clientMessageIds)&&e.data.clientMessageIds.length>0?{clientMessageIds:e.data.clientMessageIds}:{}}}const i=r;if(!Em(i))return null;const o=Array.isArray(e?.data?.clientMessageIds)?e.data.clientMessageIds.filter(f=>typeof f=="string"&&f):[],l=e?.data?.sender&&typeof e.data.sender=="object"?e.data.sender:null,c=Array.isArray(e?.data?.attachments)?e.data.attachments.filter(f=>f&&typeof f.filename=="string"&&f.filename):[],d=typeof e?.data?.messageId=="string"&&e.data.messageId?e.data.messageId:null,u=Am(e,t,i),m=(u==="assistant"?String(e?.data?.phase||"").trim().toLowerCase():"")==="commentary";return{id:`${e.sessionId}:${e.seq}`,role:u,text:i,time:Ke(e.createdAt),createdAt:e.createdAt instanceof Date?e.createdAt.getTime():new Date(e.createdAt).getTime(),...o.length>0?{clientMessageIds:o}:{},...l?{sender:l}:{},...c.length>0?{attachments:c}:{},...d?{messageId:d}:{},...u==="assistant"?m?{assistantCommentary:!0}:{assistantPreview:!0,responsePending:!0,responseFinal:!1,responseCanFinalize:!e?.data?.parentToolCallId&&!e?.data?.toolRequests?.length,...typeof e?.data?.reasoningText=="string"&&e.data.reasoningText?{liveReasoningText:e.data.reasoningText}:{}}:{}}}function od(e,t){const s=t?.data?.resultType||t?.data?.result,n=t?.eventType==="session.turn_completed"&&(!s||s==="completed");let r=-1;for(let i=e.length-1;i>=0;i-=1)if(e[i]?.responsePending){n&&e[i].responseCanFinalize&&(r=i);break}for(let i=0;i<e.length;i+=1)e[i]?.responsePending&&(e[i]={...e[i],responsePending:!1,responseFinal:i===r})}function Tm(e,t,s={}){if(!t)return e;if(t.phase==="idle")return Js(e,null,t.streamId||null);if(t.phase!=="live")return e;const n=typeof t.messageId=="string"&&t.messageId?t.messageId:null,r=typeof t.reasoningId=="string"&&t.reasoningId?t.reasoningId:null,i=n||(r?`reasoning:${r}`:"active-turn"),o=Number(s.createdAt)||Date.now(),l=e||{chat:[],activity:[],events:[],lastSeq:0},c=l.chat||[];if(n&&c.some(y=>!y.liveTurn&&y.messageId===n)||(l.closedLiveKeys||[]).includes(i)||t.streamId&&(l.closedLiveStreams||[]).includes(t.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 t.reasoningText=="string"?t.reasoningText:"",h=typeof t.text=="string"?t.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:t.streamId||p?.streamId||null,streaming:!0,truncated:t.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 Js(e,t=null,s=null){if(!e?.chat)return e;const n=e.chat.filter(l=>!(l?.liveTurn===!0&&(!t||l?.messageId===t)&&(!s||l?.streamId===s))),r=e.chat.filter(l=>l.liveTurn&&(!t||l.messageId===t)&&(!s||l.streamId===s)),i=[...new Set([...e.closedLiveKeys||[],...r.flatMap(l=>[l.liveKey,l.messageId,l.reasoningId&&`reasoning:${l.reasoningId}`].filter(Boolean))])].slice(-256),o=[...new Set([...e.closedLiveStreams||[],...t?[]:r.map(l=>l.streamId).filter(Boolean),...s?[s]:[]])].slice(-256);return n.length===e.chat.length&&!s?e:{...e,chat:n,closedLiveKeys:i,closedLiveStreams:o}}function ld(e){return e?.eventType!=="system.message"?!1:!Im(Us(e))}function Vn(e,t){return wm(Us(e),t).map((s,n)=>os({...e,seq:`${e?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function Pm(e,t){if(!Array.isArray(e)||t?.role!=="user")return[...e||[]];const s=Ft(t.text),n=hr(t.text),r=n?Ft(n.answer):"";let i=!1;return e.filter(o=>{if(i||!o?.optimistic||o.role!==t.role)return!0;const l=Ft(o.text);return l!==s&&l!==r?!0:(i=!0,!1)})}function Us(e){const t=e?.data;if(typeof t=="string")return t;if(t&&typeof t=="object"){if(typeof t.content=="string")return t.content;if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message;if(typeof t.question=="string")return t.question}return Bc(t)}function cd(e){return(e||[]).map(t=>t?.text||"").join("")}function Mm(e,t=120){const s=String(e||"").replace(/\s+/g," ").trim();return s?s.length>t?`${s.slice(0,t-3)}...`:s:""}function da(e=[]){const t=new Set,s=[];for(const n of e){const r=String(n||"").trim();if(!r)continue;const i=r.toLowerCase();t.has(i)||(t.add(i),s.push(r))}return s.join(" | ")}function _m(e,t=""){return da([e?.data?.reason,e?.data?.detail,e?.data?.message,e?.data?.error,t])}function $m(e,t=""){return da([e?.data?.message,e?.data?.detail,e?.data?.error,t])}function Rm(e,t=""){const s=Us(e),n=zt(t);return da([zt(s),n,e?.data?.detail,e?.data?.message])}function Lm(e){return e==null?"null":typeof e=="string"?JSON.stringify(e.length>32?`${e.slice(0,29)}...`:e):typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.length}]`:typeof e=="object"?"{...}":String(e)}function Om(e,t){if(!t||typeof t!="object")return"";if(e==="wait"){const r=t.seconds!=null?`${t.seconds}s`:"?",i=t.preserveWorkerAffinity===!0?" preserve=true":"",o=typeof t.reason=="string"&&t.reason?` reason=${JSON.stringify(t.reason)}`:"";return` ${r}${i}${o}`}if(e==="cron"){if(t.action==="cancel")return" cancel";const r=t.seconds!=null?`${t.seconds}s`:"?",i=typeof t.reason=="string"&&t.reason?` reason=${JSON.stringify(t.reason)}`:"";return` ${r}${i}`}const s=Object.entries(t).slice(0,4).map(([r,i])=>`${r}=${Lm(i)}`);if(s.length===0)return"";const n=Object.keys(t).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function ua(e){return e?[{text:`[${e}] `,color:"white"}]:[]}function Ee(e,t,s,n="",r="white"){return[...ua(e),{text:t,color:s},...n?[{text:` ${n}`,color:r}]:[]]}function Fm(e,t=96){return Mm(ra(Us(e)),t)||""}function Fr(e,t,s="start"){const n=typeof t?.data?.toolCallId=="string"?t.data.toolCallId:"",r=typeof t?.data?.requestId=="string"?t.data.requestId:"",i=t?.data?.toolName||t?.data?.name||(n?`tool call ${n.slice(0,8)}`:r?`tool request ${r.slice(0,8)}`:"tool"),o=t?.data?.arguments||t?.data?.args,l=t?.data?.durableSessionId,c=Om(i,o),d=s==="start"?"▶":s==="partial"?"…":"✓",u=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...ua(e),{text:`${d} ${i}${c}`,color:u},...l?[{text:` [sess ${Le(l)}]`,color:"gray"}]:[]]}function os(e){const t=Ke(e.createdAt),s=Fm(e);let n=null;if(e.eventType?.startsWith("native.")||e.eventType==="session.background_tasks_changed")return null;switch(e.eventType){case"subagent.started":case"subagent.completed":case"subagent.failed":{const r=e.eventType.slice(9),i=e.data?.agentDisplayName||e.data?.agentName||"agent",o=Number.isFinite(e.data?.durationMs)?` (${as(e.data.durationMs/1e3)})`:"";n=Ee(t,"[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(e?.data?.model||e?.data?.modelId||"model").split(":").pop();n=Ee(t,"[model]","cyan",`calling ${r}`,"white");break}case"session.artifact_presented":{const r=(e?.data??{})||{},i=String(r.filename||"artifact"),o=typeof r.note=="string"&&r.note.trim()?` — ${r.note.trim()}`:"";n=Ee(t,"[show]","cyan",`${i}${o}`,"white");break}case"session.canvas_updated":{const r=(e?.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=Ee(t,"[canvas]","cyan",`rev ${i}${l}${o}`,"white");break}case"session.canvas_data":{const r=(e?.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=Ee(t,"[canvas]","cyan",`data tick ${i}${o}${l}`,"white");break}case"tool.execution_start":n=Fr(t,e,"start");break;case"tool.execution_complete":n=Fr(t,e,"complete");break;case"tool.execution_partial_result":n=Fr(t,e,"partial");break;case"tool.execution_progress":{const r=(e?.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=Ee(t,"[tool]","cyan",`${i} ${o}`,"white");break}case"assistant.reasoning":n=Ee(t,"[reasoning]","gray",s||"…","white");break;case"assistant.intent":{const r=(e?.data??{})||{},i=typeof r.summary=="string"&&r.summary?r.summary:typeof r.intent=="string"&&r.intent?r.intent:s||"";n=Ee(t,"[intent]","gray",i||"…","white");break}case"assistant.turn_start":n=Ee(t,"[turn start]","gray",s);break;case"session.turn_completed":n=Ee(t,"[turn completed]","gray",e?.data?.iteration!=null?`iter ${e.data.iteration}`:s);break;case"session.lossy_handoff":n=Ee(t,"[lossy handoff]","yellow",$m(e,s)||"handoff to a new worker");break;case"session.dehydrated":n=Ee(t,"[dehydrated]","cyan",_m(e,s));break;case"session.hydrated":case"session.rehydrated":n=Ee(t,"[rehydrated]","green",s);break;case"session.wait_started":{const r=e?.data?.seconds!=null?`${e.data.seconds}s`:"?",i=typeof e?.data?.reason=="string"&&e.data.reason?` reason=${JSON.stringify(e.data.reason)}`:"",o=e?.data?.preserveAffinity?" preserve=true":"";n=Ee(t,"[wait]","yellow",`${r}${o}${i}`.trim());break}case"session.input_required_started":n=Ee(t,"[input]","yellow",s);break;case"session.agent_spawned":n=Ee(t,"[spawn]","cyan",e?.data?.agentId||Le(e?.data?.childSessionId),"white");break;case"session.cron_started":n=Ee(t,"[cron]","magenta",`started${e?.data?.seconds!=null?` ${e.data.seconds}s`:""}${e?.data?.reason?` reason=${JSON.stringify(e.data.reason)}`:""}`);break;case"session.cron_at_scheduled":case"session.cron_at_started":n=Ee(t,"[cron]","magenta",`scheduled${e?.data?.nextFireAt?` ${So(e.data.nextFireAt)}`:""}${e?.data?.reason?` reason=${JSON.stringify(e.data.reason)}`:""}`);break;case"session.cron_fired":n=Ee(t,"[cron]","magenta",`fired${e?.data?.reason?` reason=${JSON.stringify(e.data.reason)}`:""}`);break;case"session.cron_at_fired":n=Ee(t,"[cron]","magenta",`fired${e?.data?.scheduledAt?` ${So(e.data.scheduledAt)}`:""}${e?.data?.reason?` reason=${JSON.stringify(e.data.reason)}`:""}`);break;case"session.cron_cancelled":case"session.cron_at_cancelled":n=Ee(t,"[cron]","magenta",`cancelled${e?.data?.reason?` reason=${JSON.stringify(e.data.reason)}`:""}`);break;case"session.cron_at_completed":n=Ee(t,"[cron]","magenta",`completed${e?.data?.reason?` reason=${JSON.stringify(e.data.reason)}`:""}`);break;case"session.command_received":n=Ee(t,"[command]","magenta",`/${e?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=Ee(t,"[command]","magenta",`/${e?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.model_changed":{const r=Rs(e?.data?.oldModel)||"default",i=Rs(e?.data?.newModel)||"default",o=e?.data?.newReasoningEffort,l=o&&o!==e?.data?.oldReasoningEffort,c=e?.data?.newContextTier,d=c&&c!==e?.data?.oldContextTier&&c!=="default",u=[...l?[`effort ${o}`]:[],...d?[`context ${c}`]:[]];n=Ee(t,"[model]","cyan",`${r} → ${i}${u.length?` (${u.join(", ")})`:""}`);break}case"session.compaction_start":case"session.compaction_complete":n=Fp(t,e.eventType,e.data||{});break;case"session.error":n=Ee(t,"[error]","red",s||"session error","white");break;case"system.message":la(Us(e))?n=Ee(t,"[rehydrated]","green",Rm(e,s)||"conversation preserved"):n=Ee(t,"[system]","gray",s||"system message");break;default:n=[...ua(t),{text:`[${e.eventType}]`,color:"gray"},...s?[{text:` ${s}`,color:"white"}]:[]];break}return{id:`${e.sessionId}:${e.seq}`,eventType:e.eventType,time:t,seq:Number.isFinite(Number(e?.seq))?Number(e.seq):0,createdAt:e?.createdAt instanceof Date?e.createdAt.getTime():e?.createdAt?new Date(e.createdAt).getTime():0,text:cd(n),line:n}}function Dm(e=Ne){const t=Math.max(Ne,Number(e)||Ne);return fm.find(n=>n>t)||Math.min(1e5,t*2)}function dd(e){const t=e.sessionId||null;return{id:`${e.sessionId||""}:${e.seq}:canvas`,kind:"canvas-update",role:"canvas-update",sessionId:t,rev:Number(e?.data?.rev)||0,note:typeof e?.data?.note=="string"?e.data.note:"",text:t?`artifact://${t}/canvas.html`:"",createdAt:e.createdAt instanceof Date?e.createdAt.getTime():new Date(e.createdAt).getTime()}}function ud(e,t){const s=Ke(e.createdAt),n=`action ${t.action}${Object.keys(t.data||{}).length?" "+Bc(t.data):""}`,r=Ee(s,"[canvas]","cyan",n,"white");return{id:`${e.sessionId}:${e.seq}:canvas-action`,eventType:e.eventType,time:s,seq:Number.isFinite(Number(e?.seq))?Number(e.seq):0,createdAt:e.createdAt instanceof Date?e.createdAt.getTime():new Date(e.createdAt).getTime(),text:cd(r),line:r}}function qs(e=[],t={}){const s=Math.max(Ne,Number(t.requestedLimit??t.eventLimit??Ne)||Ne),n=[],r=[],i=[];for(const o of e){if(i.push(o),Xc(n,o),sd(n,o),td(n,o),["user.message","session.turn_completed","session.turn_stopped","session.epoch_committed"].includes(o.eventType)&&od(n,o),o.eventType==="user.message"){r.push(...Vn(o,"user"));const c=As(o,"user");if(c&&n.push(c),c?.kind==="canvas-action"){const d=ud(o,c);d&&r.push(d)}continue}if(o.eventType==="session.canvas_updated"){n.push(dd(o));const c=os(o);c&&r.push(c);continue}if(o.eventType==="assistant.message"){r.push(...Vn(o,"assistant"));const c=As(o,"assistant");c&&n.push(c);continue}if(o.eventType==="system.message"){if(ld(o)){const c=os(o);c&&r.push(c)}else{const c=As(o,"system");c&&n.push(c)}continue}if(o.eventType==="session.epoch_committed"){n.push(Zc(o));continue}if(o.eventType==="session.regenerate_refused"){n.push(Jc(o));continue}if(o.eventType==="session.regenerate_failed"){n.push(ed(o));continue}const l=os(o);l&&r.push(l)}return{chat:xs(n),activity:r,events:i.slice(-s),loadedEventLimit:s,loadedEventCount:i.length,hasOlderEvents:i.length>=s}}function Dr(e,t){const s=Array.isArray(e?.events)?e.events:[],n=Math.max(Ne,Number(e?.loadedEventLimit??Ne)||Ne),r=s.length>0&&s[s.length-1]?.seq===t?.seq?s:[...s,t].slice(-n),i={nativeTaskSnapshot:e?.nativeTaskSnapshot,closedLiveKeys:e?.closedLiveKeys||[],closedLiveStreams:e?.closedLiveStreams||[],chat:st(e?.chat||[],n),activity:st(e?.activity||[],n),events:r,lastSeq:Number.isFinite(Number(t.seq))?t.seq:e?.lastSeq||0,loadedEventLimit:n,loadedEventCount:Math.max(Number(e?.loadedEventCount||0),r.length),hasOlderEvents:!!e?.hasOlderEvents,stoppedMessageIds:Array.isArray(e?.stoppedMessageIds)?e.stoppedMessageIds:[]};if(Xc(i.chat,t),sd(i.chat,t),td(i.chat,t),i.chat=st(i.chat,n),["user.message","session.turn_completed","session.turn_stopped","session.epoch_committed"].includes(t.eventType)&&od(i.chat,t),t.eventType==="session.turn_stopped"){const l=Array.isArray(t?.data?.clientMessageIds)?t.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,Js(i)),i}if(t.eventType==="user.message"){i.activity.push(...Vn(t,"user"));const l=As(t,"user");if(l?.kind==="canvas-action"){const c=ud(t,l);c&&i.activity.push(c)}return i.activity=st(i.activity,n),l&&(Array.isArray(l.clientMessageIds)&&l.clientMessageIds.some(c=>i.stoppedMessageIds.includes(c))&&(l.stopped=!0),i.chat=Pm(i.chat,l),i.chat.push(l),i.chat=st(xs(i.chat),n)),i}if(t.eventType==="session.canvas_updated"){i.chat.push(dd(t)),i.chat=st(i.chat,n);const l=os(t);return l&&(i.activity.push(l),i.activity=st(i.activity,n)),i}if(t.eventType==="assistant.message"){i.activity.push(...Vn(t,"assistant")),i.activity=st(i.activity,n);const l=As(t,"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,Js(i,l.messageId||null)),c>=0){const u=Date.now(),p=Number(d?.liveStartedAt||d?.createdAt)||u;l.assistantCommentary||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=st(xs(i.chat),n),i}if((t.eventType==="session.turn_completed"||t.eventType==="session.turn_stopped")&&Object.assign(i,Js(i)),t.eventType==="system.message"){if(ld(t)){const l=os(t);l&&(i.activity.push(l),i.activity=st(i.activity,n))}else{const l=As(t,"system");if(!l)return i;i.chat.push(l),i.chat=st(xs(i.chat),n)}return i}if(t.eventType==="session.epoch_committed")return i.chat.push(Zc(t)),i.chat=st(i.chat,n),i;if(t.eventType==="session.regenerate_refused")return i.chat.push(Jc(t)),i.chat=st(i.chat,n),i;if(t.eventType==="session.regenerate_failed")return i.chat.push(ed(t)),i.chat=st(i.chat,n),i;const o=os(t);return o&&(i.activity.push(o),i.activity=st(i.activity,n)),i}function Sn(e,t=null,{loading:s=!1}={}){const n=typeof t?.splash=="string"&&t.splash.trim()?t.splash:null,r=n||e?.splash;if(!r)return[];const i=n?t?.splashMobile:e?.splashMobile,o=typeof i=="string"&&i.trim()?i:null,l=t?.isSystem?ps(t,e?.title||"PilotSwarm"):t?.title||e?.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 pd=.7,Bm=30,Eo=36,Br=18,Ln=18,Hr=0,md=3,Os=6,gr=10,Hm=.25,Um=.5,Ns=6,Yn=10,fd=.336,Ur=Ns,jr=Yn,Gr=Os,Wr=gr;function ws(e,t,s){return Math.max(t,Math.min(s,e))}function jm(e){return[F.SESSIONS,F.CHAT,F.INSPECTOR,F.ACTIVITY].includes(e)?e:null}function Gm(e={}){return{width:Math.max(40,Number(e.width)||120),height:Math.max(18,Number(e.height)||40)}}function Cs(e=""){const t=String(e||"").split(`
31
- `).length;return ws(t,1,md)}function hd(e){return Math.max(Os,Math.floor(e*Hm))}function gd(e,t){const s=Math.floor(Math.max(0,Number(e)||0)*Um),n=Math.max(Os,t-gr);return Math.max(Os,Math.min(n,s))}function ko(e,t){const s=Math.max(0,Number(e)||0),n=ws(Math.max(0,Number(t)||0),0,s),r=-(s/2);return{minAdjust:r,maxAdjust:Math.max(r,s/2-n)}}function en(e,t=0,s=1,n=0,r=0,i=null){const o=Gm(e),l=o.width,c=o.height,d=ws(Number(s)||1,1,md),u=jm(i),p=5+d,m=Math.max(18,c-p),h=Math.floor(l*pd)+(Number(t)||0),g=l-h-Hr;let b=!1,y=!1;h<=Br&&g>Ln?b=!0:g<=Ln&&h>Br?y=!0:h<=Br&&g<=Ln&&(y=t>=0,b=!y);let v,S;b?(v=0,S=l):y?(v=l,S=0):(v=ws(h,Bm,l-Eo-Hr),S=Math.max(Eo,l-v-Hr));const E=hd(m)+(Number(n)||0),I=m-E;let T=!1,C=!1;I<=Wr&&E>Gr?C=!0:E<=Gr&&I>Wr?T=!0:I<=Wr&&E<=Gr&&(C=(Number(n)||0)>=0,T=!C);let k,O;if(T)k=0,O=m;else if(C)k=m,O=0;else{const B=gd(c,m);k=ws(E,Os,B),O=Math.max(gr,m-k)}const R=Math.max(Ns,Math.floor(m*fd))+(Number(r)||0),H=m-R;let x=!1,P=!1;H<=jr&&R>Ur?x=!0:R<=Ur&&H>jr?P=!0:H<=jr&&R<=Ur&&(x=(Number(r)||0)>=0,P=!x);let _,$;return x?(_=m,$=0):P?($=m,_=0):(_=ws(R,Ns,Math.max(Ns,m-Yn)),$=Math.max(Yn,m-_)),{viewport:o,totalWidth:l,totalHeight:c,reservedRows:p,bodyHeight:m,promptRows:d,fullscreenPane:u,paneAdjust:Number(t)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(r)||0,leftHidden:b,rightHidden:y,inspectorHidden:x,activityHidden:P,sessionHidden:T,chatHidden:C,leftWidth:v,rightWidth:S,sessionPaneHeight:k,chatPaneHeight:O,activityPaneHeight:_,inspectorPaneHeight:$}}function Ii(e){if(e?.fullscreenPane)return[e.fullscreenPane,F.PROMPT];if(e?.leftHidden)return[F.INSPECTOR,F.ACTIVITY,F.PROMPT];if(e?.rightHidden)return[...e?.sessionHidden?[F.CHAT]:e?.chatHidden?[F.SESSIONS]:[F.SESSIONS,F.CHAT],F.PROMPT];if(e?.sessionHidden){const t=e?.inspectorHidden?[F.ACTIVITY]:e?.activityHidden?[F.INSPECTOR]:[F.INSPECTOR,F.ACTIVITY];return[F.CHAT,...t,F.PROMPT]}if(e?.chatHidden){const t=e?.inspectorHidden?[F.ACTIVITY]:e?.activityHidden?[F.INSPECTOR]:[F.INSPECTOR,F.ACTIVITY];return[F.SESSIONS,...t,F.PROMPT]}return e?.inspectorHidden?[F.SESSIONS,F.CHAT,F.ACTIVITY,F.PROMPT]:e?.activityHidden?[F.SESSIONS,F.CHAT,F.INSPECTOR,F.PROMPT]:[F.SESSIONS,F.CHAT,F.INSPECTOR,F.ACTIVITY,F.PROMPT]}function bt(e,t){const s=Ii(t);return s.includes(e)?e:s[0]||F.PROMPT}function Wm(e,t){return t?.fullscreenPane?t.fullscreenPane:t?.leftHidden?{[F.PROMPT]:F.PROMPT,[F.ACTIVITY]:F.INSPECTOR,[F.INSPECTOR]:F.INSPECTOR}[e]||F.INSPECTOR:t?.rightHidden?{[F.PROMPT]:F.PROMPT,[F.CHAT]:t?.sessionHidden?F.CHAT:F.SESSIONS,[F.SESSIONS]:F.SESSIONS}[e]||(t?.sessionHidden?F.CHAT:F.SESSIONS):{[F.PROMPT]:t?.sessionHidden?F.CHAT:F.SESSIONS,[F.ACTIVITY]:t?.chatHidden?F.SESSIONS:F.CHAT,[F.INSPECTOR]:t?.chatHidden?F.SESSIONS:F.CHAT,[F.CHAT]:t?.sessionHidden?F.CHAT:F.SESSIONS,[F.SESSIONS]:F.SESSIONS}[e]||(t?.sessionHidden?F.CHAT:F.SESSIONS)}function qm(e,t){return t?.fullscreenPane?t.fullscreenPane:t?.leftHidden?{[F.PROMPT]:F.PROMPT,[F.INSPECTOR]:F.ACTIVITY,[F.ACTIVITY]:F.ACTIVITY}[e]||F.INSPECTOR:t?.rightHidden?{[F.PROMPT]:F.PROMPT,[F.SESSIONS]:t?.chatHidden?F.SESSIONS:F.CHAT,[F.CHAT]:F.CHAT}[e]||(t?.chatHidden?F.SESSIONS:F.CHAT):t?.inspectorHidden?{[F.PROMPT]:F.PROMPT,[F.SESSIONS]:F.CHAT,[F.CHAT]:F.ACTIVITY,[F.ACTIVITY]:F.ACTIVITY}[e]||F.CHAT:t?.activityHidden?{[F.PROMPT]:F.PROMPT,[F.SESSIONS]:F.CHAT,[F.CHAT]:F.INSPECTOR,[F.INSPECTOR]:F.INSPECTOR}[e]||F.CHAT:{[F.PROMPT]:F.PROMPT,[F.SESSIONS]:F.CHAT,[F.CHAT]:F.INSPECTOR,[F.INSPECTOR]:F.ACTIVITY,[F.ACTIVITY]:F.ACTIVITY}[e]||F.CHAT}function yd(e){const t=String(e||"").trim();if(!t)return{error:"Paste a link to plugin.json or the folder that contains it."};let s;try{s=new URL(t)}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 Xn=2*1024*1024,zm=new Set(["node_modules",".git"]);function xi(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);if(typeof Buffer<"u")return Buffer.from(t).toString("base64");let s="";const n=32768;for(let r=0;r<t.length;r+=n)s+=String.fromCharCode.apply(null,t.subarray(r,r+n));return btoa(s)}function bd(e){const t=String(e||"").replace(/\s+/gu,"");if(typeof Buffer<"u")return new Uint8Array(Buffer.from(t,"base64"));const s=atob(t),n=new Uint8Array(s.length);for(let r=0;r<s.length;r+=1)n[r]=s.charCodeAt(r);return n}function Sd(e){return e.split("/").some(t=>zm.has(t))}function vd(e){const t=String(e||"").replace(/^\/+/,"").replace(/\/+$/,"");return t?t.endsWith("/plugin.json")?t.slice(0,-12):t==="plugin.json"?"":t:""}function Km(e,t){return e?`${e}/${t}`:t}function wd(e,t){const s=String(t?.message||t||"");return new Error(`could not reach ${e} from the browser (${s||"network error"}) — the host may block cross-origin reads from this portal; use Upload folder instead`)}async function Qn(e,t,s,n){let r;try{r=await e(t,{headers:{accept:"application/json",...s}})}catch(i){throw wd(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 Ed(e,t,s,n){let r;try{r=await e(t,{headers:s})}catch(o){throw wd(n,o)}if(!r.ok)throw new Error(`${n} returned HTTP ${r.status} for ${t}`);const i=await r.arrayBuffer();return new Uint8Array(i)}function Vm(e){const t=new URL(e).pathname.split("/").filter(Boolean);if(t.length<2)throw new Error(`not a GitHub repository URL: ${e}`);return{owner:t[0],repo:t[1].replace(/\.git$/u,"")}}async function Ym({repoUrl:e,ref:t,path:s},{fetchImpl:n,token:r,onProgress:i}){const{owner:o,repo:l}=Vm(e),c="https://api.github.com",d={"x-github-api-version":"2022-11-28",...r?{authorization:`Bearer ${r}`}:{}};let u=t;u||(i("resolving the default branch…"),u=(await Qn(n,`${c}/repos/${o}/${l}`,d,"api.github.com"))?.default_branch||"main"),i(`reading the file tree of ${o}/${l}@${u}…`);const p=await Qn(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=vd(s),h=Km(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))&&!Sd(w.path.slice(g.length))),y=[];let v=0,S=0;for(const w of b){S+=1;const E=w.path.slice(g.length);i(`fetching ${S}/${b.length}: ${E}`);const I=r?await Xm(n,c,o,l,w.sha,d):await Ed(n,`https://raw.githubusercontent.com/${o}/${l}/${encodeURIComponent(u)}/${w.path.split("/").map(encodeURIComponent).join("/")}`,{},"raw.githubusercontent.com");if(v+=I.length,v>Xn)throw new Error(`package exceeds the ${Math.round(Xn/1024)} KB upload limit at ${E}`);y.push({path:E,contentBase64:xi(I)})}return y}async function Xm(e,t,s,n,r,i){const o=await Qn(e,`${t}/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 bd(l)}function Qm(e){const t=new URL(e),s=t.pathname.split("/").filter(Boolean),n=s.indexOf("_git");if(n<0||n===s.length-1)throw new Error(`not an Azure DevOps repository URL: ${e}`);const r=decodeURIComponent(s[n+1]),i=s.slice(0,n).map(decodeURIComponent),o=t.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 ${e}`);return{org:l,project:c,repo:r}}async function Zm({repoUrl:e,ref:t,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}=Qm(e),u=`https://dev.azure.com/${encodeURIComponent(l)}/${encodeURIComponent(c)}/_apis/git/repositories/${encodeURIComponent(d)}`,m={authorization:i==="pat"?`Basic ${xi(new TextEncoder().encode(`:${r}`))}`:`Bearer ${r}`},f=vd(s),h=`/${f}`,g=t?`&versionDescriptor.version=${encodeURIComponent(t)}&versionDescriptor.versionType=branch`:"";o(`reading ${d}${f?`/${f}`:""}…`);const b=await Qn(n,`${u}/items?scopePath=${encodeURIComponent(h)}&recursionLevel=Full${g}&api-version=7.1`,m,"dev.azure.com"),v=(Array.isArray(b?.value)?b.value:[]).filter(C=>C?.gitObjectType==="blob"&&!C?.isFolder),S=f?`/${f}/`:"/";if(!v.find(C=>C.path===`${S}plugin.json`.replace("//","/")))throw new Error(`no plugin.json under ${h} — link to the folder that contains the manifest`);const E=[];let I=0,T=0;for(const C of v){const k=String(C.path||"").slice(S.length);if(!k||Sd(k))continue;T+=1,o(`fetching ${T}/${v.length}: ${k}`);const O=await Ed(n,`${u}/blobs/${encodeURIComponent(C.objectId)}?api-version=7.1&$format=octetStream`,{...m,accept:"application/octet-stream"},"dev.azure.com");if(I+=O.length,I>Xn)throw new Error(`package exceeds the ${Math.round(Xn/1024)} KB upload limit at ${k}`);E.push({path:k,contentBase64:xi(O)})}return E}async function Jm(e,{fetchImpl:t=typeof fetch=="function"?fetch:null,token:s=null,tokenKind:n="bearer",onProgress:r=()=>{}}={}){if(typeof t!="function")throw new Error("no fetch implementation available");const i=yd(e);if(i.error)throw new Error(i.error);const o={fetchImpl:t,token:s,tokenKind:n,onProgress:r},l=i.kind==="github"?await Ym(i,o):await Zm(i,o);if(l.length===0)throw new Error("the package folder is empty");return{kind:i.kind,files:l}}function ef(e=[]){const t=(Array.isArray(e)?e:[]).find(s=>s?.path==="plugin.json");if(!t?.contentBase64)return null;try{const s=bd(t.contentBase64),n=JSON.parse(new TextDecoder().decode(s));return String(n?.name||"").trim()||null}catch{return null}}function Io(e){return e?.isSystem?Kc(e):Number.MAX_SAFE_INTEGER}function tf(e=[]){const t=new Map;for(let s=0;s<e.length;s+=1){const n=e[s]?.sessionId;!n||t.has(n)||t.set(n,s)}return t}function sf(e=[]){if(e instanceof Map)return new Map(e);if(Array.isArray(e))return tf(e);const t=new Map;for(const[s,n]of Object.entries(e||{}))!s||typeof n!="number"||Number.isNaN(n)||t.set(s,n);return t}function nf(e){if(e instanceof Map)return e;const t=new Map;if(!Array.isArray(e))return t;for(let s=0;s<e.length;s+=1){const n=e[s];typeof n!="string"||!n||t.has(n)||t.set(n,s)}return t}function Fs(e){return!!(e&&!e.isSystem&&!e.parentSessionId)}function rf(e){return!!(e&&!e.isSystem&&(e.isGroup||!e.parentSessionId&&!e.groupId))}function xo(e,t){return!!(rf(e)&&t&&t.has(e.sessionId))}function Ao(e,t){return e.isSystem?0:e.isGroup&&xo(e,t)?1:xo(e,t)?2:e.isGroup?3:4}function No(e){const t=e?.updatedAt??e?.summaryUpdatedAt??e?.latestSummaryUpdatedAt,s=typeof t=="number"?t:Date.parse(t||"");return Number.isFinite(s)?s:0}function Co(e,t,s,n,r){const i=Ao(e,n),o=Ao(t,n);if(i!==o)return i-o;const l=Io(e),c=Io(t);if(l!==c)return l-c;if(r&&r.size>0&&Fs(e)&&Fs(t)){const y=r.has(e.sessionId)?r.get(e.sessionId):1/0,v=r.has(t.sessionId)?r.get(t.sessionId):1/0;if(y!==v)return y-v}const d=s.get(e.sessionId),u=s.get(t.sessionId);if(typeof d=="number"&&typeof u=="number"&&d!==u)return d-u;const p=No(e),m=No(t);if(p>0&&m>0&&p!==m)return p-m;const f=(e.createdAt||0)-(t.createdAt||0);if(f!==0)return f;const h=String(e.title||""),g=String(t.title||""),b=h.localeCompare(g);return b!==0?b:String(e.sessionId||"").localeCompare(String(t.sessionId||""))}function ot(e=[],t=new Set,s=[],n=null,r=null){const i=new Map,o=new Map,l=sf(s),c=nf(r),d=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const g of e)i.set(g.sessionId,g);const u=[];for(const g of e){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&&(e=[...e,...u]);for(const g of e){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)=>Co(b,y,l,d,c));const m=e.filter(g=>!(g.parentSessionId||!g.isGroup&&g.groupId)).sort((g,b)=>Co(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:t.has(g.sessionId),...p.has(g.sessionId)?{standIn:g}:{}}),!t.has(g.sessionId))for(const v of y)h(v,b+1)}for(const g of m)h(g,0);return f}const af=Object.freeze({author:"author",owner:"author",agent:"agent",status:"status",group:"group",folder:"group",model:"model",id:"id",topic:"topic",summary:"summary"}),of=Object.freeze({title:12,id:11,author:10,agent:9,summary:7,group:6,model:5,status:4});function St(e){return String(e||"").normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9@._+-]+/g," ").trim().replace(/\s+/g," ")}function kd(e){const t=String(e||"").trim(),s=[],n=[],r=/(?:(\w+):)?(?:"([^"]+)"|(\S+))/g;let i;for(;(i=r.exec(t))!==null;){const o=String(i[1]||"").toLowerCase(),l=i[2]??i[3]??"",c=St(l);if(!c)continue;const d=af[o];d?n.push({field:d,value:c}):s.push(St(o?`${o} ${l}`:l))}return{source:t,terms:s.filter(Boolean),filters:n}}function lf(e,t,s){if(Math.abs(e.length-t.length)>s)return s+1;let n=Array.from({length:t.length+1},(r,i)=>i);for(let r=1;r<=e.length;r+=1){const i=[r];let o=i[0];for(let l=1;l<=t.length;l+=1){const c=Math.min(i[l-1]+1,n[l]+1,n[l-1]+(e[r-1]===t[l-1]?0:1));i.push(c),o=Math.min(o,c)}if(o>s)return s+1;n=i}return n[t.length]}function To(e,t){if(!e||!t)return 0;if(e===t)return 16;const s=e.split(" ");if(s.includes(t))return 14;if(e.includes(t))return t.includes(" ")?13:11;if(t.length>=2&&s.some(r=>r.startsWith(t)))return 9;if(t.length>=4&&s.some(r=>r.includes(t)))return 7;if(t.length<4)return 0;const n=t.length>=6?2:1;return s.some(r=>lf(r,t,n)<=n)?4:0}function cf(e){return!e||typeof e!="object"?[]:[e.topic,e.intent,e.summary,e.title].filter(t=>typeof t=="string"&&t.trim())}function df(e,{owner:t=null,groupTitle:s=""}={}){const n=St(e?.title),r=St([e?.shortSummary,...cf(e?.summaryState)].filter(Boolean).join(" ")),i=St([t?.displayName,t?.email,t?.subject].filter(Boolean).join(" "));return{title:n,summary:r,topic:St(`${n} ${r}`),author:i,agent:St(e?.agentId),status:St(e?.status),group:St(s),model:St(`${e?.model||""} ${e?.reasoningEffort||""}`),id:St(e?.sessionId)}}function uf(e,t){const s=typeof t=="string"?kd(t):t;if(!s||s.terms.length===0&&s.filters.length===0)return 1;let n=0;for(const i of s.filters){const o=To(e?.[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(of))l==="id"&&(/^\d+$/.test(i)||i.length<8)||(o=Math.max(o,To(e?.[l]||"",i)*c));if(!o)return 0;n+=o}const r=s.terms.join(" ");return r&&e?.title?.includes(r)?n+=120:r&&e?.summary?.includes(r)&&(n+=60),n}const Et="VS Code",js="Retro",ms="Others",Po=Object.freeze([Et,js,ms]);function pf(e){return Object.freeze({...e,page:Object.freeze({...e.page||{}}),terminal:Object.freeze({...e.terminal||{}}),tui:Object.freeze({...e.tui||{}})})}function qr(e){return Number.parseInt(e,16)/255}function mf(e){const t=String(e||"").trim();return/^#[0-9a-f]{3}$/iu.test(t)?`#${t.slice(1).split("").map(s=>s+s).join("")}`:/^#[0-9a-f]{6}$/iu.test(t)?t:null}function zr(e){return e<=.03928?e/12.92:((e+.055)/1.055)**2.4}function ff(e){const t=mf(e);if(!t)return 0;const s=zr(qr(t.slice(1,3))),n=zr(qr(t.slice(3,5))),r=zr(qr(t.slice(5,7)));return .2126*s+.7152*n+.0722*r}function hf(e){const t=e?.page?.background||e?.tui?.background||e?.terminal?.background;return ff(t)>=.5}function Ge({id:e,label:t,description:s,group:n=ms,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 pf({id:e,label:t,description:s,group:n,icon:l||null,page:r,terminal:i,tui:{...c,...o}})}const gf=Ge({id:"github-dark",label:"GitHub Dark",description:"GitHub dark palette with soft blue accents and cool neutrals.",group:Et,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"}}),yf=Ge({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",group:Et,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"}}),Id=Ge({id:"workspace-dark",label:"Workspace Dark",description:"Flat workspace chrome: tone surfaces and hairlines instead of panel borders.",group:ms,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"}}),bf=Ge({id:"cobalt2",label:"Cobalt2",description:"Electric blue shell with bright yellow accents and saturated syntax colors.",group:Et,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"}}),Sf=Ge({id:"dracula",label:"Dracula",description:"Classic Dracula contrast with neon green, pink, and violet accents.",group:Et,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"}}),vf=Ge({id:"catppuccin-mocha",label:"Catppuccin Mocha",description:"Creamy dark palette with soft pastels and high legibility.",group:Et,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"}}),wf=Ge({id:"hacker-x-matrix",label:"Hacker X - Matrix",description:"Black-and-phosphor terminal palette with vivid green glow and CRT-style contrast.",group:Et,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"}}),Ef=Ge({id:"hacker-x-orion-prime",label:"Hacker X - Orion Prime",description:"Deep-space navy palette with electric cyan, violet, and amber accents.",group:Et,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"}}),kf=Ge({id:"gruvbox-dark",label:"Gruvbox Dark",description:"Retro warm palette with earthy browns, oranges, and high readability.",group:Et,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"}}),If=Ge({id:"noctis",label:"Noctis",description:"Dark cyan-tinted palette with warm and cold medium contrast accents.",group:Et,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"}}),xf=Ge({id:"noctis-obscuro",label:"Noctis Obscuro",description:"Deep obsidian palette with cool blue accents and restrained contrast for long sessions.",group:Et,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"}}),Af=Ge({id:"terminal-green",label:"Terminal Green",description:"Classic black terminal with phosphor green text, amber warnings, and crisp operator contrast.",group:js,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"}}),Nf=Ge({id:"high-contrast-mono",label:"High Contrast Mono",description:"Accessibility-first monochrome theme with cobalt selection and severity colors only where they matter.",group:ms,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"}}),Cf=Ge({id:"win95",label:"Windows 95",description:"Authentic 3D-bevelled grey, navy title bars, teal desktop, and the 16-colour VGA terminal set.",group:js,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"}}),Tf=Ge({id:"ms-dos",label:"MS-DOS 2.0",description:"CGA light-grey on black, the 16-colour CGA palette with brown, and CP437 box framing.",group:js,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"}}),Pf=Ge({id:"doom",label:"DOOM",description:"STBAR brown metal, bone type, and the three keycards as the status palette.",group:js,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"}}),Mf=Ge({id:"winamp",label:"WinAMP",description:"Bevelled grey chrome, black glass panes, phosphor green, and the spectrum ramp as the status palette.",group:js,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"}}),_f=Ge({id:"rust",label:"Rust",description:"Graphite and iron oxide, Ferris in the corner, and rustc's diagnostic levels as the status palette.",group:ms,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"}}),$f="#a35838",Rf="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",Lf=Ge({id:"duroxide",label:"Duroxide",description:"Iron oxide pressed into black felt - the durable-execution runtime's own mark, traced from the banner.",group:ms,icon:{viewBox:"0 0 64 64",paths:[{d:Rf,fill:$f}]},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"}}),Of=Ge({id:"spongebob",label:"SpongeBob",description:"Bikini Bottom at depth, sponge-yellow accents, and the cast as the status palette.",group:ms,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 Ff(e,t){const s=Po.indexOf(e.group),n=Po.indexOf(t.group),r=s===-1?Number.MAX_SAFE_INTEGER:s,i=n===-1?Number.MAX_SAFE_INTEGER:n;return r!==i?r-i:e.label.localeCompare(t.label,void 0,{sensitivity:"base"})}const xd=Object.freeze([Id,Sf,gf,yf,bf,Ef,wf,vf,kf,If,xf,Af,Nf,Cf,Tf,Pf,Mf,_f,Lf,Of].sort(Ff)),Df=new Map(xd.map(e=>[e.id,e])),Bf=Id.id;function Hf(){return xd}function Pt(e){return e?Df.get(e)??null:null}const Uf=new Set(["agent","user","system"]);function on(e){const t=Array.isArray(e?.ownerKeys)?[...new Set(e.ownerKeys.map(n=>String(n||"").trim()).filter(Boolean))]:[];return{all:e&&typeof e=="object"?e?.all===!0:!0,includeSystem:e?.includeSystem===!0,includeUnowned:e?.includeUnowned===!0,includeMe:e?.includeMe===!0,includeShared:e?.includeShared===!0,ownerKeys:t}}function jf(e){if(typeof e=="string"){const r=e.trim();return r?{filename:r,sizeBytes:null,contentType:"",isBinary:!1,uploadedAt:"",source:"agent"}:null}if(!e||typeof e!="object")return null;const t=String(e.filename||"").trim();if(!t)return null;const s=Number(e.sizeBytes),n=typeof e.contentType=="string"?e.contentType:"";return{filename:t,sizeBytes:Number.isFinite(s)&&s>=0?s:null,contentType:n,isBinary:e.isBinary===!0,uploadedAt:typeof e.uploadedAt=="string"?e.uploadedAt:"",source:Uf.has(e.source)?e.source:"agent"}}function Zn(e){const t=Array.isArray(e)?e:[],s=[],n=new Set;for(const r of t){const i=jf(r);!i||n.has(i.filename)||(n.add(i.filename),s.push(i))}return s}function Gf(e,t){const s=String(t||"").trim();return s&&Zn(e).find(n=>n.filename===s)||null}function pa(e){const t=e&&typeof e=="object"?e:{},s=Number(t.paneAdjust),n=Number(t.sessionPaneAdjust),r=Number(t.portalSessionColumnAdjust),i=Number(t.activityPaneAdjust),o=Number(t.canvasPaneAdjust),l=Number(t.diagnosticsPaneAdjust),c=Number(t.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(e){if(!Array.isArray(e))return[];const t=new Set,s=[];for(const n of e){const r=String(n||"").trim();!r||t.has(r)||(t.add(r),s.push(r))}return s}function ma(e){if(!Array.isArray(e))return[];const t=new Set,s=[];for(const n of e){const r=String(n||"").trim();!r||t.has(r)||(t.add(r),s.push(r))}return s}function Ai(e){if(!Array.isArray(e))return new Set;const t=new Set;for(const s of e){const n=String(s||"").trim();n&&t.add(n)}return t}function Wf(e){return e==="canvas"?"canvas":"panes"}const yr=Object.freeze(["paneAdjust","activityPaneAdjust","canvasPaneAdjust","diagnosticsPaneAdjust","diagnosticsSplitAdjust"]),qf=Object.freeze(["desktop","mobile"]),zf=300;function Ni(){const e={};for(const t of yr)e[t]=0;return{canvasOpen:!1,diagnosticsOpen:!1,zen:!1,layout:e,at:0}}function Kf(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=Ni();t.canvasOpen=e.canvasOpen===!0,t.diagnosticsOpen=e.diagnosticsOpen===!0,t.zen=t.canvasOpen&&e.zen===!0;const s=e.layout&&typeof e.layout=="object"?e.layout:{};for(const r of yr){const i=Number(s[r]);t.layout[r]=Number.isFinite(i)?Math.trunc(i):0}const n=Number(e.at);return t.at=Number.isFinite(n)&&n>0?Math.trunc(n):0,t}function Ad(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=[];for(const[n,r]of Object.entries(e)){const i=String(n||"").trim();if(!i||!r||typeof r!="object"||Array.isArray(r))continue;const o={};let l=0;for(const c of qf){const d=Kf(r[c]);d&&(o[c]=d,l=Math.max(l,d.at))}Object.keys(o).length>0&&t.push([i,o,l])}t.sort((n,r)=>r[2]-n[2]);const s={};for(const[n,r]of t.slice(0,zf))s[n]=r;return s}function Nd(e,t){const s=e&&typeof e=="object"?e: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:t==="canvas",diagnosticsOpen:!1,zen:!1}}function ut(e,t){const s=String(e||""),n=Number(t);return Number.isInteger(n)&&n>=2&&n<=5?`${s}#${n}`:s}function Vf(e){const t=/^(.*)#([2-5])$/.exec(String(e||""));return t?{sessionId:t[1],slot:Number(t[2])}:{sessionId:String(e||""),slot:1}}function fa(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const[s,n]of Object.entries(e)){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);t[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 t}function Cd(e){if(e==null)return null;const t=String(e).trim();return t||null}const Yf=Object.freeze(["limit","allowance","hold","no_provider"]);function Ds(e){const t=e?.pauseState;if(!t||typeof t!="object")return null;const s=String(t.kind||"");if(!Yf.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(t.provider),period:["day","week","month"].includes(String(t.period))?String(t.period):null,modelQualified:n(t.modelQualified),limitTokens:r(t.limitTokens),usedTokens:r(t.usedTokens),ceilingTokens:r(t.ceilingTokens),yourUsedTokens:r(t.yourUsedTokens),resetsAtUtc:n(t.resetsAtUtc)}}const Xf=Object.freeze(["day","week","month"]),er=Object.freeze([14,30,90]),Oe=14;function Ci({mode:e="local",branding:t=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=Nd(p,Wf(u)),h=r!=null,g=l!=null,b=pa(i);return{branding:t||{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:F.SESSIONS,budgetOpen:!1,inspectorTab:wt[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:Pt(n)?.id||Bf,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:e,connected:!1,workersOnline:null,error:null},sessions:{byId:{},groupRows:[],flat:[],activeSessionId:Cd(c),collapsedIds:Ai(l),collapsedIdsExplicit:g,pinnedIds:Jn(o),manualOrder:ma(d),sortMode:"saved",sortSnapshot:[],usedAt:{},listingSeen:!1,groupsListingSeen:!1,selectedIds:[],selectMode:!1,listDeselected:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:h,ownerFilter:on(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:fa(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:Oe,selectedProvider:null,selectedScope:"*",missingProvider:null,series:{provider:null,scope:"*",rangeDays:Oe,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:{provider:null,scope:"*",rangeDays:Oe,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 ln=e=>["used","updated"].includes(e)?e:"saved";function Td(e){return Object.fromEntries(Object.entries(e||{}).filter(([t,s])=>t&&Number.isFinite(s)&&s>0))}function Qf(e,t){const s=ot(Object.values(e.byId),new Set,e.orderById,e.pinnedIds,e.manualOrder),n=new Map(s.map((i,o)=>[i.sessionId,o])),r=i=>{if(t==="used")return e.usedAt?.[i.sessionId]||0;const o=i.updatedAt??i.summaryUpdatedAt??i.latestSummaryUpdatedAt,l=typeof o=="number"?o:Date.parse(o||"");return Number.isFinite(l)?l:0};return Object.values(e.byId).sort((i,o)=>r(o)-r(i)||(n.get(i.sessionId)??1/0)-(n.get(o.sessionId)??1/0)).map(i=>i.sessionId)}function Zf(e,t,s){const n=t.sessions;if(!n)return t;const r=ln(n.sortMode),i=r!==ln(e.sessions?.sortMode),o=s.type==="sessions/refreshSort";if(!(n.flat!==e.sessions?.flat||n.byId!==e.sessions?.byId||i||o))return t;let c=n.sortSnapshot;if(r!=="saved")if(!n.listingSeen)c=[];else if(i||o||!c?.length)c=Qf(n,r);else{const u=new Set(c),p=Object.keys(n.byId).filter(m=>!u.has(m));p.length&&(c=[...c,...p])}const d=r==="saved"&&!i?n.flat:ot(Object.values(n.byId),n.collapsedIds,n.orderById,n.pinnedIds,r==="saved"?n.manualOrder:c);return{...t,sessions:{...n,sortSnapshot:c,flat:d}}}const Jf=5,Mo=16,lE=920,Ti=e=>e&&typeof e=="object"&&!Array.isArray(e),Pi=e=>typeof e=="string"&&/^[a-zA-Z0-9_-]{1,100}$/.test(e),cE=()=>({id:crypto.randomUUID(),type:"empty"}),Mi=e=>e?e.type==="split"?[...Mi(e.first),...Mi(e.second)]:[e]:[];function eh(e){if(!Ti(e))throw new Error("Invalid MoA layout.");const t=new Set;let s=0,n=0;function r(i,o=0){if(!Ti(i)||o>15||++n>31||!Pi(i.id)||t.has(i.id))throw new Error("Invalid MoA panel tree.");if(t.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>Mo)throw new Error(`A MoA supports up to ${Mo} panels.`);if(i.type==="empty")return{id:i.id,type:"empty"};if(!["chat","canvas"].includes(i.type)||!Pi(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 e.name=="string"&&e.name.trim().slice(0,64)||"Untitled MoA",tree:e.tree==null?null:r(e.tree)}}function cn(e){const t=(n,r="moa-1",i="MoA 1")=>{let o=null;try{o=eh(n).tree}catch{}const l=Mi(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(e?.version===3&&Array.isArray(e.dashboards)){const n=new Set,r=e.dashboards.slice(0,Jf).map((i,o)=>{let l=Pi(i?.id)&&!n.has(i.id)?i.id:`moa-${o+1}`;for(;n.has(l);)l+="-copy";return n.add(l),t(i,l,`MoA ${o+1}`)});return r.length||r.push(t(null)),{version:3,composerMode:e?.composerMode==="shared"?"shared":"per-chat",activeDashboardId:r.some(i=>i.id===e.activeDashboardId)?e.activeDashboardId:r[0].id,dashboards:r}}let s=e;if(!(e?.version===2||Ti(e)&&Object.hasOwn(e,"tree"))){const n=Array.isArray(e?.slots)?e.slots.slice(0,5):[],r=Number.isInteger(e?.activeSlot)?Math.max(0,Math.min(4,e.activeSlot)):0;s=t(n[r]).tree?n[r]:n.find(i=>t(i).tree)}return{version:3,composerMode:e?.composerMode==="shared"?"shared":"per-chat",activeDashboardId:"moa-1",dashboards:[t(s)]}}const dE=e=>e.dashboards.find(t=>t.id===e.activeDashboardId)||e.dashboards[0];function uE(e,t,s){return cn({...e,dashboards:e.dashboards.map(n=>n.id===t?{...n,...s}:n)})}function pE(e,t,s){const n=cn(e),r=n.dashboards.findIndex(l=>l.id===t);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 _o(e,t,s){if(!e)return null;if(e.id===t)return s;if(e.type!=="split")return e;const n=_o(e.first,t,s),r=_o(e.second,t,s);return n?r?n===e.first&&r===e.second?e:{...e,first:n,second:r}:n:r}function _i(e){const t=String(e??"");if(!t.includes("\\n"))return t;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 t.replace(s,n=>n==="\\n"||n==="\\r\\n"?`
32
- `:n)}const Pd="activeHighlightBackground",ha="activeHighlightForeground";function th(e){return e==="anthropic-wif"}const Kr="userChat",sh="userChatLabel",nh="otherUserChatLabel",$o=new WeakMap,Ro=new WeakMap;function rh(e){return e||ha}function Md(e,{preserveColors:t=!1}={}){return(e||[]).map(s=>({...s,color:t?rh(s?.color):ha,backgroundColor:Pd,bold:s?.bold??!0}))}function kt(e,{color:t=ha,bold:s=!0}={}){return{text:e,color:t,backgroundColor:Pd,bold:s}}function vt(e,t){return[{text:String(e||""),color:t,bold:!0}]}const ih=72;function _d(e){const t=Number(e)||0;return t>0&&t<=ih}function $d(e){if(!e)return"unknown";const t=e.status||"unknown",s=t==="waiting"||t==="idle"||t==="unknown";return s&&Ds(e)?"budget_paused":e.cronActive===!0&&s?"cron_waiting":s&&(Number(e.activeChildCount)||0)>0?"awaiting_children":t}const Lo={day:"daily",week:"weekly",month:"monthly"};function Rd(e){if(!e)return"paused";switch(e.kind){case"no_provider":return"no provider";case"hold":return"paused · hold";case"allowance":return"paused · allowance";default:return"paused · limit"}}function ah(e,t=Date.now()){const s=e?.provider||"this session's provider",n=e?.resetsAtUtc?_a(e.resetsAtUtc,t):null,r=n?` Resets ${n}.`:"";switch(e?.kind){case"no_provider":return e?.provider?`No provider named ${e.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 e?.resetsAtUtc?`${s} is on hold.${r}`:`${s} is on hold until an administrator releases it.`;case"allowance":{const i=Lo[e?.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=Lo[e?.period],o=e?.modelQualified?` for ${e.modelQualified}`:"";return`${s} has reached its ${i?`${i} `:""}limit${o}.${r}`}}}function oh(e,t){const s=Ds(e);if(s)return s;const n=e?.sessionId;if(!n)return null;const i=(Array.isArray(t?.budget?.paused)?t.budget.paused:[]).find(o=>o?.sessionId===n);return i?Ds({pauseState:i.pause}):null}function lh(e,t=null){const s=oh(e,t);return s?{kind:s.kind,provider:s.provider,period:s.period,resetsAtUtc:s.kind==="no_provider"?null:s.resetsAtUtc,label:Rd(s),reason:ah(s),clears:Mg(s),color:"red"}:null}function ch(e,t){if(t==="budget_paused")return Rd(Ds(e));if(t==="cron_waiting")return"waiting";if(t==="awaiting_children"){const s=Number(e?.activeChildCount)||0;return s>0?`waiting on ${s}`:"waiting on children"}return t}function dh(e){if(!e)return null;const t=e.updatedAt||e.summaryUpdatedAt||e.latestSummaryUpdatedAt||e.createdAt||0;return{status:Ld(e)||"unknown",timestampMs:t||null,relative:t?Oa(t):"—"}}function Ld(e){const t=Od(e);return!t||t==="unknown"?"":ch(e,t)}function Od(e){return e?.rowVisualStatus||$d(e)}function $i(e){return e==="Completed"||e==="Failed"||e==="Terminated"}function ga(e){const t=$d(e);return e?.orchestrationStatus==="Failed"?"failed":$i(e?.orchestrationStatus)?null:t==="failed"?"failed":t==="error"||!["completed","cancelled","terminated","input_required"].includes(e?.status)&&String(e?.error||"").trim()&&!$i(e?.orchestrationStatus)?"warning":null}function ya(e,t="local"){const s=ga(e);if(s)return s;const n=Od(e);if(t==="remote"&&$i(e?.orchestrationStatus)&&n!=="cron_waiting"&&n!=="awaiting_children"&&n!=="waiting"&&n!=="input_required"){if(e?.orchestrationStatus==="Completed")return"completed";if(e?.orchestrationStatus==="Terminated")return"terminated"}return n==="terminated"?"terminated":n}function Ts(e,t="local"){switch(ya(e,t)){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 Fd(e,t="local"){switch(ya(e,t)){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 Pe(e){const t=String(e?.provider||"").trim(),s=String(e?.subject||"").trim();return t&&s?`${t}${s}`:null}function pn(e,t="unknown user"){return String(e?.displayName||e?.email||"").trim()||t}const mn=Pe({provider:"system",subject:"system"});function Oo(e){const t=String(e||"").trim();if(!t)return"";const s=t.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]||t).replace(/[^A-Za-z0-9]/gu,"").slice(0,2).toUpperCase()}function Ri(e){return Oo(e?.displayName)||Oo(e?.email)||"?"}function uh(e,t=!1){return Fs(e)?t?e.isGroup?"pinned:folders":"pinned:sessions":e.isGroup?"folders":e.groupId?`g:${e.groupId}`:"":null}function Dd(e,{isMine:t=!1,hueByKey:s=null}={}){if(!e)return null;const n=pn(e,e?.email||""),r=Ud(e,e?.email);return{initials:Ri(e),hue:s?.get?.(r)??Hd(r),name:n||"unknown user",isMine:!!t}}function ph(e){const t=[...new Set([...e].map(r=>String(r||"").trim().toLowerCase()).filter(Boolean))].sort(),s=new Set,n=new Map;for(const r of t){let i=Hd(r);if(s.size<On){let o=0;for(;s.has(i)&&o<On;)i=(i+1)%On,o+=1}s.add(i),n.set(r,i)}return n}let vn=null;function Bd(e){if(vn&&vn.byId===e)return vn.map;const t=[];for(const n of Object.values(e||{})){if(!n||n.isSystem||n.isGroup)continue;const r=n.owner,i=Pe(r);!i||i===mn||t.push(Ud(r,r?.email))}const s=ph(t);return vn={byId:e,map:s},s}function mh(e){const t=new Map;for(const s of Object.values(e||{})){const n=s?.owner;if(!n?.subject||!n.displayName&&!n.email)continue;const r=Pe(n);r&&!t.has(r)&&t.set(r,n)}return t}function fh(e,t){if(e?.owner?.displayName||e?.owner?.email)return e.owner;const s=t?.get?.(Pe(e?.owner))||null;return s||(e?.createdBy?{email:e.createdBy}:null)}const On=12;function Hd(e){const t=String(e||"").trim().toLowerCase();if(!t)return 0;let s=2166136261;for(let n=0;n<t.length;n+=1)s^=t.charCodeAt(n),s=Math.imul(s,16777619)>>>0;return s%On}function Ud(e,t){return String(t||e?.email||e?.displayName||(e?.provider&&e?.subject?`${e.provider}:${e.subject}`:"")||"").trim().toLowerCase()}function hh(e,t=1/0){const s=e?.sessions?.byId,n=e?.sessions?.ownerFilter||{all:!0},r=e?.auth||{},i=new Set;for(const o of Object.values(s||{})){if(!o||o.isSystem||o.isGroup)continue;const l=Pe(o.owner);if(!(!l||l===mn)&&Oi(o,n,r)&&(i.add(l),i.size>=t))break}return i.size}const Fo=new WeakMap;function Li(e){const t=e?.sessions?.byId;if(!t)return!1;const s=e.sessions.ownerFilter,n=e.auth,r=Fo.get(t);if(r&&r.filter===s&&r.auth===n)return r.value;const i=hh(e,2)>1;return Fo.set(t,{filter:s,auth:n,value:i}),i}function jd(e,t={}){return!e?.isGroup||!e?.groupId?[]:Object.values(t||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===e.groupId)}function ns(e,t={}){if(!e?.isGroup)return e?.owner??null;if(e.owner)return e.owner;const s=new Map;for(const n of jd(e,t)){const r=Pe(n?.owner);r&&!s.has(r)&&s.set(r,n.owner)}return s.size===1?s.values().next().value:null}function Do(e){return String(e||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Bo(e,t){const s=Do(e),n=Do(t?.agentId);return!!(s&&n&&s===n)}function gh(e){if(!e?.agentId||e?.isSystem)return null;const t=String(e?.title||"").trim();if(!t)return null;const s=" · ",n=t.lastIndexOf(s);if(n>0){const o=t.slice(0,n).trim(),l=t.slice(n+s.length).trim();if(o&&Bo(l,e))return{displayTitle:o,agentTitle:l}}const r=/^(.+?)\s+[–—-]\s+(.+)$/u.exec(t);if(r){const o=r[1].trim(),l=r[2].trim();if(o&&l)return{displayTitle:l,agentTitle:o}}const i=t.indexOf(": ");if(i>0){const o=t.slice(0,i).trim(),l=t.slice(i+2).trim();if(l&&Bo(o,e))return{displayTitle:l,agentTitle:o}}return null}function yh(e){const t=String(e||""),s=t.indexOf(": ");if(s<=0)return null;const n=t.slice(0,s).trim(),r=t.slice(s+2).trim();return!n||!r?null:{userTitle:r,typeTitle:n}}const bh=[[/&lt;/g,"<"],[/&gt;/g,">"],[/&quot;/g,'"'],[/&#0?39;/g,"'"],[/&apos;/g,"'"],[/&nbsp;/g," "],[/&amp;/g,"&"]];function Sh(e){let t=String(e??"");if(!t.includes("&"))return t;for(const[s,n]of bh)t=t.replace(s,n);return t}function ba(e){return Sh(vh(e))}function vh(e){const t=String(e?.title||"").trim(),s=gh(e);if(!s)return t;const n=yh(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function Gd(e,t){const s=Le(e?.sessionId);if(e?.isSystem)return`${ps(e,t)} (${s})`;const n=ba(e);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function Oi(e,t={},s={},n=void 0){if(!t||t.all===!0||e?.isGroup)return!0;if(e?.isSystem)return t.includeSystem===!0;const r=Pe(n!==void 0?n:e?.owner);if(!r)return t.includeUnowned===!0;if(r===mn)return t.includeSystem===!0;const i=Pe(s?.principal);return t.includeMe&&i&&r===i||t.includeShared===!0&&r!==i?!0:Array.isArray(t.ownerKeys)&&t.ownerKeys.includes(r)}function Sa(e,t={},s={},n=null){const r=ns(e,n||{});if(Oi(e,t,s,r))return!0;if(!n)return!1;if(e?.isGroup)return jd(e,n).some(l=>Sa(l,t,s,n));let i=e,o=0;for(;i?.parentSessionId&&o<16;){const l=n[i.parentSessionId];if(!l)return!1;if(Oi(l,t,s))return!0;i=l,o+=1}return!1}function wh(e){return(e||[]).map(t=>t?.text||"").join("")}function va(e){const t=new Map,s=new Map;for(const n of Object.values(e||{})){const r=n?.parentSessionId;r&&(s.set(n.sessionId,r),t.has(r)||t.set(r,[]),t.get(r).push(n.sessionId))}return{childMap:t,parentMap:s}}function Ho(e){const{childMap:t}=va(e),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=(t.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(e||{}))r(i);return s}function Uo(e=[],t={}){const{parentMap:s}=va(t),n=new Map;for(const r of e){let i=s.get(r.sessionId);for(;i;)n.set(i,(n.get(i)||0)+1),i=s.get(i)}return n}function wa(e={}){if(!e||typeof e!="object")return Ho(e);const t=$o.get(e);if(t)return t;const s=Ho(e);return $o.set(e,s),s}function Ea(e=[],t={}){if(!Array.isArray(e))return Uo(e,t);const s=Ro.get(e);if(s)return s;const n=Uo(e,t);return Ro.set(e,n),n}function Wd(e,t,s,n){const r=s.get(e)||0,i=n.get(e)||0,o=Math.max(0,r-i),l=t?.collapsed?r:o;return l?{text:`[+${l}]`,color:"cyan"}:null}function tr(e){if(!e)return"scheduled";const t=e instanceof Date?e:new Date(e);if(Number.isNaN(t.getTime()))return"scheduled";try{return t.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 t.toISOString().replace(/\.000Z$/,"Z")}}function Eh(e){return e?.cronActive===!0&&e?.cronKind==="wall-clock"?{text:`[cron ${tr(e.cronNextFireAt)}]`,color:"magenta"}:e?.cronActive===!0&&typeof e?.cronInterval=="number"?{text:`[cron ${as(e.cronInterval)}]`,color:"magenta"}:null}function qd(e){return!!(e&&!e.isSystem&&(e.isGroup||!e.parentSessionId&&!e.groupId))}function kh(e,t){const s=[];typeof e?.regenStage=="string"&&e.regenStage&&s.push({text:`↻ regen:${e.regenStage}`,color:"magenta"});const n=Ld(e);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:Ts(e,t)}));const r=Ta(e?.model,e?.reasoningEffort);r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r,color:"cyan"}));const i=Rp(e?.contextUsage);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i.text,color:i.color}));const o=Lp(e?.contextUsage);return o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color})),s}function Ih(e,t,s,n,r){const i=[],o=s.connection?.mode||"local",l=e.depth>0?`${" ".repeat(Math.max(0,e.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(e.sessionId),m=c.has(e.sessionId);if(p&&i.push({text:"▌",color:"cyan",bold:!0,role:"selection"}),e.depth===0&&qd(t)&&c.size>0&&(m&&!t?.isSystem?i.push({text:"📌 ",color:"yellow"}):i.push({text:" ",color:"gray"})),t?.isGroup)i.push({text:"🗂 ",color:"cyan",bold:!0});else if(t?.isSystem)i.push({text:"⚙ ",color:"yellow",bold:!0});else if(t?.serviceKind)i.push({text:"⚗ ",color:"magenta",bold:!0});else{const _=Fd(t,o);i.push({text:_?`${_} `:" ",color:Ts(t,o),role:"status"})}const f=t?.isGroup?"cyan":t?.isSystem?"yellow":Ts(t,o),h=ns(t,s.sessions?.byId||{}),g=Le(t?.sessionId),b=t?.updatedAt||t?.summaryUpdatedAt||t?.latestSummaryUpdatedAt||t?.createdAt||0,y=b?Iy(b):"",v=Ta(t?.model,t?.reasoningEffort),S=t?.isSystem?ps(t,s.branding?.title||"PilotSwarm"):ba(t),w=!!(t?.isSystem||t?.isGroup||S&&S.trim()),E=[...i];if(Li(s)&&!t?.isSystem&&!t?.isGroup){const _=Pe(s?.auth?.principal),$=!!(_&&Pe(h)===_),B=h?Ri(h):"?";E.push({text:`[${B}] `,color:$?"green":"cyan",bold:!0,ownerChip:!0})}w?E.push({text:S,color:f,bold:!!(t?.isSystem||t?.isGroup)}):(E.push({text:g,color:f}),y&&(E.push({text:" · ",color:"gray"}),E.push({text:y,color:"gray"})),v&&(E.push({text:" · ",color:"gray"}),E.push({text:v,color:"green"})));const I=Wd(t?.sessionId,e,n,r);I&&E.push({text:` ${I.text}`,color:I.color,bold:I.bold,role:"collapseBadge"});const T=ya(t,o)==="budget_paused"||t?.status==="waiting"?lh(t,s):null;T&&E.push({text:` ${T.label}`,color:T.color});const C=Eh(t);C&&E.push({text:" ⏱",color:"magenta"});const k=[],O=t?.contextUsage?.compaction?.state,N=na(t?.contextUsage);t?.isGroup?t?.memberCount!=null&&k.push({text:`${t.memberCount}`,color:"gray"}):O==="running"?k.push({text:"⇊",color:"magenta"}):O==="failed"?k.push({text:"!",color:"red"}):N!=null?k.push({text:`${N}%`,color:N>=85?"red":N>=70?"yellow":"green"}):k.push({text:"—",color:"gray"});const R=[];t?.isGroup&&t?.memberCount!=null&&(R.push({text:`${t.memberCount} member${t.memberCount===1?"":"s"}`,color:"gray"}),y&&(R.push({text:" · ",color:"gray"}),R.push({text:y,color:"gray"})));const H=[],x=()=>{H.length&&H.push({text:" · ",color:"gray"})};if(t?.isGroup)H.push(...R);else{w&&(H.push({text:g,color:"cyan"}),y&&(x(),H.push({text:y,color:"gray"})),v&&(x(),H.push({text:v,color:"green"})));const _=t?.contextUsage;_&&Number.isFinite(_.currentTokens)&&Number.isFinite(_.tokenLimit)&&_.tokenLimit>0&&(x(),H.push({text:`ctx ${se(_.currentTokens)}/${se(_.tokenLimit)}`,color:"gray"}));const $=n?.[t?.sessionId];$&&(x(),H.push({text:`${$} child${$===1?"":"ren"}`,color:"gray"})),C&&(x(),H.push({text:C.text,color:C.color})),T&&(x(),H.push({text:T.reason,color:T.color})),(t?.visibility==="shared_read"||t?.visibility==="shared_write")&&(x(),H.push({text:t.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...E,...w&&y&&!t?.isGroup?[{text:" ",color:"gray"},{text:y,color:"gray"}]:[],...k.length&&!t?.isGroup?[{text:" · ",color:"gray"},...k]:[],...t?.isGroup&&R.length?[{text:" ",color:"gray"},...R]:[]],titleRuns:E,ctxRuns:k,metaRuns:R,badgeRuns:[],selectedMetaRuns:H,detailRuns:H,childCount:n?.get?.(t?.sessionId)||0,chrome:{kind:t?.isGroup?"group":t?.isSystem?"system":t?.serviceKind?"service":"session",title:w?S:g,untitled:!w,statusColor:Ts(t,o),accentColor:f,pinned:m,selectMode:u,checked:p,owner:Li(s)&&!t?.isSystem&&!t?.isGroup?{initials:h?Ri(h):"?",isMine:!!(Pe(s?.auth?.principal)&&Pe(h)===Pe(s?.auth?.principal))}:null,childBadge:I?{text:I.text,color:I.color}:null,pause:T,cron:!!C,age:y||null,model:v||null,shortId:g,ctx:k.length>0?{text:k[0].text,color:k[0].color}:null}}}function xh(e){return String(e||"").trim().toLowerCase()}function Ps(e,t){const s=xh(t);return s?String(e||"").toLowerCase().includes(s):!0}const jo=new WeakMap,Go=new WeakMap;function Ah(e,t){if(e?.isGroup)return e.title||"";if(e?.groupId)return t?.[`group:${e.groupId}`]?.title||"";let s=e;const n=new Set;for(;s?.parentSessionId&&!n.has(s.parentSessionId);)if(n.add(s.parentSessionId),s=t?.[s.parentSessionId],s?.groupId)return t?.[`group:${s.groupId}`]?.title||"";return""}function Nh(e,t){const s=ns(e,t);if(s)return s;let n=e;const r=new Set;for(;n?.parentSessionId&&!r.has(n.parentSessionId);)if(r.add(n.parentSessionId),n=t?.[n.parentSessionId],n?.owner)return n.owner;return null}function Ch(e){const t=e.sessions?.byId||{},s=[e.sessions?.orderById,e.sessions?.pinnedIds,e.sessions?.sortMode&&e.sessions.sortMode!=="saved"?e.sessions.sortSnapshot:e.sessions?.manualOrder],n=Go.get(t);if(n&&ka(n.deps,s))return n;const r=ot(Object.values(t),new Set,e.sessions?.orderById,e.sessions?.pinnedIds,e.sessions?.sortMode&&e.sessions.sortMode!=="saved"?e.sessions.sortSnapshot:e.sessions?.manualOrder),i=new Map,o=new Map,l=new Map,c=[];for(let p=0;p<r.length;p+=1){const m=r[p];c[m.depth]=m.sessionId,c.length=m.depth+1,i.set(m.sessionId,m.depth>0?c[m.depth-1]:null),o.set(m.sessionId,m),l.set(m.sessionId,p)}const d=new Map(r.map(p=>{const m=t[p.sessionId]||p.standIn;return[p.sessionId,df(m,{owner:Nh(m,t),groupTitle:Ah(m,t)})]})),u={deps:s,expanded:r,parentById:i,entryById:o,baseIndex:l,documents:d};return Go.set(t,u),u}function Th(e,t){const s=Array.isArray(e.sessions?.flat)?e.sessions.flat:[];if(!t)return s;const n=jo.get(s),r=[e.sessions?.byId,e.sessions?.ownerFilter,e.auth,e.sessions?.orderById,e.sessions?.pinnedIds,e.sessions?.sortMode&&e.sessions.sortMode!=="saved"?e.sessions.sortSnapshot:e.sessions?.manualOrder,e.sessions?.filterExceptionId];if(n?.query===t&&ka(n.deps,r))return n.result;const i=e.sessions?.byId||{},o=kd(t),{expanded:l,parentById:c,entryById:d,baseIndex:u,documents:p}=Ch(e),m=new Map;for(const w of l){const E=i[w.sessionId]||w.standIn;if(!E||!Sa(E,e.sessions?.ownerFilter,e.auth||{},i))continue;const I=uf(p.get(w.sessionId),o);I>0&&m.set(w.sessionId,I)}const f=new Set(m.keys()),h=e.sessions?.filterExceptionId;h&&d.has(h)&&m.set(h,Number.MAX_SAFE_INTEGER);const g=new Set,b=new Map;for(const[w,E]of m){let I=w;const T=new Set;for(;I&&!T.has(I);)T.add(I),g.add(I),b.set(I,Math.max(b.get(I)||0,E)),I=c.get(I)||null}const y=new Map;for(const w of g){const E=c.get(w)||null;y.has(E)||y.set(E,[]),y.get(E).push(w)}for(const w of y.values())w.sort((E,I)=>(b.get(I)||0)-(b.get(E)||0)||(u.get(E)||0)-(u.get(I)||0));const v=[],S=(w,E)=>{const I=d.get(w);if(!I)return;const T=y.get(w)||[];v.push({...I,depth:E,collapsed:!1,hasChildren:T.length>0,searchIncluded:!0,searchMatch:f.has(w),searchScore:m.get(w)||0});for(const C of T)S(C,E+1)};for(const w of y.get(null)||[])S(w,0);return jo.set(s,{query:t,deps:r,result:v}),v}function Ph(e){const t=e?.filterExceptionId||null,s=e?.byId||{};if(!t||!s[t])return null;const n=new Set([t]);let r=s[t],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 Wo=new WeakMap;function ka(e,t){if(!e||e.length!==t.length)return!1;for(let s=0;s<e.length;s+=1)if(e[s]!==t[s])return!1;return!0}function us(e){const t=String(e.sessions?.filterQuery||"").trim(),s=Th(e,t),n=wa(e.sessions.byId),r=Ea(s,e.sessions.byId),i=e.sessions?.ownerFilter||{all:!0},o=e.auth||{},l=new Set(Array.isArray(e.sessions?.pinnedIds)?e.sessions.pinnedIds:[]),c=new Set(Array.isArray(e.sessions?.selectedIds)?e.sessions.selectedIds:[]),d=Ph(e.sessions);let u=Wo.get(s);return u||(u=new Map,Wo.set(s,u)),s.filter(p=>!!(e.sessions.byId[p.sessionId]||p.standIn)).map(p=>{const m=e.sessions.byId[p.sessionId]||p.standIn,f=p.sessionId===e.sessions.activeSessionId&&!e.sessions.listDeselected,h=l.has(p.sessionId),g=c.has(p.sessionId),b=[p,m,f,h,g,t,i,o,e.connection?.mode,e.sessions.selectMode,n,r,e.branding?.title,e.canvas?.bySessionId?.[p.sessionId],e.canvas?.prefs?.[p.sessionId],m?.pauseState,e.budget?.paused],y=u.get(p.sessionId);if(y&&ka(y.deps,b))return y.row;const v=Ih(p,m,e,n,r),S={sessionId:p.sessionId,text:wh(v.runs),...v,depth:p.depth,status:m?.status,statusColor:Ts(m,e.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:qd(m),ownerBadge:Li(e)&&!m?.isSystem&&!m?.isGroup&&ns(m,e.sessions.byId)?Dd(ns(m,e.sessions.byId),{isMine:!!(Pe(e?.auth?.principal)&&Pe(ns(m,e.sessions.byId))===Pe(e?.auth?.principal)),hueByKey:Bd(e.sessions.byId)}):null,orderable:Fs(m),orderContainer:uh(m,h),canvasMark:ig(e,p.sessionId),pause:v.chrome?.pause||null,searchMatch:p.searchMatch===!0,searchScore:Number(p.searchScore)||0};return u.set(p.sessionId,{deps:b,row:S}),S}).filter(p=>{if(t||d?.has(p.sessionId))return!0;const m=e.sessions.byId[p.sessionId];if(!Sa(m,i,o,e.sessions.byId))return!1;const f=ns(m,e.sessions.byId),h=f?`${pn(f,"")} ${f.email||""}`:"";return Ps(p.text,t)||Ps(p.sessionId,t)||Ps(h,t)})}function Fi(e,t=8){const s=us(e);if(s.length===0)return[];const n=new Set(s.map(p=>p.sessionId)),r=(Array.isArray(e.sessions?.flat)?e.sessions.flat:[]).filter(p=>n.has(p.sessionId)),i=r.findIndex(p=>p.sessionId===e.sessions.activeSessionId),o=Math.max(0,i);if(r.length<=t)return s;const l=Math.floor(t/2);let c=Math.max(0,o-l),d=Math.min(r.length,c+t);d>r.length&&(d=r.length,c=Math.max(0,d-t));const u=r.slice(c,d);return wa(e.sessions.byId),Ea(r,e.sessions.byId),s.filter(p=>u.some(m=>m.sessionId===p.sessionId))}function gt(e){const t=e.sessions.activeSessionId;return t&&e.sessions.byId[t]||null}function Mh(e){const t=e.sessions?.navigationIntent;if(!t||t.status!=="failed")return null;const s=t.errorKind==="not_found"?"not_found":"network";return{sessionId:t.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 mE(e){const t=e.sessions?.ownerFilterAutoAdmitted||null,s=t?.ownerKey&&Array.isArray(e.sessions?.ownerFilter?.ownerKeys)&&e.sessions.ownerFilter.ownerKeys.includes(t.ownerKey);if(t?.sessionId&&s&&e.sessions?.byId?.[t.sessionId]){const r=e.sessions.byId[t.sessionId]?.owner;return`Added ${pn(r,"its owner")} to your session filters so the linked session is listed.`}const n=e.sessions?.filterExceptionId||null;return!n||!e.sessions?.byId?.[n]?null:"Showing linked session outside your current filters."}function zd(e){return!e||e.isGroup?!1:(e.status||"")==="running"}function Kd(e=[],t=[],s=()=>!0){const n=new Set(t);for(let r=(e||[]).length-1;r>=0;r-=1){const i=e[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 _h(e,t=[]){const s=e?.pendingQuestion;if(!s?.question)return null;const n=[_i(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(`- ${_i(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:${e.sessionId}:${s.question}`,role:"system",text:n.join(`
33
- `),time:"",createdAt:Kd(t,["session.input_required_started"]),cardTitle:"Question",cardTitleColor:"cyan",cardBorderColor:"cyan"}}function $h(e,t=[]){const s=e?.answeredPendingQuestion,n=String(s?.question||"").trim(),r=String(s?.answer||"").trim();if(!n||!r||Vd(t,n))return null;const i=s.pendingPhase==="queued"?"queued":"pending",o=Number(s.answeredAt||0)||e.updatedAt||Date.now();return{id:`answered-question:${e.sessionId}:${n}:${o}`,role:"user",text:`The user was asked: "${n}"
34
- The user responded: "${r}"`,time:"",createdAt:o,optimistic:!0,pendingPhase:i}}function Rh(e,t){if(!e||!t?.id)return null;const s=String(t.text||"").trim();return s?{id:`pending-outbox:${e}:${t.id}`,role:"user",text:s,time:"",createdAt:Number(t.createdAt)||Date.now(),pendingPhase:t.phase==="cancelling"?"cancelling":t.phase==="rejected"?"rejected":t.phase==="queued"?"queued":"pending"}:null}function Vd(e,t){const s=String(t||"").trim();return s?(e||[]).some(n=>hr(n?.text||"")?.question?.trim()===s):!1}function Lh(e,t=[]){const s=String(e?.error||"").trim();if(!s||Kn(s))return null;const n=ga(e);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:${e.sessionId}`,role:"system",text:i,time:"",createdAt:Kd(t,["session.error","session.turn_completed"],o=>mr(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 qo(e=[],t){for(let s=e.length-1;s>=0;s-=1){const n=e[s];if(n?.eventType===t)return Number(n?.seq||0)}return 0}function Oh(e){const t=String(e||"").replace(/\s+/g," ").trim();return t?t.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function Fh(e,t=0){const s=Array.isArray(e?.activity)?e.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)<=t)continue;const o=Oh(i.text);if(o)return{...i,summaryText:o}}return null}function Dh(e,t,s=[],n=[]){if(!e||e?.pendingQuestion?.question)return null;const r=String(e?.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(t?.events)?t.events:[],f=qo(m,"user.message"),h=qo(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),v=y[y.length-1]||null,S=String(v?.data?.content||v?.data?.text||v?.data?.message||"").trim();if(S)return{kind:"thinking",label:"Thinking",text:S,createdAt:v?.createdAt||e.updatedAt||Date.now(),lastUserSeq:f,lastAssistantSeq:h,tokenSeq:v?.seq||0};const w=Fh(t,b);return w?.summaryText?{kind:r==="running"?"working":"sending",label:r==="running"?"Working":"Sending",text:w.summaryText,createdAt:w.createdAt||e.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||e.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||e.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||e.updatedAt||Date.now(),lastUserSeq:f,lastAssistantSeq:h,tokenSeq:0}:c?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:o?.createdAt||e.updatedAt||Date.now(),lastUserSeq:f,lastAssistantSeq:h,tokenSeq:0}:r==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:e.updatedAt||Date.now(),lastUserSeq:f,lastAssistantSeq:h,tokenSeq:0}:null}function Ia(e){const t=e.sessions.activeSessionId,s=t&&e.sessions.byId[t]||null;if(!t)return Sn(e.branding);if(s?.isGroup){const u=Object.values(e.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=e.history.bySessionId.get(t),r=n?.chat||[];if(!r.length&&n?.loadState==="loading"){const u=Sn(e.branding,s,{loading:!0});if(u.length)return u}if(!r.length&&["loading","failed"].includes(n?.loadState))return[{id:`history-load:${t}:${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&&!Vd(r,s.pendingQuestion.question)?_h(s,i):null,l=$h(s,r),c=s?.chatWarnings?.length?null:Lh(s,i);if((!n||r.length===0)&&!o&&!l&&!c&&!s?.chatWarnings?.length)return Sn(e.branding,s);const d=mm(r.length>0?r:Sn(e.branding,s),s,i);if(o&&d.push(o),l&&d.push(l),c){const u=d.findLastIndex(p=>p.kind==="session-warning"&&mr(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 Vr(e,t="gray",s={}){return[{text:e,color:t,bold:!!s.bold,underline:!!s.underline}]}function Yd(e){return e?.role==="user"&&e?.sender?.kind==="system"}function Bh(e,t={}){const s=Ke(e?.createdAt||e?.time),n=e?.sender,r=n?.kind==="user"?Pe(n):null,i=t?.viewerKey||null,o=t?.ownerKey||null,l=t?.sharedContext===!0,c=e?.role==="user",u=c&&!!r&&!!i&&!(c&&r&&i&&r===i),m=l&&c&&o&&(r&&r===o||!r&&i&&i===o)?" (owner)":"",f=Yd(e)?n?.display||"System":c?(u?n.display||n.subject||"User":"You")+m:e?.role==="assistant"?"Agent":e?.role==="system"?"System":"PilotSwarm";let h=null,g=null;e?.pendingPhase==="pending"?(h="○",g="yellow"):e?.pendingPhase==="queued"?(h="✓",g="cyan"):e?.pendingPhase==="cancelling"||e?.pendingPhase==="rejected"?(h="x",g="red"):e?.role==="user"&&!e?.optimistic&&!e?.pendingPhase&&(e?.stopped?(h="⊘",g="yellow"):e?.redelivered?(h="✓✓↻",g="yellow"):(h="✓✓",g="green"));const b=e?.pendingPhase==="pending"?"yellow":e?.pendingPhase==="queued"?"cyan":e?.pendingPhase==="cancelling"||e?.pendingPhase==="rejected"?"red":u?nh:e?.role==="user"?sh:e?.role==="assistant"?"green":e?.role==="system"?"yellow":"white";return{time:s,glyph:h,glyphColor:g,roleLabel:f,roleColor:b,fromOtherPerson:u}}function zo(e,t={}){const{time:s,glyph:n,glyphColor:r,roleLabel:i,roleColor:o}=Bh(e,t),l=s?`[${s}] `:"",c=[...Vr(l,"gray")];return n&&c.push(...Vr(`${n} `,r)),c.push(...Vr(`${i}: `,o,{bold:!0})),c}function Kt(e){return Array.isArray(e)?(e||[]).map(t=>t?.text||"").join(""):e?.kind==="markdownTable"?"[table]":String(e?.text||"")}function Xd(){return[{text:"",color:null}]}function Hh(e){const t=(e||[]).find(n=>Kt(n).trim().length>0);if(t?.kind==="markdownTable")return!0;const s=Kt(t).trimStart();return/^[┌│└]/.test(s)}function sr(e){const t=Array.isArray(e)?[...e]:[];for(;t.length>0;){const s=t[0];if(Kt(s).trim().length>0)break;t.shift()}return t}function Uh(e){const t=String(e||"").replace(/\r\n/g,`
38
- `),s=t.trim();if(!s)return null;if(s.startsWith("[SYSTEM:")&&s.endsWith("]"))return{leadingText:"",systemText:s.slice(8,-1).trim()};const n=t.lastIndexOf(`
39
-
40
- [SYSTEM:`);if(n>=0&&t.trimEnd().endsWith("]")){const r=t.slice(0,n).trimEnd(),i=t.slice(n+2).trim();if(i.startsWith("[SYSTEM:"))return{leadingText:r,systemText:i.slice(8,-1).trim()}}return jh.test(s)?{leadingText:"",systemText:s}:null}const jh=/^(?: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 Qd(e){const t=Uh(e);if(t){const o=[];t.leadingText&&o.push({kind:"text",text:t.leadingText});const l=zt(t.systemText);return l&&o.push({kind:"system",text:l}),o}const s=String(e||"").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=zt(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=zt(d.join(`
44
- `).trim());if(!p){o=u+1;continue}n.push({kind:"system",text:p}),o=u+1}return i(),n}function Gh(e){return e?e?.role==="system"?!la(e?.text||"")||!!zt(e?.text||""):e?.role!=="user"&&e?.role!=="assistant"?!1:Qd(e?.text||"").some(t=>t.kind==="system"):!1}function Ko(e){return Gh(e)?"system":e?.role||"other"}function Zd(e,t){return!e||!t||e.kind==="chat-call"||t.kind==="chat-call"?!1:Ko(e)!==Ko(t)}function Wh(e){const t=String(e||"").replace(/\s+/g," ").trim();if(!t)return"System notice.";const s=/^The session was dehydrated and has been rehydrated on a new worker(?: \(([^)]+)\))?\./.exec(t);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(t)?.[1]?.trim()||t;return r.length>=t.length?r.length>160?`${r.slice(0,159).trimEnd()}…`:r:`${r}…`}function qh(e,t=""){const s=Wh(e);return{kind:"systemNotice",text:`${t?`[${t}] `:""}System: ${s}`,summary:s,body:ss(e),color:"gray"}}function Di({title:e,summary:t,body:s,timestamp:n="",color:r="gray",callPreview:i,callKey:o}){const l=String(e||"System").trim()||"System",c=String(t||"").replace(/\s+/g," ").trim();return{kind:"systemNotice",text:`${n?`[${n}] `:""}${l}${c?`: ${c}`:""}`,summary:c,body:ss(s||c),color:r,...i!==void 0?{callPreview:`${l} — ${Ls(i)}`,callKey:o}:{}}}function zh(e){return e?.label?[{text:e.label,color:e.kind==="working"?"yellow":"cyan",bold:!0}]:null}function Kh(e,t){return t?(e||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||t})):s):e}function Vh(e){const t=(e||[]).find(s=>Kt(s).trim().length>0);return t?Kt(t).trimStart().startsWith("┌"):!1}function dn(e,t){!Array.isArray(t)||t.length===0||(e.length>0&&Vh(t)&&Kt(e[e.length-1]).trim().length>0&&e.push([{text:"",color:null}]),e.push(...t))}function Yh(e){const t=String(e||""),s=/^\s*Sub-agent\s+completed\b/i.test(t),n=/^\s*Sub-agents\s+completed/i.test(t);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(t))!==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 Xh(e,t,s){const n=Math.max(20,Number(s)||20),r=Ke(t?.createdAt||t?.time),i=Yh(e),o=l=>{const c=String(l||"").replace(/^session-/i,"");return Le(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[Di({title:`Sub-agent Response — ${l}`,callPreview:i.result||i.status,callKey:`${t.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[Di({title:`Sub-agent Responses (${i.agents.length})`,callPreview:i.agents.map(d=>Ls(d.result)||d.status).join(" · "),callKey:`${t.id}:agents`,summary:c,timestamp:r,body:l.join(`
49
-
50
- ---
51
-
52
- `),color:"cyan"})]}return Ue({title:"System",timestamp:r,body:e,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function Vo(e,t){const s=Math.max(12,Math.min(72,Number(t)||12)),n=Math.max(1,s-4),r=Ke(e?.createdAt||e?.time),i=String(e?.thinkingLabel||"Thinking…").trim()||"Thinking…",o=e?.progressKind==="working"?"yellow":(e?.progressKind==="sending","cyan"),l=_e([{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(e?.text||"").trim()?sr(ds(ss(e.text),{width:n})).flatMap(m=>jc(m,n)):[],p=[[{text:"┌─",color:"gray"},...l,{text:`${"─".repeat(d)}┐`,color:"gray"}]];for(const m of u)p.push([{text:"│ ",color:"gray"},...Uc(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 Qh(e){return String(e||"").split(`
53
- `).reduce((t,s)=>Math.max(t,ra(s).length),0)}const Yo=new WeakMap;function Ms(e,t,s={}){if(!e||typeof e!="object")return Xo(e,t,s);const n=JSON.stringify([t,s]);let r=Yo.get(e);if(r?.has(n))return r.get(n);const i=Xo(e,t,s);return r||(r=new Map,Yo.set(e,r)),r.size>=4&&r.delete(r.keys().next().value),r.set(n,i),i}function Xo(e,t,s={}){if(e?.kind==="chat-call")return s.tableMode==="sentinel"?[Yc(e)]:[];if(s.tableMode==="sentinel"&&(e?.sender?.kind==="agent"||e?.agentCallPreview!==void 0)){const d=e.cardTitle||e.sender?.display||"Agent message";return[{kind:"chatCall",callKey:e.id,category:"Agent",text:`${d} — ${Ls(e.agentCallPreview??e.text)}`,body:e.text,time:e.time}]}if(e?.splash){const d=e.mobileText&&Qh(e.text)>t;return[{kind:"markup",value:d?e.mobileText:e.text,splashAlt:!d&&e.mobileText?e.mobileText:null}]}if(e?.thinking)return Vo(e,t);if((e?.liveTurn||e?.streamSettling||e?.assistantPreview)&&s.tableMode==="sentinel"){const d=!e?.assistantPreview&&!!(e?.liveTurn||e?.streamSettling);return[{kind:"assistantPreview",width:t,text:d?"Message preview":"Agent update",statusText:d?e?.liveTurn?e?.text?"Responding":"Thinking":e?.streamSettling?"Finishing":"":"",previewKey:`assistant:${e?.liveKey||e?.messageId||e?.id||"active-turn"}`,body:ss(e?.text||""),reasoningText:String(e?.reasoningText||e?.liveReasoningText||""),isLive:e?.liveTurn===!0,final:e?.responseFinal===!0,truncated:e?.truncated===!0,liveStartedAt:Number(e?.liveStartedAt||e?.createdAt)||0,time:e?.time||"",headerRuns:zo(e,s)}]}if(e?.liveTurn&&s.tableMode!=="sentinel"&&e.reasoningText){const d=Vo({...e,text:e.reasoningText},t);return e.text?[...d,...Ms({...e,reasoningText:""},t,s)]:d}if(e?.noChrome)return sr(ds(ss(e?.text||""),{width:Math.max(20,t),tableMode:s.tableMode}));if(e?.role==="user"){const d=hr(e?.text||"");if(d)return[...d.question==="a question"?[]:Ue({title:"Question",timestamp:Ke(e?.createdAt||e?.time),body:_i(d.question),width:Math.max(20,t),titleColor:Kr,borderColor:Kr,tableMode:s.tableMode}),...Ms({...e,text:d.answer},t,s)]}if(s.allowLeadingSystemNotices!==!1&&(e?.role==="user"||e?.role==="assistant")){const d=Qd(e?.text||"");if(d.some(u=>u.kind==="system")){const u=[];let p=!1;for(const f of d)f.kind!=="system"&&f.text.trim()&&(dn(u,Ms({...e,text:f.text},t,{...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()||dn(m,Xh(f.text,e,t));if(m.length>0)return m}}if(Yd(e))return[Di({title:e?.sender?.display||"Agent kickoff",summary:"opening instruction",timestamp:Ke(e?.createdAt||e?.time),body:e?.text||"",color:"gray"})];if(e?.role!=="user"&&e?.role!=="assistant"){const d=zt(e?.text||"");if(e?.role==="system"&&!d)return[];const u=!!e?.cardTitle&&String(e.cardTitle).toLowerCase()!=="system";if(e?.role==="system"&&!u)return[qh(d||e?.text||"",Ke(e?.createdAt||e?.time))];const p=e?.role==="system"&&(!e?.cardTitle||String(e.cardTitle).toLowerCase()==="system");return Ue({title:e?.cardTitle||(e?.role==="system"?"System":"PilotSwarm"),cardKey:e?.id,timestamp:Ke(e?.createdAt||e?.time),body:ss(e?.text||""),width:Math.max(20,t),titleColor:e?.cardTitleColor||(e?.role==="system"?"yellow":"cyan"),borderColor:e?.cardBorderColor||"gray",tableMode:s.tableMode,...p?{bodyColor:"gray",fitToContent:!0}:{}})}const n=sr(ds(ss(e?.text||""),{width:t,tableMode:s.tableMode})),r=Kh(n,e?.pendingPhase==="cancelling"?"red":e?.role==="user"?Kr:null),i=s.skipPrefix?[]:zo(e,s),o=Zh(e,s);if(r.length===0){const d=i.length>0?[i]:[];return o.length>0?[...d,...o]:d}if(Hh(r)){const d=i.length>0?[i,...r]:r;return e?.streaming&&Qo(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 e?.streaming&&Qo(l),l.push(...o),l}function Qo(e){const t=[...e].reverse().find(s=>Array.isArray(s)&&s.some(n=>String(n?.text||"").trim()));t?t.push({text:" ▍",color:"cyan",role:"streamingCaret"}):e.push([{text:"▍",color:"cyan",role:"streamingCaret"}])}function Zh(e,t={}){const s=Array.isArray(e?.attachments)?e.attachments:[];return s.length===0?[]:t.tableMode==="sentinel"?[{kind:"imageAttachments",sessionId:String(e?.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 Jh=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 eg(e){const t=Math.max(0,Math.floor((Number(e)||0)/1e3));if(t<60)return`${t}s`;const s=Math.floor(t/60),n=t%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 tg=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),sg=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function ng(e,t){const s=String(e||"").toLowerCase();return s==="search_skills"||s.includes("skill")?t?"loading skills…":"loaded skills":tg.has(s)?t?"reading facts…":"read facts":sg.has(s)?t?"writing facts…":"wrote facts":s.startsWith("graph_")?/upsert|delete|archive|merge|remove|set_/.test(s)?t?"writing to the graph…":"wrote to the graph":t?"reading the graph…":"read the graph":s.startsWith("facts_")||s.endsWith("_fact")||s.endsWith("_facts")?/store|write|set|delete|purge|update/.test(s)?t?"writing facts…":"wrote facts":t?"reading facts…":"read facts":""}function rg(e){const t=String(e?.eventType||"");if(t==="tool.execution_start"||t==="tool.execution_complete"){const n=(String(e?.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=ng(n,t==="tool.execution_start");if(r)return r;const i=n.length>28?`${n.slice(0,27)}…`:n;return t==="tool.execution_start"?`running tool: ${i}…`:`finished tool: ${i}`}switch(t){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(e?.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 br(e,t={}){const s=gt(e);if(!s||s.isGroup)return[];if(String(s?.status||"").toLowerCase()!=="running")return[];const r=e.history?.bySessionId?.get(s.sessionId)||null,i=Array.isArray(r?.chat)?r.chat:[];let o=0;for(let v=i.length-1;v>=0;v-=1)if(i[v]?.role==="user"){o=Number(i[v]?.createdAt||0);break}const l=Array.isArray(r?.activity)?r.activity:[];let c=0,d=0;for(let v=l.length-1;v>=0;v-=1){const S=l[v],w=S?.eventType,E=Number(S?.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 v=l.length-1;v>=0;v-=1){const S=l[v];if(!(!S||Jh.has(S.eventType))){if(Number(S.createdAt||0)<=d)break;p=S;break}}const m=Number.isFinite(t.now)?t.now:Date.now(),f=u>0?eg(m-u):"",h=String(t.spinnerFrame||"").trim()||"●",g=p?rg(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(t.maxWidth)||80)));return[_e(b,y)]}const Zo=4;let wn=[];function xa(e,t=80,s={}){const n=e?.sessions?.activeSessionId??null,r=n?e?.sessions?.byId?.[n]??null:null,i={sessionId:n,session:r,byId:e?.sessions?.byId??null,chat:e?.history?.bySessionId?.get?.(n)?.chat??null,events:r?.chatWarnings?.length||r?.error||r?.pendingQuestion?e?.history?.bySessionId?.get?.(n)?.events??null:null,branding:e?.branding??null,principal:e?.auth?.principal??null,maxWidth:t,tableMode:s?.tableMode??null};for(const g of wn)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=>(wn.unshift({...i,lines:g}),wn.length>Zo&&(wn.length=Zo),g),l=Ia(e);if(!l||l.length===0)return o([{text:"No messages yet.",color:"gray"}]);const c=Pe(e?.auth?.principal),d=e?.sessions?.activeSessionId,u=d?e?.sessions?.byId?.[d]:null,p=Pe(u?.owner),m=!!(u&&(u.visibility&&u.visibility!=="private"||p&&c&&p!==c||c&&l.some(g=>g?.role==="user"&&g?.sender?.kind==="user"&&Pe(g.sender)&&Pe(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 v={starting:"Starting",running:"Running",waiting:"Waiting",completed:"Done",failed:"Failed",cancelled:"Cancelled",interrupted:"Interrupted"};dn(h,Ms({...b,cardTitle:"Native tasks",cardTitleColor:"cyan",cardBorderColor:"cyan",text:b.tasks.map(S=>`[${v[S.status]||S.status}] ${S.title}`+(S.toolCalls?` · ${S.toolCalls} calls`:"")+(S.error||S.result||S.preview?`
54
- ${String(S.error||S.result||S.preview).replace(/\s+/g," ").slice(0,240)}`:"")).join(`
55
-
56
- `)},t,f))}else if(b?.kind==="epoch-divider")h.push(cg(b,t));else if(b?.kind==="regen-refused")h.push(ug(b,t));else if(b?.kind==="regen-failed")h.push(pg(b,t));else if(b?.kind==="canvas-update")h.push(lg(b,b.sessionId||n));else if(b?.kind==="canvas-action")h.push(og(b));else{const v=Ms(b,t,f);dn(h,v)}const y=l[g+1];y&&Zd(b,y)&&Kt(h[h.length-1]).trim().length>0&&h.push(Xd())}return o(h.length>0?h:[{text:"No messages yet.",color:"gray"}])}function ig(e,t){if(!t)return null;let s=null;for(let n=1;n<=5;n+=1){const r=ut(t,n),i=e?.canvas?.bySessionId?.[r],o=e?.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 Jo=null;function Aa(e){const t=e?.sessions?.activeSessionId||null,s=e?.canvas?.bySessionId,n=e?.canvas?.prefs,r=e?.ui?.canvasSlot,i=e?.ui?.canvasOpen,o=e?.canvas?.flipSeq,l=Jo;if(l&&l.sessionId===t&&l.bySessionId===s&&l.prefs===n&&l.canvasSlot===r&&l.canvasOpen===i&&l.flipSeq===o)return l.result;const c=ag(e);return Jo={sessionId:t,bySessionId:s,prefs:n,canvasSlot:r,canvasOpen:i,flipSeq:o,result:c},c}function ag(e){const t=e?.sessions?.activeSessionId||null,s=Number(e?.ui?.canvasSlot)||1,n=e?.canvas?.bySessionId||{},r=[];if(t)for(let g=1;g<=5;g+=1){const b=n[ut(t,g)];if(!b||(b.latestRev||0)<=0||b.sizeBytes===0)continue;const y=e?.canvas?.prefs?.[ut(t,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=t?ut(t,i):null,l=o?n[o]:null,c=o?e?.canvas?.prefs?.[o]:null,d=l?.latestRev||0,u=c?.lastViewedRev||0,p=l?.latestDataRev||0,m=c?.lastViewedDataRev||0,f=e?.ui?.canvasOpen?"canvas":"panes",h=d>0&&l?.sizeBytes!==0;return{sessionId:t,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:e?.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 og(e){const t=e?.data&&typeof e.data=="object"?Object.keys(e.data):[],s=t.length===1&&typeof e.data[t[0]]=="string"?e.data[t[0]].slice(0,120):t.length?JSON.stringify(e.data).slice(0,120):"";let n="";if(t.length)try{n=JSON.stringify(e.data,null,2)}catch{n=""}return{runs:[{text:"[canvas] ",color:"cyan",bold:!0},{text:`${e.action||"action"}`,color:"white"},...s?[{text:` — ${s}`,color:"gray"}]:[]],canvasAction:!0,canvasActionName:e?.action||"action",canvasActionDetail:s,canvasActionPayload:n,canvasActionTime:e?.time||""}}function lg(e,t){const s=Number(e?.rev)||0,n=typeof e?.note=="string"&&e.note.trim()?` — ${e.note.trim()}`:"",r=[{text:"[canvas] ",color:"cyan",bold:!0},{text:`rev ${s}${n} `,color:"white"}];return t&&(r.push({text:"[artifact: canvas.html]",color:"cyan",underline:!0,href:`artifact://${t}/canvas.html`}),r.push({text:" (press a to download)",color:"gray"})),{runs:r,canvasUpdate:!0}}function Na(e,t,s){const r=Math.max(24,Number(s)||80)-e.length;if(r<2)return[{text:e.trim(),color:t,bold:!0}];const i=Math.min(6,Math.floor(r/2));return i<1?[{text:e.trim(),color:t,bold:!0}]:[{text:"─".repeat(i),color:t},{text:e,color:t,bold:!0},{text:"─".repeat(i),color:t}]}function cg(e,t){const s=Number.isFinite(e?.turnsArchived)?e.turnsArchived:null,n=` ↻ context regenerated · epoch ${e?.epoch??"?"}${s!=null?` · ${s} turn${s===1?"":"s"} archived`:""} `;return Na(n,"magenta",t)}const dg={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 ug(e,t){const s=String(e?.reason||"unknown"),r=` ↻ regeneration refused · ${dg[s]||s.replace(/_/g," ")} `;return Na(r,"yellow",t)}function pg(e,t){const s=String(e?.stage||"unknown"),n=String(e?.error||"").split(`
57
- `)[0],r=n.length>120?`${n.slice(0,117)}…`:n,i=` ✕ regeneration failed at ${s}${r?` · ${r}`:""} `;return Na(i,"red",t)}function Jd(e){const t=e.sessions.activeSessionId;return t?Array.isArray(e.outbox?.bySessionId?.[t])?e.outbox.bySessionId[t].map(s=>Rh(t,s)).filter(Boolean):[]:[]}function Ca(e,t=80,s={}){const n=Jd(e);if(!n||n.length===0)return[];const r=Math.max(20,Number(t)||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()){dn(m,Ms(g,r,f));const b=n[h+1];b&&Zd(g,b)&&Kt(m[m.length-1]).trim().length>0&&m.push(Xd())}return m}function mg(e){const t=Ia(e),s=[],n=new Set;for(const r of t||[])for(const i of Yp(r?.text||"")){const o=`${i.sessionId}/${i.filename}`;n.has(o)||(n.add(o),s.push(i))}return s}function fg(e){const t=Ia(e),s=[],n=new Set;for(const r of t||[])for(const i of Xp(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 Ta(e,t){const s=Rs(e);if(!s)return"";const n=String(t||"").trim();return n?`${s}:${n}`:s}function hg(e){return Rs(e)||"(unknown)"}function eu(e,t={}){const s=gt(e),n=e.sessions?.byId||{},r=Array.isArray(e.sessions?.flat)?e.sessions.flat:[],i=wa(n),o=Ea(r,n),l=_d(t?.width);if(!s)return{color:"cyan",title:vt("Chat","cyan"),titleRight:null,animateTitleRight:!1};const c=Le(s.sessionId),d=s.isSystem?"yellow":"cyan",u=vt(s.isSystem?`⚙ ${ps(s,e.branding?.title||"PilotSwarm")}`:ba(s)||"Chat",d),p=r.find(w=>w.sessionId===s.sessionId),m=Wd(s.sessionId,p,i,o);m&&u.push({text:` ${m.text}`,color:m.color}),l||u.push({text:` [${c}]`,color:"gray"});const f=e.history?.bySessionId?.get(s.sessionId)||null,h=Array.isArray(e.outbox?.bySessionId?.[s.sessionId])?e.outbox.bySessionId[s.sessionId]:[],g=Dh(s,f,f?.chat||[],h),b=e.connection?.mode||"local",y=kh(s,b),v=zh(g),S=v?[...y,...y.length?[{text:" · ",color:"gray"}]:[],...v]:y;return{color:s.isSystem?"yellow":"cyan",title:u,titleRight:S.length?S:null,animateTitleRight:!!g}}function gg(e){const t=e.sessions.activeSessionId;return t?e.history.bySessionId.get(t)?.activity||[]:[]}function tu(e){const t=du(e),s=t.selected?t.nodes.find(o=>o.label===t.selected):null,n=vt("Worker","gray");if(!s)return n.push({text:" none",color:"gray"}),{title:n,lines:[{text:t.degraded&&t.registryError?`No worker selected — ${t.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?kt(o.text):{text:o.text,color:o.color,bold:o.bold});return s.executing.length===0&&r.push({text:`Nothing executing in the ${t.windowLabel} window.`,color:"gray"}),{title:n,lines:r}}function Pa(e,t=12){const s=gg(e),n=gt(e),r=vt("Activity","gray");return n?.isGroup?{title:r,disabled:!0,lines:[{text:mu,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 su(e){switch(String(e||"").toLowerCase()){case"error":return"red";case"warn":return"yellow";case"debug":return"blue";case"trace":return"magenta";default:return"green"}}function nu(e,t){return e==="orchestration"?"magenta":e==="activity"?"cyan":su(t)}function yg(e){return e==="raw"?"raw summary":"pretty text"}function bg(e){return e?.sessionId?`session-${e.sessionId}`:null}function Sg(e,t){const s=Array.isArray(e.logs?.entries)?e.logs.entries:[],n=e.logs?.filter||{},r=bg(t);return s.filter(i=>!(!i||n.source==="currentOrchestration"&&r&&i.orchId!==r||n.level&&n.level!=="all"&&String(i.level||"").toLowerCase()!==n.level))}function vg(e){const t=fn(e?.podName)||e?.podName||"node",s=e?.sessionId||(String(e?.orchId||"").startsWith("session-")?String(e.orchId).slice(8):""),n=String(e?.level||"info").toUpperCase(),r=e?.category==="orchestration"?"◆":e?.category==="activity"?"●":"•";return[{text:`[${e?.time||"--:--:--"}] `,color:"gray"},{text:`${r} `,color:nu(e?.category,e?.level)},{text:`${t} `,color:"white",bold:!0},...s?[{text:`[${Le(s)}] `,color:"gray"}]:[],{text:`${n} `,color:su(e?.level),bold:!0},{text:e?.rawLine||e?.message||"",color:"white"}]}function wg(e){const t=e?.sessionId||(String(e?.orchId||"").startsWith("session-")?String(e.orchId).slice(8):"");return[{text:`${t?`[${Le(t)}] `:""}${e?.prettyMessage||e?.message||e?.rawLine||""}`,color:nu(e?.category,e?.level),bold:String(e?.level||"").toLowerCase()==="warn"||String(e?.level||"").toLowerCase()==="error"}]}function Eg(e,t){const s=e.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:yg(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=Sg(e,t);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"?vg(o):wg(o))]}function el(e){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(e||""))}function kg(e){return/\.(json|jsonl)$/i.test(String(e||""))}function Ig(e){return wt.map(t=>({text:t===e?`[${t}] `:`${t} `,color:t===e?"magenta":"gray",bold:t===e}))}function xg(e=""){const t=String(e||"").split(`
58
- `);return t.length>0?t.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function tl(e,{selected:t=!1,width:s=24,label:n=null}={}){const r=Math.max(8,s),i=el(e)?"# ":kg(e)?"{ ":"• ",o=iu(`${i}${n||e}`,r).padEnd(r," ");return t?kt(o):{text:o,color:el(e)?"cyan":"white",bold:!1}}function ft(e){return e.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function Ag(e,t={}){if(!e)return new Set;const{childMap:s}=va(t),n=new Set([e]),r=[e];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 nr(e,t=ft(e)){const s=gt(e)?.sessionId||null,n=Array.isArray(e.sessions?.flat)?e.sessions.flat.map(c=>c?.sessionId||c).filter(Boolean):[],r=Object.keys(e.files?.bySessionId||{}).filter(Boolean);if(t==="allSessions")return[...new Set([...n,...r])];const i=Ag(s,e.sessions?.byId||{});if(i.size===0)return[];const o=[],l=new Set;for(const c of[s,...n,...Object.keys(e.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 sl(e){const s=gt(e)?.sessionId;if(!s)return[];const r=e.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 rs(e){const t=ft(e);gt(e)?.sessionId;const s=e.files?.filter?.query||"",n=nr(e,t),r=t==="allSessions"||n.length>1,i=[];for(const o of n){const l=Zn(e.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?`[${Le(o)}] ${d}`:d})}}return i.filter(o=>Ps(o.filename,s)||Ps(o.sessionId,s)||Ps(o.label,s))}function jt(e){const t=rs(e);if(t.length===0)return null;const s=e.files?.selectedArtifactId||null;if(s){const o=t.find(l=>l.id===s);if(o)return o}if(ft(e)==="allSessions"){const o=gt(e)?.sessionId||null,l=o&&e.files?.bySessionId?.[o]?.selectedFilename||null;if(o&&l){const c=t.find(d=>d.sessionId===o&&d.filename===l);if(c)return c}return t[0]}const r=gt(e)?.sessionId||null,i=r&&e.files?.bySessionId?.[r]?.selectedFilename||null;return t.find(o=>o.sessionId===r&&o.filename===i)||t[0]}function Ma(e,t={}){const s=gt(e),n=Math.max(12,Number(t?.listWidth)||Number(t?.width)||24),r=Math.max(18,Number(t?.previewWidth)||Number(t?.width)||36),i=t?.showHints!==!1,o=s?.sessionId||null,l=ft(e),c=e.files?.filter?.query||"",d=rs(e),u=jt(e),p=u?.filename||null,m=Math.max(0,d.findIndex(R=>R.id===u?.id)),f=u?.sessionId&&p&&e.files?.bySessionId?.[u.sessionId]?.previews?.[p]||null,h=f||u?.entry||null,g=s?Le(s.sessionId):"",b=nr(e,l),y=l!=="allSessions"&&b.some(R=>R&&R!==o),v=[...new Set([...Array.isArray(e.sessions?.flat)?e.sessions.flat.map(R=>R?.sessionId||R):[],...Object.keys(e.files?.bySessionId||{})])].filter(Boolean),S=l==="allSessions"&&v.some(R=>!e.files?.bySessionId?.[R]?.loaded||e.files?.bySessionId?.[R]?.loading),w=l==="allSessions"&&v.map(R=>e.files?.bySessionId?.[R]?.error).find(Boolean)||null,E=[Ig("files"),...s||l==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(l==="allSessions")S&&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((R,H)=>tl(R.filename,{selected:H===m,width:n,label:R.label})));else if(s){const R=o?e.files?.bySessionId?.[o]:null;Array.isArray(R?.entries)&&R.entries;const H=d.filter(x=>b.includes(x.sessionId));R?.loading?E.push({text:"Loading exported files…",color:"gray"}):R?.error?E.push({text:R.error,color:"red"}):H.length===0&&b.every(x=>{const P=e.files?.bySessionId?.[x]?.entries;return!Array.isArray(P)||P.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(...H.map((x,P)=>tl(x.filename,{selected:P===m,width:n,label:x.label})))}let I,T;!s&&l!=="allSessions"?(T=[{text:"Preview",color:"cyan",bold:!0}],I=[{text:"No session selected.",color:"gray"}]):p?f?.loading?(T=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||u?.sessionId&&u.sessionId!==o)&&u?.sessionId?[{text:` · ${Le(u.sessionId)}`,color:"gray"}]:[]],I=[{text:"Loading file preview…",color:"gray"}]):f?.error?(T=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||u?.sessionId&&u.sessionId!==o)&&u?.sessionId?[{text:` · ${Le(u.sessionId)}`,color:"gray"}]:[]],I=[{text:f.error,color:"red"}]):(T=[{text:`Preview: ${p}`,color:"cyan",bold:!0},...(l==="allSessions"||u?.sessionId&&u.sessionId!==o)&&u?.sessionId?[{text:` · ${Le(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"}]:[]],I=f?.renderMode==="markdown"?sr(ds(f?.content||"",{width:r})):xg(f?.content||"")):(T=[{text:"Preview",color:"cyan",bold:!0}],I=[{text:"Select a file to preview it here.",color:"gray"}]);const C=l==="allSessions"?"Files: all sessions":s?`Files: ${g}${y?" tree":""}`:"Files",k=l==="allSessions"?"all sessions":s?`${g}${y?" tree":""}`:"Files",O=l==="allSessions"?`Artifacts${d.length>0?` [${d.length}]`:""}`:`Artifacts${y?" tree":""}${d.length>0?` [${d.length}]`:""}`,N=c?` · @${c}`:"";return{panelTitle:[{text:`${C}${N}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${k}${N}`,color:"magenta",bold:!0}],listTitle:[{text:`${O}${N}`,color:"cyan",bold:!0}],listLines:E,listBodyLines:E.slice(1),selectedIndex:m,selectedFilename:p,selectedSessionId:u?.sessionId||null,scope:l,previewTitle:T,previewLines:I,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:e.ui.scroll.filePreview||0,fullscreen:!!e.files?.fullscreen,fullscreenTitle:[{text:C,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 nl(e){if(!e)return"—";const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"—":t.toISOString().slice(0,10)}function Es(e){const t=Number(e)||0;return t<=0?"0 B":t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Ng(e){const t=String(e||"").toLowerCase();return t.endsWith(".md")?"markdown":t.endsWith(".json")?"json":/\.(mjs|cjs|js)$/.test(t)?"javascript":"text"}function $t(e){const t=e.admin||{},s=t.profile||null,n=t.ghcpKey||{editing:!1,draft:"",saving:!1,error:null},r=s?{provider:s.provider||"",subject:s.subject||"",email:s.email||null,displayName:s.displayName||null}:e.auth?.principal||null,i=t.systemGhcpKey||{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null},o=!!s?.isAdmin,l=e.auth?.adminScope??s?.adminScope??"unrestricted",c=o&&l==="unrestricted",d=t.modelProviders||{},u=Array.isArray(d.providers)?d.providers:[],p=Array.isArray(d.models)?d.models:[],m=u.filter(M=>M?.class!=="shared"&&(M?.mine===!0||M?.usableByMe===!0)),f=u.filter(M=>M?.class==="shared"),h=M=>M.flatMap(K=>p.filter(re=>re?.providerId===K.name||re?.providerId===K.typeId).map(re=>{const ye=re?.modelName||re?.name||String(re?.qualifiedName||"").split(":").pop(),Me=re?.providerId===K.name&&re?.qualifiedName?re.qualifiedName:`${K.name}:${ye}`;return{provider:K.name,providerClass:K.class,model:ye,qualifiedName:Me,supportedReasoningEfforts:Array.isArray(re?.supportedReasoningEfforts)?re.supportedReasoningEfforts:[],defaultReasoningEffort:re?.defaultReasoningEffort||null,supportedContextTiers:Array.isArray(re?.supportedContextTiers)?re.supportedContextTiers:[],defaultContextTier:re?.defaultContextTier||null}})),g=d.defaults||{},b=new Map;for(const M of p)!M?.providerId||b.has(M.providerId)||b.set(M.providerId,{id:M.providerId,label:M.providerType||M.providerId,usesWorkloadIdentity:th(M.providerType)});const y=M=>({name:M.name,typeId:M.typeId||M.type||null,usesWorkloadIdentity:b.get(M.typeId||M.type)?.usesWorkloadIdentity===!0,class:M.class==="shared"?"shared":"personal",hasCredential:!!M.hasCredential,usableByMe:M.usableByMe!==!1,systemUseEnabled:!!M.systemUseEnabled,systemEligible:!!M.systemEligible,isClusterDefault:!!M.isClusterDefault,isMyDefault:!!M.isMyDefault,isSystemDefault:!!M.isSystemDefault}),v=o&&Array.isArray(g.systemOverrides)?g.systemOverrides:[],S=new Map(v.map(M=>[M.agentId,M])),w=new Map;for(const M of Object.values(e.sessions?.byId||{}))!M?.isSystem||!M?.agentId||w.has(M.agentId)||w.set(M.agentId,{agentId:M.agentId,title:ps(M,e.branding?.title||"PilotSwarm")});for(const M of v)w.has(M.agentId)||w.set(M.agentId,{agentId:M.agentId,title:M.agentId});const E=g.system?.effective||null,I=[...w.values()].sort((M,K)=>M.title.localeCompare(K.title)).map(M=>{const K=S.get(M.agentId)||null;return{...M,effectiveModel:(K||E)?.model||null,source:K?"agent_override":E?.source||"system_default",override:K}}),T=d.selection||{},C=d.page==="shared"&&o?"shared":"mine",k={loading:!!d.loading,error:d.error||null,page:C,providerTypes:[...b.values()].sort((M,K)=>M.id.localeCompare(K.id)),myProviders:m.map(M=>({...y(M),selected:M.name===T.providerName})),sharedProviders:f.map(M=>({...y(M),selected:M.name===T.providerName})),userChoices:h([...f.filter(M=>M.usableByMe!==!1),...m.filter(M=>M.usableByMe!==!1)]),clusterChoices:o?h(f):[],systemChoices:o?h([...f,...m.filter(M=>M.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:v,systemAgentRoutes:o?I.map(M=>({...M,selected:M.agentId===T.agentId})):[],selection:{focus:T.focus==="agents"?"agents":"providers",providerName:T.providerName||(C==="shared"?f[0]?.name:m[0]?.name)||null,agentId:T.agentId||I[0]?.agentId||null},mutation:{pending:d.mutation?.pending||null,error:d.mutation?.error||null}},O=o&&!!n.storeAsSystem,N=O?!!i.configured:!!s?.githubCopilotKeySet,R=O?"System key":"key",H=i.configured&&i.changedBy?` (set by ${i.changedBy})`:"",x=n.saving?"Saving...":n.editing?"Editing — Enter to save, Esc to cancel":O?i.configured?`System key configured — ownerless system sessions use it for GitHub Copilot models${H}`:"System key not configured — ownerless system sessions fall back to env GITHUB_TOKEN":s?.githubCopilotKeySet?"Configured (overrides env GITHUB_TOKEN for this user)":"Not configured (using env GITHUB_TOKEN fallback)",P=t.packages||{},_=Array.isArray(P.list)?P.list:[],$=M=>!!(c||M?.owner&&r&&M.owner.provider===r.provider&&M.owner.subject===r.subject),B=M=>$(M)||!!M?.canEdit,j=mh(e?.sessions?.byId),W=Bd(e?.sessions?.byId),A=new Set;for(const M of _){if(M?.scope==="shared")continue;const K=Pe(M?.owner)||String(M?.createdBy||"").trim().toLowerCase();!K||K===mn||A.add(K)}const G=A.size>1,D=(M,K,re)=>`${M}${K==="shared"?"shared":"user"}${K==="shared"?"":re?.subject??""}`,Y=P.selectedName?D(P.selectedName,P.selectedSelector?.scope??null,P.selectedSelector?.owner??r??null):null,J=M=>t.section!=="packages"||P.selectedName!==M.name?!1:P.selectedSelector?.scope?D(M.name,M.scope,M.owner)===Y:!0,te=M=>({name:M.name,scope:M.scope==="shared"?"shared":"user",owner:M.owner??null,enabled:!!M.enabled,semver:M.active?.semver||null,sha7:M.active?.sha256?String(M.active.sha256).slice(0,7):null,agentCount:Array.isArray(M.active?.manifest?.agents)?M.active.manifest.agents.length:0,canManage:B(M),ownerBadge:M.scope==="shared"||!G?null:Dd(fh(M,j),{hueByKey:W}),selected:J(M)}),Z=M=>!!(M?.owner&&r&&M.owner.provider===r.provider&&M.owner.subject===r.subject),ne=e.sessions?.ownerFilter,ae=M=>{if(!ne||ne.all===!0)return!0;const K=Pe(M?.owner);return K?Array.isArray(ne.ownerKeys)&&ne.ownerKeys.includes(K):ne.includeUnowned===!0},oe=_.filter(M=>M.scope==="shared").map(te),ve=_.filter(M=>M.scope!=="shared"&&Z(M)).map(te),be=_.filter(M=>M.scope!=="shared"&&!Z(M)&&ae(M)).map(M=>({...te(M),ownerLabel:M?.createdBy||M?.owner?.subject||"another user"})),Q=["providers","packages","workers","features"].includes(t.section)?t.section:"providers",ce=[{id:"providers",kind:"section",depth:0,label:"Model Providers",selected:!1},{id:"myProviders",kind:"subsection",depth:1,label:"My Providers",selected:Q==="providers"&&C==="mine"},...o?[{id:"sharedProviders",kind:"subsection",depth:1,label:"Shared Providers",selected:Q==="providers"&&C==="shared"}]:[],{id:"features",kind:"section",depth:0,label:"Feature flags",selected:Q==="features"},{id:"agents",kind:"section",depth:0,label:"Packages",selected:Q==="packages"&&!P.selectedName},{id:"group:shared",kind:"group",depth:1,label:"Shared",count:oe.length},...oe.map(M=>({id:`pkg:shared:${M.name}`,kind:"package",depth:2,label:M.name,...M})),{id:"group:user",kind:"group",depth:1,label:"User",count:ve.length},...ve.map(M=>({id:`pkg:user:${M.name}`,kind:"package",depth:2,label:M.name,...M})),...be.length>0?[{id:"group:others",kind:"group",depth:1,label:"Other users",count:be.length},...be.map(M=>({id:`pkg:user:${M.owner?.subject??"?"}:${M.name}`,kind:"package",depth:2,label:M.name,...M}))]:[],...o?[{id:"workers",kind:"section",depth:0,label:"Workers",selected:Q==="workers"}]:[]],ge=P.detail||null;let Qe=null;if(P.selectedName){const M=_.filter(pe=>pe.name===P.selectedName),K=(P.selectedSelector?.scope?M.find(pe=>D(pe.name,pe.scope,pe.owner)===Y):M[0])??M[0]??null,re=ge?.versions?.find(pe=>pe.versionId===ge.activeVersionId)||null,ye=re?.manifest||K?.active?.manifest||{},We=Date.now()-9e4,at=(Array.isArray(P.workerState)?P.workerState:[]).filter(pe=>{const U=pe?.updatedAt instanceof Date?pe.updatedAt:new Date(pe?.updatedAt??0);return!Number.isNaN(U.getTime())&&U.getTime()>=We}),qe=at.length,xt=pe=>{const U=pe.installed||{},q=ge?.scope||K?.scope||P.selectedSelector?.scope||null,le=ge?.owner?.subject||K?.owner?.subject||P.selectedSelector?.owner?.subject||"",he=q==="user"?`${P.selectedName}#user${le?`:${le.slice(0,8)}`:""}`:`${P.selectedName}#shared`;return U[he]??U[P.selectedName]},we=re?at.filter(pe=>xt(pe)?.semver===re.semver&&xt(pe)?.status==="ok").length:0,ze=K??ge,At=ze?$(ze):!1,Cr=ze?B(ze):!1;Qe={name:P.selectedName,loading:!!P.detailLoading,error:P.detailError||null,scope:(ge?.scope||K?.scope)==="shared"?"shared":"user",enabled:ge?!!ge.enabled:!!K?.enabled,canManage:At,canEdit:Cr,editors:Array.isArray(ge?.editors)?ge.editors.map(pe=>({provider:pe.provider,subject:pe.subject,label:pe.displayName||pe.email||pe.subject,grantedByDisplay:pe.grantedByDisplay||null})):[],createdBy:ge?.createdBy||K?.createdBy||null,createdAtText:nl(ge?.createdAt||K?.createdAt),description:typeof ye.description=="string"?ye.description:"",activeSemver:re?.semver||K?.active?.semver||null,activeSha12:re?.sha256?String(re.sha256).slice(0,12):null,sizeText:Es(re?.sizeBytes??K?.active?.sizeBytes),agents:Array.isArray(ye.agents)?ye.agents.map(pe=>({name:pe.name,description:pe.description||"",toolCount:Array.isArray(pe.tools)?pe.tools.length:0,skillCount:Array.isArray(pe.skills)?pe.skills.length:0})):[],versions:(ge?.versions||[]).map(pe=>({semver:pe.semver,sha12:String(pe.sha256||"").slice(0,12),dateText:nl(pe.createdAt),active:pe.versionId===ge?.activeVersionId})),fleet:qe>0&&re?{current:we,total:qe,text:`${we}/${qe} workers current`}:null,actionPending:P.action?.pending||null,actionError:P.action?.error||null,hasSharedCounterpart:M.some(pe=>pe.scope==="shared"),hasOwnUserCounterpart:M.some(pe=>pe.scope!=="shared"&&Z(pe)),copyCount:M.length}}const $e=P.workspace||{};let it=null;if(P.selectedName){const M=$e.tree,K=new Set($e.expandedDirs||[]),re=[];if(M){const Me=we=>{const ze=we.split("/");for(let At=1;At<ze.length;At++)if(!K.has(ze.slice(0,At).join("/")))return!1;return!0},We=Array.isArray(M.dirs)?M.dirs:[],at=Array.isArray(M.files)?M.files:[],qe=we=>String(we).split("/").join("\0"),xt=[...We.map(we=>({type:"dir",path:we})),...at.map(we=>({type:"file",path:we.path,size:we.size}))].sort((we,ze)=>qe(we.path)<qe(ze.path)?-1:1);for(const we of xt){if(!Me(we.path))continue;const ze=we.path.split("/").length-1;re.push({type:we.type,path:we.path,label:we.path.split("/").pop()+(we.type==="dir"?"/":""),depth:ze,expanded:we.type==="dir"?K.has(we.path):void 0,sizeText:we.type==="file"?Es(we.size):null,selected:$e.selectedPath===we.path})}}const ye=$e.file;it={loading:!!$e.treeLoading,error:$e.treeError||null,semver:$e.tree?.semver||null,treeRows:re,file:ye?{path:ye.path,sizeText:Es(ye.size),truncated:!!ye.truncated,isBinary:ye.encoding==="base64",text:ye.encoding==="base64"?null:String(ye.content||""),language:Ng(ye.path)}:null,fileLoading:!!$e.fileLoading,fileError:$e.fileError||null,selectedPath:$e.selectedPath||null}}const Ye=t.workers||{},It=Array.isArray(Ye.list)?Ye.list:[],V=9e4,me=Date.now(),Be=M=>!Number.isFinite(M)||M<0?"—":M<6e4?`${Math.round(M/1e3)}s ago`:M<36e5?`${Math.round(M/6e4)}m ago`:`${Math.round(M/36e5)}h ago`,ke=M=>{if(!Number.isFinite(M)||M<0)return null;if(M<60)return`${Math.round(M)}s`;if(M<3600)return`${Math.floor(M/60)}m`;const K=Math.floor(M/3600);return K<48?`${K}h ${Math.floor(M%3600/60)}m`:`${Math.floor(K/24)}d ${K%24}h`},de=It.map(M=>{const K=M?.updatedAt instanceof Date?M.updatedAt:new Date(M?.updatedAt??0),re=Number.isNaN(K.getTime())?Number.NaN:me-K.getTime(),ye=M?.health||{},Me=M?.info||{},We=M?.state?.["agent-packages"]||null,at=We?.installed&&typeof We.installed=="object"?Object.values(We.installed):[],qe=at.filter(xt=>xt?.status==="error").length;return{id:String(M?.workerNodeId??""),pool:String(M?.pool??"default"),phase:["starting","ready","draining"].includes(M?.phase)?M.phase:"ready",live:Number.isFinite(re)&&re<=V,agoText:Be(re),uptimeText:ke(ye.uptimeS),rssText:Es(ye.rssBytes),sessions:Number.isFinite(ye.activeSessions)?ye.activeSessions:null,eventLoopText:Number.isFinite(ye.eventLoopDelayP99Ms)?`${ye.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:M?.owner?.subject?String(M.owner.subject):null,pkgEpoch:Number.isFinite(We?.epoch)?We.epoch:null,pkgText:We?`${at.length-qe} ok${qe?` · ${qe} error`:""}`:null}}).sort((M,K)=>M.pool===K.pool?M.id<K.id?-1:1:M.pool<K.pool?-1:1),Re=de.filter(M=>M.live),Ie={loading:!!Ye.loading,error:Ye.error||null,empty:de.length===0&&!Ye.loading,rows:de,counts:{registered:de.length,live:Re.length,ready:Re.filter(M=>M.phase==="ready").length,starting:Re.filter(M=>M.phase==="starting").length,draining:Re.filter(M=>M.phase==="draining").length,pools:[...new Set(Re.map(M=>M.pool))].length},summaryText:de.length?`${Re.length} live / ${de.length} registered`:null},et={loading:!!P.loading,error:P.error||null,empty:_.length===0&&!P.loading,sharedCount:oe.length,userCount:ve.length,selectedName:P.selectedName||null,detail:Qe,workspace:it,changelog:P.changelog||null,addDialog:{open:!!P.addDialog?.open,kind:P.addDialog?.kind||"repo",scope:P.addDialog?.scope||"user",repoUrl:P.addDialog?.repoUrl||"",ref:P.addDialog?.ref||"",path:P.addDialog?.path||"",url:P.addDialog?.url||"",authToken:P.addDialog?.authToken||"",submitting:!!P.addDialog?.submitting,progress:P.addDialog?.progress||null,error:P.addDialog?.error||null}},z=[];return Q==="workers"?(z.push({id:"workersRefresh",label:"Refresh workers",key:"r"}),z.push({id:"showPackages",label:"Packages",key:"a"}),z.push({id:"showProviders",label:"Model Providers",key:"m"}),z.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!t.visible,loading:!!t.loading,loadError:t.loadError||null,principal:r,isAdmin:o,adminScope:l,adminPolicyLabel:l==="cluster"?"Cluster-scoped admin · system-session access retained":"Unrestricted admin access",section:Q,settingsTree:ce,packages:et,workers:Ie,modelProviders:k,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:N,storeAsSystem:O,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:x},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:z}):Q==="packages"?(z.push({id:"packagesRefresh",label:"Refresh packages",key:"r"}),z.push({id:"packagesNext",label:"Next package",key:"j"}),z.push({id:"packagesPrev",label:"Previous package",key:"k"}),z.push({id:"showProviders",label:"Model Providers",key:"m"}),z.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!t.visible,loading:!!t.loading,loadError:t.loadError||null,principal:r,isAdmin:o,adminScope:l,adminPolicyLabel:l==="cluster"?"Cluster-scoped admin · system-session access retained":"Unrestricted admin access",section:Q,settingsTree:ce,packages:et,workers:Ie,modelProviders:k,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:N,storeAsSystem:O,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:x},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:z}):Q==="providers"?(z.push({id:"addProvider",label:"Add GitHub provider",key:"e"}),z.push({id:"cycleUserDefault",label:"Cycle my default",key:"u"}),o&&(z.push({id:"cycleClusterDefault",label:"Cycle cluster default",key:"l"}),z.push({id:"cycleSystemDefault",label:"Cycle system default",key:"s"}),z.push({id:"toggleSystemUse",label:"Toggle system use",key:"t"}),z.push({id:"cycleSystemOverride",label:"Cycle system-agent override",key:"o"})),z.push({id:"refreshProviders",label:"Refresh",key:"r"}),z.push({id:"showPackages",label:"Packages",key:"a"}),z.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!t.visible,loading:!!t.loading,loadError:t.loadError||null,principal:r,isAdmin:o,adminScope:l,adminPolicyLabel:l==="cluster"?"Cluster-scoped admin · system-session access retained":"Unrestricted admin access",section:Q,settingsTree:ce,packages:et,workers:Ie,modelProviders:k,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:N,storeAsSystem:O,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:x},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:z}):(n.editing?(z.push({id:"save",label:"Save",key:"Enter"}),z.push({id:"cancel",label:"Cancel",key:"Esc"})):(z.push({id:"edit",label:N?`Replace ${R}`:`Set ${R}`,key:"e"}),N&&z.push({id:"clear",label:`Clear ${R}`,key:"c"}),z.push({id:"refresh",label:"Refresh",key:"r"})),z.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),Q==="ghcp"&&z.splice(z.length-1,0,{id:"showPackages",label:"Packages",key:"a"}),{visible:!!t.visible,loading:!!t.loading,loadError:t.loadError||null,principal:r,isAdmin:o,adminScope:l,adminPolicyLabel:l==="cluster"?"Cluster-scoped admin · system-session access retained":"Unrestricted admin access",section:Q,settingsTree:ce,packages:et,workers:Ie,modelProviders:k,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:N,storeAsSystem:O,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:x},systemGhcpKey:{supported:!!i.supported,loading:!!i.loading,configured:!!i.configured,changedBy:i.changedBy||null,changedAt:i.changedAt||null,error:i.error||null},actions:z})}const Cg={day:"Day",week:"Week",month:"Month"};function Tg(e){const t=e.auth?.authorization?.role;return t==="admin"||t==="anonymous"||!!e.admin?.profile?.isAdmin}function Pg(e){const t=/T(\d{2}:\d{2})/.exec(String(e||""));return t?`${t[1]} UTC`:null}function _a(e,t=Date.now()){const s=e?Date.parse(e):NaN;if(!Number.isFinite(s))return null;const n=Pg(e),r=n?` (${n})`:"",i=s-t;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 Mg(e){return e?.kind==="no_provider"||e?.kind==="hold"||e?.resetsAtUtc?null:"waits until someone changes it"}function _g(e,t){return new Date(e-t*864e5).toISOString().slice(0,10)}function tn(e,t,s){return e===1?t:s}function Yr(e,t,s){const n=t?e?.quotaTokens:e?.yourQuotaTokens,r=t?e?.usedTokens:e?.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?se(o):"—",p=Number.isFinite(i)?se(i):"∞",m=Number(e?.quotaTokens),f=Number(e?.usedTokens),h=Number.isFinite(m)&&m>0&&Number.isFinite(f)&&f>=m,g=!t&&h&&(d==null||d<100),b=w=>{const E=t?e?.[w]:e?.[`your${w[0].toUpperCase()}${w.slice(1)}`];return E==null?null:Number(E)},y=b("inputTokens"),v=Number.isFinite(y)?{input:y,output:b("outputTokens")||0,cacheRead:b("cacheReadTokens")||0,cacheWrite:b("cacheWriteTokens")||0}:null,S=v?`in ${se(v.input)} (cache r ${se(v.cacheRead)} · w ${se(v.cacheWrite)}) · out ${se(v.output)}`:null;return{providerExhausted:g,ruleId:e?.ruleId||null,split:v,splitText:S,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:e?.windowStartUtc||null,resetsAtUtc:e?.resetsAtUtc||null,resetsLabel:_a(e?.resetsAtUtc,s)}}function $g(e,{overall:t,selectedProvider:s,selectedScope:n="*",nowMs:r,overModels:i=0}){const o=String(e?.providerName||""),l=e?.rowKind==="model"?"model":"provider",c=String(e?.scope||"*"),d=e?.class==="shared",u=Number.isFinite(Number(e?.allowancePct))?Number(e.allowancePct):100,p=e?.holdUntilUtc||null,m=e?.holdIndefinite===!0,f=m||(p?Date.parse(p)>r:!1),h=l==="provider"&&Number(e?.modelRowCount)||0,g=e?.ownedByMe!==!1,b=e?.manageable===!0,y=typeof e?.ownerLabel=="string"&&e.ownerLabel?e.ownerLabel:null,v=o===s&&(l==="provider"?n==="*":c===n),S=e?.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"&&t&&u<100&&g?["day","week","month"].some(w=>e?.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 ${_a(p,r)}`}:null,modelRowCount:h,selected:v,expanded:o===s&&h>0,expandLabel:h===0?null:o===s?`hide ${h} ${tn(h,"model","models")}`:i>0?`show ${h} ${tn(h,"model","models")} — ${i} over limit`:`show ${h} ${tn(h,"model","models")}`,overModels:l==="provider"?i:0,cells:{day:Yr(S.day,t,r),week:Yr(S.week,t,r),month:Yr(S.month,t,r)}}}function Rg(e){const t=e.budget||{},s=t.agents||{},n=t.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 ru(e){const t=e.budget||{},s=t.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(t.grid)?t.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(S=>[S.day,Number(S.total)||0])),v=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:v,share:f>0?v/f:0,sparkline:u.map(S=>y.get(S)||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 Lg(e){const t=e.budget||{},s=Date.now(),n=Tg(e),r=t.overall===!0,i=er.includes(Number(t.rangeDays))?Number(t.rangeDays):Oe,o=Array.isArray(t.grid)?t.grid:[],l=t.error||null,c=t.loaded===!0,d=t.selectedProvider||null,u=t.selectedScope||"*",p=o.reduce((D,Y)=>D+(Y?.rowKind==="model"?0:1),0),m=[],f=new Map;for(const D of o){if(D?.rowKind!=="model")continue;["day","week","month"].some(J=>{const te=D?.periods?.[J],Z=Number(te?.quotaTokens),ne=Number(r?te?.usedTokens:te?.yourUsedTokens);return Number.isFinite(Z)&&Z>0&&Number.isFinite(ne)&&ne>Z})&&f.set(D.providerName,(f.get(D.providerName)||0)+1)}for(const D of o)D?.rowKind==="model"&&D?.providerName!==d||m.push($g(D,{overall:r,selectedProvider:d,selectedScope:u,nowMs:s,overModels:f.get(D?.providerName)||0}));const h=m.find(D=>D.selected)||m.find(D=>D.kind==="provider"&&D.providerName===d)||null,g=m.find(D=>D.kind==="provider"&&D.providerName===d)||null,b=Array.isArray(t.paused)?t.paused:[],y=new Map;for(const D of b){const J=Ds({pauseState:D?.pause})?.provider||null;J&&y.set(J,(y.get(J)||0)+1)}const v=[...y.entries()].sort((D,Y)=>Y[1]-D[1]||D[0].localeCompare(Y[0]))[0]||null,S=b.length,w=v&&v[1]===S?v[0]:null,E=t.pausedError||null,I={count:S,error:E,stale:!!E&&S>0,provider:v?v[0]:null,sentence:S===0?null:`${S} ${tn(S,"session is","sessions are")} waiting${w?` on ${w}`:""}.`},T=t.missingProvider||null,C=T&&y.get(T)||0,k=C>0?{provider:T,count:C,sentence:`No provider is named ${T}, and ${C} ${tn(C,"session waits","sessions wait")} on it. They run again as soon as a provider takes that name.`}:null,O=t.series||{},N=new Map((Array.isArray(O.days)?O.days:[]).map(D=>[String(D?.dayUtc||"").slice(0,10),D])),R=[];for(let D=i-1;D>=0;D-=1){const Y=_g(s,D),J=N.get(Y);R.push({dayUtc:Y,label:Y.slice(5),tokens:Number(J?.tokensTotal)||0,turns:Number(J?.turns)||0})}const H=R.reduce((D,Y)=>Math.max(D,Y.tokens),0),x=h?.cells?.day||null,P=x?.quotaTokens??null,_=Math.max(H,P||0);for(const D of R)D.pct=_>0?Math.round(D.tokens/_*100):0;const $=O.error||null,B=O.loaded===!0,j={provider:O.provider||null,days:R,peak:H,peakLabel:se(H),scaleMax:_,quotaTokens:P,quotaLabel:x?.quotaLabel??"∞",quotaPct:P!=null&&_>0?Math.round(P/_*100):null,rangeDays:i,rangeLabel:`Last ${i} days`,loading:O.loading===!0,loaded:B,error:$,failed:!!$&&!B,stale:!!$&&B,empty:B&&!$&&H===0,mixedScope:!1},W=t.systemUsage||{},A=n&&h&&W.provider===d&&(W.scope||"*")===u&&(W.rangeDays||Oe)===i,G=!n||!h?null:{loading:A&&W.loading===!0,loaded:A&&W.loaded===!0,error:A&&W.error||null,stale:A&&!!W.error&&W.loaded===!0,rangeDays:i,rangeLabel:`Last ${i} days`,tokens:Number(A?W.totals?.tokensTotal:0)||0,tokensLabel:se(Number(A?W.totals?.tokensTotal:0)||0),turns:Number(A?W.totals?.turns:0)||0,models:(A&&Array.isArray(W.breakdown)?W.breakdown:[]).map(D=>({key:String(D?.key||D?.label||"unknown"),label:String(D?.label||D?.key||"Unknown model"),tokens:Number(D?.tokensTotal)||0,tokensLabel:se(Number(D?.tokensTotal)||0),turns:Number(D?.turns)||0})).sort((D,Y)=>Y.tokens-D.tokens||D.label.localeCompare(Y.label))};return{open:!!e.ui?.budgetOpen,isAdmin:n,loading:!!t.loading,refreshing:!!t.refreshing,loaded:c,error:l,fetchedAt:Number(t.fetchedAt)||0,failed:!!l&&!c,stale:!!l&&c,empty:c&&!l&&p===0,overall:r,rangeDays:i,rangeOptions:er.map(D=>({value:D,label:`${D}d`})),overallLabel:"Show all user spend",usageHeading:r?"All user spend":"My spend",columns:Xf.map(D=>({id:D,label:Cg[D]})),rows:m,providerCount:p,selectedProvider:d,selectedScope:u,selected:h,selectedProviderRow:g,paused:I,missing:k,series:j,systemSpend:G}}function Og(e){const t=e.ui.focusRegion,s=e.ui.fullscreenPane||null,n=gt(e),r=!!n?.pendingQuestion?.question,i=n?.sessionId&&Array.isArray(e.outbox?.bySessionId?.[n.sessionId])?e.outbox.bySessionId[n.sessionId]:[],o=i.length>0,l=i.some(b=>b?.phase==="pending"),c=e.ui.promptEdit?.sessionId===n?.sessionId,d=c&&e.ui.promptEdit?.phase==="queued",u=c&&e.ui.promptEdit?.phase==="cancelling",p=s===t?"v/esc close fullscreen":"v fullscreen";if(e.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(e.ui.modal?.type==="renameSession")return{left:"Rename the selected session title",right:"type title · left/right move · enter save · esc cancel"};if(e.ui.modal?.type==="shareSession")return{left:"Share the selected session",right:"name [r|w] grants · -name revokes · enter apply · esc close"};if(e.ui.modal?.type==="artifactPicker")return{left:"Select a linked artifact or URL",right:"up/down move · enter open/download · a/esc close"};if(e.ui.modal?.type==="modelPicker")return{left:"Select a model for the new session",right:"up/down move · enter next · esc cancel"};if(e.ui.modal?.type==="reasoningEffortPicker")return{left:"Select reasoning effort for the new session",right:"up/down move · enter create · esc cancel"};if(e.ui.modal?.type==="themePicker")return{left:"Select a theme",right:"up/down move · enter apply · esc close"};if(e.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(e.ui.modal?.type==="sessionGroupPicker")return{left:"Move selected session(s) to a group",right:"up/down move · enter choose · esc cancel"};if(e.ui.modal?.type==="sessionGroupName")return{left:"Name the new group",right:"type name · left/right move · enter create · esc cancel"};if(e.ui.modal?.type==="logFilter")return{left:"Adjust log filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(e.ui.modal?.type==="filesFilter")return{left:"Adjust files browser filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(e.ui.modal?.type==="sessionOwnerFilter")return{left:"Adjust session filters",right:"up/down choose · space toggle · esc close"};const m=!!e.sessions?.selectMode,f=Array.isArray(e.sessions?.selectedIds)?e.sessions.selectedIds.length:0;if(m&&t===F.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={[F.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",[F.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`,[F.INSPECTOR]:e.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`:e.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`:e.ui.inspectorTab==="files"?e.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":e.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`:e.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`,[F.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`,[F.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[t]||h[F.SESSIONS];return zd(gt(e))&&(g=`ctrl-x stop · ${g}`),{left:e.ui.statusText,right:g}}function fs(e){return(e||[]).reduce((t,s)=>t+String(s?.text||"").length,0)}function _e(e,t){if(t<=0)return[];const s=[];let n=t;for(const r of e||[]){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 dt(e){return Array.from(String(e||"")).length}function iu(e,t){const s=String(e||"");return t<=0?"":dt(s)<=t?s:t===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,t-1).join("")}…`}function _s(e,t){const s=iu(e,t),n=Math.max(0,t-dt(s));return s+" ".repeat(n)}function fe(e,t="white",s={}){return{text:String(e||""),color:t,...s}}function Xe(e){const t=Number(e);if(!Number.isFinite(t)||t<0)return"?";if(t<1024)return`${Math.round(t)} B`;if(t<1024*1024){const n=t/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=t/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function rl(e,t){const s=Number(e),n=Number(t);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 au(e,t=18){const s=String(e||"").replace(/\s+/g," ").trim();return s?dt(s)>t?`${Array.from(s).slice(0,Math.max(1,t-1)).join("")}…`:s:""}function Fg(e){const t=e?.data;if(typeof t=="string")return t;if(t&&typeof t=="object"){if(typeof t.content=="string")return t.content;if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message;if(typeof t.question=="string")return t.question}return""}function ou(e=[]){const t=new Set,s=[];for(const n of e){const r=String(n||"").trim();if(!r)continue;const i=r.toLowerCase();t.has(i)||(t.add(i),s.push(r))}return s.join(" | ")}function Dg(e,t=""){return ou([e?.data?.reason==="cron_at"?"cron":e?.data?.reason,e?.data?.detail,e?.data?.message,e?.data?.error,t])}function Bg(e,t=""){return ou([e?.data?.message,e?.data?.detail,e?.data?.error,t])}function fn(e){const t=String(e||"").trim();if(!t||t==="(unknown)")return null;const s=t.split(/[/:]/).pop()||t,n=s.length<=5?s:s.slice(-5);return n.replace(/^[^a-zA-Z0-9]+/,"")||n}const Hg=300*1e3,Ug="last 5m";function $a(e){let t=0;for(const s of e.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)&&(t=Math.max(t,r))}return(!Number.isFinite(t)||t<=0)&&(t=Date.now()),{startMs:t-Hg,endMs:t,label:Ug}}function jg(e,t){if(!e||!t)return!1;const s=Number(e.createdAtMs||0);return Number.isFinite(s)?s>=t.startMs&&s<=t.endMs:!1}function lu(e,t){if(!e||!t)return!1;const s=e?.createdAt instanceof Date?e.createdAt.getTime():new Date(e?.createdAt||0).getTime();return Number.isFinite(s)?s>=t.startMs&&s<=t.endMs:!1}const Gg=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done","model"]);function Wg(e){return Gg.has(e)}function qg(e){const t=Dc(e?.createdAt),s=fn(e?.workerNodeId),n=Fg(e),r=au(n,20),i=e?.createdAt instanceof Date?e.createdAt.getTime():new Date(e?.createdAt||0).getTime(),o={time:t,createdAtMs:Number.isFinite(i)?i:0,nodeLabel:s,color:"white",detail:"",type:"other"};switch(e?.eventType){case"session.turn_started":return{...o,type:"turn_start",color:"gray",detail:`turn ${e?.data?.iteration??"?"}`};case"session.turn_completed":{const l=Number(e?.data?.turnIndex??e?.data?.iteration);return{...o,type:"turn_end",color:"gray",detail:`turn ${e?.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 ${as(e?.data?.seconds??0)}`};case"session.wait_completed":return{...o,type:"timer",color:"yellow",detail:`${as(e?.data?.seconds??0)} up`};case"session.lossy_handoff":{const l=Bg(e,r);return{...o,type:"dehydrate",color:"yellow",detail:l?`lossy ${l}`:"lossy handoff"}}case"session.dehydrated":return{...o,type:"dehydrate",color:"cyan",detail:`ZZ ${Dg(e,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 ${e?.data?.agentId||Le(e?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${as(e?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${tr(e?.data?.nextFireAtMs??e?.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 ${tr(e?.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:`/${e?.data?.cmd||"?"}`};case"session.command_completed":return{...o,type:"cmd_done",color:"magenta",detail:`/${e?.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=Rs(e?.data?.oldModel)||"default",c=Rs(e?.data?.newModel)||"default",d=e?.data?.newReasoningEffort,u=d&&d!==e?.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 cu(e=[]){const t=[];for(const s of e||[]){const n=qg(s);n&&t.push({...n,nodeLabel:Wg(n.type)?"orch":n.nodeLabel||"orch"})}return t}function zg(e=[]){const t=[];for(let s=0;s<e.length;s+=1){const n=e[s];if(n?.type!=="spawn"||n?.nodeLabel!=="orch"){t.push(n);continue}let r=1;for(;s+r<e.length;){const i=e[s+r];if(i?.type!=="spawn"||i?.nodeLabel!=="orch"||i?.time!==n.time)break;r+=1}if(r===1){t.push(n);continue}t.push({...n,detail:`spawn x${r}`}),s+=r-1}return t}function Kg(e){const t=String(e?.error||"").trim();if(!t)return null;const s=ga(e);if(!s)return null;const n=e?.updatedAt?Number(e.updatedAt):Date.now(),r=Number.isFinite(n)?n:Date.now();return{time:Dc(r),createdAtMs:r,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${au(t,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function Vg(e,t){const s=Kg(t);return!s||(e||[]).some(r=>!r||r.nodeLabel!=="orch"||r.detail!==s.detail?!1:Math.abs(Number(r.createdAtMs||0)-s.createdAtMs)<=6e4)?e:[...e||[],s]}function Yg(e,t,s){if(!Number.isFinite(t)||!Number.isFinite(s)||s<t)return[];const n=new Set;for(const r of e.history.bySessionId.values()){const i=cu(r?.events||[]);for(const o of i){if(!o?.nodeLabel||o.nodeLabel==="orch")continue;const l=Number(o.createdAtMs||0);Number.isFinite(l)&&(l<t||l>s||n.add(o.nodeLabel))}}return Array.from(n).sort((r,i)=>r.localeCompare(i))}function Xg(e,t){const s=new Set;for(const n of e.history.bySessionId.values())for(const r of n?.events||[]){if(!lu(r,t))continue;const i=fn(r?.workerNodeId);i&&s.add(i)}return Array.from(s).sort((n,r)=>n.localeCompare(r))}function Ra(e){const t=e.slice();for(;t.length>0;){const s=t[t.length-1],n=String(s.text??"").replace(/\s+$/,"");if(n===""){t.pop();continue}t[t.length-1]={...s,text:n};break}return t}function il(e){return Array.isArray(e?.runs)?e.runs.reduce((t,s)=>t+dt(String(s.text??"")),0):Array.isArray(e)?e.reduce((t,s)=>t+dt(String(s.text??"")),0):dt(String(e?.text??""))}function Qg(e,t,s){const n=[{text:_s("TIME",t),color:"white",bold:!0},{text:" ",color:null}];return e.forEach((r,i)=>{i>0&&n.push({text:" ",color:null}),n.push({text:_s(r,s),color:"white",bold:!0})}),Ra(n)}function Zg(e,t,s,n=1/0){const r=`${"-".repeat(t)} ${e.map(()=>"─".repeat(s)).join(" ")}`;return fe(Number.isFinite(n)?r.slice(0,Math.max(t,n)):r,"gray")}function Jg(e,t,s){const n=e?.orchestration?.bySessionId?.[t?.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=Xe(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(Xe(i.kvTotalValueBytes)),r=s<=40?l.join(" · "):o.join(" | "),r||(r="orchestration stats unavailable")}return Ue({title:"Stats",body:r,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function ey(e,t,s,n){const r=t.includes(e.nodeLabel)?e.nodeLabel:t.includes("…")?"…":t[t.length-1],i=[{text:_s(e.time||"",s),color:"white"},{text:" ",color:null}];return t.forEach((o,l)=>{l>0&&i.push({text:" ",color:null}),o===r?i.push({text:_s(e.detail||"",n),color:e.color||"white",bold:!!e.bold,underline:!!e.underline,...e.completedTurn!=null?{completedTurn:e.completedTurn}:{}}):i.push({text:_s("│",n),color:"gray"})}),Ra(i)}const ty=new Set(["none","minimal","low","medium","high","xhigh","max"]);function sy(e){const t=String(e||"").trim();if(!t)return"unknown";const s=t.split(":").filter(Boolean);if(s.length===0)return"unknown";const n=String(s[s.length-1]).toLowerCase(),r=s.length>1&&ty.has(n)?s.length-2:s.length-1;return s[Math.max(0,r)]||s[0]||"unknown"}function al(e){const t=Number(e||0);if(!Number.isFinite(t))return"?K";const s=t/1e3;return`${s.toFixed(Math.abs(s)>=10?1:2)}K`}function Qt(e){return Number(e||0).toLocaleString("en-US")}function ny(e){const t=new Map;for(const s of e||[]){if(s?.eventType!=="session.turn_completed")continue;const n=Number(s?.data?.turnIndex??s?.data?.iteration);Number.isFinite(n)&&t.set(n,s.data||{})}return t}function ry(e,{expanded:t,selected:s,maxWidth:n}){const r=t?"v":">",i=sy(e?.model),o=e?.durationMs!=null?`${(Number(e.durationMs)/1e3).toFixed(1)}s`:"n/a",l=`${r} Mod: ${i} tok ${al(e?.tokensInput)}/${al(e?.tokensOutput)} dur ${o}`,c=[];if(s?c.push(kt(_s(l,Math.max(18,n)))):c.push([{text:l,color:"magenta"}]),t){const d=[["model",e?.reasoningEffort?`${e?.model||"(unknown)"}:${e.reasoningEffort}`:e?.model||"(unknown)"],["duration",e?.durationMs!=null?`${Qt(e.durationMs)} ms`:null],["tokens",`${Qt(e?.tokensInput)} in / ${Qt(e?.tokensOutput)} out`],["cache",`${Qt(e?.tokensCacheRead)} read / ${Qt(e?.tokensCacheWrite)} write`],["tools",`${Qt(e?.toolCalls)} calls / ${Qt(e?.toolErrors)} errors`],["names",Array.isArray(e?.toolNames)&&e.toolNames.length?e.toolNames.join(", "):null],["worker",e?.workerNodeId||null],["result",e?.resultType||null],["error",e?.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 iy(e,t,s,n={}){const r=!!n?.allowWideColumns,i=Jg(e,t,s),o=e.history.bySessionId.get(t.sessionId),l=Vg(zg(cu(o?.events||[])),t);if(l.length===0)return{stickyLines:i,lines:[fe("No events yet - interact with this session to populate the sequence diagram.")]};const c=$a(e),d=l.filter(N=>jg(N,c)),u=(d.length>0?d:l).slice(-48),p=Yg(e,c.startMs,c.endMs),m=Array.from(new Set(u.map(N=>N.nodeLabel).filter(N=>N&&N!=="orch"))).sort((N,R)=>N.localeCompare(R)),f=p.length>0?p:m,h=Math.min(13,Math.max(8,...u.map(N=>dt(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 v=Math.max(0,y.length-1),S=Math.max(4,Math.floor((g-h-1-v)/Math.max(1,y.length))),w=n?.sequenceExpansion||null,E=w?ny(o?.events||[]):null,I=w?new Set((w.expandedTurns||[]).map(Number)):null,T=w&&w.selectedTurn!=null?Number(w.selectedTurn):null,C=[];for(const N of u)if(C.push(ey(N,y,h,S)),w&&N.completedTurn!=null){const R=Number(N.completedTurn),H=E.get(R);if(H)for(const x of ry(H,{expanded:I.has(R),selected:T===R,maxWidth:g}))C.push(x)}const k=Qg(y,h,S),O=C.reduce((N,R)=>Math.max(N,il(R)),il(k));return{stickyLines:[...i,fe(`Window: ${c.label}`,"gray"),k,Zg(y,h,S,O)],lines:C}}function ay(e){const t=[],s=new Set;for(const n of e.sessions.flat||[])!n?.sessionId||s.has(n.sessionId)||(s.add(n.sessionId),t.push(n.sessionId));for(const n of Object.keys(e.sessions.byId||{}))s.has(n)||(s.add(n),t.push(n));return t}function oy(e,t=null){const s=e?.events||[];for(let n=s.length-1;n>=0;n-=1){if(t&&!lu(s[n],t))continue;const r=fn(s[n]?.workerNodeId);if(r)return r}return null}function ly(e){return!Number.isFinite(e)||e<0?null:e<6e4?`${Math.round(e/1e3)}s ago`:e<36e5?`${Math.round(e/6e4)}m ago`:`${Math.round(e/36e5)}h ago`}function cy(e){if(!Number.isFinite(e)||e<0)return null;if(e<60)return`${Math.round(e)}s`;if(e<3600)return`${Math.floor(e/60)}m`;const t=Math.floor(e/3600);return t<48?`${t}h ${Math.floor(e%3600/60)}m`:`${Math.floor(t/24)}d ${t%24}h`}function dy(e,t,s){const n=e?.isSystem?ps(e,t):e?.title||Le(e?.sessionId),r=e?.isSystem?"⚙ ":e?.serviceKind?"⚗ ":`${Fd(e)||"."} `;return{sessionId:e?.sessionId||null,text:`${r}${n}`,color:e?.isSystem?"yellow":Ts(e),bold:!!e?.isSystem,active:!!s}}function du(e){const t=$a(e),s=e.branding?.title||"PilotSwarm",n=e.sessions.activeSessionId,r=Array.isArray(e.admin?.workers?.list)?e.admin.workers.list:[],i=Date.now(),o=9e4,l=new Map;for(const f of r){const h=fn(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:ly(b),uptimeText:cy(y.uptimeS),rssText:Number.isFinite(y.rssBytes)?Es(y.rssBytes):null,heapText:Number.isFinite(y.heapUsedBytes)?Es(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(([,v])=>!!v).map(([v])=>v).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(([v,S])=>({name:v,semver:S?.semver??null,status:S?.status==="error"?"error":"ok",error:S?.error?String(S.error):null})):[],pkgLastError:f?.state?.["agent-packages"]?.lastError?String(f.state["agent-packages"].lastError):null,executing:[]})}for(const f of Xg(e,t))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 ay(e)){const h=e.sessions.byId[f];if(!h)continue;const g=e.history.bySessionId.get(f);g?.events||(c+=1);const b=oy(g,t),y=b?l.get(b):null;y&&y.executing.push(dy(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=e.ui?.nodeMapSelectedNode,m=p&&d.some(f=>f.label===p)?p:d[0]?.label??null;return{windowLabel:t.label,degraded:u.length===0,registryError:e.admin?.workers?.error||null,registryFetchedAt:e.admin?.workers?.fetchedAt||0,registryLoading:!!e.admin?.workers?.loading,registryAttempts:e.admin?.workers?.attempts||0,registryLastAttemptAt:e.admin?.workers?.lastAttemptAt||0,registryLastSkip:e.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 uy(e,t,s={}){const n=du(e);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(Ra(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 py(e,t=72){const s=e.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,t-4),o=[],l=[];let c=0;for(const f of n){const h=_e([{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,v=!!g.disabled,S=_e([{text:"· ",color:"gray"},{text:g.modelName||g.qualifiedName||g.id,color:v?"gray":"white",bold:!!g.isDefault&&!v},...g.cost?[{text:` [${g.cost}]`,color:"gray"}]:[],...v?[{text:" ⊘ needs GitHub key",color:"yellow"}]:[],...g.isDefault?[{text:" ← current default",color:"gray"}]:[]],i),w=y?kt(S.map(E=>E.text).join("").padEnd(i," ")):S;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,fs(h)):Math.max(f,String(h?.text||"").length),0)+4),t)}}function my(e,t=76){const s=e.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,t-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 v=f.collapsed?"▸":"▾",S=f.sectionKind==="package"&&f.packageScope==="user"&&!f.mine?" [private]":"";y=_e([{text:`${b}${v} `,color:"cyan"},{text:f.title||"Section",color:"white",bold:!0},...S?[{text:S,color:"cyan"}]:[],...f.meta?[{text:` · ${f.meta}`,color:"gray"}]:[]],i)}else{const v=f?.kind==="generic"||f?.supportsDirectStart!==!1,S=f?.kind==="generic"?"○ ":"★ ",w=f?.title||f?.agentName||f?.id||"Agent",E=f?.kind==="generic"?"":f?.packageTitle||f?.packageName||"",I=s.sort==="used"&&Number(f?.usageCount)>0?` ${f.usageCount}×`:"";y=_e([{text:`${b}${S}`,color:v?"yellow":"gray"},{text:w,color:v?"white":"gray",bold:v},...E?[{text:` ${E}`,color:"gray"}]:[],...I?[{text:I,color:"cyan"}]:[]],i)}o.push(g?kt(y.map(v=>v.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.":"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,fs(h)):Math.max(f,String(h?.text||"").length),0)+4),t)}}function fy(e,t=64){const s=e.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,t-4),o=n.map((u,p)=>{const m=p===r,f=_e([{text:"· ",color:"gray"},{text:String(u?.label||u?.id||"effort"),color:"white",bold:!0},...u?.isDefault?[{text:" ← model default",color:"gray"}]:[]],i);return m?kt(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,fs(p)):Math.max(u,String(p?.text||"").length),0)+4),t)}}function hy(e,t=64){const s=e.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,t-4),o=n.map((p,m)=>{const f=m===r,h=_e([{text:"· ",color:"gray"},{text:String(p?.label||p?.id||"tier"),color:"white",bold:!0},...p?.isDefault?[{text:" ← model default",color:"gray"}]:[]],i);return f?kt(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,fs(m)):Math.max(p,String(m?.text||"").length),0)+4),t)}}function gy(e,t=72){const s=e.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,t-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=_e([{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?kt(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,fs(p)):Math.max(u,String(p?.text||"").length),0)+4),t)}}function yy(e,t=76){const s=e.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,dt(i||"(untitled session)")+18,dt(o)+18),t)}}function by(e,t=76){const s=e.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,dt(i)+18),t)}}function Sy(e,t=82){const s=e.ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=String(s.value||""),r=s.sessionId||e.ui.promptAttachments?.[0]?.sessionId||e.sessions?.activeSessionId||null,i=r&&e.sessions?.byId?.[r]||null,o=r?i?Gd(i,e.branding?.title):Le(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,dt(n||"~/path/to/file.md")+20,dt(o)+20),t)}}function La(e,t={},s=96,n="Filters",r="Choose how this pane is filtered and rendered."){const i=Array.isArray(e.items)?e.items:[],o=Math.max(0,Number(e.selectedIndex)||0),l=i[o]||null,c=i.map((d,u)=>{const p=t?.[d.id]||d.options?.[0]?.id,m=(d.options||[]).map(f=>f.id===p?kt(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:e.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 uu(e,t={},s={}){return e?e.kind==="all"?t?.all===!0:t?.all===!0?!1:e.kind==="system"?t?.includeSystem===!0:e.kind==="unowned"?t?.includeUnowned===!0:e.kind==="me"?t?.includeMe===!0&&!!Pe(s?.principal):e.kind==="shared"?t?.includeShared===!0:e.kind==="owner"?Array.isArray(t?.ownerKeys)&&t.ownerKeys.includes(e.ownerKey):!1:!1}function ol(e=[],t={},s={}){if(t?.all===!0)return"All sessions";const n=e.filter(r=>r?.kind!=="all"&&uu(r,t,s)).map(r=>r.kind==="me"?"Me":r.label);return n.length>0?n.join(" + "):"All sessions"}function vy(e,t=88){const s=e.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return null;const n=Array.isArray(s.items)?s.items:[],r=e.sessions?.ownerFilter||{all:!0},i=e.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=uu(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?Md(h,{preserveColors:!0}):h}),d=[[{text:"Active: ",color:"gray"},{text:ol(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)?fs(p):dt(p?.text||"")),0)+8,dt(ol(n,r,i))+16),t)}}function wy(e,t=96){const s=e.ui.modal;return!s||s.type!=="logFilter"?null:La(s,e.logs?.filter||{},t,"Log Filters","Choose how the log pane is filtered and rendered.")}function Ey(e,t=88){const s=e.ui.modal;return!s||s.type!=="filesFilter"?null:La(s,e.files?.filter||{},t,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function ky(e,t=88){const s=e.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,t-4),o=n.filter(f=>f.kind==="artifact"),l=n.filter(f=>f.kind==="url"),c=o.reduce((f,h)=>{const g=e.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=_e([{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=_e([{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=e.files?.bySessionId?.[f.sessionId]?.downloads?.[f.filename];g=_e([{text:b?.localPath?"ok ":"dl ",color:b?.localPath?"green":"cyan",bold:!0},{text:`${Le(f.sessionId)}/`,color:"gray"},{text:f.filename,color:"white"}],i)}return h!==r?g:kt(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=e.sessions?.byId?.[p.sessionId]||null,h=e.files?.bySessionId?.[p.sessionId]?.downloads?.[p.filename]||null;m=[[{text:p.filename,color:"white",bold:!0}],[{text:f?Gd(f,e.branding?.title):Le(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,fs(h)):Math.max(f,String(h?.text||"").length),0)+4),t)}}function se(e){return e==null||!Number.isFinite(e)?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e4?`${(e/1e3).toFixed(1)}K`:e>=1e3?e.toLocaleString("en-US"):String(e)}function Oa(e){if(!e)return"—";const t=Date.now()-e;return t<6e4?`${Math.max(1,Math.floor(t/1e3))}s ago`:t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function Iy(e){if(!e)return"—";const t=Date.now()-e;if(t<6e4)return"<1min";const s=Math.floor(t/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 ll(e){if(!e)return"—";const t=e instanceof Date?e:new Date(e);if(Number.isNaN(t.getTime()))return"—";const s=t.toLocaleDateString(void 0,{month:"short",day:"numeric"}),n=t.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",second:"2-digit"});return`${s}, ${n}`}function cl(e){if(!e)return"—";const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit",timeZoneName:"short"})}function Qs(e){return["session","fleet","users"].includes(e)?e:"session"}function Sr(e,t){const s=Qs(e),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"}),_e(n,t)}function xy(e,t,s){if(!t)return[fe("No session selected.")];const n=e.sessionStats?.bySessionId?.[t.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(Sr("session",o)),i.push(fe("")),i.push(_e([{text:"Session ",color:"cyan",bold:!0},{text:Le(t.sessionId),color:"white"}],o));const l=t.isSystem?"system":t.owner?"user":"unowned",c=t.isSystem?"system":t.owner?pn(t.owner):"(?) unowned",d=t.owner?.email||"—";i.push(_e([{text:"Owner ",color:"cyan",bold:!0},{text:c,color:t.owner?"white":"gray"}],o)),i.push(_e([{text:"Email ",color:"cyan",bold:!0},{text:d,color:t.owner?.email?"white":"gray"}],o)),i.push(_e([{text:"Type ",color:"cyan",bold:!0},{text:l,color:l==="user"?"white":"gray"}],o)),r.agentId&&i.push(_e([{text:"Agent ",color:"cyan",bold:!0},{text:r.agentId,color:"white"}],o));const u=Ta(r.model||t.model,r.reasoningEffort||t.reasoningEffort);u&&i.push(_e([{text:"Model ",color:"cyan",bold:!0},{text:u,color:"white"}],o)),t.createdAt&&i.push(_e([{text:"Created ",color:"cyan",bold:!0},{text:cl(t.createdAt),color:"white"}],o)),t.updatedAt&&i.push(_e([{text:"Updated ",color:"cyan",bold:!0},{text:cl(t.updatedAt),color:"white"}],o)),i.push(fe(""));const p=Array.isArray(n.tokensByModel)?n.tokensByModel:[];p.length>1&&(i.push(...Ue({title:"Models",body:p.map(N=>`${hg(N.model)} · ${N.turnCount||0} turns · ${se(N.totalTokensInput)} in / ${se(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(...Ue({title:"Tokens",body:ls([["Input",se(r.tokensInput)],["Output",se(r.tokensOutput)],["Total",se(m)],["Cache Read",se(r.tokensCacheRead)],["Cache Write",se(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,v=b?b.distillMode==="deterministic"||!b.distillMode&&!b.distillerModel?"fast":String(b.distillerModel||"llm").replace(/^[^:]*:/,""):null,S=b?`${b.turnsArchived??0} turn${b.turnsArchived===1?"":"s"} · ${(Number(b.totalMs)/1e3).toFixed(1)}s${v?` · ${v}`:""}`:null;i.push(...Ue({title:"Persistence",body:ls([["Epoch",String(y)],["Regens",g>0?String(g):null],["Last Regen",S],["Snapshot",Xe(r.snapshotSizeBytes)],["Uncompressed",r.rawSizeBytes?Xe(r.rawSizeBytes):null],["Compression",rl(r.rawSizeBytes,r.snapshotSizeBytes)],["Dehydrations",String(r.dehydrationCount)],["Hydrations",String(r.hydrationCount)],["Lossy Handoffs",String(r.lossyHandoffCount)],["Last Dehydrated",r.lastDehydratedAt?ll(r.lastDehydratedAt):null],["Last Hydrated",r.lastHydratedAt?ll(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,R=N==null?"—":`${(N*100).toFixed(1)}%`,H=(w.totalTokensInput||0)+(w.totalTokensOutput||0);i.push(fe("")),i.push(...Ue({title:`Tree (${w.sessionCount} sessions)`,body:ls([["Input",se(w.totalTokensInput)],["Output",se(w.totalTokensOutput)],["Total",se(H)],["Cache Read",se(w.totalTokensCacheRead)],["Cache Write",se(w.totalTokensCacheWrite)],["Hit Ratio",R],["Snapshot",Xe(w.totalSnapshotSizeBytes)],["Uncompressed",w.totalRawSizeBytes?Xe(w.totalRawSizeBytes):null],["Compression",rl(w.totalRawSizeBytes,w.totalSnapshotSizeBytes)],["Dehydrations",String(w.totalDehydrationCount)],["Hydrations",String(w.totalHydrationCount)]]),width:o,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const x=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];x.length>1&&(i.push(fe("")),i.push(...Ue({title:"Tree By Model",body:My(x),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const E=Array.isArray(n.skillUsage)?n.skillUsage:[];E.length>0&&(i.push(fe("")),i.push(...Ue({title:`Skills (${E.length})`,body:dl(E,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const I=n.treeSkillUsage,T=Array.isArray(I?.rolledUp)?I.rolledUp:[],C=Array.isArray(I?.perSession)?I.perSession.length:0;T.length>0&&C>1&&(i.push(fe("")),i.push(...Ue({title:`Tree Skills (${T.length})`,body:dl(T,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const k=n.factsStats,O=n.treeFactsStats;if(k&&Array.isArray(k.rows)&&k.rows.length>0){i.push(fe(""));const N=pu(k.rows),R=N?N.split(`
60
- `).length:0,H=`${k.totalCount} · ${Xe(k.totalBytes)}`;let x=N;O&&O.totalCount>k.totalCount&&(x+=`
61
- Tree (${O.sessionIds.length} sessions): ${O.totalCount} · ${Xe(O.totalBytes)}`),R>0&&i.push(...Ue({title:`Facts (${H})`,body:x,width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return i}function ls(e,t={}){const s=t.gap??2,n=(e||[]).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(t.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 vr(e,t){const s=String(e??"");if(!Number.isFinite(t)||t<=0)return s;const n=Math.floor(t);return s.length<=n?s:n<=1?s.slice(0,n):`${s.slice(0,n-1)}…`}function hn(e,t={}){const s=t.gap??2,n=(e||[]).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 dl(e,t){const s=e.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(t)&&t>0?Math.max(8,Math.floor(t)-l):1/0,d=s.map((p,m)=>{const f=p.kind==="learned"?"L":"S",h=String(p.name||"(unknown)");return[vr(`${f} ${h}`,c),n[m]]}),u=hn(d);return e.length>s.length?`${u}
64
- … ${e.length-s.length} more`:u}function pu(e){const s=e.slice().sort((n,r)=>(r.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),Xe(n.totalValueBytes||0)]);return hn(s)}function Ay(e){const t=e.oldestUnreconciledAgeSeconds==null?"-":as(Math.max(0,Number(e.oldestUnreconciledAgeSeconds)||0));return hn([["pending",String(Number(e.pendingTotal)||0)],["unreconciled",String(Number(e.unreconciled)||0)],["ttl-blocked",String(Number(e.ttlBlocked)||0)],["oldest",t],["reconciled",String(Number(e.reconciledUnswept)||0)]])}function Ny(e){switch(e){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(e||"retrieval")}}function Cy(e,t){const s=e.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(t)&&t>0?Math.max(10,Math.floor(t)-l):1/0,d=s.map((p,m)=>{const f=p.namespace?` ${p.namespace}`:"";return[vr(`${Ny(p.operation)}${f}`,c),n[m],r[m]]}),u=hn(d);return e.length>s.length?`${u}
65
- … ${e.length-s.length} more`:u}function Ty(e,t){const s=e.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,t);r.push(Sr("fleet",i)),r.push(fe(""));const o=n.windowStart?`Since: ${Oa(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(_e([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],i)),r.push(_e([{text:`Sessions: ${n.totals.sessionCount}`,color:"white"},{text:` Tokens: ${se(n.totals.totalTokensInput)} in / ${se(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 v=y.totalTokensInput>0?y.totalTokensCacheRead/y.totalTokensInput:null;g.push(b),g.push(Fa(y,v)),g.push("")}r.push(...Ue({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(...Ue({title:"Fleet Totals",body:ls([["Sessions",String(n.totals.sessionCount)],["Tokens In",se(n.totals.totalTokensInput)],["Tokens Out",se(n.totals.totalTokensOutput)],["Total Tokens",se(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",se(n.totals.totalTokensCacheRead)],["Cache Write",se(n.totals.totalTokensCacheWrite)],["Hit Ratio",u],["Snapshots",Xe(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(...Ue({title:`Fleet Skills (${p.length})`,body:Py(p,t),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(...Ue({title:`Fleet Retrieval (${se(g)})`,body:Cy(m,t),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} · ${Xe(f.totalBytes)}`;r.push(...Ue({title:`Shared Facts (${g})`,body:pu(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(...Ue({title:`Fact Tombstones (${Number(h.pendingTotal)||0})`,body:Ay(h),width:i,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),r}function Py(e,t){const n=e.slice().sort((h,g)=>{const b=E=>E==="learned"?1:0,y=b(h.kind)-b(g.kind);if(y!==0)return y;const v=h.agentId?0:1,S=g.agentId?0:1;if(v!==S)return v-S;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(t)&&t>0?Math.max(10,Math.floor(t)-u):1/0,m=n.map((h,g)=>{const b=h.kind==="learned"?"L":"S",y=h.agentId||".",v=String(h.name||"(unknown)");return[vr(`${b} ${y}/${v}`,p),r[g],i[g]]}),f=hn(m);return e.length>n.length?`${f}
67
- … ${e.length-n.length} more`:f}function My(e){const t=e.slice().sort((n,r)=>(r.totalTokensInput||0)-(n.totalTokensInput||0)),s=[];for(const n of t){const r=n.cacheHitRatio;s.push(`${String(n.model||"(unknown)")} · ${n.sessionCount||0} sess · ${n.turnCount||0} turns`),s.push(Fa(n,r)),s.push("")}return s.join(`
68
- `).trimEnd()}function Fa(e,t){const s=t==null?"—":`${(t*100).toFixed(1)}%`,n=(Number(e.totalTokensInput)||0)+(Number(e.totalTokensOutput)||0),r=[["Input",se(e.totalTokensInput||0)],["Output",se(e.totalTokensOutput||0)],["Total",se(n)],["Turns",se(e.turnCount||0)],["Cache Read",se(e.totalTokensCacheRead||0)],["Cache Write",se(e.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",Xe(e.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(e.totalOrchestrationHistorySizeBytes))&&r.push(["Orch",Xe(e.totalOrchestrationHistorySizeBytes||0)]),ls(r).split(`
69
- `).map(o=>` ${o}`).join(`
70
- `)}function Bi(e){return e?.ownerKind==="system"?"System":e?.ownerKind==="unowned"?"Unowned":pn(e?.owner,"Unknown User")}function _y(e){if(e?.ownerKind!=="user")return"";const t=String(e?.owner?.email||"").trim(),s=Bi(e);return t&&t!==s?t:""}function $y(e,t){const s=Array.isArray(e?.byModel)?e.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=vr(String(i.model||"(default)"),Math.max(12,t-10));r.push(`${o} · ${i.sessionCount||0} sess · ${i.turnCount||0} turns`),r.push(Fa(i,i.cacheHitRatio)),r.push("")}return s.length>n.length&&r.push(`… ${s.length-n.length} more models`),r.join(`
71
- `).trimEnd()}function Ry(e,t){const s=e.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,t);r.push(Sr("users",i)),r.push(fe(""));const o=n.windowStart?`Since: ${Oa(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(_e([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],i)),r.push(_e([{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(...Ue({title:"User Totals",body:ls([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",se(n.totals.totalTokensInput||0)],["Tokens Out",se(n.totals.totalTokensOutput||0)],["Total Tokens",se((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",se(n.totals.totalTokensCacheRead||0)],["Cache Write",se(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",d],["Snapshots",Xe(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",Xe(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=_y(m),h=m.cacheHitRatio,g=h==null?"—":`${(h*100).toFixed(1)}%`,b=f?`${Bi(m)} <${f}>`:Bi(m),y=ls([["Sessions",String(m.sessionCount||0)],["Tokens In",se(m.totalTokensInput||0)],["Tokens Out",se(m.totalTokensOutput||0)],["Total Tokens",se((m.totalTokensInput||0)+(m.totalTokensOutput||0))],["Cache Read",se(m.totalTokensCacheRead||0)],["Cache Write",se(m.totalTokensCacheWrite||0)],["Hit Ratio",g],["Snapshots",Xe(m.totalSnapshotSizeBytes||0)],["Orch Size",Xe(m.totalOrchestrationHistorySizeBytes||0)]]),v=$y(m,i);r.push(fe("")),r.push(...Ue({title:`${b} (${m.sessionCount||0})`,body:v?`${y}
72
-
73
- ${v}`: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 Vt(e,t={}){const s=gt(e),n=e.ui.inspectorTab,r=Math.max(18,Number(t?.width)||36),i=!!t?.allowWideColumns,o=_d(r);if(s?.isGroup)return{title:vt("Inspector","magenta"),activeTab:n,tabs:wt,disabled:!0,stickyLines:[],lines:[fe(mu,"gray")]};const l=s?Le(s.sessionId):"",c=n==="sequence"||n==="nodes"?$a(e):null,d=n==="nodes"?[...vt("Node Map","magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:s?n==="sequence"?[...vt(o?"Sequence":`Sequence: ${l}`,"magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:n==="logs"?[...vt(o?"Logs":`Logs: ${l}`,"magenta")]:n==="history"?[...vt(o?"Duroxide Events":`Duroxide Event History: ${l}`,"magenta")]:n==="stats"?[...vt(o?"Stats":`Stats: ${l}`,"magenta"),{text:` [${Qs(e.ui?.statsViewMode)}]`,color:"gray"}]:[...vt(o?"Files":`Files: ${l}`,"magenta")]:n==="stats"?`Stats: ${Qs(e.ui?.statsViewMode).replace(/^./u,m=>m.toUpperCase())}`:"No session selected";let u,p=[];switch(n){case"sequence":{const m=s?iy(e,s,r,{allowWideColumns:i,sequenceExpansion:t?.sequenceExpansion||null}):{stickyLines:[],lines:["No session selected."]};p=m.stickyLines||[],u=m.lines;break}case"logs":u=s?Eg(e,s):["No session selected."];break;case"nodes":u=uy(e,r,{});break;case"files":u=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":u=s?Dy(e,s):["No session selected."];break;case"stats":u=Qs(e.ui?.statsViewMode)==="users"?Ry(e,r):Qs(e.ui?.statsViewMode)==="fleet"?Ty(e,r):s?xy(e,s,r):[Sr("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:wt,stickyLines:p,lines:u}}const Ly={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"},mu="Select a session to see details.";function Oy(e){const t=e.timestampMs?new Date(e.timestampMs).toISOString().slice(11,23):"???",s=Ly[e.kind]||"gray",n=[],r=[{text:`#${e.eventId}`,color:"white",bold:!0},{text:` ${t}`,color:"gray"},{text:` ${e.kind}`,color:s,bold:e.kind.includes("Failed")}];if(e.sourceEventId!=null&&r.push({text:` ←#${e.sourceEventId}`,color:"cyan"}),n.push(r),e.data)try{const i=JSON.parse(e.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=e.data.length>120?e.data.slice(0,117)+"...":e.data;n.push({text:` ${i}`,color:"white"})}return n}function Fy(e){const t={...e};if(t.data)try{t.data=JSON.parse(t.data)}catch{}return JSON.stringify(t,null,2)}function Dy(e,t){const s=e.executionHistory?.bySessionId?.[t.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=e.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=Fy(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=Oy(n[o]);for(const c of l)i.push(c);o<n.length-1&&i.push({text:"────────────────────────────────",color:"gray"})}return i}function By(e,t=88){const s=e.ui.modal;return!s||s.type!=="historyFormat"?null:La(s,{format:e.executionHistory?.format||"pretty"},t,"Execution History Format","Choose the display format for duroxide execution history events.")}function ul(e=[]){const t=[];for(const s of e)t.length>0&&t.push({text:" ",color:"gray"}),t.push({text:`${s.label} `,color:"gray"}),t.push({text:"██",color:s.color,backgroundColor:s.color});return t}function Hy(e,t=80){const s=e.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||e.ui.themeId||null,l=n.find(m=>m.id===o)||null,c=i&&i.id!==o,d=Math.max(24,t-4),u=n.map((m,f)=>{const h=m.id===o?" [current]":"",g=`${m.label}${h}`.slice(0,d);return f===r?kt(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"}],ul([{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"}]),ul([{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(t,80)),rows:u,selectedRowIndex:r,detailsTitle:"Theme Details",detailsLines:p}}function Uy(e){const t=e.ui.modal;return!t||t.type!=="confirm"?null:{title:t.title||"Confirm",message:t.message||"Are you sure?",confirmLabel:t.confirmLabel||"Confirm"}}function zs(e,t){return e.selectedName!==t.name?!0:typeof t.seq=="number"?(e.selectionSeq??0)!==t.seq:!1}function pl(e){return{mode:"mine",userId:null,data:null,users:[],drafts:{},loading:!1,saving:!1,error:null,generation:(e?.generation||0)+1,fetchedAt:null,userQuery:""}}function En(e){return JSON.stringify([e?.provider,e?.subject])}function Ut(e){const t=String(e??"").trim();return t||null}function Xr(e){return new Map(e)}function Zs(e){return new Set(e)}function jy(e){return Array.isArray(e)?[...e]:[]}function Gy(e){return Array.isArray(e)?[...e]:[]}const Wy=5e3;function ml(e,t){const s=[],n=new Set;for(const r of e||[])!r||n.has(r)||t[r]&&(n.add(r),s.push(r));return s}function fu(e){return!!(e&&!e.isSystem&&(e.isGroup||!e.parentSessionId&&!e.groupId))}function kn(e,t){const s=[],n=new Set;for(const r of e||[]){if(!r||n.has(r))continue;n.add(r);const i=t?.[r];(!i||fu(i))&&s.push(r)}return s}function qy(e,t,s){const n={},r=new Set([...Object.keys(t||{}),...Object.keys(e||{})]);for(const i of r){const o=(t||{})[i],l=(e||{})[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?.[Vf(i).sessionId];d&&d.isGroup||(n[i]=c)}return n}function hu(e){return Zs(e)}function zy(e,t){const s=[],n=new Set([e]);let r=t?.[e]||null;for(;r;){let i=null;if(r.parentSessionId&&t?.[r.parentSessionId]?i=r.parentSessionId:!r.isGroup&&r.groupId&&t?.[`group:${r.groupId}`]&&(i=`group:${r.groupId}`),!i||n.has(i))break;s.push(i),n.add(i),r=t[i]||null}return s}function fl(e,t,s){const n=hu(e);if(!s||!t?.[s])return n;for(const r of zy(s,t))n.delete(r);return n}function hl(e,t){if(e===t)return!0;if(!(e instanceof Set)||!(t instanceof Set)||e.size!==t.size)return!1;for(const s of e)if(!t.has(s))return!1;return!0}function Ky(e){return{...e||{}}}function Nt(e){return{...e||{}}}function gl(e){return{...e||{}}}function In(e){return{...e||{}}}function Qr(e){return{scope:e?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof e?.query=="string"?e.query:""}}function Vy(e){return(Array.isArray(e)?e.filter(Boolean):[]).slice(-1e3)}function Yy(e){return[F.SESSIONS,F.CHAT,F.INSPECTOR,F.ACTIVITY].includes(e)?e:null}function Zr(e,t){const s=Array.isArray(e)?e.filter(Boolean):[],n=Math.max(Ne,Number(t)||Ne);return s.length>n?s.slice(-n):s}function Hi(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(!Hi(e[r],t[r]))return!1;return!0}if(!e||!t||typeof e!="object"||typeof t!="object")return!1;const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const r of s)if(!Object.prototype.hasOwnProperty.call(t,r)||!Hi(e[r],t[r]))return!1;return!0}function Dt(e){const t=e?.updatedAt;if(typeof t=="number"&&Number.isFinite(t))return t;if(t instanceof Date)return t.getTime();const s=Date.parse(t||"");return Number.isFinite(s)?s:0}function Xy(e,t){const s=Dt(e),n=Dt(t);return s>0&&n>0&&n<=s}const Qy=new Set(["completed","failed","cancelled","error"]);function sn(e){const t=e?.statusVersion;if(t==null||t===""||typeof t=="boolean")return null;const s=Number(t);return Number.isSafeInteger(s)&&s>0?s:null}function Zy(e,t){const s=sn(e),n=sn(t);if(s!=null&&n!=null){if(n<s)return!0;if(n>s)return!1}const r=e?.status,i=t?.status;if(!r||!i||r===i||Qy.has(i))return!1;if(s!=null&&n!=null)return!0;if(r==="running")return Xy(e,t);const o=Dt(e),l=Dt(t);return i==="running"&&o>0&&l>0&&l<o}const Jy=new Set(["status","statusVersion","updatedAt","orchestrationStatus","pendingQuestion","waitReason","pauseState","error","result"]);function yl(e={},t={}){let s=e||{};const n=Zy(e,t),r=sn(e);for(const[i,o]of Object.entries(t||{}))if(o!==void 0&&!(n&&Jy.has(i))&&!(i==="updatedAt"&&r!=null&&r===sn(t)&&Dt(t)<Dt(e))&&!(i==="statusVersion"&&r!=null&&sn(t)==null)){if(i==="pendingQuestion"&&sb(e,o,t)){s===e&&(s={...e||{}}),s.pendingQuestion=null;continue}Hi(e?.[i],o)||(s===e&&(s={...e||{}}),s[i]=o)}return s}function bl(e){if(!e)return"unknown";const t=e.status||"unknown",s=t==="waiting"||t==="idle"||t==="unknown";return s&&Ds(e)?"budget_paused":e.cronActive===!0&&s?"cron_waiting":s&&(Number(e.activeChildCount)||0)>0?"awaiting_children":t}function eb(e,t,s){if(!t?.sessionId||t.isGroup)return t;const n=bl(t),r=e?.rowVisualStatus||bl(e||t);if(!e)return t.rowVisualStatus===n&&t.rowVisualStatusCandidate==null&&t.rowVisualStatusCandidateSince==null?t:{...t,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0};if(n===r)return t.rowVisualStatus===n&&t.rowVisualStatusCandidate==null&&t.rowVisualStatusCandidateSince==null?t:{...t,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0};const o=e.rowVisualStatusCandidate===n&&Number(e.rowVisualStatusCandidateSince)||s;return s-o>=Wy?{...t,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0}:t.rowVisualStatus===r&&t.rowVisualStatusCandidate===n&&Number(t.rowVisualStatusCandidateSince)===o?t:{...t,rowVisualStatus:r,rowVisualStatusCandidate:n,rowVisualStatusCandidateSince:o}}const tb=new Set(["running","input_required"]);function Jr(e){const t=new Map;for(const r of Object.values(e||{})){if(!r?.sessionId||r.isGroup||!tb.has(r.status))continue;const i=new Set([r.sessionId]);let o=r.parentSessionId;for(;o&&e[o]&&!i.has(o);)i.add(o),t.set(o,(t.get(o)||0)+1),o=e[o].parentSessionId}let s=!1;const n={};for(const[r,i]of Object.entries(e||{})){const o=t.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:e}function Sl(e={},t={},s){let n=!1;const r={};for(const[i,o]of Object.entries(t)){const l=eb(e[i],o,s);r[i]=l,l!==o&&(n=!0)}return n?r:t}function vl(e){return String(e?.question||"").trim()}function sb(e,t,s){const n=vl(t);if(!n)return!1;const r=Dt({updatedAt:t?.askedAt})||Dt(s);return[e?.answeredPendingQuestion,e?.resolvedInputQuestion].some(i=>{if(vl(i)!==n)return!1;const o=Dt({updatedAt:i?.answeredAt});return!r||!o||r<=o})}function nb(e=[]){const t=(e||[]).find(n=>n?.sessionId&&n.isSystem&&Kc(n)===0);return t?.sessionId?t.sessionId:(e||[]).find(n=>n?.sessionId)?.sessionId||null}function wl(e=[]){const t=new Set((e||[]).map(n=>n?.sessionId).filter(Boolean)),s=new Set;for(const n of e||[]){if(!n?.sessionId)continue;n.isGroup&&s.add(n.sessionId);const r=n.parentSessionId;r&&t.has(r)&&s.add(r)}return s}function El(e={}){const t=String(e?.filterQuery||"").trim(),s=on(e?.ownerFilter);return!!t||s.all!==!0}function rb(e,t=[]){const s=us(e),n=e.sessions?.activeSessionId||null;if(n&&s.some(i=>i.sessionId===n)||e.sessions?.navigationIntent||n&&e.sessions?.byId?.[n]&&!El(e.sessions)||n&&!e.sessions?.listingSeen)return n;if(El(e.sessions))return s[0]?.sessionId||null;const r=s.length>0?s.map(i=>e.sessions?.byId?.[i.sessionId]||null).filter(Boolean):t;return nb(r)}function ib(e,t){return t===e.sessions.activeSessionId?e.ui:{...e.ui,scroll:{...e.ui.scroll,chat:0,inspector:0,activity:0},followBottom:{...e.ui.followBottom||{},chat:!0,inspector:!0,activity:!0}}}function ab(e,t,s){const n=t.byId?.[s];if(!n||n.isGroup||n.isSystem)return null;const r=on(t.ownerFilter);if(r.all===!0)return null;const i=Pe(n.owner);if(!i||i===mn)return null;const o=Pe(e.auth?.principal);if(o&&i===o||r.includeShared||r.ownerKeys.includes(i))return null;const l={...t,ownerFilterExplicit:!0,ownerFilter:{...r,ownerKeys:[...r.ownerKeys,i]},ownerFilterAutoAdmitted:{sessionId:s,ownerKey:i}};return us({...e,sessions:l}).some(d=>d.sessionId===s)?l:null}function ob(e,t){const s=t?.ownerKey;return!s||e.all===!0||e.includeShared||e.ownerKeys.includes(s)?e:{...e,ownerKeys:[...e.ownerKeys,s]}}function ys(e,t){let s=t;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=fl(s.collapsedIds,s.byId,i);hl(p,s.collapsedIds)||(s={...s,collapsedIds:p,flat:ot(Object.values(s.byId||{}),p,s.orderById,s.pinnedIds,s.manualOrder)})}if(r&&s.filterExceptionId!==r&&s.ownerFilterAutoAdmitted?.sessionId!==r&&!us({...e,sessions:s}).some(m=>m.sessionId===r)){const m=ab(e,s,r);m?s=m:s={...s,filterExceptionId:r}}const o={...e,sessions:s},l=rb(o,Object.values(s.byId||{})),c=fl(s.collapsedIds,s.byId,l);return{sessions:{...!hl(c,s.collapsedIds)?{...s,collapsedIds:c,flat:ot(Object.values(s.byId||{}),c,s.orderById,s.pinnedIds,s.manualOrder)}:s,activeSessionId:l},ui:ib(e,l)}}function ei(e={},t=0,s=[]){const n=Ky(e);let r=Number.isFinite(t)?t: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 lb(e=[],t=[]){const s=ot(e,new Set,{},t),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 e||[]){const o=i?.sessionId;!o||typeof n[o]=="number"||(n[o]=r,r+=1)}return{orderById:n,nextOrderOrdinal:r}}function cb(e,t,s=null){const n=String(e||""),r=Number.isFinite(t)?t:Number.isFinite(s)?s:n.length;return Math.max(0,Math.min(r,n.length))}function kl(e,t){const s=String(e||"");return(Array.isArray(t)?t.filter(Boolean):[]).filter(r=>{if(r?.kind==="image")return!0;const i=String(r?.token||"").trim();return i&&s.includes(i)})}function db(e,t){const s=t.sessionId??t.session?.sessionId,n=/^(history|files|canvas|orchestration|executionHistory|sessionStats|outbox)\//.test(t.type)||t.type==="sessions/merged";if(s&&n&&e.sessions?.goneIds?.includes(s))return e;const r=mb(e,t);return r===e?r:ub(e,Zf(e,r,t),t)}function ub(e,t,s){const n=t.ui;if(n.sessionViewDevice!=="desktop")return t;const r=t.sessions.activeSessionId||null;if(!r||t.sessions.byId?.[r]?.isGroup)return t;const i=e.sessions.activeSessionId||null;if(s.type==="profileSettings/apply")return{...t,ui:Il(n,n.sessionViews?.[r]?.desktop||Ni())};if(r!==i)return n.sessionViewsLoaded?{...t,ui:Il(n,n.sessionViews?.[r]?.desktop||Ni())}:t;const o=Ui(n),l=Ui(e.ui);if(gu(o,l))return t;const c={...n.sessionViews?.[r]||{},desktop:{...o,at:Date.now()}};return{...t,ui:{...n,sessionViews:{...n.sessionViews||{},[r]:c}}}}function Ui(e){const t={};for(const s of yr)t[s]=Number(e.layout?.[s])||0;return{canvasOpen:e.canvasOpen===!0,diagnosticsOpen:e.diagnosticsOpen===!0,zen:e.canvasOpen===!0&&e.canvasZen===!0,layout:t}}function gu(e,t){if(e.canvasOpen!==t.canvasOpen||e.diagnosticsOpen!==t.diagnosticsOpen||e.zen!==t.zen)return!1;for(const s of yr)if(e.layout[s]!==t.layout[s])return!1;return!0}function Il(e,t){const s=Ui(e),n={canvasOpen:t.canvasOpen===!0,diagnosticsOpen:t.diagnosticsOpen===!0,zen:t.canvasOpen===!0&&t.zen===!0,layout:t.layout||{}};return gu(s,{...n,layout:{...s.layout,...n.layout}})?e:{...e,canvasOpen:n.canvasOpen,diagnosticsOpen:n.diagnosticsOpen,canvasZen:n.zen,rightPaneMode:n.canvasOpen?"canvas":"panes",...n.canvasOpen?{}:{canvasMaximized:!1},layout:{...e.layout||{},...n.layout}}}function pb(e,t){const s={...e||{}};for(const[n,r]of Object.entries(t||{})){const i=Number(r?.desktop?.at)||0,o=Number(s[n]?.desktop?.at)||0;(!s[n]||i>o)&&(s[n]=r)}return s}function mb(e,t){switch(t.type){case"connection/ready":return{...e,connection:{...e.connection,connected:!0,workersOnline:t.workersOnline??e.connection.workersOnline,error:null},ui:{...e.ui,statusText:t.statusText??e.ui.statusText??"Ready"}};case"connection/error":return{...e,connection:{...e.connection,connected:!1,error:t.error},ui:{...e.ui,statusText:t.statusText||t.error||"Connection error"}};case"auth/context":return{...e,admin:En(e.auth?.principal)!==En(t.principal)||e.auth?.authorization?.role!==t.authorization?.role?{...e.admin,features:pl(e.admin.features)}:e.admin,auth:{principal:t.principal??null,authorization:t.authorization??null}};case"ui/status":return{...e,ui:{...e.ui,statusText:t.text}};case"ui/theme":return{...e,ui:{...e.ui,themeId:t.themeId||e.ui.themeId}};case"ui/sessionViewDevice":{const s=t.device==="desktop"||t.device==="mobile"?t.device:null;return s===e.ui.sessionViewDevice?e:{...e,ui:{...e.ui,sessionViewDevice:s}}}case"ui/touchScale":return!!t.enabled==!!e.ui.touchScale?e:{...e,ui:{...e.ui,touchScale:!!t.enabled}};case"ui/agentPickerUsage":{const s=t.usage&&typeof t.usage=="object"&&!Array.isArray(t.usage)?t.usage:{};return{...e,ui:{...e.ui,agentPickerUsage:s}}}case"ui/sessionDetailCollapsed":return!!t.collapsed==!!e.ui.sessionDetailCollapsed?e:{...e,ui:{...e.ui,sessionDetailCollapsed:!!t.collapsed}};case"ui/moaSaveStatus":return{...e,ui:{...e.ui,moaSaveStatus:t.status,moaDirty:t.status==="saved"&&e.ui.moaRevision===t.revision?!1:e.ui.moaDirty}};case"ui/moa":return{...e,ui:{...e.ui,moa:cn(t.value),moaDirty:!0,moaRevision:(e.ui.moaRevision||0)+1}};case"profileSettings/apply":{const s=t.settings&&typeof t.settings=="object"&&!Array.isArray(t.settings)?t.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"?pb(Ad(s.sessionViews),e.ui.sessionViews):e.ui.sessionViews,f=u||d?Nd(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"),v=!!(e.sessions.navigationIntent&&e.sessions.navigationIntent.status!=="failed"),S=Object.prototype.hasOwnProperty.call(s,"activeSessionId")&&!v&&!e.sessions.localSelectionMade,w=Object.keys(e.sessions.byId||{}).length>0,E=i?{...e.ui.layout||{},...pa(s.layoutAdjustments)}:e.ui.layout,I=g?w?kn(Jn(s.pinnedSessionIds),e.sessions.byId):Jn(s.pinnedSessionIds):e.sessions.pinnedIds,T=b?w?hu(Ai(s.collapsedSessionIds),e.sessions.byId):Ai(s.collapsedSessionIds):e.sessions.collapsedIds,C=y?ma(s.sessionOrder):e.sessions.manualOrder,k=S?Cd(s.activeSessionId):e.sessions.activeSessionId,O=Td(s.sessionUsedAt),N={...e.sessions,...r?{ownerFilter:ob(on(s.sessionOwnerFilter),e.sessions.ownerFilterAutoAdmitted),ownerFilterExplicit:!0}:{},pinnedIds:I,manualOrder:C,sortMode:Object.hasOwn(s,"sessionSortMode")?ln(s.sessionSortMode):e.sessions.sortMode,usedAt:Object.fromEntries([...new Set([...Object.keys(O),...Object.keys(e.sessions.usedAt||{})])].map(H=>[H,Math.max(O[H]||0,e.sessions.usedAt?.[H]||0)])),collapsedIds:T,collapsedIdsExplicit:b?!0:e.sessions.collapsedIdsExplicit,activeSessionId:k,flat:g||b||y?ot(Object.values(e.sessions.byId),T,e.sessions.orderById,I,C):e.sessions.flat},R=w&&(r||g||b||S)?ys(e,N):{sessions:N,ui:e.ui};return{...e,sessions:R.sessions,ui:{...R.ui,moa:!e.ui.moaDirty&&Object.prototype.hasOwnProperty.call(s,"moa")?cn(s.moa):R.ui.moa,moaLoaded:!0,themeId:n?s.themeId.trim():R.ui.themeId,touchScale:o?s.touchScale:R.ui.touchScale,sessionDetailCollapsed:l?s.sessionDetailCollapsed:R.ui.sessionDetailCollapsed,agentPickerUsage:c?s.agentPickerUsage:R.ui.agentPickerUsage,rightPaneMode:d?s.rightPaneMode:R.ui.rightPaneMode,...f?{canvasOpen:f.canvasOpen,diagnosticsOpen:f.diagnosticsOpen,canvasZen:f.zen===!0}:{},layout:E,sessionViews:m,sessionViewsLoaded:!0},canvas:h?{...e.canvas,prefs:qy(e.canvas.prefs,fa(s.canvasPrefs),w?e.sessions.byId:null)}:e.canvas}}case"ui/modal":return{...e,ui:{...e.ui,modal:t.modal??null}};case"ui/viewport":{const s=e.ui.layout?.viewportWidth??120,n=e.ui.layout?.viewportHeight??40,r=Math.max(40,t.width??s),i=Math.max(18,t.height??n);return r===s&&i===n?e:{...e,ui:{...e.ui,layout:{...e.ui.layout||{},viewportWidth:r,viewportHeight:i}}}}case"ui/paneAdjust":return{...e,ui:{...e.ui,layout:{...e.ui.layout||{},paneAdjust:Number(t.paneAdjust)||0}}};case"ui/sessionPaneAdjust":return{...e,ui:{...e.ui,layout:{...e.ui.layout||{},sessionPaneAdjust:Number(t.sessionPaneAdjust)||0}}};case"ui/portalSessionColumnAdjust":return{...e,ui:{...e.ui,layout:{...e.ui.layout||{},portalSessionColumnAdjust:Number(t.portalSessionColumnAdjust)||0}}};case"ui/canvasPaneAdjust":return{...e,ui:{...e.ui,layout:{...e.ui.layout||{},canvasPaneAdjust:Number(t.canvasPaneAdjust)||0}}};case"budget/tab":{const s=["summary","agents"].includes(t.tab)?t.tab:"providers";return e.budget.tab===s?e:{...e,budget:{...e.budget,tab:s}}}case"budget/summary/filter":{const s=e.budget.summary,n=[14,30,90].includes(Number(t.days))?Number(t.days):s.days,r=Array.isArray(t.providers)?t.providers.map(o=>String(o??"").trim()).filter(Boolean):s.providers,i=["all","shared","users","custom"].includes(t.preset)?t.preset:Array.isArray(t.providers)?"custom":s.preset;return{...e,budget:{...e.budget,summary:{...s,days:n,providers:r,preset:i}}}}case"budget/summary/loading":return{...e,budget:{...e.budget,summary:{...e.budget.summary,loading:!0}}};case"budget/summary/loaded":return{...e,budget:{...e.budget,summary:{...e.budget.summary,loading:!1,error:null,fetchedAt:Number(t.fetchedAt)||Date.now(),data:t.data&&typeof t.data=="object"?t.data:null}}};case"budget/agents/loading":return{...e,budget:{...e.budget,agents:{...e.budget.agents,loading:!0}}};case"budget/agents/loaded":return{...e,budget:{...e.budget,agents:{...e.budget.agents,loading:!1,error:null,fetchedAt:Number(t.fetchedAt)||Date.now(),data:t.data&&typeof t.data=="object"?t.data:null}}};case"budget/agents/failed":return{...e,budget:{...e.budget,agents:{...e.budget.agents,loading:!1,error:String(t.error||"The agent pivot could not be read.")}}};case"budget/summary/failed":return{...e,budget:{...e.budget,summary:{...e.budget.summary,loading:!1,error:String(t.error||"The summary could not be read.")}}};case"ui/diagnosticsSplitAdjust":return{...e,ui:{...e.ui,layout:{...e.ui.layout||{},diagnosticsSplitAdjust:Number(t.diagnosticsSplitAdjust)||0}}};case"ui/diagnosticsPaneAdjust":return{...e,ui:{...e.ui,layout:{...e.ui.layout||{},diagnosticsPaneAdjust:Number(t.diagnosticsPaneAdjust)||0}}};case"ui/activityPaneAdjust":return{...e,ui:{...e.ui,layout:{...e.ui.layout||{},activityPaneAdjust:Number(t.activityPaneAdjust)||0}}};case"ui/focus":return{...e,ui:{...e.ui,focusRegion:t.focusRegion,requestedFocusRegion:t.requestedFocusRegion??t.focusRegion}};case"ui/sequenceExpandedTurns":return{...e,ui:{...e.ui,sequenceExpandedTurns:Array.isArray(t.turns)?t.turns:[]}};case"ui/sequenceSelectedTurn":return{...e,ui:{...e.ui,sequenceSelectedTurn:t.turn==null?null:Number(t.turn)}};case"sessions/filterQuery":{const s={...e.sessions,filterQuery:typeof t.query=="string"?t.query:"",navigationIntent:null,filterExceptionId:null,ownerFilterAutoAdmitted:null};return{...e,sessions:s}}case"sessions/ownerFilter":{const s={...e.sessions,ownerFilterExplicit:!0,ownerFilter:on(t.filter),navigationIntent:null,filterExceptionId:null,ownerFilterAutoAdmitted:null},n=ys(e,s);return{...e,sessions:n.sessions,ui:n.ui}}case"sessions/navigationIntent":{const s=String(t.sessionId||"").trim();if(!s)return e;const n={...e.sessions,listDeselected:!1,navigationIntent:{sessionId:s,status:"pending"},filterExceptionId:null,ownerFilterAutoAdmitted:null},r=ys(e,n);return{...e,sessions:r.sessions,ui:r.ui}}case"sessions/navigationIntentFailed":{const s=e.sessions.navigationIntent,n=String(t.sessionId||"").trim();return!s||n&&s.sessionId!==n?e:{...e,sessions:{...e.sessions,navigationIntent:{sessionId:s.sessionId,status:"failed",errorKind:t.errorKind==="not_found"?"not_found":"network"}}}}case"ui/modalSelection":{const s=e.ui.modal;if(!s)return e;if(s.type==="help")return{...e,ui:{...e.ui,modal:{...s,selectedIndex:Math.max(0,Number(t.index)||0)}}};if(!Array.isArray(s.items)||s.items.length===0)return e;const n=Math.max(0,Math.min(t.index??0,s.items.length-1)),r=s.type==="themePicker"?s.items[n]?.id:null;return{...e,ui:{...e.ui,...r?{themeId:r}:{},modal:{...s,selectedIndex:n}}}}case"ui/scroll":return{...e,ui:{...e.ui,scroll:{...e.ui.scroll,[t.pane]:Math.max(0,t.offset??0)}}};case"ui/followBottom":{if(t.pane!=="chat"&&t.pane!=="inspector"&&t.pane!=="activity")return e;const s=!!t.followBottom;return e.ui.followBottom?.[t.pane]===s?e:{...e,ui:{...e.ui,followBottom:{...e.ui.followBottom||{},[t.pane]:s}}}}case"ui/nodeMapSelect":return t.label?{...e,ui:{...e.ui,nodeMapSelectedNode:String(t.label)}}:e;case"ui/inspectorTab":return{...e,ui:{...e.ui,inspectorTab:t.inspectorTab,fullscreenPane:t.inspectorTab==="files"&&e.ui.fullscreenPane===F.INSPECTOR?null:e.ui.fullscreenPane,scroll:{...e.ui.scroll,inspector:0},followBottom:{...e.ui.followBottom||{},inspector:!0}},files:t.inspectorTab==="files"?e.files:{...e.files,fullscreen:!1}};case"ui/statsViewMode":return{...e,ui:{...e.ui,statsViewMode:["session","fleet","users"].includes(t.statsViewMode)?t.statsViewMode:"session",scroll:{...e.ui.scroll,inspector:0}}};case"ui/prompt":return{...e,ui:{...e.ui,prompt:t.prompt,promptCursor:cb(t.prompt,t.promptCursor,e.ui.promptCursor),promptRows:Cs(t.prompt),promptAttachments:kl(t.prompt,e.ui.promptAttachments)}};case"ui/promptEdit":return{...e,ui:{...e.ui,promptEdit:t.promptEdit??null}};case"ui/promptAttachments":return{...e,ui:{...e.ui,promptAttachments:kl(e.ui.prompt,t.attachments)}};case"sessions/gone":{const s=t.sessionId;if(!s)return e;const n=!!e.sessions.byId[s],r=e.sessions.activeSessionId===s,i=e.history.bySessionId.has(s)||[e.files,e.canvas,e.orchestration,e.executionHistory,e.outbox,e.sessionStats].some(p=>Object.hasOwn(p?.bySessionId||{},s));if(!n&&!r&&!i)return e;const o={...e.sessions.byId};delete o[s];const l=Jr(o),c=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds.filter(p=>p!==s):e.sessions.selectedIds,d=new Map(e.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{...e,history:{...e.history,bySessionId:d},files:u(e.files),orchestration:u(e.orchestration),executionHistory:u(e.executionHistory),canvas:u(e.canvas),outbox:u(e.outbox),sessionStats:u(e.sessionStats),sessions:{...e.sessions,byId:l,selectedIds:c,activeSessionId:r?null:e.sessions.activeSessionId,goneIds:[...new Set([...e.sessions.goneIds||[],s])].slice(-1e3)}}}case"sessions/loaded":{const s={};let n=!1;const r=Date.now();for(const I of e.sessions.groupRows||[])s[I.sessionId]=e.sessions.byId[I.sessionId]||I;for(const I of t.sessions){const T=e.sessions.byId[I.sessionId];s[I.sessionId]=bo(T,yl(T,I),e.history.bySessionId.get(I.sessionId)?.events,r)}e.sessions.activeSessionId&&e.sessions.byId[e.sessions.activeSessionId]&&!e.sessions.byId[e.sessions.activeSessionId]?.isGroup&&!s[e.sessions.activeSessionId]&&(s[e.sessions.activeSessionId]={...e.sessions.byId[e.sessions.activeSessionId]},n=!0);const i=Jr(s),o=Sl(e.sessions.byId,i,r);for(const[I,T]of Object.entries(o))if(T!==e.sessions.byId[I]){n=!0;break}const l=Object.keys(e.sessions.byId),c=Object.keys(o);if(l.length!==c.length&&(n=!0),!n){for(const I of c)if(!e.sessions.byId[I]){n=!0;break}}if(!n)return e;const d=Object.values(o),u=Object.keys(e.sessions.orderById||{}).length>0,p=wl(d),m=!!e.sessions.collapsedIdsExplicit,{orderById:f,nextOrderOrdinal:h}=u?ei(e.sessions.orderById,e.sessions.nextOrderOrdinal,d):lb(d,e.sessions.pinnedIds),g=m?Zs(e.sessions.collapsedIds):p,b=e.sessions.listingSeen===!0;if(m&&b){const I=wl(Object.values(e.sessions.byId));for(const T of p)I.has(T)||g.add(T)}const y=kn(e.sessions.pinnedIds,o),v=ml(e.sessions.selectedIds,o),S=ot(d,g,f,y,e.sessions.manualOrder),w={...e.sessions,byId:o,goneIds:(e.sessions.goneIds||[]).filter(I=>!t.sessions.some(T=>T.sessionId===I)),collapsedIds:g,collapsedIdsExplicit:m,listingSeen:!0,pinnedIds:y,selectedIds:v,selectMode:e.sessions.selectMode&&v.length>0,flat:S,activeSessionId:e.sessions.activeSessionId,orderById:f,nextOrderOrdinal:h},E=ys(e,w);return{...e,sessions:E.sessions,ui:E.ui}}case"sessions/groupsLoaded":{const s=Array.isArray(t.groups)?t.groups:[],n={...e.sessions.byId},r=Array.isArray(t.sessions)?t.sessions:Object.values(e.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=kn(e.sessions.pinnedIds,n),{orderById:c,nextOrderOrdinal:d}=ei(e.sessions.orderById,e.sessions.nextOrderOrdinal,Object.values(n)),u=e.sessions.groupsListingSeen===!0,p=Zs(e.sessions.collapsedIds);for(const h of s)u&&(e.sessions.byId[h.sessionId]||p.add(h.sessionId));const m={...e.sessions,groupRows:[...s,...o],byId:n,pinnedIds:l,orderById:c,nextOrderOrdinal:d,collapsedIds:p,groupsListingSeen:!0,flat:ot(Object.values(n),p,c,l,e.sessions.manualOrder)},f=ys(e,m);return{...e,sessions:f.sessions,ui:f.ui}}case"sessions/merged":{if(!t.session?.sessionId)return e;const s=e.sessions.byId[t.session.sessionId],n=bo(s,yl(s,t.session),e.history.bySessionId.get(t.session.sessionId)?.events),r=Sl(e.sessions.byId,Jr({...e.sessions.byId,[t.session.sessionId]:n}),Date.now());let i=!1;for(const[p,m]of Object.entries(r))if(m!==e.sessions.byId[p]){i=!0;break}if(!i)return e;const o=kn(e.sessions.pinnedIds,r),{orderById:l,nextOrderOrdinal:c}=ei(e.sessions.orderById,e.sessions.nextOrderOrdinal,Object.values(r)),d={...e.sessions,byId:r,pinnedIds:o,flat:ot(Object.values(r),e.sessions.collapsedIds,l,o,e.sessions.manualOrder),activeSessionId:e.sessions.activeSessionId,orderById:l,nextOrderOrdinal:c},u=ys(e,d);return{...e,sessions:u.sessions,ui:u.ui}}case"sessions/sortMode":return{...e,sessions:{...e.sessions,sortMode:ln(t.mode)}};case"sessions/refreshSort":return{...e,sessions:{...e.sessions}};case"sessions/used":return t.sessionId?{...e,sessions:{...e.sessions,usedAt:{...e.sessions.usedAt,[t.sessionId]:t.at||Date.now()}}}:e;case"sessions/selected":{e={...e,sessions:{...e.sessions,listDeselected:!1,localSelectionMade:!0,usedAt:t.sessionId?{...e.sessions.usedAt,[t.sessionId]:Date.now()}:e.sessions.usedAt}};const s=e.sessions.activeSessionId,n={...e.ui.chatScrollBySession||{}},r={...e.ui.chatFollowBottomBySession||{}};s&&s!==t.sessionId&&(n[s]=Number(e.ui.scroll?.chat)||0,r[s]=e.ui.followBottom?.chat!==!1);const i=s!==t.sessionId,o={...e.ui.promptDraftBySession||{}};let l=e.ui.prompt,c=e.ui.promptCursor,d=e.ui.promptAttachments,u=e.ui.promptEdit??null;if(i){if(!!!e.ui.promptEdit&&s){const h={prompt:String(e.ui.prompt||""),attachments:Array.isArray(e.ui.promptAttachments)?e.ui.promptAttachments:[]};h.prompt||h.attachments.length>0?o[s]=h:delete o[s]}const f=t.sessionId?o[t.sessionId]:null;delete o[t.sessionId],l=f?.prompt||"",c=l.length,d=Array.isArray(f?.attachments)?f.attachments:[],u=null}const p=!!(e.sessions.navigationIntent&&e.sessions.navigationIntent.sessionId!==t.sessionId);return{...e,sessions:{...e.sessions,activeSessionId:t.sessionId,...p?{navigationIntent:null,filterExceptionId:null,ownerFilterAutoAdmitted:null}:{}},ui:{...e.ui,chatScrollBySession:n,chatFollowBottomBySession:r,promptDraftBySession:o,prompt:l,promptCursor:c,promptRows:Cs(l),promptAttachments:d,promptEdit:u,statusText:s!==t.sessionId?"":e.ui.statusText,scroll:{...e.ui.scroll,chat:Number(n[t.sessionId])||0,inspector:0,activity:0},followBottom:{...e.ui.followBottom||{},chat:r[t.sessionId]!==!1,inspector:!0,activity:!0}}}}case"ui/revealCreatedSession":return{...e,files:{...e.files,fullscreen:!1,paneOpen:!1},ui:{...e.ui,revealedCreatedSessionId:t.sessionId,fullscreenPane:null}};case"ui/fullscreenPane":{const s=Yy(t.fullscreenPane);return{...e,files:s?{...e.files,fullscreen:!1}:e.files,ui:{...e.ui,fullscreenPane:s,focusRegion:s||e.ui.focusRegion}}}case"sessions/collapse":{const s=Zs(e.sessions.collapsedIds);return s.add(t.sessionId),{...e,sessions:{...e.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:ot(Object.values(e.sessions.byId),s,e.sessions.orderById,e.sessions.pinnedIds,e.sessions.manualOrder)}}}case"sessions/expand":{const s=Zs(e.sessions.collapsedIds);return s.delete(t.sessionId),{...e,sessions:{...e.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:ot(Object.values(e.sessions.byId),s,e.sessions.orderById,e.sessions.pinnedIds,e.sessions.manualOrder)}}}case"sessions/pinToggle":{const s=String(t.sessionId||"").trim();if(!s)return e;const n=e.sessions.byId[s];if(!fu(n))return e;const r=jy(e.sessions.pinnedIds),o=r.indexOf(s)>=0?r.filter(l=>l!==s):[...r,s];return{...e,sessions:{...e.sessions,pinnedIds:o,flat:ot(Object.values(e.sessions.byId),e.sessions.collapsedIds,e.sessions.orderById,o,e.sessions.manualOrder)}}}case"sessions/reorder":{const s=String(t.sessionId||"").trim();if(!s)return e;const n=e.sessions.byId[s];if(!Fs(n))return e;const r=t.beforeSessionId==null?null:String(t.beforeSessionId).trim()||null;if(r===s)return e;const o=(Array.isArray(e.sessions.manualOrder)&&e.sessions.manualOrder.length>0?e.sessions.manualOrder:(e.sessions.flat||[]).map(u=>u.sessionId).filter(u=>Fs(e.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===(e.sessions.manualOrder||[]).length&&c.every((u,p)=>u===e.sessions.manualOrder[p])?e:{...e,sessions:{...e.sessions,manualOrder:c,flat:ot(Object.values(e.sessions.byId),e.sessions.collapsedIds,e.sessions.orderById,e.sessions.pinnedIds,c)}}}case"sessions/selectMode":{const s=!!t.enabled;return s===!!e.sessions.selectMode&&(s||e.sessions.selectedIds.length===0)?e:{...e,sessions:{...e.sessions,selectMode:s,selectedIds:s?e.sessions.selectedIds:[]}}}case"sessions/selectToggle":{const s=String(t.sessionId||"").trim(),n=s?e.sessions.byId[s]:null;if(!n||n.isSystem||n.isGroup)return e;const r=Gy(e.sessions.selectedIds),o=r.indexOf(s)>=0?r.filter(l=>l!==s):[...r,s];return{...e,sessions:{...e.sessions,selectedIds:o,selectMode:o.length>0?!0:e.sessions.selectMode}}}case"sessions/selectSet":{const s=Array.isArray(t.sessionIds)?t.sessionIds:[],n=ml(s,e.sessions.byId).filter(r=>!e.sessions.byId[r]?.isSystem&&!e.sessions.byId[r]?.isGroup);return{...e,sessions:{...e.sessions,selectedIds:n,selectMode:n.length>0?!0:e.sessions.selectMode}}}case"sessions/listReselect":return e.sessions.listDeselected?{...e,sessions:{...e.sessions,listDeselected:!1}}:e;case"sessions/listDeselect":return{...e,sessions:{...e.sessions,listDeselected:!0,selectedIds:[],selectMode:!1}};case"sessions/selectClear":return e.sessions.selectedIds.length===0&&!e.sessions.selectMode?e:{...e,sessions:{...e.sessions,selectedIds:[],selectMode:!1}};case"history/loadState":{if(!e.sessions.byId[t.sessionId])return e;const s=Xr(e.history.bySessionId);return s.set(t.sessionId,{...s.get(t.sessionId),loadState:t.loadState}),{...e,history:{...e.history,bySessionId:s}}}case"history/set":{const s=e.history.bySessionId.get(t.sessionId)||null,n=s?.chat||[],r=Math.max(Ne,Number(t.history?.loadedEventLimit??s?.loadedEventLimit??Ne)||Ne),i=Zr(xs(t.history?.chat||[]),r),o=n[n.length-1]?.id||null,l=i[i.length-1]?.id||null,c=t.sessionId===e.sessions.activeSessionId&&l!==o,d=Xr(e.history.bySessionId);return d.set(t.sessionId,{...t.history||{},chat:i,activity:Zr(t.history?.activity||[],r),events:Zr(t.history?.events||[],r),loadedEventLimit:r}),{...e,history:{...e.history,bySessionId:d},ui:c&&e.ui.followBottom?.chat!==!1?{...e.ui,scroll:{...e.ui.scroll,chat:0}}:e.ui}}case"history/evict":{const s=Array.isArray(t.sessionIds)?t.sessionIds:[];if(s.length===0)return e;const n=Xr(e.history.bySessionId);for(const c of s)n.delete(c);const r=gl(e.outbox?.bySessionId);for(const c of s)delete r[c];const i={...e.ui.chatScrollBySession||{}};for(const c of s)delete i[c];const o={...e.ui.chatFollowBottomBySession||{}};for(const c of s)delete o[c];const l={...e.ui.promptDraftBySession||{}};for(const c of s)delete l[c];return{...e,history:{...e.history,bySessionId:n},outbox:{...e.outbox,bySessionId:r},ui:{...e.ui,chatScrollBySession:i,chatFollowBottomBySession:o,promptDraftBySession:l}}}case"outbox/setSessionItems":{const s=t.sessionId;if(!s)return e;const n=Array.isArray(t.items)?t.items.filter(Boolean):[],r=gl(e.outbox?.bySessionId);return n.length===0?delete r[s]:r[s]=n,{...e,outbox:{...e.outbox,bySessionId:r}}}case"orchestration/statsLoading":{const s=In(e.orchestration.bySessionId);return s[t.sessionId]={...s[t.sessionId]||{},loading:!0,error:null},{...e,orchestration:{...e.orchestration,bySessionId:s}}}case"orchestration/statsLoaded":{const s=In(e.orchestration.bySessionId);return s[t.sessionId]={loading:!1,error:null,fetchedAt:t.fetchedAt||Date.now(),stats:t.stats||null},{...e,orchestration:{...e.orchestration,bySessionId:s}}}case"orchestration/statsError":{const s=In(e.orchestration.bySessionId);return s[t.sessionId]={...s[t.sessionId]||{},loading:!1,error:t.error||"Failed to load orchestration stats",fetchedAt:t.fetchedAt||Date.now()},{...e,orchestration:{...e.orchestration,bySessionId:s}}}case"orchestration/evict":{const s=Array.isArray(t.sessionIds)?t.sessionIds:[];if(s.length===0)return e;const n=In(e.orchestration.bySessionId);for(const r of s)delete n[r];return{...e,orchestration:{...e.orchestration,bySessionId:n}}}case"executionHistory/loading":{const s={...e.executionHistory?.bySessionId||{}};return s[t.sessionId]={...s[t.sessionId]||{},loading:!0,error:null},{...e,executionHistory:{...e.executionHistory,bySessionId:s}}}case"executionHistory/loaded":{const s={...e.executionHistory?.bySessionId||{}},n=t.events||[],r=1e3,i=n.length>r?n.slice(-r):n;return s[t.sessionId]={loading:!1,error:null,fetchedAt:t.fetchedAt||Date.now(),events:i},{...e,executionHistory:{...e.executionHistory,bySessionId:s}}}case"executionHistory/evict":{const s=Array.isArray(t.sessionIds)?t.sessionIds:[];if(s.length===0)return e;const n={...e.executionHistory?.bySessionId||{}};for(const r of s)delete n[r];return{...e,executionHistory:{...e.executionHistory,bySessionId:n}}}case"executionHistory/error":{const s={...e.executionHistory?.bySessionId||{}};return s[t.sessionId]={...s[t.sessionId]||{},loading:!1,error:t.error||"Failed to load execution history",fetchedAt:t.fetchedAt||Date.now()},{...e,executionHistory:{...e.executionHistory,bySessionId:s}}}case"executionHistory/format":return{...e,executionHistory:{...e.executionHistory,format:t.format||"pretty"}};case"sessionStats/loading":{const s={...e.sessionStats?.bySessionId||{}};return s[t.sessionId]={...s[t.sessionId]||{},loading:!0},{...e,sessionStats:{...e.sessionStats,bySessionId:s}}}case"sessionStats/loaded":{const s={...e.sessionStats?.bySessionId||{}};return s[t.sessionId]={loading:!1,fetchedAt:Date.now(),summary:t.summary||null,tokensByModel:Array.isArray(t.tokensByModel)?t.tokensByModel:[],treeStats:t.treeStats||null,skillUsage:t.skillUsage||null,treeSkillUsage:t.treeSkillUsage||null,factsStats:t.factsStats||null,treeFactsStats:t.treeFactsStats||null},{...e,sessionStats:{...e.sessionStats,bySessionId:s}}}case"fleetStats/loading":return{...e,fleetStats:{...e.fleetStats,loading:!0}};case"fleetStats/loaded":return{...e,fleetStats:{loading:!1,data:t.data||null,userStats:t.userStats||null,skillUsage:t.skillUsage||null,retrievalUsage:t.retrievalUsage||null,sharedFactsStats:t.sharedFactsStats||null,factsTombstoneStats:t.factsTombstoneStats||null,fetchedAt:Date.now()}};case"admin/visibility":{const s=!!t.visible;return e.admin.visible===s&&!(s&&e.ui.budgetOpen)?e:{...e,ui:s&&e.ui.budgetOpen?{...e.ui,budgetOpen:!1}:e.ui,admin:{...e.admin,visible:s,ghcpKey:s?e.admin.ghcpKey:{editing:!1,draft:"",saving:!1,error:null,lastSavedAt:e.admin.ghcpKey.lastSavedAt},modelProviders:s?e.admin.modelProviders:{...e.admin.modelProviders,create:{...e.admin.modelProviders.create,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null}}}}}case"admin/profile/loading":return{...e,admin:{...e.admin,loading:!0,loadError:null}};case"admin/profile/loaded":return{...e,admin:{...e.admin,loading:!1,loadError:null,profile:t.profile||null,features:En(e.admin.profile)!==En(t.profile)||!!e.admin.profile?.isAdmin!=!!t.profile?.isAdmin?pl(e.admin.features):e.admin.features,ghcpKey:{...e.admin.ghcpKey,error:e.admin.ghcpKey.editing?e.admin.ghcpKey.error:null}}};case"admin/profile/loadFailed":return{...e,admin:{...e.admin,loading:!1,loadError:t.error?String(t.error):"Failed to load profile"}};case"admin/ghcpKey/beginEdit":{const s=typeof t.draft=="string"?t.draft:"";return{...e,admin:{...e.admin,ghcpKey:{editing:!0,draft:s,cursorIndex:s.length,saving:!1,error:null,lastSavedAt:e.admin.ghcpKey.lastSavedAt,storeAsSystem:!!e.admin.ghcpKey.storeAsSystem}}}}case"admin/ghcpKey/setDraft":{if(!e.admin.ghcpKey.editing)return e;const s=typeof t.draft=="string"?t.draft:"",n=Number.isFinite(t.cursorIndex)?Number(t.cursorIndex):s.length,r=Math.max(0,Math.min(n,s.length));return s===e.admin.ghcpKey.draft&&r===e.admin.ghcpKey.cursorIndex?e:{...e,admin:{...e.admin,ghcpKey:{...e.admin.ghcpKey,draft:s,cursorIndex:r,error:null}}}}case"admin/ghcpKey/cancelEdit":return!e.admin.ghcpKey.editing&&!e.admin.ghcpKey.draft?e:{...e,admin:{...e.admin,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:e.admin.ghcpKey.lastSavedAt,storeAsSystem:!!e.admin.ghcpKey.storeAsSystem}}};case"admin/ghcpKey/saving":return{...e,admin:{...e.admin,ghcpKey:{...e.admin.ghcpKey,saving:!0,error:null}}};case"admin/ghcpKey/saveFailed":return{...e,admin:{...e.admin,ghcpKey:{...e.admin.ghcpKey,saving:!1,error:t.error?String(t.error):"Failed to save key"}}};case"admin/ghcpKey/saved":return{...e,admin:{...e.admin,profile:t.profile||e.admin.profile,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:Date.now(),storeAsSystem:!!e.admin.ghcpKey.storeAsSystem}}};case"admin/ghcpKey/setSystemTarget":{const s=!!t.value;return!!e.admin.ghcpKey.storeAsSystem===s?e:{...e,admin:{...e.admin,ghcpKey:{...e.admin.ghcpKey,storeAsSystem:s,error:null}}}}case"admin/systemGhcpKey/loading":return{...e,admin:{...e.admin,systemGhcpKey:{...e.admin.systemGhcpKey,loading:!0,error:null}}};case"admin/systemGhcpKey/loaded":{const s=t.status||{};return{...e,admin:{...e.admin,systemGhcpKey:{supported:!0,loading:!1,configured:!!s.configured,changedBy:s.changedBy||null,changedAt:s.changedAt||null,error:null}}}}case"admin/systemGhcpKey/loadFailed":return{...e,admin:{...e.admin,systemGhcpKey:{...e.admin.systemGhcpKey,loading:!1,error:t.error?String(t.error):"Failed to load System key status"}}};case"admin/modelProviders/loading":return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,loading:!0,error:null}}};case"admin/modelProviders/loaded":return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,loading:!1,error:null,providers:Array.isArray(t.providers)?t.providers:[],models:Array.isArray(t.models)?t.models:[],defaults:t.defaults||null,fetchedAt:Date.now()}}};case"admin/modelProviders/loadFailed":return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,loading:!1,error:t.error?String(t.error):"Failed to load model providers"}}};case"admin/modelProviders/mutationPending":return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,mutation:{pending:t.pending||"change",error:null}}}};case"admin/modelProviders/mutationDone":return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,mutation:{pending:null,error:null}}}};case"admin/modelProviders/mutationFailed":return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,mutation:{pending:null,error:t.error?String(t.error):"The provider change failed"}}}};case"admin/modelProviders/mutationDismissed":return e.admin?.modelProviders?.mutation?.error?{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,mutation:{...e.admin.modelProviders.mutation,error:null}}}}:e;case"admin/modelProviders/select":return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,selection:{focus:t.focus==="agents"?"agents":"providers",providerName:t.providerName??e.admin.modelProviders.selection?.providerName??null,agentId:t.agentId??e.admin.modelProviders.selection?.agentId??null}}}};case"admin/modelProviders/page":{const s=t.page==="shared"?"shared":"mine";return s===e.admin.modelProviders.page?e:{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,page:s,selection:{...e.admin.modelProviders.selection,focus:"providers",providerName:null}}}}}case"admin/modelProviders/createBegin":{const s=String(t.name||""),n=t.mode==="update";return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,create:{editing:!0,mode:n?"update":"create",stage:n||t.stage==="credential"?"credential":"name",name:n?s:"",typeId:String(t.typeId||""),shared:t.shared===!0,draft:n?"":s,cursorIndex:n?0:s.length,saving:!1,error:null}}}}}case"admin/modelProviders/createDraft":{const s=String(t.draft||"").replace(/\r?\n/gu,""),n=Math.max(0,Math.min(Number(t.cursorIndex)||0,s.length));return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,create:{...e.admin.modelProviders.create,draft:s,cursorIndex:n,error:null}}}}}case"admin/modelProviders/createType":return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,create:{...e.admin.modelProviders.create,typeId:String(t.typeId||""),error:null}}}};case"admin/modelProviders/createCredential":return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,create:{...e.admin.modelProviders.create,stage:"credential",name:String(t.name||""),draft:"",cursorIndex:0,error:null}}}};case"admin/modelProviders/createSaving":return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,create:{...e.admin.modelProviders.create,draft:"",cursorIndex:0,saving:!0,error:null}}}};case"admin/modelProviders/createFailed":{const s=e.admin.modelProviders.create,n=s.stage==="credential";return{...e,admin:{...e.admin,modelProviders:{...e.admin.modelProviders,create:{...s,draft:n?"":s.draft,cursorIndex:n?0:s.cursorIndex,saving:!1,error:t.error?String(t.error):"The provider could not be created"}}}}}case"admin/modelProviders/createEnd":return{...e,admin:{...e.admin,modelProviders:{...e.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(t.section)?t.section:"ghcp";return{...e,admin:{...e.admin,section:s}}}case"admin/features":return{...e,admin:{...e.admin,features:{...e.admin.features,...t.patch}}};case"admin/workers/attempt":{const s=e.admin.workers||{};return{...e,admin:{...e.admin,workers:{...s,attempts:(s.attempts||0)+1,lastAttemptAt:Date.now(),lastSkip:t.skip||null}}}}case"admin/workers/loading":return{...e,admin:{...e.admin,workers:{...e.admin.workers,loading:!0,error:null}}};case"admin/workers/loaded":return{...e,admin:{...e.admin,workers:{loading:!1,error:null,list:Array.isArray(t.list)?t.list:[],fetchedAt:Date.now()}}};case"admin/workers/loadFailed":return{...e,admin:{...e.admin,workers:{...e.admin.workers,loading:!1,error:t.error||"Failed to load workers"}}};case"admin/packages/loading":return{...e,admin:{...e.admin,packages:{...e.admin.packages,loading:!0,error:null}}};case"admin/packages/loaded":{const s=e.admin.packages,n=Array.isArray(t.list)?t.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{...e,admin:{...e.admin,packages:{...s,loading:!1,error:null,list:n,workerState:Array.isArray(t.workerState)?t.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{...e,admin:{...e.admin,packages:{...e.admin.packages,loading:!1,error:t.error||"Failed to load packages"}}};case"admin/packages/select":return{...e,admin:{...e.admin,section:"packages",packages:{...e.admin.packages,selectedName:t.name||null,selectedSelector:t.selector||null,selectionSeq:(e.admin.packages.selectionSeq??0)+1,detail:null,detailLoading:!!t.name,detailError:null,changelog:null,action:{pending:null,error:null},workspace:{tree:null,treeLoading:!!t.name,treeError:null,expandedDirs:[],selectedPath:null,file:null,fileLoading:!1,fileError:null}}}};case"admin/packages/detail/loaded":return zs(e.admin.packages,t)?e:{...e,admin:{...e.admin,packages:{...e.admin.packages,detail:t.detail,detailLoading:!1,detailError:null}}};case"admin/packages/detail/loadFailed":return zs(e.admin.packages,t)?e:{...e,admin:{...e.admin,packages:{...e.admin.packages,detail:null,detailLoading:!1,detailError:t.error||"Failed to load package"}}};case"admin/packages/changelog/loaded":return zs(e.admin.packages,t)?e:{...e,admin:{...e.admin,packages:{...e.admin.packages,changelog:t.content||null}}};case"admin/packages/tree/loaded":{if(zs(e.admin.packages,t))return e;const s=Array.isArray(t.tree?.dirs)?t.tree.dirs.filter(n=>!n.includes("/")):[];return{...e,admin:{...e.admin,packages:{...e.admin.packages,workspace:{...e.admin.packages.workspace,tree:t.tree,treeLoading:!1,treeError:null,expandedDirs:s}}}}}case"admin/packages/tree/loadFailed":return zs(e.admin.packages,t)?e:{...e,admin:{...e.admin,packages:{...e.admin.packages,workspace:{...e.admin.packages.workspace,treeLoading:!1,treeError:t.error||"Failed to load package files"}}}};case"admin/packages/toggleDir":{const s=e.admin.packages.workspace,n=new Set(s.expandedDirs);return n.has(t.dir)?n.delete(t.dir):n.add(t.dir),{...e,admin:{...e.admin,packages:{...e.admin.packages,workspace:{...s,expandedDirs:[...n]}}}}}case"admin/packages/file/loading":return{...e,admin:{...e.admin,packages:{...e.admin.packages,workspace:{...e.admin.packages.workspace,selectedPath:t.path,file:null,fileLoading:!0,fileError:null}}}};case"admin/packages/file/loaded":return e.admin.packages.workspace.selectedPath!==t.file?.path||typeof t.seq=="number"&&(e.admin.packages.selectionSeq??0)!==t.seq?e:{...e,admin:{...e.admin,packages:{...e.admin.packages,workspace:{...e.admin.packages.workspace,file:t.file,fileLoading:!1,fileError:null}}}};case"admin/packages/file/loadFailed":return e.admin.packages.workspace.selectedPath!==t.path||typeof t.seq=="number"&&(e.admin.packages.selectionSeq??0)!==t.seq?e:{...e,admin:{...e.admin,packages:{...e.admin.packages,workspace:{...e.admin.packages.workspace,fileLoading:!1,fileError:t.error||"Failed to load file"}}}};case"admin/packages/action/pending":return{...e,admin:{...e.admin,packages:{...e.admin.packages,action:{pending:t.action,error:null}}}};case"admin/packages/action/done":return{...e,admin:{...e.admin,packages:{...e.admin.packages,action:{pending:null,error:null}}}};case"admin/packages/action/failed":return{...e,admin:{...e.admin,packages:{...e.admin.packages,action:{pending:null,error:t.error||"Action failed"}}}};case"admin/packages/addDialog/open":{const s={...Ci().admin.packages.addDialog,open:!0,updateName:t.updateName||null,scope:t.scope==="shared"?"shared":"user"};return{...e,admin:{...e.admin,section:"packages",packages:{...e.admin.packages,addDialog:s}}}}case"admin/packages/addDialog/close":return{...e,admin:{...e.admin,packages:{...e.admin.packages,addDialog:{...Ci().admin.packages.addDialog,open:!1}}}};case"admin/packages/addDialog/setField":{const s=e.admin.packages.addDialog;return t.field in s?{...e,admin:{...e.admin,packages:{...e.admin.packages,addDialog:{...s,[t.field]:t.value,error:null}}}}:e}case"admin/packages/addDialog/submitting":return{...e,admin:{...e.admin,packages:{...e.admin.packages,addDialog:{...e.admin.packages.addDialog,submitting:!0,progress:null,error:null}}}};case"admin/packages/addDialog/progress":return{...e,admin:{...e.admin,packages:{...e.admin.packages,addDialog:{...e.admin.packages.addDialog,progress:t.message||null}}}};case"admin/packages/addDialog/failed":return{...e,admin:{...e.admin,packages:{...e.admin.packages,addDialog:{...e.admin.packages.addDialog,submitting:!1,progress:null,error:t.error||"Failed to import package"}}}};case"admin/systemGhcpKey/saved":{const s=t.status||{};return{...e,admin:{...e.admin,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:Date.now(),storeAsSystem:!!e.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(t.sessionIds)?t.sessionIds:[];if(s.length===0)return e;const n=Nt(e.files.bySessionId);for(const r of s)n[r]&&(n[r]={...n[r],previews:{}});return{...e,files:{...e.files,bySessionId:n}}}case"files/sessionLoading":{const s=Nt(e.files.bySessionId),n=s[t.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null};return s[t.sessionId]={...n,loading:!0,error:null},{...e,files:{...e.files,bySessionId:s}}}case"files/sessionLoaded":{const s=Nt(e.files.bySessionId),n=s[t.sessionId]||{previews:{},downloads:{}},r=Zn(t.entries),i=Number(t.fetchedAt)||0,o=c=>r.some(d=>d.filename===c),l=n.selectedFilename&&o(n.selectedFilename)?n.selectedFilename:t.selectedFilename&&o(t.selectedFilename)?t.selectedFilename:r[0]?.filename||null;return s[t.sessionId]={...n,entries:r,selectedFilename:l,loading:!1,loaded:!0,fetchedAt:i,error:null},{...e,files:{...e.files,bySessionId:s}}}case"files/sessionError":{const s=Nt(e.files.bySessionId),n=s[t.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null};return s[t.sessionId]={...n,loading:!1,loaded:!0,error:t.error||"Failed to load files"},{...e,files:{...e.files,bySessionId:s}}}case"files/select":{const s=Nt(e.files.bySessionId),n=s[t.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null};return s[t.sessionId]={...n,selectedFilename:t.filename||null},{...e,files:{...e.files,bySessionId:s,selectedArtifactId:t.sessionId&&t.filename?`${t.sessionId}/${t.filename}`:e.files.selectedArtifactId},ui:{...e.ui,scroll:{...e.ui.scroll,filePreview:0}}}}case"files/toggleMark":{const s=String(t.artifactId||"");if(!s)return e;const n=new Set(e.files.markedIds||[]);return n.has(s)?n.delete(s):n.add(s),{...e,files:{...e.files,markedIds:[...n]}}}case"files/setMarks":return{...e,files:{...e.files,markedIds:Array.isArray(t.artifactIds)?[...new Set(t.artifactIds.map(String))]:[]}};case"files/previewOrigin":return{...e,files:{...e.files,previewOrigin:t.origin||null,restoreArtifactId:t.origin==="chat"?t.restoreArtifactId??e.files.restoreArtifactId??null:null}};case"files/pane":return{...e,files:{...e.files,paneOpen:!!t.open,paneRestoresToHidden:t.open?e.files.paneOpen?e.files.paneRestoresToHidden:!!t.restoresToHidden:!1}};case"ui/rightPaneMode":{const s=t.mode==="canvas"?"canvas":"panes",n=t.sessionId||e.sessions.activeSessionId||null;let r=e.canvas.prefs;if(n){const i=r[n]||{optedOut:!1,lastViewedRev:0};s==="canvas"&&i.optedOut?r={...r,[n]:{...i,optedOut:!1}}:s==="panes"&&t.manual&&!i.optedOut&&(r={...r,[n]:{...i,optedOut:!0}})}return{...e,ui:{...e.ui,rightPaneMode:s,canvasOpen:s==="canvas"},canvas:{...e.canvas,prefs:r}}}case"ui/canvasOpen":{const s=typeof t.open=="boolean"?t.open:!e.ui.canvasOpen,n=t.sessionId||e.sessions.activeSessionId||null;let r=e.canvas.prefs;if(n){const i=r[n]||{optedOut:!1,lastViewedRev:0};s&&i.optedOut?r={...r,[n]:{...i,optedOut:!1}}:!s&&t.manual&&!i.optedOut&&(r={...r,[n]:{...i,optedOut:!0}})}return{...e,ui:{...e.ui,canvasOpen:s,rightPaneMode:s?"canvas":"panes",...s?{}:{canvasMaximized:!1,canvasZen:!1}},canvas:{...e.canvas,prefs:r}}}case"ui/canvasZen":{const s=typeof t.on=="boolean"?t.on:!e.ui.canvasZen;return s===!!e.ui.canvasZen?e:{...e,ui:{...e.ui,canvasZen:s,...s?{canvasOpen:!0,rightPaneMode:"canvas"}:{}}}}case"canvas/zenRail":{const s=String(t.sessionId||"").trim(),n=Number(t.px);if(!s||!Number.isFinite(n))return e;const r=e.canvas.prefs[s]||{optedOut:!1,lastViewedRev:0},i=Math.max(260,Math.min(720,Math.round(n)));return{...e,canvas:{...e.canvas,prefs:{...e.canvas.prefs,[s]:{...r,zenRailPx:i}}}}}case"ui/canvasMaximized":{const s=typeof t.on=="boolean"?t.on:!e.ui.canvasMaximized;return s===!!e.ui.canvasMaximized?e:{...e,ui:{...e.ui,canvasMaximized:s}}}case"ui/diagnosticsOpen":{const s=typeof t.open=="boolean"?t.open:!e.ui.diagnosticsOpen;return s===e.ui.diagnosticsOpen?e:{...e,ui:{...e.ui,diagnosticsOpen:s}}}case"ui/budgetOpen":{const s=typeof t.open=="boolean"?t.open:!e.ui.budgetOpen,n=t.provider===void 0?void 0:Ut(t.provider),r=s&&n!==void 0?{...e.budget,selectedProvider:n}:e.budget,i=s&&e.admin.visible;return s===e.ui.budgetOpen&&r===e.budget&&!i?e:{...e,ui:{...e.ui,budgetOpen:s},admin:i?{...e.admin,visible:!1}:e.admin,budget:r}}case"budget/loading":{const s=t.refresh===!0||e.budget.loaded===!0;return{...e,budget:{...e.budget,loading:!s,refreshing:s,error:null}}}case"budget/loaded":{const s=e.budget,n=Array.isArray(t.grid),r=n?t.grid:s.grid,i=n&&s.selectedProvider&&!t.grid.some(p=>p?.providerName===s.selectedProvider),o=i?null:s.selectedProvider,l=s.selectedScope||"*",c=n&&!i&&l!=="*"&&!t.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{...e,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(t.paused)?t.paused:s.paused,pausedError:Array.isArray(t.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??Oe,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:o===s.selectedProvider&&d===l?s.systemUsage:{provider:null,scope:"*",rangeDays:s.rangeDays??Oe,totals:null,days:[],breakdown:[],loading:!1,loaded:!1,error:null,fetchedAt:0}}}}case"budget/pausedFailed":{const s=t.error?String(t.error?.message||t.error):"";return{...e,budget:{...e.budget,loading:!1,refreshing:!1,pausedError:s||"Could not read what is waiting"}}}case"budget/loadFailed":{const s=t.error?String(t.error?.message||t.error):"";return{...e,budget:{...e.budget,loading:!1,refreshing:!1,error:s||"Could not read providers and budgets"}}}case"budget/overall":{const s=typeof t.overall=="boolean"?t.overall:!e.budget.overall;return s===e.budget.overall?e:{...e,budget:{...e.budget,overall:s}}}case"budget/rangeDays":{const s=Number(t.rangeDays);return!er.includes(s)||s===e.budget.rangeDays?e:{...e,budget:{...e.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=Ut(t.provider),n=typeof t.scope=="string"&&t.scope?t.scope:"*",r=e.budget.selectedProvider,i=e.budget.selectedScope||"*";let o=s,l=n;return s===r&&n===i&&(n==="*"&&(o=null),l="*"),o===r&&l===i?e:{...e,budget:{...e.budget,selectedProvider:o,selectedScope:l,missingProvider:null,series:{provider:null,scope:"*",rangeDays:e.budget.rangeDays??Oe,days:[],loading:!1,loaded:!1,error:null,fetchedAt:0},systemUsage:{provider:null,scope:"*",rangeDays:e.budget.rangeDays??Oe,totals:null,days:[],breakdown:[],loading:!1,loaded:!1,error:null,fetchedAt:0}}}}case"budget/series/loading":{const s=Ut(t.provider),n=typeof t.scope=="string"&&t.scope?t.scope:"*",r=Number(t.rangeDays)||e.budget.rangeDays||Oe;return{...e,budget:{...e.budget,series:{...e.budget.series,provider:s,scope:n,rangeDays:r,loading:!0,error:null}}}}case"budget/series/loaded":{const s=Ut(t.provider),n=typeof t.scope=="string"&&t.scope?t.scope:"*",r=t.rangeDays===void 0?e.budget.rangeDays||Oe:Number(t.rangeDays);return s!==e.budget.selectedProvider||n!==(e.budget.selectedScope||"*")||r!==(e.budget.rangeDays||Oe)?e:{...e,budget:{...e.budget,series:{provider:s,scope:n,rangeDays:r,days:Array.isArray(t.days)?t.days:[],loading:!1,loaded:!0,error:null,fetchedAt:Date.now()}}}}case"budget/series/failed":{const s=Ut(t.provider),n=typeof t.scope=="string"&&t.scope?t.scope:"*",r=t.rangeDays===void 0?e.budget.rangeDays||Oe:Number(t.rangeDays);if(s!==e.budget.selectedProvider||n!==(e.budget.selectedScope||"*")||r!==(e.budget.rangeDays||Oe))return e;const i=t.error?String(t.error?.message||t.error):"";return{...e,budget:{...e.budget,series:{...e.budget.series,provider:s,scope:n,rangeDays:r,loading:!1,error:i||"Could not read the daily usage"}}}}case"budget/systemUsage/loading":{const s=Ut(t.provider),n=typeof t.scope=="string"&&t.scope?t.scope:"*",r=Number(t.rangeDays)||e.budget.rangeDays||Oe;return{...e,budget:{...e.budget,systemUsage:{...e.budget.systemUsage,provider:s,scope:n,rangeDays:r,loading:!0,error:null}}}}case"budget/systemUsage/loaded":{const s=Ut(t.provider),n=typeof t.scope=="string"&&t.scope?t.scope:"*",r=t.rangeDays===void 0?e.budget.rangeDays||Oe:Number(t.rangeDays);if(s!==e.budget.selectedProvider||n!==(e.budget.selectedScope||"*")||r!==(e.budget.rangeDays||Oe))return e;const i=t.report||{};return{...e,budget:{...e.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=Ut(t.provider),n=typeof t.scope=="string"&&t.scope?t.scope:"*",r=t.rangeDays===void 0?e.budget.rangeDays||Oe:Number(t.rangeDays);if(s!==e.budget.selectedProvider||n!==(e.budget.selectedScope||"*")||r!==(e.budget.rangeDays||Oe))return e;const i=t.error?String(t.error?.message||t.error):"";return{...e,budget:{...e.budget,systemUsage:{...e.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(t.slot))&&Number(t.slot)>=1&&Number(t.slot)<=5?Number(t.slot):1;return{...e,ui:{...e.ui,rightPaneMode:"canvas",canvasOpen:!0,canvasSlot:s},canvas:{...e.canvas,flipSeq:(e.canvas.flipSeq||0)+1}}}case"ui/canvasSlot":{const s=Number.isInteger(Number(t.slot))&&Number(t.slot)>=1&&Number(t.slot)<=5?Number(t.slot):1;return s===(e.ui.canvasSlot||1)?e:{...e,ui:{...e.ui,canvasSlot:s}}}case"canvas/viewed":{const s=String(t.sessionId||"").trim();if(!s)return e;const n=Number(t.rev),r=Number(t.dataRev),i=ut(s,t.slot),o=e.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)?e:{...e,canvas:{...e.canvas,prefs:{...e.canvas.prefs,[i]:{...o,lastViewedRev:l,lastViewedDataRev:c}}}}}case"canvas/seed":{const s=Array.isArray(t.entries)?t.entries:[];if(!s.length)return e;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=ut(i,l),d=(n||e.canvas.bySessionId)[c]||{};(d.latestRev||0)>=o&&d.name!==void 0||(n=n||{...e.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?{...e,canvas:{...e.canvas,bySessionId:n}}:e}case"canvas/updated":{const s=String(t.sessionId||"").trim(),n=Number(t.rev);if(!s||!Number.isFinite(n)||n<=0)return e;const r=Number.isInteger(Number(t.slot))&&Number(t.slot)>=1&&Number(t.slot)<=5?Number(t.slot):1,i=ut(s,r),o=e.canvas.bySessionId[i]||{};return(o.latestRev||0)>=n?e:{...e,canvas:{...e.canvas,bySessionId:{...e.canvas.bySessionId,[i]:{...o,slot:r,...typeof t.name=="string"?{name:t.name}:{},latestRev:n,note:typeof t.note=="string"?t.note:"",sizeBytes:Number.isFinite(Number(t.sizeBytes))?Number(t.sizeBytes):null,responseContract:t.responseContract&&typeof t.responseContract=="object"?t.responseContract:null}}}}}case"canvas/data":{const s=String(t.sessionId||"").trim(),n=Number.isInteger(Number(t.slot))&&Number(t.slot)>=1&&Number(t.slot)<=5?Number(t.slot):1,r=ut(s,n),i=Number(t.dataRev);if(!s||!Number.isFinite(i)||i<=0)return e;const o=e.canvas.bySessionId[r]||{},l=Number(t.planeSeq),c=Number.isFinite(l)&&l>0;if(c){if((o.planeSeq||0)>=l)return e}else if(o.planeSeq||(o.latestDataRev||0)>=i)return e;return{...e,canvas:{...e.canvas,bySessionId:{...e.canvas.bySessionId,[r]:{...o,latestDataRev:Math.max(i,o.latestDataRev||0),...c?{planeSeq:l}:{},dataPayload:t.payload&&typeof t.payload=="object"?t.payload:null,dataPatch:c&&t.patch&&typeof t.patch=="object"?t.patch:null}}}}}case"canvas/planeReleased":{const s=String(t.sessionId||"").trim();if(!s)return e;let n=!1;const r={...e.canvas.bySessionId};for(let i=1;i<=5;i++){const o=ut(s,i),l=r[o];if(l&&l.planeSeq){const{planeSeq:c,...d}=l;r[o]=d,n=!0}}return n?{...e,canvas:{...e.canvas,bySessionId:r}}:e}case"canvas/snapshot":{const s=String(t.sessionId||"").trim();if(!s)return e;const n=Number.isInteger(Number(t.slot))&&Number(t.slot)>=1&&Number(t.slot)<=5?Number(t.slot):1,r=ut(s,n),i=e.canvas.bySessionId[r]||{},o=Number(t.rev)||0;return{...e,canvas:{...e.canvas,bySessionId:{...e.canvas.bySessionId,[r]:{...i,slot:n,...typeof t.name=="string"&&(i.latestRev||0)<=o?{name:t.name}:{},latestRev:Math.max(i.latestRev||0,o),note:(i.latestRev||0)>o?i.note:typeof t.note=="string"?t.note:i.note||"",sizeBytes:(i.latestRev||0)>o?i.sizeBytes:Number.isFinite(Number(t.sizeBytes))?Number(t.sizeBytes):i.sizeBytes??null,responseContract:(i.latestRev||0)>o?i.responseContract??null:t.responseContract&&typeof t.responseContract=="object"?t.responseContract:null,snapshotLoaded:!0}}}}}case"canvas/snapshotInvalidate":{const s=String(t.sessionId||"").trim(),n=e.canvas.bySessionId[s];return!s||!n?.snapshotLoaded?e:{...e,canvas:{...e.canvas,bySessionId:{...e.canvas.bySessionId,[s]:{...n,snapshotLoaded:!1}}}}}case"files/htmlViewMode":return{...e,files:{...e.files,htmlViewMode:t.mode==="source"?"source":"rendered"}};case"files/htmlFitWidth":return{...e,files:{...e.files,htmlFitWidth:!!t.enabled}};case"files/htmlZoom":{const s=Number(t.zoom),n=Number.isFinite(s)?Math.min(3,Math.max(.5,Math.round(s*100)/100)):1;return{...e,files:{...e.files,htmlZoom:n}}}case"files/clearMarks":return{...e,files:{...e.files,markedIds:[]}};case"files/selectGlobal":return{...e,files:{...e.files,selectedArtifactId:t.artifactId||null},ui:{...e.ui,scroll:{...e.ui.scroll,filePreview:0}}};case"files/previewLoading":{const s=Nt(e.files.bySessionId),n=s[t.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:t.filename||null},r={...n.previews||{},[t.filename]:{...n.previews?.[t.filename]||{},loading:!0,error:null}};return s[t.sessionId]={...n,previews:r},{...e,files:{...e.files,bySessionId:s}}}case"files/previewLoaded":{const s=Nt(e.files.bySessionId),n=s[t.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:t.filename||null},r={...n.previews||{},[t.filename]:{loading:!1,error:null,content:t.content||"",contentType:t.contentType||"text/plain",renderMode:t.renderMode||"text",isBinary:t.isBinary===!0,sizeBytes:Number.isFinite(t.sizeBytes)?t.sizeBytes:null,uploadedAt:t.uploadedAt||"",source:t.source||"agent"}};return s[t.sessionId]={...n,previews:r},{...e,files:{...e.files,bySessionId:s}}}case"files/previewError":{const s=Nt(e.files.bySessionId),n=s[t.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:t.filename||null},r={...n.previews||{},[t.filename]:{...n.previews?.[t.filename]||{},loading:!1,error:t.error||"Failed to load file preview"}};return s[t.sessionId]={...n,previews:r},{...e,files:{...e.files,bySessionId:s}}}case"files/downloaded":{const s=Nt(e.files.bySessionId),n=s[t.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:t.filename||null},r={...n.downloads||{},[t.filename]:{localPath:t.localPath||null,downloadedAt:t.downloadedAt||Date.now()}};return s[t.sessionId]={...n,downloads:r},{...e,files:{...e.files,bySessionId:s}}}case"files/deleted":{e={...e,files:{...e.files,markedIds:(e.files.markedIds||[]).filter(p=>p!==`${t.sessionId}/${t.filename}`)}};const s=Nt(e.files.bySessionId),n=s[t.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},r=Zn(n.entries).filter(p=>p.filename!==t.filename),i=n.selectedFilename===t.filename?r[0]?.filename||null:n.selectedFilename,{[t.filename]:o,...l}=n.previews||{},{[t.filename]:c,...d}=n.downloads||{},u=t.sessionId&&t.filename?`${t.sessionId}/${t.filename}`:null;return s[t.sessionId]={...n,entries:r,previews:l,downloads:d,selectedFilename:i},{...e,files:{...e.files,bySessionId:s,selectedArtifactId:e.files.selectedArtifactId===u?i?`${t.sessionId}/${i}`:null:e.files.selectedArtifactId},ui:{...e.ui,scroll:{...e.ui.scroll,filePreview:0}}}}case"files/fullscreen":return{...e,files:{...e.files,fullscreen:!!t.fullscreen},ui:t.fullscreen?{...e.ui,focusRegion:"inspector",fullscreenPane:null}:e.ui};case"files/filter":return{...e,files:{...e.files,filter:{...Qr(e.files.filter),...Qr(t.filter)},...Qr(t.filter).scope==="selectedSession"?{}:{selectedArtifactId:e.files.selectedArtifactId||null}},ui:{...e.ui,scroll:{...e.ui.scroll,filePreview:0}}};case"logs/config":return{...e,logs:{...e.logs,available:!!t.available,availabilityReason:t.availabilityReason||e.logs.availabilityReason}};case"logs/tailing":return{...e,logs:{...e.logs,tailing:!!t.tailing}};case"logs/filter":return{...e,logs:{...e.logs,filter:{...e.logs.filter,...t.filter||{}}}};case"logs/set":return{...e,logs:{...e.logs,entries:Vy(t.entries)}};case"logs/append":{const s=(Array.isArray(t.entries)?t.entries:[t.entry]).filter(Boolean);if(s.length===0)return e;const n=[...e.logs.entries||[],...s],r=n.length>1e3?n.slice(-1e3):n;return{...e,logs:{...e.logs,entries:r}}}default:return e}}function Da(e,t){const s=Array.isArray(t)?t.filter(r=>r?.origin&&r?.label):[];if(s.length<2)return[{label:null,url:String(e||"")}];let n;try{const r=new URL(String(e||""));n=`${r.pathname}${r.search}${r.hash}`}catch{return[{label:null,url:String(e||"")}]}return s.map(r=>({label:String(r.label),url:`${r.origin}${n}`}))}function yu(e){const t=Array.isArray(e)?e:[];return t.length<=1?String(t[0]?.url||""):t.map(s=>`${s.label}: ${s.url}`).join(`
75
- `)}function fb(e,t){let s=t;const n=new Set;return{getState(){return s},dispatch(r){const i=e(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 xl(e,t,s){const n=t?.nativeTaskSnapshot;return n?.ownerId?Qc({...e,nativeTaskSnapshot:void 0},{version:1,...n,tasks:(t.chat||[]).filter(r=>r.kind==="native-task-group").flatMap(r=>r.tasks).filter(r=>r.ownerId===n.ownerId)},{sessionId:s,seq:n.liveSeq}):e}function hb(e){return e?{...e.scope==="shared"||e.scope==="user"?{scope:e.scope}:{},...e.scope==="user"&&e.owner?.provider&&e.owner?.subject?{owner:{provider:e.owner.provider,subject:e.owner.subject}}:{}}:null}const gb=2e4,yb=2e4,bb=3e4,Sb=30,Al="Session refresh failed",vb=3,wb=200,Eb=new Set([F.SESSIONS,F.CHAT,F.INSPECTOR,F.ACTIVITY]);function kb(e){if(!e?.groupId)return null;const t=e.latestSummaryUpdatedAt?new Date(e.latestSummaryUpdatedAt).getTime():null,s=e.memberCount??0;return{sessionId:`group:${e.groupId}`,groupId:e.groupId,isGroup:!0,title:e.title||e.groupId,status:"group",description:e.description??null,owner:e.owner??null,shortSummary:`${s} grouped session${s===1?"":"s"}`,summaryUpdatedAt:Number.isFinite(t)?t:null,latestSummaryUpdatedAt:Number.isFinite(t)?t:null,memberCount:s,runningCount:e.runningCount??0,waitingCount:e.waitingCount??0,completedCount:e.completedCount??0,failedCount:e.failedCount??0,cancelledCount:e.cancelledCount??0,createdAt:e.createdAt?new Date(e.createdAt).getTime():0,updatedAt:e.updatedAt?new Date(e.updatedAt).getTime():Date.now()}}function xn(e){return!e?.sessionId||e.isGroup?e:{...e,groupId:e.viewerGroupId??null,parentSessionId:e.parentSessionId??null}}function Fn(e){return String(e||"").startsWith("group:")?String(e).slice(6):null}function Ks(e){return Fn(e)!==null}function Ib(e){const t=new Map;for(const s of e||[]){const n=s?.reason==="system"?"system":"not found";t.set(n,(t.get(n)||0)+1)}return[...t.entries()].map(([s,n])=>`${n} ${s}`).join(", ")}function ti(e){const t=Number(e?.status),s=String(e?.code||"").toUpperCase();return t===404||t===403||s==="NOT_FOUND"||s==="FORBIDDEN"?"not_found":"network"}function Vs(e){const t=Number(e?.status),s=String(e?.code||"").toUpperCase();return t===404||t===403||s==="NOT_FOUND"||s==="FORBIDDEN"}async function Nl(e,t){if(typeof e.listSessionsPage!="function")return e.listSessions();const s=[];let n=null;const r=new Set;for(;;){const i=await e.listSessionsPage({limit:wb,cursor:n,systemFilter:t,viewerOnly:!0}),o=Array.isArray(i?.sessions)?i.sessions:[];if(s.push(...o),!i?.hasMore)break;if(!i?.nextCursor)throw new Error("Session catalog page reported more rows without a next cursor");const l=`${Number(i.nextCursor.updatedAt)}\0${String(i.nextCursor.sessionId||"")}`;if(r.has(l))throw new Error("Session catalog page repeated its next cursor");r.add(l),n=i.nextCursor}return s}async function xb(e){if(typeof e.listSessionsPage!="function")return e.listSessions();const[t,s]=await Promise.all([Nl(e,"only"),Nl(e,"exclude")]),n=new Set;return[...t,...s].filter(r=>{const i=String(r?.sessionId||"");return!i||n.has(i)?!1:(n.add(i),!0)})}function Ab(e=[]){const t=[],s=new Map;for(const n of e){const r=n?.providerId||"models";let i=s.get(r);i||(i={providerId:r,providerType:n?.providerType||"provider",models:[]},s.set(r,i),t.push(i)),i.models.push(n)}return t}function Cl(e,t){let s=e.findIndex(n=>n.qualifiedName===t&&!n.disabled);return s<0&&(s=e.findIndex(n=>!n.disabled)),s<0?0:s}function Dn(e){if(!Array.isArray(e))return[];const t=[];for(const s of e){const n=String(s||"").trim().toLowerCase();!n||t.includes(n)||t.push(n)}return t}function Tl(e){const t=Dn(e?.supportedReasoningEfforts);if(t.length===0)return null;const s=String(e?.defaultReasoningEffort||"").trim().toLowerCase();return s&&t.includes(s)?s:t.includes("medium")?"medium":t[0]||null}function Bn(e){if(!Array.isArray(e))return[];const t=[];for(const s of e){const n=String(s||"").trim().toLowerCase();!n||t.includes(n)||n!=="default"&&n!=="long_context"||t.push(n)}return t}function Nb(e){const t=Bn(e?.supportedContextTiers);if(t.length===0)return null;const s=String(e?.defaultContextTier||"").trim().toLowerCase();return s&&t.includes(s)?s:t.includes("default")?"default":t[0]||null}const bu={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function Cb(e){const t=Number(e);return!Number.isSafeInteger(t)||t<=0?null:t%1e6===0?`${t/1e6}M`:t%1e3===0?`${t/1e3}K`:t.toLocaleString("en-US")}function Tb(e,t){const s=Cb(t);return s?e==="long_context"?`Long context (${s} tokens, higher cost)`:`Default (${s} tokens)`:bu[e]||e}function ji(e=[]){for(let t=e.length-1;t>=0;t-=1){const s=e[t];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 Pb(e){return ji([e])}function Pl(e,t=[]){let s=Rc(e);for(const n of t){const r=Lc(s,n?.eventType,n?.data,{timestamp:n?.createdAt});r&&(s=r)}return s}function rr(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(!rr(e[r],t[r]))return!1;return!0}if(!e||!t||typeof e!="object"||typeof t!="object")return!1;const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const r of s)if(!Object.prototype.hasOwnProperty.call(t,r)||!rr(e[r],t[r]))return!1;return!0}function nn(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(e instanceof Date)return e.getTime();const t=Date.parse(e||"");return Number.isFinite(t)?t:0}function Ba(e,t){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(e?.statusVersion),r=s(t?.statusVersion);if(n!=null&&r!=null)return r<=n;const i=nn(e?.updatedAt),o=nn(t?.updatedAt);return i>0&&o>0&&o<=i}function Mb(e){return!e||e==="idle"||e==="unknown"||e==="pending"}function _b(e,t){return e?.status==="waiting"&&typeof e?.waitReason=="string"&&e.waitReason.trim().length>0&&(t?.waitReason===void 0||t?.waitReason===null)&&Mb(t?.status)&&Ba(e,t)}function $b(e,t){return e?.cronActive===!0&&t?.cronActive!==!0&&!vu(t?.status)&&!Su(t?.orchestrationStatus)&&Ba(e,t)}function Rb(e,t){if(!t?.sessionId)return null;const s={sessionId:t.sessionId};let n=!1;for(const[l,c]of Object.entries(t))l==="sessionId"||c===void 0||rr(e?.[l],c)||(s[l]=c,n=!0);if(t.pendingQuestion===void 0&&e?.pendingQuestion&&t.status!=="input_required"&&!Ba(e,t)&&(s.pendingQuestion=null,n=!0),_b(e,t)?(s.status!==e.status&&(s.status=e.status,n=!0),s.waitReason!==e.waitReason&&(s.waitReason=e.waitReason,n=!0)):t.waitReason===void 0&&e?.waitReason&&t.status!=="waiting"&&t.status!=="input_required"&&(s.waitReason=null,n=!0),um(e,t)?s.error!==e.error&&(s.error=e.error,n=!0):t.error===void 0&&e?.error&&t.status!=="failed"&&t.status!=="error"&&(s.error=null,n=!0),t.result===void 0&&e?.result&&t.status!=="completed"&&(s.result=null,n=!0),$b(e,t))for(const l of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])e?.[l]!=null&&(rr(s[l],e[l])||(s[l]=e[l],n=!0));else if(t.cronActive!==!0){e?.cronReason&&(s.cronReason=null,n=!0);for(const l of["cronKind","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])e?.[l]!=null&&t[l]===void 0&&(s[l]=null,n=!0);e?.cronInterval!=null&&t.cronInterval===void 0&&(s.cronInterval=null,n=!0)}if((vu(t.status)||Su(t.orchestrationStatus))&&e?.contextUsage?.compaction?.state==="running"&&t.contextUsage===void 0){const l={...e.contextUsage};delete l.compaction,s.contextUsage=Object.keys(l).length>0?l:null,n=!0}if(n)for(const l of["statusVersion","updatedAt"])t[l]!==void 0&&(s[l]=t[l]);return n?s:null}function Ml(e){return String(e||"").replace(/\r\n/g,`
76
- `).trim()}function Su(e){return e==="Completed"||e==="Failed"||e==="Terminated"}function vu(e){return e==="completed"||e==="failed"||e==="cancelled"}function nt(e){return String(e||"").slice(0,8)}function ir(e){const t=String(e?.provider||"").trim(),s=String(e?.subject||"").trim();return t&&s?`${t}${s}`:null}function An(e,t="unknown user"){return String(e?.displayName||e?.email||"").trim()||t}const Lb=ir({provider:"system",subject:"system"});function _l(e){const t=e.auth?.principal||null,s=ir(t),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=An(t,"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(e.sessions?.byId||{})){const o=i?.owner,l=ir(o);!l||l===s||l===Lb||r.has(l)||r.set(l,o)}for(const[i,o]of[...r.entries()].sort((l,c)=>An(l[1]).localeCompare(An(c[1])))){const l=An(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 ar(e){return ir(e)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,includeShared:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function Ob(e){return!!(e?.includeSystem||e?.includeUnowned||e?.includeMe||e?.includeShared||Array.isArray(e?.ownerKeys)&&e.ownerKeys.length>0)}function Fb(e,t,s){const n=e||ar(s);if(!t)return n;if(t.kind==="all")return n.all?ar(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(t.kind==="system"&&(r.includeSystem=!r.includeSystem),t.kind==="unowned"&&(r.includeUnowned=!r.includeUnowned),t.kind==="me"&&(r.includeMe=!r.includeMe),t.kind==="shared"&&(r.includeShared=!r.includeShared),t.kind==="owner"&&t.ownerKey){const i=r.ownerKeys.indexOf(t.ownerKey);i>=0?r.ownerKeys.splice(i,1):r.ownerKeys.push(t.ownerKey)}return Ob(r)?r:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function Ha(e){if(!e?.agentId||e?.isSystem)return null;const t=String(e?.title||"").trim();if(!t)return null;const s=t.indexOf(": ");return s>0&&t.slice(0,s).trim()||null}function Db(e){const t=Ha(e);return t?Math.max(1,60-`${t}: `.length):60}function Bb(e){const t=String(e?.title||"").trim();if(!t)return"";const s=Ha(e);if(s&&t.startsWith(`${s}: `)){const n=t.slice(`${s}: `.length).trim();return!n||n===nt(e?.sessionId)?"":n}return t===nt(e?.sessionId)?"":t}function Hb(e,t){const s=String(t||"").trim();if(s)return s;const n=String(e||"").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):"Agent"}function Ub(e){const t=String(e?.packageScope||e?.scope||"shared"),s=String(e?.ownerLabel||"");return`pkg:${t}:${s}:${String(e?.packageName||"")}`}function Nn(e){return String(e||"").toLowerCase().replace(/[^a-z0-9]+/g,"")}function jb(e){const t=new Map;for(const u of e)u?.agentName&&t.set(Nn(u.agentName),u);const s=new Map,n=new Map;for(const u of e){const p=Nn(u.agentName),m=(u.startedBy||[]).map(h=>Nn(h)).filter(h=>h&&t.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(Nn(u.agentName))||[])c(f,p+1,u.agentName)}};for(const u of e)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=t.get(n.get(m)),m===u)return!0;return!1};for(const u of e)!l.has(u)&&d(u)&&c(u,0,null);for(const u of e)c(u,0,null);return o}function Gb(e=[]){const t=e.findIndex(n=>n.kind!=="section");if(t>=0)return t;const s=e.findIndex(n=>n.kind==="section"&&n.collapsed);return s>=0?s:0}const $l=["used","name","package"],wu="used",si="agentPickerUsage";function Wb(e){return[e?.label,e?.agentName,e?.title,e?.description,e?.packageTitle,e?.packageName,...Array.isArray(e?.tools)?e.tools:[]].filter(Boolean).join(" ").toLowerCase()}function Rl(e,t){const s=String(t||"").toLowerCase().split(/\s+/).filter(Boolean);if(s.length===0)return 0;const n=Wb(e),r=`${e?.label||""} ${e?.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 Gi(e,t){return!e||!t?.agentName?0:Number(e[String(t.agentName)])||0}function qb(e,t){const s=(n,r)=>String(n.label||n.agentName||"").localeCompare(String(r.label||r.agentName||""),void 0,{sensitivity:"base"});return e==="name"?s:e==="package"?(n,r)=>String(n.packageTitle||n.packageName||"").localeCompare(String(r.packageTitle||r.packageName||""),void 0,{sensitivity:"base"})||s(n,r):(n,r)=>Gi(t,r)-Gi(t,n)||s(n,r)}function Ll(e=[],t={}){const{query:s="",sort:n=wu,usage:r=null,genericItem:i=null}=t||{},o=[],l=String(s||"").trim();i&&(!l||Rl({label:i.label,description:i.description},l)>=0)&&o.push({...i,depth:0});const c=e.filter(f=>f&&f.kind!=="section"),d=new Map;for(const f of c){const h=f.builtin?"builtin":Ub(f);d.has(h)||d.set(h,[]),d.get(h).push(f)}const u=[];for(const f of d.values())for(const h of jb(f))u.push({...h,depth:0});const p=l?u.map(f=>({agent:f,score:Rl(f,l)})).filter(f=>f.score>=0):u.map(f=>({agent:f,score:0})),m=qb(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:Gi(r,f)});return o}function Ol(e){return`📎 ${String(e||"").trim()}`}function Fl(e,t){const s=String(e||""),n=Fe(s,t,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 zb(e,t,s,n){const r=String(e||""),i=Fe(r,t),o=Fe(r,s),l=String(n||"");return{prompt:`${r.slice(0,i)}${l}${r.slice(o)}`,cursor:i+l.length}}function Kb(e,t="session"){return String(e||"").replace(/\s+/gu," ").trim()||t}function Vb(e){const t=String(e?.sessionId||"").trim(),s=nt(t)||"session";return`Referenced session: ${Kb(e?.title,s)} — session://${t}`}function Dl(e,t,s){if(!t)return Rt(e,String(e||"").length,s);const n=String(e||""),r=n.slice(t.tokenEnd,t.tokenEnd+1),i=!r||/\s/u.test(r);return zb(n,t.tokenStart,t.tokenEnd,`${String(s||"")}${i?" ":""}`)}function Yb(e,t=[]){let s=String(e||"");for(const n of t||[]){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 Bl=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Hl=4*1024*1024,ni=4;function Xb(e,t=[]){const s=Array.isArray(t)?t.filter(i=>i?.sessionId&&i?.filename&&i?.kind!=="image"):[];if(s.length===0)return String(e||"");const n=s.map(i=>`[Attached file: ${i.filename} — artifact://${i.sessionId}/${i.filename}]`),r=Yb(e,s);return n.join(`
79
- `)+(r?`
80
-
81
- ${r}`:"")}function bs(e,t){return String(e||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(t)||0))}function Eu(e){return Array.from(String(e||"")).length}function Qb(e){const t=[];for(const s of e||[]){if(s?.kind==="markup"){const n=Oc(s.value||"");for(const r of n)t.push(r);continue}if(Array.isArray(s)){t.push(s);continue}t.push(s)}return t}function Zb(e,t){const s=Math.max(1,Number(t)||1),n=Eu(e);return Math.max(1,Math.ceil(n/s))}function Ss(e,t){const s=Math.max(1,Number(t)||1);return Qb(e).reduce((n,r)=>{if(!r)return n+1;if(Array.isArray(r)){const i=r.reduce((o,l)=>o+Eu(l?.text||""),0);return n+Math.max(1,Math.ceil(i/s))}return n+Zb(r.text||"",s)},0)}function Fe(e,t){const s=String(e||"");return Math.max(0,Math.min(Number(t)||0,s.length))}function ku(e){return String(e||"").split(`
82
- `)}function Jb(e,t){const n=String(e||"").slice(0,Fe(e,t)).split(`
83
- `),r=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:r.length}}function eS(e,t,s){const n=ku(e),r=Math.max(0,Math.min(Number(t)||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 Fe(e,o+i)}function Rt(e,t,s){const n=String(e||""),r=Fe(n,t),i=String(s||"");return{prompt:`${n.slice(0,r)}${i}${n.slice(r)}`,cursor:r+i.length}}function Zt(e,t){const s=String(e||""),n=Fe(s,t);return n<=0?{prompt:s,cursor:n}:{prompt:`${s.slice(0,n-1)}${s.slice(n)}`,cursor:n-1}}function Cn(e){return/\s/u.test(e||"")}function Iu(e,t,s){const n=String(e||"");let r=Fe(n,t);if(s<0){for(;r>0&&Cn(n[r-1]);)r-=1;for(;r>0&&!Cn(n[r-1]);)r-=1;return r}for(;r<n.length&&Cn(n[r]);)r+=1;for(;r<n.length&&!Cn(n[r]);)r+=1;return r}function tS(e,t){const s=String(e||""),n=Fe(s,t),r=Iu(s,n,-1);return r===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,r)}${s.slice(n)}`,cursor:r}}function sS(e,t,s){const n=ku(e);if(n.length<=1)return Fe(e,t);const r=Jb(e,t),i=Math.max(0,Math.min(r.line+s,n.length-1));return i===r.line?Fe(e,t):eS(e,i,r.column)}const Wi=3e3,nS=new Set(["logs","sequence"]),rS=2e5,iS=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),aS=new Set([".json",".jsonl"]),oS=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function xu(e){const t=String(e||""),s=t.lastIndexOf(".");return s>=0?t.slice(s).toLowerCase():""}function lS(e,t=""){const s=xu(e),n=String(t||"").toLowerCase();return oS.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}const ri=12e4;function Ul(e,t=rS){const s=String(e??"");return s.length<=t?s:`${s.slice(0,t)}
84
-
85
- [Preview truncated at ${t.toLocaleString()} characters. Open the artifact directly if you need the full file.]`}function cS(e){const t=Number(e);if(!Number.isFinite(t)||t<0)return"?";if(t<1024)return`${Math.round(t)} B`;if(t<1024*1024){const n=t/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=t/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function dS(e,t="",s=null){const n=[`Preview is not available here for ${e}.`,""];return t&&n.push(`Type: ${t}`),s!=null&&n.push(`Size: ${cS(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
86
- `)}function jl(e,t,s="",n=null){const r=String(s||"").toLowerCase(),i=xu(e);if(n?.isBinary===!0||lS(e,s))return{content:dS(e,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=Ul(t);if(iS.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(aS.has(i)||r.includes("json"))try{return{content:Ul(JSON.stringify(JSON.parse(String(t??"")),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 uS=1e4,pS=140,mS=1500,fS={day:"Daily",week:"Weekly",month:"Monthly"};function vs(e){const t=typeof e?.message=="string"?e.message.trim():"";return t||String(e??"").trim()||"The request failed."}function hS(e,t,s=Date.now()){if(e?.hasCredential===!1)return{state:"no_credential",text:"no credential — nothing can run on it"};if(e?.holdIndefinite===!0||(e?.holdUntilUtc?Date.parse(e.holdUntilUtc)>s:!1))return{state:"hold",text:"on hold — new turns wait until it is released"};if(!t)return{state:"unknown",text:"budget unknown"};const r=Array.isArray(t.rules)?t.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:fS[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 gS{constructor({store:t,transport:s}){this.store=t,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(t){return this.store.subscribe(t)}dispatch(t){return this.store.dispatch(t)}setStatus(t){this.dispatch({type:"ui/status",text:t})}getPromptAttachments(){const t=this.getState().ui.promptAttachments;return Array.isArray(t)?t.filter(Boolean):[]}setPromptAttachments(t){this.dispatch({type:"ui/promptAttachments",attachments:Array.isArray(t)?t:[]})}getSessionOutbox(t){if(!t)return[];const s=this.getState().outbox?.bySessionId?.[t];return Array.isArray(s)?s.filter(Boolean):[]}setSessionOutboxItems(t,s){t&&this.dispatch({type:"outbox/setSessionItems",sessionId:t,items:Array.isArray(s)?s:[]})}buildOutboxItem(t,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(t||""),createdAt:Date.now(),phase:r,attempted:!1,clientMessageIds:[n]}}getPendingOutboxItems(t){return this.getSessionOutbox(t).filter(s=>s?.phase==="pending")}getQueuedOutboxItems(t){return this.getSessionOutbox(t).filter(s=>s?.phase==="queued")}getNavigableOutboxItems(t){return this.getSessionOutbox(t).filter(s=>s?.phase==="pending"||s?.phase==="queued"||s?.phase==="cancelling")}getEditableOutboxItems(t){return this.getPendingOutboxItems(t).filter(s=>s?.attempted!==!0)}getPromptEditSessionMatch(t=this.getState().sessions.activeSessionId){const s=this.getState().ui.promptEdit;return s?.sessionId===t?s:null}enterPendingPromptEdit(t,s){if(!t||!s)return!1;const r=this.getNavigableOutboxItems(t).find(c=>c.id===s);if(!r)return!1;const i=this.getState().ui,o=this.getPromptEditSessionMatch(t),l=o?{...o,itemId:s,phase:r.phase}:{sessionId:t,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(F.PROMPT),!0}exitPendingPromptEdit({restoreDraft:t=!0}={}){const s=this.getState().ui.promptEdit;return s?(this.dispatch({type:"ui/promptEdit",promptEdit:null}),t&&this.setPrompt(s.draftPrompt||"",Number.isFinite(s.draftCursor)?s.draftCursor:String(s.draftPrompt||"").length),!0):!1}selectPreviousPendingPrompt(t=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(t);if(s.length===0)return!1;const n=this.getPromptEditSessionMatch(t);if(!n)return this.enterPendingPromptEdit(t,s[s.length-1].id);const r=s.findIndex(i=>i.id===n.itemId);return r<=0?!1:this.enterPendingPromptEdit(t,s[r-1].id)}selectNextPendingPrompt(t=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(t),n=this.getPromptEditSessionMatch(t);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(t,s[r+1].id)}async cancelSelectedOutboxPrompt(){const t=this.getState().ui.promptEdit;if(!t?.sessionId||!t?.itemId)return!1;const n=this.getSessionOutbox(t.sessionId).find(i=>i.id===t.itemId);return n?n.phase==="cancelling"?(this.exitPendingPromptEdit({restoreDraft:!0}),!1):await this.cancelOutboxItem(t.sessionId,t.itemId)?(this.exitPendingPromptEdit({restoreDraft:!0}),!0):!1:!1}cancelSelectedPendingPrompt(){const t=this.getState().ui.promptEdit;if(!t?.sessionId||!t?.itemId)return!1;const s=this.getSessionOutbox(t.sessionId);if(!s.find(i=>i.id===t.itemId&&i.phase==="pending"))return!1;const r=s.filter(i=>i.id!==t.itemId);return this.setSessionOutboxItems(t.sessionId,r),this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"ui/status",text:"Cancelled pending prompt"}),!0}async cancelOutboxItem(t,s){if(!t||!s)return!1;const n=this.getSessionOutbox(t),r=n.find(o=>o.id===s);if(!r||r.phase==="cancelling")return!1;this.getPromptEditSessionMatch(t)?.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(t,n.map(o=>o.id===s?{...o,phase:"cancelling"}:o)),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(t,i),this.dispatch({type:"ui/status",text:"Cancelling queued prompt"})}catch(o){return this.setSessionOutboxItems(t,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(t,o),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(t,i)}catch{}this.dispatch({type:"ui/status",text:"Cancelled pending prompt"})}return!0}async cancelLatestQueuedOutbox(t=this.getState().sessions.activeSessionId){if(!t)return!1;const s=this.getQueuedOutboxItems(t);if(s.length===0)return!1;const n=s[s.length-1];return await this.cancelOutboxItem(t,n.id)}queuePromptInOutbox(t,s,n=null){const r=this.buildOutboxItem(s,"pending");return Array.isArray(n?.attachments)&&n.attachments.length>0&&(r.attachments=n.attachments),this.setSessionOutboxItems(t,[...this.getSessionOutbox(t),r]),r}addPendingImageFiles(t){const s=Array.from(t||[]).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(!Bl.has(c)){o.push({name:l.name||"image",reason:"unsupported type"});continue}if((Number(l.size)||0)>Hl){o.push({name:l.name||"image",reason:"over 4 MB"});continue}if(r.length+i.length>=ni){o.push({name:l.name||"image",reason:`max ${ni} 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(t,s){const n=String(t?.contentType||"").toLowerCase();return!Bl.has(n)||(Number(t?.sizeBytes)||0)>Hl||this.getPromptAttachments().filter(i=>i?.kind==="image").length>=ni?!1:(this.setPromptAttachments([...this.getPromptAttachments(),{kind:"image",uploaded:!0,sessionId:s,filename:t.filename,contentType:n,sizeBytes:Number(t?.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 t=null;try{t=await this.transport.captureClipboardImage()}catch(s){return this.dispatch({type:"ui/status",text:`Clipboard read failed: ${s?.message||s}`}),!1}if(!t?.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,t.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(t){const s=this.getPromptAttachments(),r=s.filter(i=>i?.kind==="image")[t];r&&this.setPromptAttachments(s.filter(i=>i!==r))}async uploadPendingImageAttachments(t,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(t,l.file,d),r.push({filename:d})}return r}acknowledgeOutboxPrompt(t,s,n=null){if(!t)return!1;const r=this.getSessionOutbox(t);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(t,r.filter((u,p)=>p!==c)),this.getPromptEditSessionMatch(t)?.itemId===d?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const i=Ml(s);if(!i)return!1;const o=r.findIndex(c=>(c?.phase==="pending"||c?.phase==="queued"||c?.phase==="cancelling")&&Ml(c.text)===i);if(o===-1)return!1;const l=r[o];return this.setSessionOutboxItems(t,r.filter((c,d)=>d!==o)),this.getPromptEditSessionMatch(t)?.itemId===l?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}acknowledgeCancelledOutboxPrompt(t,s=[]){if(!t)return!1;const n=new Set((s||[]).filter(c=>typeof c=="string"&&c));if(n.size===0)return!1;const r=this.getSessionOutbox(t),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(t,i);const l=this.getPromptEditSessionMatch(t);return l&&o.has(l.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}scheduleOutboxDispatch(t){if(!t||(this._outboxDispatchTimers||(this._outboxDispatchTimers=new Map),this._outboxDispatchTimers.has(t)))return;const s=setTimeout(()=>{this._outboxDispatchTimers.delete(t),this.dispatchPendingOutbox(t).catch(()=>{})},10);this._outboxDispatchTimers.set(t,s)}async dispatchPendingOutbox(t){if(!t)return!1;await Promise.resolve();const s=this.outboxFlushPromises.get(t);if(s)return await s.catch(()=>{}),this.getPendingOutboxItems(t).length>0&&this.scheduleOutboxDispatch(t),!1;const n=this.getPendingOutboxItems(t),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(t).filter(h=>!u.has(h.id));this.setSessionOutboxItems(t,[...p,d]);const m=this.getPromptEditSessionMatch(t);m&&u.has(m.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const f=(async()=>{await this.transport.sendMessage(t,d.text,{enqueueOnly:!0,clientMessageIds:d.clientMessageIds,...Array.isArray(d.attachments)&&d.attachments.length>0?{attachments:d.attachments}:{}});const g=this.getSessionOutbox(t).map(b=>b.id===d.id?{...b,phase:"queued"}:b);return this.setSessionOutboxItems(t,g),this.syncSessionEvents(t).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(h=>{const g=h?.code==="FORBIDDEN"||h?.code==="UNAUTHORIZED"||h?.status===403||h?.status===401,b=this.getSessionOutbox(t);if(g){const y=b.map(v=>v.id===d.id?{...v,phase:"rejected"}:v);this.setSessionOutboxItems(t,y),setTimeout(()=>{const v=this.getSessionOutbox(t),S=v.filter(w=>!(w.id===d.id&&w.phase==="rejected"));S.length!==v.length&&this.setSessionOutboxItems(t,S)},6e3)}else{const y=b.map(v=>v.id===d.id?{...d,phase:"pending",attempted:!0}:v);this.setSessionOutboxItems(t,y)}throw this.dispatch({type:"ui/status",text:h?.message||String(h)}),h}).finally(()=>{this.outboxFlushPromises.delete(t),this.getPendingOutboxItems(t).length>0&&this.scheduleOutboxDispatch(t)});return this.outboxFlushPromises.set(t,f),await f}async flushQueuedOutbox(t){return await this.dispatchPendingOutbox(t)}maybeFlushQueuedOutbox(t){return!t||this.getPendingOutboxItems(t).length===0?!1:(this.scheduleOutboxDispatch(t),!0)}getPromptReferenceContext(){const t=this.getState();return Fl(t.ui.prompt,t.ui.promptCursor)}acceptPromptReferenceAutocomplete(){const t=this.getPromptReferenceContext();return t?t.kind==="sessions"?this.acceptSessionPromptReference(t):this.acceptArtifactPromptReference(t):!1}acceptArtifactPromptReference(t=this.getPromptReferenceContext()){if(!t||t.kind!=="artifacts")return!1;const s=this.getState(),n=jt(s),r=n?.sessionId||s.sessions.activeSessionId||null,i=n?.filename||null;if(!r||!i)return!1;const o=Ol(i),l=Dl(s.ui.prompt,t,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(F.PROMPT),this.dispatch({type:"ui/status",text:`Attached ${i}`}),!0}acceptSessionPromptReference(t=this.getPromptReferenceContext()){if(!t||t.kind!=="sessions")return!1;const s=this.getState(),r=us(s)[0]||null,i=r?.sessionId&&s.sessions.byId[r.sessionId]||null;if(!i?.sessionId)return!1;const o=Vb(i),l=Dl(s.ui.prompt,t,o);return this.setPrompt(l.prompt,l.cursor),this.setFocus(F.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${nt(i.sessionId)}`}),!0}setSessionFilterQuery(t=""){this.dispatch({type:"sessions/filterQuery",query:String(t||"")})}openSessionOwnerFilter(){const t=this.getState(),s=_l(t);this.dispatch({type:"ui/modal",modal:{type:"sessionOwnerFilter",title:"Session Filter",previousFocus:t.ui.focusRegion,selectedIndex:0,items:s}}),this.dispatch({type:"ui/status",text:"Up/Down choose entry · Space toggle · Esc close"})}toggleSessionOwnerFilter(t=null){const s=this.getState(),n=s.ui.modal;if(!n||n.type!=="sessionOwnerFilter")return;const r=t==null?Math.max(0,Number(n.selectedIndex)||0):Math.max(0,Number(t)||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 t=this.getState(),s=t.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return;const n=_l(t),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(t={}){this.dispatch({type:"files/filter",filter:t})}clearPromptReferenceBrowser(){this.promptReferenceSignature=null,this.promptReferenceSyncVersion+=1,this.getState().sessions.filterQuery&&this.setSessionFilterQuery(""),this.getState().files.filter?.query&&this.setFilesFilter({query:""})}syncPromptReferenceBrowser(){const t=this.getState(),s=Fl(t.ui.prompt,t.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=t.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(nr(this.getState(),"selectedSession")),l=rs(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:t=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:ar(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(t||"").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:Al})}).finally(()=>{this.catalogPollInFlight=!1}))},4e3)}async stop(){this._featureRefreshSerial=(this._featureRefreshSerial||0)+1,this._featureUserSerial=(this._featureUserSerial||0)+1;for(const t of this._liveTurnIdleTimers?.values()||[])clearTimeout(t);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 t=this.activeSessionSubscriptionId;if(t){clearTimeout(this._liveTurnIdleTimers?.get(t)),this._liveTurnIdleTimers?.delete(t);const s=this.getState().history.bySessionId.get(t);s&&this.dispatch({type:"history/set",sessionId:t,history:{...s,chat:s.chat.filter(n=>!n.liveTurn)}})}this.activeSessionUnsub&&(this.activeSessionUnsub(),this.activeSessionUnsub=null),this.activeSessionSubscriptionId=null}handleSessionGone(t){t&&(Ks(t)||(this.sessionRefreshSeq=(this.sessionRefreshSeq||0)+1,this.activeSessionSubscriptionId===t&&this.detachActiveSession(),this.activeSessionDetailSessionId===t&&this.activeSessionDetailTimer&&(clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null),this.dispatch({type:"sessions/gone",sessionId:t})))}detachLogStream(){this.logUnsubscribe&&(this.logUnsubscribe(),this.logUnsubscribe=null)}async refreshSessions(){this.refreshWorkerRegistryIfStale().catch(()=>{}),this.refreshFeatureFlagsIfStale().catch(()=>{});const t=this.sessionRefreshSeq=(this.sessionRefreshSeq||0)+1,s=this.getState(),n=!s.connection.connected||!!s.connection.error,r=s.ui.statusText===Al,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(kb).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 xb(this.transport)).map(xn);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,xn(g)]:this.dispatch({type:"sessions/navigationIntentFailed",sessionId:u.sessionId,errorKind:"not_found"})}catch(g){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:u.sessionId,errorKind:ti(g)})}const p=i;if(p&&!Ks(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,xn(g)])}if(t!==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 v=this.getState().sessions.navigationIntent;if(v&&v.sessionId===f&&v.status!=="failed")try{await this.loadSession(f)}catch(S){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:f,errorKind:ti(S)})}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 v=Object.values(b.sessions.byId).filter(S=>S?.parentSessionId===y.parentSessionId).map(S=>S.sessionId).filter(S=>S&&S!==f).slice(0,6);await Promise.all(v.map(S=>this.syncSessionDetail(S).catch(()=>{})));for(const S of v)h.add(S)}}await this.syncVisibleSessionDetails(h).catch(()=>{}),this.ensureInspectorData().catch(()=>{}),this.evictStaleSessionState()}async refreshWorkerRegistryIfStale(){const t=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(t?.loading){this.dispatch({type:"admin/workers/attempt",skip:"already in flight"});return}if(t?.fetchedAt&&Date.now()-t.fetchedAt<2e4){this.dispatch({type:"admin/workers/attempt",skip:"fresh"});return}this.dispatch({type:"admin/workers/attempt",skip:null}),await this.refreshAdminWorkers()}evictStaleSessionState(){const t=this.getState(),s=t.sessions.activeSessionId,n=Date.now(),r=6e4,i=20,o=Object.entries(t.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(t.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(t.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=[...t.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(t=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=en({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??Cs(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),r=this.getSessionListMaxRows(n),i=Fi(s,r),o=[...new Set(i.map(l=>l.sessionId).filter(l=>l&&!Ks(l)&&!t.has(l)))];o.length!==0&&await Promise.all(o.map(l=>this.syncSessionDetail(l).catch(()=>{})))}async catchUpSessionHistory(t,s,n){let i;try{i=await this.transport.getSessionEvents(t,n,1e3)}catch(u){return Vs(u)&&this.handleSessionGone(t),null}if(!Array.isArray(i)||i.length>=1e3)return null;if(i.length===0)return s;let o=this.getState().history.bySessionId.get(t)||s;for(const u of i)u.seq<=(o.lastSeq||0)||(o=Dr(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:t,history:o});for(const u of i)this.reconcileOutboxAgainstEvent(t,u);const l=ji(i),c=this.getState().sessions.byId[t]||{},d=Pl(c.contextUsage,i);return(l||d)&&this.dispatch({type:"sessions/merged",session:{sessionId:t,...l||{},...d?{contextUsage:d}:{}}}),o}async ensureSessionHistory(t,s={}){if(!t)return null;if(this.sessionHistoryLoads.has(t))return this.sessionHistoryLoads.get(t);const n=this.getState().history.bySessionId.get(t);if(!s.force&&n?.events&&n?.loadState!=="failed")return n;this.dispatch({type:"history/loadState",sessionId:t,loadState:"loading"});const r=this.loadSessionHistory(t,{...s,force:!0});this.sessionHistoryLoads.set(t,r);try{const i=await r;return this.dispatch({type:"history/loadState",sessionId:t,loadState:"loaded"}),i}catch(i){throw this.dispatch({type:"history/loadState",sessionId:t,loadState:"failed"}),i}finally{this.sessionHistoryLoads.get(t)===r&&this.sessionHistoryLoads.delete(t)}}async loadSessionHistory(t,{force:s=!1}={}){if(!t)return null;const n=this.getState().history.bySessionId.get(t),r=Math.min(mS,Math.max(Ne,Number(n?.loadedEventLimit??Ne)||Ne));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(t,n,i);if(l)return l}return(async()=>{let l;try{l=await this.transport.getSessionEvents(t,void 0,r)}catch(g){if(Vs(g))return this.handleSessionGone(t),null;throw g}const c=this.getState().history.bySessionId.get(t),d=[...new Map([...l||[],...c?.events||[]].map(g=>[g.seq,g])).values()].sort((g,b)=>g.seq-b.seq);let u={...qs(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=Dr({chat:[g],events:[],activity:[],lastSeq:0},b).chat[0];u.chat=u.chat.map(v=>v.messageId===g.messageId?{...y,...v}:v)}}u=xl(u,c,t),this.dispatch({type:"history/set",sessionId:t,history:u});for(const g of l||[])this.reconcileOutboxAgainstEvent(t,g);const m=ji(l),f=this.getState().sessions.byId[t]||{},h=Pl(f.contextUsage,l);return(m||h)&&this.dispatch({type:"sessions/merged",session:{sessionId:t,...m||{},...h?{contextUsage:h}:{}}}),u})()}async ensureInspectorData(t=this.getState().ui.inspectorTab){if(t==="sequence"){const s=this.getState().sessions.activeSessionId;if(!s)return;await this.ensureSessionHistory(s).catch(()=>{}),await this.ensureOrchestrationStats(s).catch(()=>{});return}if(t==="nodes"){this.refreshWorkerRegistryIfStale().catch(()=>{});const s=this.getState(),n=en({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??Cs(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),r=this.getSessionListMaxRows(n),i=Fi(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(t==="files"&&await this.ensureFilesForScope(ft(this.getState())),t==="history"){const s=this.getState().sessions.activeSessionId,n=s&&this.getState().executionHistory?.bySessionId?.[s]||null;s&&!n&&await this.ensureExecutionHistory(s)}t==="stats"&&(await this.ensureSessionStats().catch(()=>{}),await this.ensureFleetStats().catch(()=>{}))}async ensureOrchestrationStats(t,{force:s=!1}={}){if(!t||typeof this.transport.getOrchestrationStats!="function")return null;const n=this.getState().orchestration.bySessionId?.[t]||null,r=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&r-n.fetchedAt<gb)return n;if(!s&&this.sessionOrchestrationStatsLoads.has(t))return this.sessionOrchestrationStatsLoads.get(t);this.dispatch({type:"orchestration/statsLoading",sessionId:t});const i=(async()=>{try{const o=await this.transport.getOrchestrationStats(t);return this.dispatch({type:"orchestration/statsLoaded",sessionId:t,stats:o,fetchedAt:Date.now()}),this.getState().orchestration.bySessionId?.[t]||null}catch(o){return Vs(o)?(this.handleSessionGone(t),null):(this.dispatch({type:"orchestration/statsError",sessionId:t,error:o?.message||String(o),fetchedAt:Date.now()}),null)}})().finally(()=>{this.sessionOrchestrationStatsLoads.delete(t)});return this.sessionOrchestrationStatsLoads.set(t,i),i}async ensureSessionStats({force:t=!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(!(!t&&n?.loading)&&!(!t&&n&&Number.isFinite(n.fetchedAt)&&r-n.fetchedAt<yb)){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:t=!1}={}){if(typeof this.transport.getFleetStats!="function")return;const s=this.getState().fleetStats,n=Date.now();if(!(!t&&s?.loading)&&!(!t&&s?.data&&Number.isFinite(s.fetchedAt)&&n-s.fetchedAt<bb)){this.dispatch({type:"fleetStats/loading"});try{const i={since:new Date(Date.now()-Sb*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 t=this.getState();return t.admin?.visible?"admin":t.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(F.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 t=await this.transport.getCurrentUserProfile();return this.dispatch({type:"admin/profile/loaded",profile:t}),await this.refreshSystemGhcpKeyStatus(t),t||null}catch(t){return this.dispatch({type:"admin/profile/loadFailed",error:t?.message||String(t)}),null}}async refreshSystemGhcpKeyStatus(t=null){if(!(t||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(t){t&&!this.getState().admin?.profile?.isAdmin||this.dispatch({type:"admin/ghcpKey/setSystemTarget",value:!!t})}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(t,s){this.dispatch({type:"admin/modelProviders/mutationPending",pending:t});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:t,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:t,type:s,credentials:n,baseUrl:r}))}async updateAdminProviderCredential({name:t,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:t,credentials:s}))}async deleteAdminProvider(t,{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](t))}async setAdminProviderSystemUse(t,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:t,enabled:s===!0}))}async setAdminModelDefault(t,s=null){return typeof this.transport.setModelDefault!="function"?{ok:!1,result:null,error:"Model defaults are not available on this transport."}:this._runAdminModelProviderMutation(`${t}Default`,()=>this.transport.setModelDefault({scope:t,provider:s?.provider??null,model:s?.qualifiedName??s?.model??null,reasoningEffort:s?.reasoningEffort??s?.defaultReasoningEffort??null,contextTier:s?.contextTier??s?.defaultContextTier??null}))}async setAdminSystemModelDefault(t=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:t?.provider??null,model:t?.qualifiedName??t?.model??null,reasoningEffort:t?.reasoningEffort??t?.defaultReasoningEffort??null,contextTier:t?.contextTier??t?.defaultContextTier??null,restartExisting:s?{disposition:s}:!1}))}async setAdminSystemAgentModel(t,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:t,provider:s?.provider,model:s?.qualifiedName??s?.model,reasoningEffort:s?.reasoningEffort??s?.defaultReasoningEffort??null,contextTier:s?.contextTier??s?.defaultContextTier??null}))}async clearAdminSystemAgentModel(t){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(t))}beginAdminCreateProvider({shared:t=!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:t,mode:"create"})}beginAdminCreateGithubProvider(){this.beginAdminCreateProvider({shared:!1})}beginAdminUpdateProviderCredential(t){!t?.name||t.class==="shared"||this.dispatch({type:"admin/modelProviders/createBegin",name:t.name,typeId:t.typeId,shared:!1,mode:"update",stage:"credential"})}_adminProviderTypeUsesWorkloadIdentity(t){return($t(this.getState()).modelProviders?.providerTypes||[]).find(n=>n.id===t)?.usesWorkloadIdentity===!0}cycleAdminProviderCreateType(){const t=$t(this.getState()).modelProviders,s=this.getState().admin?.modelProviders?.create;if(!s?.editing||s.saving||s.stage!=="name")return;const n=t.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(t,s=String(t||"").length){this.dispatch({type:"admin/modelProviders/createDraft",draft:t,cursorIndex:s})}insertAdminProviderCreateText(t){const s=this.getState().admin?.modelProviders?.create;if(!s?.editing||s.saving)return;const n=String(t||"").replace(/\r?\n/gu,""),r=Rt(s.draft||"",s.cursorIndex||0,n);this.setAdminProviderCreateDraft(r.prompt,r.cursor)}deleteAdminProviderCreateChar(){const t=this.getState().admin?.modelProviders?.create;if(!t?.editing||t.saving)return;const s=Zt(t.draft||"",t.cursorIndex||0);this.setAdminProviderCreateDraft(s.prompt,s.cursor)}moveAdminProviderCreateCursor(t){const s=this.getState().admin?.modelProviders?.create;if(!s?.editing||s.saving)return;const n=s.draft||"";this.setAdminProviderCreateDraft(n,Fe(n,(s.cursorIndex||0)+t))}moveAdminProviderCreateCursorToBoundary(t){const s=this.getState().admin?.modelProviders?.create;if(!s?.editing||s.saving)return;const n=s.draft||"";this.setAdminProviderCreateDraft(n,t==="start"?0:n.length)}advanceAdminProviderCreate(){const t=this.getState().admin?.modelProviders?.create;if(!t?.editing||t.saving||t.stage!=="name")return;const s=String(t.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 t=this.getState().admin?.modelProviders?.create;if(!t?.editing||t.saving||t.stage!=="credential")return;const s=this._adminProviderTypeUsesWorkloadIdentity(t.typeId),n=String(t.draft||"").trim();if(!n&&!s){this.dispatch({type:"admin/modelProviders/createFailed",error:"Enter a provider credential."});return}const r={name:t.name,type:t.typeId,credentials:s?{kind:"workloadIdentity"}:/github/i.test(t.typeId)?{githubToken:n}:{apiKey:n},shared:s?!0:t.shared===!0};this.dispatch({type:"admin/modelProviders/createSaving"});const i=t.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:t,providerName:s,agentId:n}={}){this.dispatch({type:"admin/modelProviders/select",focus:t,providerName:s,agentId:n})}setAdminModelProviderPage(t){t==="shared"&&!this.getState().admin?.profile?.isAdmin||this.dispatch({type:"admin/modelProviders/page",page:t})}stepAdminModelProviderSelection(t){const s=$t(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+t+r.length)%r.length];this.setAdminModelProviderSelection(n==="agents"?{focus:n,agentId:l.agentId}:{focus:n,providerName:l.name})}async toggleSelectedAdminProviderSystemUse(){const t=$t(this.getState()).modelProviders,s=t.myProviders.find(n=>n.name===t.selection?.providerName);if(!(!s||!this.getState().admin?.profile?.isAdmin))return this.setAdminProviderSystemUse(s.name,!s.systemUseEnabled)}async deleteSelectedAdminProvider(){const t=$t(this.getState()).modelProviders,s=[...t.myProviders,...t.sharedProviders].find(n=>n.name===t.selection?.providerName);if(s)return this.deleteAdminProvider(s.name,{shared:s.class==="shared"})}requestDeleteSelectedAdminProvider(){const t=$t(this.getState()).modelProviders,s=[...t.myProviders,...t.sharedProviders].find(n=>n.name===t.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:F.ADMIN}})}async cycleAdminModelDefault(t,{restartDisposition:s=null}={}){const n=$t(this.getState()).modelProviders,r=t==="user"?n.userChoices:t==="cluster"?n.clusterChoices:n.systemChoices,i=t==="user"?n.mySessionDefault?.configured?.model:t==="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 t==="system"?this.setAdminSystemModelDefault(c,{restartDisposition:s}):this.setAdminModelDefault(t,c)}async cycleSelectedAdminSystemAgentOverride(){const t=$t(this.getState()).modelProviders,s=t.systemAgentRoutes.find(l=>l.agentId===t.selection?.agentId)||t.systemAgentRoutes[0];if(!s)return;const n=[null,...t.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(t){this.dispatch({type:"admin/section",section:t}),t==="features"&&this.refreshFeatureFlags(),t==="providers"&&(this.getState().admin?.modelProviders?.fetchedAt||this.refreshAdminModelProviders().catch(()=>{})),t==="packages"&&(this.getState().admin?.packages?.fetchedAt||this.refreshAdminAgentPackages().catch(()=>{})),t==="workers"&&this.refreshAdminWorkers().catch(()=>{})}async selectFeatureScope(t,s=null){["mine","cluster","users"].includes(t)&&(this.getState().admin?.features?.saving||t!=="mine"&&!this._featureIsAdmin()||t==="users"&&s!==null&&(!Number.isSafeInteger(s)||s<=0)||(this.dispatch({type:"admin/features",patch:{mode:t,userId:t==="users"?s:null,data:null,error:null,notice:null,fetchedAt:null,dirtyDrafts:{}}}),await this.refreshFeatureFlags()))}_featureIsAdmin(){const t=this.getState(),s=t.auth?.authorization?.role;return t.admin?.profile?.isAdmin===!0&&(!s||s==="admin"||s==="anonymous")}_featureContext(){const t=this.getState(),s=t.admin.features;return JSON.stringify([s.generation,s.mode,s.userId,t.auth?.principal?.provider,t.auth?.principal?.subject,t.auth?.authorization?.role,t.admin.profile?.provider,t.admin.profile?.subject,t.admin.profile?.isAdmin])}async _featureRequest(t){let s;try{return await Promise.race([Promise.resolve().then(t),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 t=this.getState().admin,s=t?.features;!t?.visible||t.section!=="features"||s?.loading||s?.saving||Object.keys(s?.dirtyDrafts||{}).length||s?.fetchedAt&&Date.now()-s.fetchedAt<2e4||await this.refreshFeatureFlags({background:!0})}setFeatureDraftDirty(t,s){const n={...this.getState().admin.features.dirtyDrafts};s?n[t]=!0:delete n[t],this.dispatch({type:"admin/features",patch:{dirtyDrafts:n}})}_featureDraftKey(t){const s=this.getState().admin.features;return JSON.stringify([s.mode,s.mode==="users"?s.userId:null,t])}getFeatureDraft(t){return this.getState().admin.features.drafts?.[this._featureDraftKey(t)]}getFeatureDraftCount(t){return Object.values(this.getState().admin.features.drafts||{}).filter(s=>s.mode===t).length}setFeatureDraft(t,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===t);if(!r?.supported)return;const i=this._featureDraftKey(t),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:t,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(t){if(this.getState().admin.features.saving)return;const s=this.getFeatureDraft(t),n=this._featureContext();if(s?.uncertain&&!await this.refreshFeatureFlags()||n!==this._featureContext()||this.getFeatureDraft(t)!==s)return;if(s?.uncertain){const i=this.getState().admin.features.data?.flags?.find(o=>o.featureKey===t)?.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(t)],this.dispatch({type:"admin/features",patch:{drafts:r,error:null,notice:null}})}reviewFeatureDraft(t){const s=this.getState().admin.features;if(s.saving||s.loading||s.mode!=="mine"&&!this._featureIsAdmin())return;const n=this._featureDraftKey(t),r=s.drafts?.[n],i=s.data?.flags?.find(o=>o.featureKey===t);!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(t){const s=this.getFeatureDraft(t);if(!s)return;const n=this.getState().admin.features.data?.flags?.find(r=>r.featureKey===t);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(t,s.values,{draft:s})}async searchFeatureUsers(t=""){if(!this._featureIsAdmin())return;const s=this._featureUserSerial=(this._featureUserSerial||0)+1,n=this._featureContext();this.dispatch({type:"admin/features",patch:{userQuery:String(t),usersLoading:!0,metadataError:null}});const r=()=>this._featureUserSerial===s&&this._featureContext()===n;try{const i=await this._featureRequest(()=>this.transport.listFeatureFlagUsers(String(t)));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:t=!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,...t?{}:{error:null}}}),!t&&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(t,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===t);if(!i?.supported||r.mode==="users"&&!r.userId)return;const o=this._featureContext(),l=this._featureDraftKey(t),c=n?.expectedRevision??i.revision,d=JSON.stringify([o,t,c,s]);this._featureMutationRetries??=new Map;const u=this._featureMutationRetries.get(d)??globalThis.crypto.randomUUID();this._featureMutationRetries.set(d,u);const p={featureKey:t,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,b=g.flags.map(S=>S.featureKey===t?f:S),y=b.find(S=>S.featureKey==="copilot.native_tasks")?.effective===!0,v=b.map(S=>{if(S.featureKey!=="agents.base_v2")return S;const{reason:w,...E}=S,T=(S.cluster?.allowUserOverride??S.defaultAllowUserOverride)&&S.user?S.user.enabled:S.cluster?.enabled??S.defaultEnabled;return{...E,effective:T&&y,...T&&!y?{reason:"requires_native_tasks"}:{}}});this.dispatch({type:"admin/features",patch:{data:{...g,flags:v}}})}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(t){this.dispatch({type:"ui/nodeMapSelect",label:t?String(t):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 t=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(t)?t.length:0} row(s)`),this.dispatch({type:"admin/workers/loaded",list:t})}catch(t){console.warn(`[PilotSwarmUi] worker-registry fetch failed: ${t?.message||t}`),this.dispatch({type:"admin/workers/loadFailed",error:t?.message||String(t)})}}async refreshAdminAgentPackages(){if(typeof this.transport.listAgentPackages!="function"){this.dispatch({type:"admin/packages/loadFailed",error:"Packages are not available on this deployment."});return}this.dispatch({type:"admin/packages/loading"});try{const[t,s]=await Promise.all([this.transport.listAgentPackages(),typeof this.transport.listAgentWorkerState=="function"?this.transport.listAgentWorkerState().catch(()=>[]):[]]);this.dispatch({type:"admin/packages/loaded",list:t,workerState:s})}catch(t){this.dispatch({type:"admin/packages/loadFailed",error:t?.message||String(t)})}}async selectAdminPackage(t,s=null){if(this.dispatch({type:"admin/packages/select",name:t,selector:s}),!t)return;const n=this.getState().admin?.packages?.selectionSeq??0;await Promise.all([(async()=>{try{const r=await this.transport.getAgentPackage(t,s);if(!r)throw new Error(`package "${t}" not found`);this.dispatch({type:"admin/packages/detail/loaded",name:t,seq:n,detail:r})}catch(r){this.dispatch({type:"admin/packages/detail/loadFailed",name:t,seq:n,error:r?.message||String(r)})}})(),(async()=>{try{const r=await this.transport.getAgentPackageTree(t,null,s);if((this.getState().admin?.packages?.selectionSeq??0)!==n)return;this.dispatch({type:"admin/packages/tree/loaded",name:t,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(t,null,"CHANGELOG.md",s);if((this.getState().admin?.packages?.selectionSeq??0)!==n)return;this.dispatch({type:"admin/packages/changelog/loaded",name:t,seq:n,content:typeof l=="string"?l:l?.content??l?.text??""})}catch{}})():this.dispatch({type:"admin/packages/changelog/loaded",name:t,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:t,seq:n,error:r?.message||String(r)})}})()])}async stepAdminPackageSelection(t){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?t>0?-1:0:o)+t))];l&&(l.name!==s.selectedName||r(l)!==i)&&await this.selectAdminPackage(l.name,hb(l))}toggleAdminPackageDir(t){this.dispatch({type:"admin/packages/toggleDir",dir:t})}async selectAdminPackageFile(t){const s=this.getState().admin?.packages,n=s?.selectedName;if(!n||!t)return;const r=s?.selectionSeq??0,i=s?.selectedSelector??null;this.dispatch({type:"admin/packages/file/loading",path:t});try{const o=await this.transport.getAgentPackageFile(n,null,t,i);this.dispatch({type:"admin/packages/file/loaded",seq:r,file:o})}catch(o){this.dispatch({type:"admin/packages/file/loadFailed",seq:r,path:t,error:o?.message||String(o)})}}async runAdminPackageAction(t,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:t});try{switch(t){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,t==="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: ${t}`)}if(this.dispatch({type:"admin/packages/action/done"}),await this.refreshAdminAgentPackages(),t!=="delete"){const o=t==="promote"?{scope:"shared",...i?.owner?{owner:i.owner}:{}}:t==="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(t){this.dispatch({type:"admin/packages/addDialog/failed",error:t})}async submitAdminUploadPackage(t,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(t,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(t,s="user"){const n=String(t||"").trim();n&&this.dispatch({type:"admin/packages/addDialog/open",updateName:n,scope:s})}closeAdminAddPackage(){this.dispatch({type:"admin/packages/addDialog/close"})}setAdminAddPackageField(t,s){this.dispatch({type:"admin/packages/addDialog/setField",field:t,value:s})}async submitAdminAddPackage(){const t=this.getState().admin?.packages?.addDialog;if(!t?.open||t.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(t.repoUrl||"").trim(),n=yd(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(t.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 Jm(s,{token:i,tokenKind:o,onProgress:d=>this.dispatch({type:"admin/packages/addDialog/progress",message:d})});if(t.updateName){const d=ef(l);if(d&&d!==t.updateName){this.dispatch({type:"admin/packages/addDialog/failed",error:`That folder builds "${d}", not "${t.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,t.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(t,s=String(t||"").length){this.dispatch({type:"admin/ghcpKey/setDraft",draft:t,cursorIndex:s})}insertAdminGhcpKeyText(t){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=String(t||"").replace(/\r?\n/g,""),r=Rt(s.draft||"",s.cursorIndex||0,n);this.setAdminGhcpKeyDraft(r.prompt,r.cursor)}deleteAdminGhcpKeyChar(){const t=this.getState().admin?.ghcpKey;if(!t?.editing)return;const s=Zt(t.draft||"",t.cursorIndex||0);this.setAdminGhcpKeyDraft(s.prompt,s.cursor)}moveAdminGhcpKeyCursor(t){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,Fe(n,(s.cursorIndex||0)+t))}moveAdminGhcpKeyCursorToBoundary(t){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,t==="start"?0:n.length)}cancelAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/cancelEdit"})}async saveAdminGhcpKey(){const t=!!this.getState().admin.ghcpKey.storeAsSystem,s=t?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:t?"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(t){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 t=!!this.getState().admin.ghcpKey.storeAsSystem,s=t?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:t?"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(t){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:t=void 0}={}){this.getState().admin?.visible&&this.closeAdminConsole(),this.dispatch({type:"ui/budgetOpen",open:!0,...t===void 0?{}:{provider:t}}),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(t){this.dispatch({type:"budget/tab",tab:t}),t==="summary"&&this.loadUsageSummary().catch(()=>{}),t==="agents"&&this.loadUsageAgents().catch(()=>{})}async setUsageSummaryFilter({days:t,providers:s,preset:n}={}){this.dispatch({type:"budget/summary/filter",days:t,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 t=this.getState().budget?.summary||{};this.dispatch({type:"budget/agents/loading"});try{const s=await this.transport.getProviderUsageAgents({days:t.days||14,...Array.isArray(t.providers)&&t.providers.length?{providers:t.providers}:{}});this.dispatch({type:"budget/agents/loaded",data:s,fetchedAt:Date.now()})}catch(s){this.dispatch({type:"budget/agents/failed",error:vs(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 t=this.getState().budget?.summary||{};this.dispatch({type:"budget/summary/loading"});try{const s=await this.transport.getProviderUsageSummary({days:t.days||14,...Array.isArray(t.providers)&&t.providers.length?{providers:t.providers}:{}});this.dispatch({type:"budget/summary/loaded",data:s,fetchedAt:Date.now()})}catch(s){this.dispatch({type:"budget/summary/failed",error:vs(s)})}}setBudgetOverall(t){const s=this.getState().budget?.overall===!0;this.dispatch({type:"budget/overall",...typeof t=="boolean"?{overall:t}:{}});const n=this.getState().budget||{};if(!(n.overall===s||!n.selectedProvider))return this.loadProviderSeries(n.selectedProvider,n.selectedScope||"*")}async setBudgetRangeDays(t){const s=Number(t);if(!er.includes(s))return;const n=this.getState().budget?.rangeDays??Oe;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(t,s="*"){this.dispatch({type:"budget/selectProvider",provider:t,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[t,s]=await Promise.all([this._readBudgetPart(()=>this.transport.getProviderUsageGrid()),this._readBudgetPart(()=>this.transport.listPausedSessions())]);this._settleBudgetRead([["grid","the provider table",t,n=>n?.rows||[]],["paused","the paused sessions",s,n=>n?.sessions||[]]])}async refreshProviderTable(){await this.loadProviderTable();const t=this.getState().budget||{};t.selectedProvider&&await Promise.all([this.loadProviderSeries(t.selectedProvider,t.selectedScope||"*"),this.loadProviderSystemUsage(t.selectedProvider,t.selectedScope||"*")])}async loadProviderSeries(t,s="*"){const n=String(t??"").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??Oe;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:vs(l)})}}async loadProviderSystemUsage(t,s="*"){const n=this.getState().auth?.authorization?.role,r=n==="admin"||n==="anonymous"||this.getState().admin?.profile?.isAdmin===!0,i=String(t??"").trim();if(!r||!i||typeof this.transport.getProviderUsage!="function")return;const o=s&&s!=="*"?s:null,l=this.getState().budget?.rangeDays??Oe;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:vs(c)})}}async refreshBudgetPausesIfStale(t){if(typeof this.transport.listPausedSessions!="function")return;const s=this.getState();if(s.ui?.budgetOpen||!(Array.isArray(t)?t:[]).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:t=!1}={}){if(typeof this.transport.listPausedSessions!="function"){if(t)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&&t||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(t){try{return{value:await t(),error:null}}catch(s){return{value:null,error:vs(s)}}}_settleBudgetRead(t){const s={},n=[];for(const[o,l,c,d]of t)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=t.some(([o,,l])=>o==="grid"&&l.error);this.dispatch(i?{type:"budget/loadFailed",error:r}:{type:"budget/pausedFailed",error:r})}async _runBudgetChange(t){try{const s=await t();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=vs(s);return this.dispatch({type:"ui/status",text:n}),await this.loadProviderTable().catch(()=>{}),{ok:!1,error:n,code:s?.code||null,result:null}}}_refuseBudgetChange(t){return this.dispatch({type:"ui/status",text:t}),{ok:!1,error:t,code:"UNSUPPORTED",result:null}}async createProvider({name:t,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:t,type:s,credentials:n,baseUrl:r}))}async deleteProvider(t,{shared:s=null}={}){const n=(this.getState().budget?.grid||[]).find(o=>o?.providerName===t&&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](t))}async setProviderLimit({provider:t,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:t,period:s,model:n,tokens:r}))}async removeProviderLimit({provider:t,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:t,period:s,model:n}))}async setProviderAllowance({provider:t,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:t,pct:s}))}async setProviderHold({provider:t,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:t,untilUtc:s,release:n}))}async setClusterDefault(t){return typeof this.transport.setClusterDefault!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setClusterDefault(t))}async setMyDefault(t){return typeof this.transport.setMyDefault!="function"?this._refuseBudgetChange("Providers and budgets are not available on this deployment."):this._runBudgetChange(()=>this.transport.setMyDefault(t))}async ensureExecutionHistory(t,{force:s=!1}={}){if(!t||typeof this.transport.getExecutionHistory!="function")return null;const n=this.getState().executionHistory?.bySessionId?.[t]||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:t});try{const i=await this.transport.getExecutionHistory(t);this.dispatch({type:"executionHistory/loaded",sessionId:t,events:i||[],fetchedAt:Date.now()})}catch(i){console.error("[executionHistory] fetch error:",i?.message||i),this.dispatch({type:"executionHistory/error",sessionId:t,error:i?.message||String(i),fetchedAt:Date.now()})}return this.getState().executionHistory?.bySessionId?.[t]||null}async ensureFilesForScope(t=ft(this.getState()),{force:s=!1}={}){const n=nr(this.getState(),t);return n.length===0?t==="allSessions"?[]:null:t==="allSessions"||n.length>1?Promise.allSettled(n.map(r=>this.ensureFilesForSession(r,{force:s}))):this.ensureFilesForSession(n[0],{force:s})}async ensureSelectedFilePreview(){const t=jt(this.getState());return!t?.sessionId||!t?.filename?null:this.ensureFilePreview(t.sessionId,t.filename).catch(()=>null)}async ensureFilesForSession(t,{force:s=!1}={}){if(!t||typeof this.transport.listArtifacts!="function")return null;const n=this.getState().files.bySessionId[t];if(!s&&n?.loading)return n;const r=Date.now()-(Number(n?.fetchedAt)||0);if(!s&&n?.loaded&&r<uS)return n.selectedFilename&&await this.ensureFilePreview(t,n.selectedFilename).catch(()=>{}),n;this.dispatch({type:"files/sessionLoading",sessionId:t});try{const i=await this.transport.listArtifacts(t),o=Date.now();this.dispatch({type:"files/sessionLoaded",sessionId:t,entries:i,fetchedAt:o});const l=this.getState().files.bySessionId[t];return l?.selectedFilename&&await this.ensureFilePreview(t,l.selectedFilename).catch(()=>{}),l}catch(i){return this.dispatch({type:"files/sessionError",sessionId:t,error:i?.message||String(i)}),null}}async ensureFilePreview(t,s,{force:n=!1}={}){if(!t||!s||typeof this.transport.downloadArtifact!="function")return null;const r=this.getState().files.bySessionId[t],i=r?.previews?.[s];let o=Gf(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(t,s)}catch{o=null}this.dispatch({type:"files/previewLoading",sessionId:t,filename:s});try{const l=o?.isBinary===!0?jl(s,"",o.contentType||"",o):jl(s,await this.transport.downloadArtifact(t,s),o?.contentType||"",o);return this.dispatch({type:"files/previewLoaded",sessionId:t,filename:s,...l}),l}catch(l){return this.dispatch({type:"files/previewError",sessionId:t,filename:s,error:l?.message||String(l)}),null}}buildArtifactPickerItems(t=[],s=[]){const n=(t||[]).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(t||[]).length>1&&n.push({id:"__downloadAll__",kind:"downloadAll"}),n}buildArtifactPickerModal({artifactLinks:t,httpLinks:s,previousFocus:n,selectedId:r}={}){const i=this.buildArtifactPickerItems(t,s);if(i.length===0)return null;const o=i.findIndex(l=>l.id===r);return{type:"artifactPicker",title:"Linked Items",previousFocus:n,artifactLinks:t,httpLinks:s,items:i,selectedIndex:o>=0?o:0,exportDirectory:typeof this.transport.getArtifactExportDirectory=="function"?this.transport.getArtifactExportDirectory():null}}getArtifactPickerSelectionId(){const t=this.getState().ui.modal;return!t||t.type!=="artifactPicker"?null:t.items?.[t.selectedIndex||0]?.id||null}replaceArtifactPickerModal(t=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:t||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(t,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(t,s);this.dispatch({type:"files/downloaded",sessionId:t,filename:s,localPath:n?.localPath||"",downloadedAt:Date.now()});const r=this.getState().sessions.activeSessionId;return(t===r||this.getState().ui.inspectorTab==="files")&&(await this.ensureFilesForSession(t,{force:!0}).catch(()=>null),t===r&&(this.dispatch({type:"files/select",sessionId:t,filename:s}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(t,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 t=this.getState(),s=jt(t);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:t.sessions.activeSessionId||ft(t)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:r}=s,i=ft(t);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=t.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 ${nt(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 t=jt(this.getState());if(!t?.sessionId||!t?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),null;this.dispatch({type:"ui/status",text:`Downloading ${t.filename}...`});const s=await this.saveArtifactDownload(t.sessionId,t.filename);return s?.localPath?(this.dispatch({type:"ui/status",text:`Downloaded ${t.filename}`}),s):null}toggleArtifactMark(t){t?.id&&this.dispatch({type:"files/toggleMark",artifactId:t.id})}markArtifactRange(t){if(!t?.id)return;const s=rs(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===t.id);if(o<0)return;if(i<0){this.dispatch({type:"files/toggleMark",artifactId:t.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:t=!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(!t)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:t=!1}={}){const s=this.getState(),n=jt(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const r=ft(s),i=r==="allSessions"?`${nt(n.sessionId)} ${n.filename}`:n.filename;if(!t)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=jt(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 ${nt(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 t=this.getState(),s=t.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=mg(t),r=fg(t);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:t.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 t=this.getState().ui.modal;if(!t||t.type!=="artifactPicker")return;const s=t.items?.[t.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=(t.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(t){const s=ft(this.getState());await this.ensureFilesForScope(s);const n=rs(this.getState());if(n.length===0)return;const r=jt(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+t)),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 ${nt(l.sessionId)} ${l.filename}`:`Previewing ${l.filename}`}))}async selectFileBrowserItem(t){if(!t?.sessionId||!t?.filename)return;this.dispatch({type:"files/previewOrigin",origin:"list"});const s=ft(this.getState());s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:t.id}):this.dispatch({type:"files/select",sessionId:t.sessionId,filename:t.filename}),await this.ensureFilePreview(t.sessionId,t.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${nt(t.sessionId)} ${t.filename}`:`Previewing ${t.filename}`})}toggleFilePreviewFullscreen(){const t=this.getState(),s=t.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=t.files.bySessionId[s],r=!!t.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 t=this.getState(),s=t.ui.focusRegion,n=t.ui.fullscreenPane||null,r=s===F.PROMPT?n:s;if(!Eb.has(r)||r===F.INSPECTOR&&t.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===F.PROMPT&&this.setFocus(r)}openFilesFilter(){const t=ft(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 = ${t==="allSessions"?"All sessions":"Selected session tree"}`})}setNavigationIntent(t){const s=String(t||"").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:ti(r)})});return}Object.keys(n.sessions.byId).length>0&&this.scheduleSessionsRefresh(0)}async loadSession(t){if(!t)return;const s=this.navigationGeneration=(this.navigationGeneration||0)+1;if(this.getState().sessions.activeSessionId!==t&&(this.getState().ui.promptEdit&&this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"sessions/selected",sessionId:t}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.getState().sessions.byId[t]?.isGroup){this.detachActiveSession();return}await Promise.all([this.ensureSessionHistory(t,{force:!0}),this.syncSessionDetail(t).catch(()=>{})]),!(this.navigationGeneration!==s||this.getState().sessions.activeSessionId!==t)&&(this.attachActiveSession(t),this.ensureInspectorData().catch(()=>{}),this.dispatch({type:"canvas/snapshotInvalidate",sessionId:t}),this.ensureCanvasSnapshot(t).catch(()=>{}))}reconcileOutboxAgainstEvent(t,s){if(!(!t||!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(t,s.eventType==="user.message"?n:void 0,i);else s.eventType==="user.message"&&typeof n=="string"&&n.trim()&&this.acknowledgeOutboxPrompt(t,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(t,n)}}}maybeRevealPresentedArtifact(t,s){const n=String(s?.data?.filename||"").trim();if(!n||t!==this.getState().sessions.activeSessionId)return!1;const r=s?.createdAt?Date.parse(s.createdAt):Number.NaN;if(Number.isFinite(r)&&Date.now()-r>ri)return!1;const i=s?.data?.fullscreen===!0;return this.revealArtifact(t,n,i?{fullscreen:!0}:{pane:!0}).catch(()=>{}),!0}applyCanvasUpdate(t,s){const n=Number(s?.data?.rev);if(!t||!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:t,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(t!==o.sessions.activeSessionId||o.canvas.prefs[ut(t,i)]?.optedOut)return!0;const l=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(l)&&Date.now()-l>ri||this.dispatch({type:"canvas/flip",sessionId:t,slot:i}),!0}submitCanvasAction(t,s,n=1){if(!t)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[ut(t,n)]?.responseContract||null,i=nm(r,s);if(!i.ok)return Promise.resolve(i);this.canvasActionLimiters||(this.canvasActionLimiters=new Map);let o=this.canvasActionLimiters.get(t);if(o||(o=am(),this.canvasActionLimiters.set(t,o)),!o())return Promise.resolve({ok:!1,reason:"rate limited"});const l=rm(i.action,i.data);return this.transport.sendMessage(t,l,{enqueueOnly:!0}).then(()=>(this.syncSessionEvents(t).catch(()=>{}),{ok:!0,action:i.action})).catch(c=>({ok:!1,reason:c?.message||String(c)}))}async ensureCanvasSnapshot(t){if(t&&!this.getState().canvas.bySessionId[t]?.snapshotLoaded){if(typeof this.transport.getSessionEventsBefore!="function"){this.dispatch({type:"canvas/snapshot",sessionId:t,rev:0});return}try{const s=await this.transport.getSessionEventsBefore(t,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:t,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(t,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:t,slot:l,dataRev:Number(c.data.dataRev),payload:c.data.payload,note:typeof c.data.note=="string"?c.data.note:""})}}catch{}}}applyCanvasPresented(t,s){const n=Number(s?.data?.slot),r=Number.isInteger(n)&&n>=1&&n<=5?n:1;if(!t)return!1;const i=this.getState();if(t!==i.sessions.activeSessionId||i.canvas.prefs[ut(t,r)]?.optedOut)return!1;const o=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(o)&&Date.now()-o>ri?!1:(this.dispatch({type:"canvas/flip",sessionId:t,slot:r}),!0)}subscribeCanvasKv(t,s){if(!t||typeof s!="function")return()=>{};this._canvasKvListeners||(this._canvasKvListeners=new Map),this._canvasKvListeners.has(t)||this._canvasKvListeners.set(t,new Set);const n=this._canvasKvListeners.get(t);return n.add(s),()=>{n.delete(s),n.size===0&&this._canvasKvListeners.delete(t)}}applyCanvasDataEvent(t,s){this.dispatch({type:"canvas/data",sessionId:t,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(t,s){if(!t||!s)return!1;if(s.eventType==="session.access_revoked")return this.handleSessionGone(t),!0;if(s.transient===!0){if(s.eventType==="session.native_tasks_tick"){const p=this.getState().history.bySessionId.get(t),m=Qc(p,s.data,{sessionId:t,seq:s.liveSeq});return m&&m!==p&&this.dispatch({type:"history/set",sessionId:t,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(t)?.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(t);if(m&&s.data?.phase==="idle"&&(clearTimeout(m),this._liveTurnIdleTimers.delete(t)),s.data?.phase==="idle"){const g=this.getState().history.bySessionId.get(t);if(!g)return!0;const b=s.data?.streamId||null,y=new Set(g.chat.filter(S=>S.liveTurn&&(!b||S.streamId===b||(g.closedLiveStreams||[]).includes(S.streamId)||(g.closedLiveKeys||[]).includes(S.liveKey))).map(S=>S.liveKey));this.dispatch({type:"history/set",sessionId:t,history:{...Js(g,null,b),chat:g.chat.filter(S=>!S.liveTurn||!y.has(S.liveKey)||Date.now()-S.liveStartedAt>=200)}});const v=setTimeout(()=>{this._liveTurnIdleTimers?.delete(t);const S=this.getState().history.bySessionId.get(t);if(!S)return;const w=S.chat.filter(I=>!I.liveTurn||!y.has(I.liveKey)),E=w.length===S.chat.length?S:{...S,chat:w};E!==S&&this.dispatch({type:"history/set",sessionId:t,history:E})},1200);return v.unref?.(),this._liveTurnIdleTimers.set(t,v),!0}const f=this.getState().history.bySessionId.get(t)||{chat:[],activity:[],events:[],lastSeq:0},h=this.preservePausedChatWindow(t,f);return this.dispatch({type:"history/set",sessionId:t,history:Tm(h,s.data,{sessionId:t,seq:s.liveSeq,createdAt:Date.now()})}),!0}if(s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(t,s),s.eventType==="session.canvas_kv"){const p=this._canvasKvListeners?.get(t);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:t}),!1}this._liveTurnIdleTimers?.has(t)&&(s.eventType==="session.turn_completed"||s.eventType==="session.turn_stopped")&&(clearTimeout(this._liveTurnIdleTimers.get(t)),this._liveTurnIdleTimers.delete(t));const n=this.getState(),r=this.preservePausedChatWindow(t,n.history.bySessionId.get(t)||{chat:[],activity:[],events:[],lastSeq:0});if(s.seq<=(r.lastSeq||0))return!1;this.dispatch({type:"history/set",sessionId:t,history:Dr(r,s)});const i=this.getState().sessions.byId[t],o=nn(s.createdAt),l=nn(i?.updatedAt);if(s.eventType==="session.input_required_started"&&s.data?.question&&(!o||!l||o>=l)&&this.dispatch({type:"sessions/merged",session:{sessionId:t,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=hr(s.data?.content),m=Math.max(l,nn(i.pendingQuestion.askedAt));p?.question===i.pendingQuestion.question&&(!o||!m||o>=m)&&this.dispatch({type:"sessions/merged",session:{sessionId:t,pendingQuestion:null,resolvedInputQuestion:{question:p.question,answeredAt:o}}})}s.eventType==="session.artifact_presented"&&this.maybeRevealPresentedArtifact(t,s),s.eventType==="session.canvas_updated"&&this.applyCanvasUpdate(t,s),s.eventType==="session.canvas_presented"&&this.applyCanvasPresented(t,s),s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(t,s),this.reconcileOutboxAgainstEvent(t,s);const c=Pb(s),d=this.getState().sessions.byId[t]||{sessionId:t},u=Lc(d.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(c||u)&&this.dispatch({type:"sessions/merged",session:{sessionId:t,...c||{},...u?{contextUsage:u}:{}}}),this.maybeFlushQueuedOutbox(t,this.getState().sessions.byId[t]||d),this.scheduleSessionDetailSync(t),!0}preservePausedChatWindow(t,s){const n=this.getState();if(n.sessions.activeSessionId!==t||n.ui.followBottom?.chat!==!1)return s;const r=Math.max(Ne,Number(s?.loadedEventLimit??Ne)||Ne),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(t){if(!t||typeof this.transport.getSessionEvents!="function")return;const s=this.getState().history.bySessionId.get(t);if(!s?.events){await this.ensureSessionHistory(t,{force:!0});return}const n=Number(s.lastSeq||0);let r=null;try{r=await this.transport.getSessionEvents(t,n,200)}catch(i){if(Vs(i)){this.handleSessionGone(t);return}throw i}if(!(!Array.isArray(r)||r.length===0))for(const i of r)this.mergeSessionEvent(t,i)}attachActiveSession(t){this.activeSessionSubscriptionId===t&&this.activeSessionUnsub||(this.detachActiveSession(),this.activeSessionSubscriptionId=t,this.activeSessionUnsub=this.transport.subscribeSession(t,s=>{this.mergeSessionEvent(t,s)}),this.syncSessionEvents(t).catch(()=>{}))}scheduleSessionDetailSync(t,s=250){typeof this.transport.getSession!="function"||!t||Ks(t)||(this.activeSessionDetailTimer&&clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailSessionId=t,this.activeSessionDetailTimer=setTimeout(()=>{const n=this.activeSessionDetailSessionId;this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.syncSessionDetail(n).catch(()=>{})},s))}scheduleSessionsRefresh(t=0){this.sessionRefreshTimer&&clearTimeout(this.sessionRefreshTimer),this.sessionRefreshTimer=setTimeout(()=>{this.sessionRefreshTimer=null,this.refreshSessions().catch(()=>{})},Math.max(0,t))}async syncSessionDetail(t){if(typeof this.transport.getSession!="function"||!t||Ks(t))return;let s=null;try{s=await this.transport.getSession(t)}catch(i){if(Vs(i)){this.handleSessionGone(t);return}throw i}if(!s)return;const n=this.getState().sessions.byId[t]||null,r=Rb(n,s);(r||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:r||{sessionId:t}}),this.maybeFlushQueuedOutbox(t,s)}async openCreatedSession(t,s={}){const n=t.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:xn({...t,...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(t={}){try{const s=this.applyActiveGroupDefault(t),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(t,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(t,n);return this._recordAgentPickerUse(t),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(t,s){!s||!t?.sessionId||typeof this.transport.placeSessionsInGroup=="function"&&(t.viewerGroupId??null)!==s&&await this.transport.placeSessionsInGroup([t.sessionId],s).catch(()=>{})}getMovableGroupSessionSelection(){const t=this.getState(),s=t.sessions.activeSessionId&&!t.sessions.listDeselected?[t.sessions.activeSessionId]:[];return(Array.isArray(t.sessions.selectedIds)&&t.sessions.selectedIds.length>0?t.sessions.selectedIds:s).map(r=>t.sessions.byId[r]).filter(r=>r&&!r.isSystem&&!r.isGroup&&!r.parentSessionId)}async openMoveToGroupModal(){const t=this.getState(),s=this.getMovableGroupSessionSelection();if(s.length===0){const c=t.sessions.activeSessionId?t.sessions.byId[t.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:t.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(t){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(t.title||"").trim();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",mode:"rename",groupId:t.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 t=this.getState();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:t.ui.focusRegion,sessionIds:[],value:"",cursorIndex:0,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"}),null}async moveSessionsToGroup(t,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,t??null);else if(typeof this.transport.moveSessionsToGroup=="function")await this.transport.moveSessionsToGroup(t??null,r);else if(t&&typeof this.transport.assignSessionsToGroup=="function")await this.transport.assignSessionsToGroup(t,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(),t&&c>0&&await this.loadSession(`group:${t}`).catch(()=>{});const d=t?`group ${n||t}`:"No Group",u=l.length>0?` · skipped ${l.length} (${Ib(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 t=this.getState().ui.modal;if(!t||t.type!=="sessionGroupPicker")return;const s=t.items?.[t.selectedIndex||0];if(!s)return;if(s.kind==="newGroup"){const r=(t.sessionLabels||[]).length===1?`${t.sessionLabels[0]} Group`:`${(t.sessionIds||[]).length} Session Group`;this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:t.previousFocus,sessionIds:t.sessionIds||[],value:r,cursorIndex:r.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"});return}const n=t.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{await this.moveSessionsToGroup(s.kind==="noGroup"?null:s.groupId,t.sessionIds||[],{statusTitle:s.label})}catch(r){this.dispatch({type:"ui/status",text:`Move failed: ${r?.message||String(r)}`})}}updateSessionGroupNameModal(t){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=typeof t=="function"?t(s):t;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setSessionGroupNameValue(t,s=String(t||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="sessionGroupName")return;const r=bs(t,n.maxLength||80),i=Fe(r,s);this.updateSessionGroupNameModal({value:r,cursorIndex:i})}insertSessionGroupNameText(t){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=Rt(s.value||"",s.cursorIndex||0,bs(t,s.maxLength||80));this.setSessionGroupNameValue(n.prompt,n.cursor)}deleteSessionGroupNameChar(){const t=this.getState().ui.modal;if(!t||t.type!=="sessionGroupName")return;const s=Zt(t.value||"",t.cursorIndex||0);this.setSessionGroupNameValue(s.prompt,s.cursor)}moveSessionGroupNameCursor(t){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",Fe(s.value||"",(s.cursorIndex||0)+t))}moveSessionGroupNameCursorToBoundary(t){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",t==="start"?0:String(s.value||"").length)}async confirmSessionGroupNameModal(){const t=this.getState().ui.modal;if(!t||t.type!=="sessionGroupName")return;const s=String(t.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"Group name cannot be empty"});return}if(t.mode==="rename"&&t.groupId){const r=t.previousFocus;this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r);try{await this.transport.updateSessionGroup(t.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=t.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{const r=await this.transport.createSessionGroup({title:s,description:`${(t.sessionIds||[]).length} grouped session${(t.sessionIds||[]).length===1?"":"s"}`,sessionIds:t.sessionIds||[]}),i=t.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(t={}){if(t&&Object.prototype.hasOwnProperty.call(t,"groupId"))return t;const s=this.getState(),n=s.sessions?.activeSessionId?s.sessions.byId[s.sessions.activeSessionId]:null;if(!n?.isGroup)return t;const r=n.groupId||Fn(n.sessionId);return r?{...t,groupId:r}:t}getActiveSession(t=this.getState()){const s=t.sessions?.activeSessionId;return s&&t.sessions.byId[s]||null}async openSessionAgentPicker(t={},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(t);return}const c=[];for(const h of i){const g=String(h?.name||"").trim();g&&c.push({id:g,kind:"agent",agentName:g,title:Hb(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=$l.includes(this._agentPickerSort)?this._agentPickerSort:wu,f=Ll(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:Gb(f),previousFocus:n,sessionOptions:t}}),this.dispatch({type:"ui/status",text:"Select an agent and press Enter"})}async openNewSessionFlow(t={}){if((typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0){await this.createSession(t);return}if(typeof this.transport.listModels=="function"){await this.openModelPicker(t);return}await this.openSessionAgentPicker(t)}async openReasoningEffortPicker(t,s={},n=null){const r=n??this.getState().ui.focusRegion,i=Dn(t?.supportedReasoningEfforts),o=s?.reasoningEffort||Tl(t);if(!i.length||!o){await this.openContextTierPicker(t,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 ${t?.modelName||t?.qualifiedName||"model"}`:`Reasoning effort for ${t?.modelName||t?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:r,modelItem:t,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a reasoning effort and press Enter"})}async openContextTierPicker(t,s={},n=null){const r=n??this.getState().ui.focusRegion,i=Bn(t?.supportedContextTiers),o=s?.contextTier||Nb(t);if(!i.length||!o){if(s?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r),await this.switchSessionModel({...s,model:t?.id});return}await this.openSessionAgentPicker(s,r);return}const l=i.map(d=>({id:d,tier:d,tokenLimit:t?.contextWindowSizes?.[d]||null,label:Tb(d,t?.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 ${t?.modelName||t?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:r,modelItem:t,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a context window and press Enter"})}async openModelPicker(t={}){if(typeof this.transport.listModels!="function"){await this.openSessionAgentPicker(t);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,t):await this._buildCatalogPickerGroups(s,t);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:t?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:i,groups:o,selectedIndex:l,previousFocus:this.getState().ui.focusRegion,sessionOptions:t}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async _resolveProviderNamespace(){if(typeof this.transport.listProviders!="function")return null;try{const[t,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(t?.providers)?t.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(t,s,n){const r=t.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(t.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||t.defaults?.mine?.model||t.defaults?.cluster?.model||(typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0),u=[],p=c.map(m=>{const f=hS(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),v={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:Dn(g.supportedReasoningEfforts),defaultReasoningEffort:g.defaultReasoningEffort||null,supportedContextTiers:Bn(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(v),v})}}).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:Cl(u,d)}}async _buildCatalogPickerGroups(t,s){const n=typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0,r=typeof this.transport.getModelsByProvider=="function"?this.transport.getModelsByProvider():Ab(t),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:Dn(d.supportedReasoningEfforts),defaultReasoningEffort:d.defaultReasoningEffort||null,supportedContextTiers:Bn(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:Cl(o,s?.model||n)}}async _resolveGhcpUserKeySet(){const t=this.getState().admin?.profile;if(typeof t?.githubCopilotKeySet=="boolean")return t.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(t=null){this._onSwitchModelApplied=typeof t=="function"?t: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(t={}){const s=t.sessionId||this.getState().sessions.activeSessionId,n=String(t.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 t?{reasoningEffort:t.reasoningEffort??null}:{},..."contextTier"in t?{contextTier:t.contextTier??null}:{},source:"ui"});const r=t.reasoningEffort?`${n}:${t.reasoningEffort}`:n,i=t.contextTier?` · ${bu[t.contextTier]||t.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 t=Hf().map(r=>({id:r.id,label:r.label,description:r.description,group:r.group,page:r.page,terminal:r.terminal,tui:r.tui}));if(t.length===0){this.dispatch({type:"ui/status",text:"No themes available"});return}const s=this.getState().ui.themeId,n=Math.max(0,t.findIndex(r=>r.id===s));this.dispatch({type:"ui/modal",modal:{type:"themePicker",title:"Theme Picker",items:t,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 t=this.getState(),s=this.getPromptDraftSessionId();this.dispatch({type:"ui/modal",modal:{type:"artifactUpload",title:s?`Upload Artifact (${nt(s)})`:"Upload Artifact",sessionId:s,previousFocus:t.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(t){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=typeof t=="function"?t(s):t;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setArtifactUploadValue(t,s=String(t||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="artifactUpload")return;const r=String(t||"").replace(/\r?\n/g,""),i=Fe(r,s);this.updateArtifactUploadModal({value:r,cursorIndex:i})}insertArtifactUploadText(t){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=Rt(s.value||"",s.cursorIndex||0,String(t||"").replace(/\r?\n/g,""));this.setArtifactUploadValue(n.prompt,n.cursor)}deleteArtifactUploadChar(){const t=this.getState().ui.modal;if(!t||t.type!=="artifactUpload")return;const s=Zt(t.value||"",t.cursorIndex||0);this.setArtifactUploadValue(s.prompt,s.cursor)}moveArtifactUploadCursor(t){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",Fe(s.value||"",(s.cursorIndex||0)+t))}moveArtifactUploadCursorToBoundary(t){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",t==="start"?0:String(s.value||"").length)}async ensurePromptAttachmentSessionId(){const t=this.getPromptAttachments()[0]?.sessionId||null;if(t)return this.getState().sessions.activeSessionId!==t&&await this.loadSession(t),t;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(t,s,{force:n=!0,fullscreen:r=!1,pane:i=!1,preserveSession:o=!1}={}){const l=t||this.getState().sessions.activeSessionId,c=String(s||"").trim();if(!l||!c)return!1;if(this.dispatch({type:"files/previewOrigin",origin:"chat",restoreArtifactId:this.getState().files.selectedArtifactId||null}),!o&&this.getState().sessions.activeSessionId!==l&&await this.loadSession(l).catch(()=>null),i||this.dispatch({type:"ui/inspectorTab",inspectorTab:"files"}),i){const d=!!this.getCurrentLayout()?.rightHidden;d&&this.expandRightColumn(),this.dispatch({type:"files/pane",open:!0,restoresToHidden:d})}else this.setFocus("inspector");return await this.ensureFilesForSession(l,{force:n}).catch(()=>null),this.dispatch({type:"files/select",sessionId:l,filename:c}),await this.ensureFilePreview(l,c,{force:n}).catch(()=>null),r&&this.dispatch({type:"files/fullscreen",fullscreen:!0}),!0}async closeArtifactPane(){const t=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}),t&&this.collapseRightColumn(),this.dispatch({type:"ui/focus",focusRegion:F.CHAT}),{collapsedRightColumn:!!t}}expandRightColumn(){this.dispatch({type:"ui/paneAdjust",paneAdjust:0});const t=this.getCurrentLayout({paneAdjust:0}),s=this.getState().ui.focusRegion,n=bt(s,t);n!==s&&this.setFocus(n)}collapseRightColumn(){const s=(this.getState().ui.layout||{}).viewportWidth??120,n=Math.floor(s*pd),r=s-Ln-n;this.dispatch({type:"ui/paneAdjust",paneAdjust:r});const i=this.getCurrentLayout({paneAdjust:r}),o=this.getState().ui.focusRegion,l=bt(o,i);l!==o&&this.setFocus(l)}async closeArtifactPreview(){const t=this.getState(),s=t.files.previewOrigin;if(this.dispatch({type:"files/fullscreen",fullscreen:!1}),s!=="chat"){this.dispatch({type:"files/previewOrigin",origin:null}),this.setFocus(F.INSPECTOR);return}const n=t.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:F.CHAT})}async stepArtifactPreview(t){const s=this.getState();if(s.files.previewOrigin!=="chat"){await this.moveFileSelection(t);return}const n=sl(s);if(n.length===0){await this.moveFileSelection(t);return}const r=n.indexOf(s.files.selectedArtifactId),o=(r>=0?r:t>0?-1:n.length)+(t>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(t){const s=this.getState(),n=s.files.previewOrigin==="chat"?sl(s):rs(s).map(i=>i.id);if(n.length===0)return!1;const r=n.indexOf(s.files.selectedArtifactId);return r<0?!0:t>0?r<n.length-1:r>0}async finalizeArtifactUpload(t,{sessionId:s=null,suppressStatus:n=!1}={}){const r=s||t?.sessionId||await this.ensurePromptAttachmentSessionId();if(!r||!t?.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:t.filename}),await this.ensureFilePreview(r,t.filename,{force:!0}).catch(()=>null),n||this.dispatch({type:"ui/status",text:`Uploaded ${t.filename}`}),{sessionId:r,filename:t.filename}}async applyUploadedPromptAttachment(t,{sessionId:s=null,suppressStatus:n=!1}={}){const r=s||t?.sessionId||await this.ensurePromptAttachmentSessionId();if(!r||!t?.filename)throw new Error("Upload did not return a session id and filename");const i=Ol(t.filename),o=this.getState().ui.prompt,l=this.getState().ui.promptCursor,c=this.getPromptAttachments(),d=c.findIndex(p=>p?.sessionId===r&&p?.filename===t.filename);if(this.getState().sessions.activeSessionId!==r&&await this.loadSession(r),d===-1||!o.includes(c[d]?.token||i)){const p=Rt(o,l,`${i} `);this.setPrompt(p.prompt,p.cursor)}const u=d>=0?c.map((p,m)=>m===d?{...p,sessionId:r,filename:t.filename,resolvedPath:t.resolvedPath||t.localPath||t.filename,sizeBytes:t.sizeBytes,token:i}:p):[...c,{id:`${r}/${t.filename}`,sessionId:r,filename:t.filename,resolvedPath:t.resolvedPath||t.localPath||t.filename,sizeBytes:t.sizeBytes,token:i}];return this.setPromptAttachments(u),await this.ensureFilesForSession(r,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:r,filename:t.filename}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(r,t.filename,{force:!0}).catch(()=>null),this.setFocus(F.PROMPT),n||this.dispatch({type:"ui/status",text:d>=0?`Re-attached ${t.filename}`:`Attached ${t.filename}`}),{sessionId:r,existingAttachmentIndex:d,token:i}}async uploadArtifactFiles(t=[],{sessionId:s=null}={}){const n=Array.isArray(t)?t.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(t=[]){return this.uploadArtifactFiles(t)}async confirmArtifactUploadModal(){const t=this.getState().ui.modal;if(!t||t.type!=="artifactUpload")return;const s=String(t.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=t.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 t=this.getState(),s=t.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=t.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=Bb(n),i=Ha(n),o=Db(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:n.isGroup?"Rename folder":`Rename (${nt(s)})`,sessionId:s,previousFocus:t.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 t=this.getState(),s=Array.isArray(t.sessions.selectedIds)?t.sessions.selectedIds:[];if(t.sessions.selectMode&&s.length>=1){const i=this.getBulkSelectedSessionActions(t).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:t.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=t.sessions.activeSessionId;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}const r=t.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:t.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 (${nt(n)})`,sessionId:n,previousFocus:t.ui.focusRegion,sessionTitle:String(r.title||"").trim(),state:String(r.state||"").trim(),canRegenerate:!1}})}async pickTerminateAction(t){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),t==="complete"?await this.completeActiveSession():t==="cancel"?await this.cancelActiveSession():t==="delete"?await this.deleteActiveSession():t==="regenerate"&&await this.regenerateActiveSession()}getBulkSelectedSessionActions(t=this.getState()){const s=Array.isArray(t.sessions.selectedIds)?t.sessions.selectedIds:[],r=[...new Set(s.map(o=>String(o||"").trim()).filter(Boolean))].map(o=>t.sessions.byId[o]).filter(Boolean),i=r.filter(o=>!o.isSystem&&!o.isGroup);return{selected:r,eligible:i,skippedCount:r.length-i.length}}updateRenameSessionModal(t){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return null;const n=typeof t=="function"?t(s):t;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setRenameSessionValue(t,s=String(t||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="renameSession")return;const r=bs(t,n.maxLength),i=Fe(r,s);this.updateRenameSessionModal({value:r,cursorIndex:i})}insertRenameSessionText(t){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=Rt(s.value||"",s.cursorIndex||0,bs(t,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const t=this.getState().ui.modal;if(!t||t.type!=="renameSession")return;const s=Zt(t.value||"",t.cursorIndex||0);this.setRenameSessionValue(s.prompt,s.cursor)}moveRenameSessionCursor(t){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",Fe(s.value||"",(s.cursorIndex||0)+t))}moveRenameSessionCursorToBoundary(t){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",t==="start"?0:String(s.value||"").length)}async confirmRenameSessionModal(){const t=this.getState().ui.modal;if(!t||t.type!=="renameSession")return;const s=t.sessionId;if(!s)return;const n=String(t.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||Fn(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=t.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=t.previousFocus;this.dispatch({type:"ui/modal",modal:null}),o&&this.setFocus(o),this.dispatch({type:"ui/status",text:`Renaming ${nt(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${nt(s)}`})}catch(l){this.dispatch({type:"ui/status",text:`Rename failed: ${l?.message||String(l)}`})}}async cycleSessionVisibility(){const t=this.getState(),s=t.sessions.activeSessionId,n=s?t.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=hs(["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 t=this.getState(),s=t.sessions.activeSessionId,n=s?t.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 (${nt(s)})`,sessionId:s,previousFocus:t.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(t){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return null;const n=typeof t=="function"?t(s):t;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setShareSessionValue(t,s=String(t||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="shareSession")return;const r=bs(t,120),i=Fe(r,s);this.updateShareSessionModal({value:r,cursorIndex:i})}insertShareSessionText(t){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=Rt(s.value||"",s.cursorIndex||0,bs(t,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const t=this.getState().ui.modal;if(!t||t.type!=="shareSession")return;const s=Zt(t.value||"",t.cursorIndex||0);this.setShareSessionValue(s.prompt,s.cursor)}moveShareSessionCursor(t){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",Fe(s.value||"",(s.cursorIndex||0)+t))}moveShareSessionCursorToBoundary(t){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",t==="start"?0:String(s.value||"").length)}async confirmShareSessionModal(){const t=this.getState().ui.modal;if(!t||t.type!=="shareSession")return;const s=t.sessionId;if(!s)return;const n=String(t.value||"").trim(),r=t.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=(t.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 t=this.getState().ui.modal;t&&(this.dispatch({type:"ui/modal",modal:null}),t.type==="themePicker"&&t.currentThemeId&&this.dispatch({type:"ui/theme",themeId:t.currentThemeId}),t.previousFocus&&this.setFocus(t.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?.[si];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(t){const s=String(t||"").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[si]||{}};i[s]=(Number(i[s])||0)+1,r[si]=i,this.dispatch({type:"ui/agentPickerUsage",usage:i}),await this.transport.setCurrentUserProfileSettings({settings:r})}catch{}}_refreshAgentPicker(t){const s=this.getState().ui.modal;if(!s||s.type!=="sessionAgentPicker")return;const n={...s,...t},r=Ll(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(t){this._refreshAgentPicker({query:String(t??"")})}setAgentPickerSort(t){$l.includes(t)&&(this._agentPickerSort=t,this._refreshAgentPicker({sort:t}))}moveAgentPickerSection(){return!1}moveModalSelection(t){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+t)});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=hs(l,c,t),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+t,s.items.length-1));this.dispatch({type:"ui/modalSelection",index:r})}moveModalPane(t){const s=this.getState().ui.modal;if(s?.type==="sessionAgentPicker"){this.moveAgentPickerSection(t);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)+t+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 t=this.getState().ui.modal;if(t){if(t.type==="help"){this.closeModal();return}if(t.type==="confirm"){const s=t.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s),t.action==="cancelSession"?await this.cancelActiveSession({confirmed:!0}):t.action==="completeSession"?await this.completeActiveSession("Completed by user",{confirmed:!0}):t.action==="deleteSession"?await this.deleteActiveSession({confirmed:!0}):t.action==="regenerateSession"?await this.regenerateActiveSession({confirmed:!0,...t.extras||{}}):t.action==="deleteArtifact"?await this.deleteSelectedArtifact({confirmed:!0}):t.action==="deleteMarkedArtifacts"?await this.deleteMarkedArtifacts({confirmed:!0}):t.action==="deleteAdminProvider"&&await this.deleteSelectedAdminProvider();return}if(t.type==="artifactUpload"){await this.confirmArtifactUploadModal();return}if(t.type==="renameSession"){await this.confirmRenameSessionModal();return}if(t.type==="shareSession"){await this.confirmShareSessionModal();return}if(t.type==="sessionGroupPicker"){await this.confirmSessionGroupPickerModal();return}if(t.type==="sessionGroupName"){await this.confirmSessionGroupNameModal();return}if(t.type==="sessionOwnerFilter"){this.toggleSessionOwnerFilter();return}if(t.type==="filesFilter"){const s=t.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s);return}if(t.type==="themePicker"){const s=t.items?.[t.selectedIndex||0],n=Pt(s?.id);if(!n){this.dispatch({type:"ui/status",text:"Unable to apply that theme"});return}const r=t.previousFocus;this.dispatch({type:"ui/modal",modal:null}),r&&this.setFocus(r),this.dispatch({type:"ui/status",text:`Applied theme: ${n.label}`});return}if(t.type==="modelPicker"){const s=t.items?.[t.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=t.previousFocus;if(!s){if(t.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=Tl(s);if(t.sessionOptions?.mode==="switchModel"){await this.openReasoningEffortPicker(s,{...t.sessionOptions||{},model:s.id,reasoningEffort:r??null},n);return}await this.openReasoningEffortPicker(s,{...t.sessionOptions||{},model:s.id,...r?{reasoningEffort:r}:{}},n);return}if(t.type==="reasoningEffortPicker"){const s=t.items?.[t.selectedIndex||0],n=t.previousFocus,r=t.sessionOptions||{};await this.openContextTierPicker(t.modelItem,{...r,...s?.id?{reasoningEffort:s.id}:{}},n);return}if(t.type==="contextTierPicker"){const s=t.items?.[t.selectedIndex||0],n=t.previousFocus,r=t.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:t.modelItem?.id||r.model});return}await this.openSessionAgentPicker(i,n);return}if(t.type==="sessionAgentPicker"){const s=t.items?.[t.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=t.previousFocus,r=t.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(t.type==="logFilter"){this.closeModal();return}if(t.type==="historyFormat"){this.closeModal();return}t.type==="artifactPicker"&&await this.downloadArtifactModalSelection()}}openLogFilter(){const t=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"logFilter",title:"Log Filters",previousFocus:t,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 t=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"historyFormat",title:"Execution History Format",previousFocus:t,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 t=this.getState().logs;if(!t.available){this.dispatch({type:"ui/status",text:t.availabilityReason||"Log tailing is not available in this environment"});return}if(t.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 t=this.getState(),s=t.ui.prompt,n=this.getPromptAttachments(),r=n[0]?.sessionId||null,i=Xb(s,n);let o=t.sessions.activeSessionId;r&&(o=r,t.sessions.activeSessionId!==r&&await this.loadSession(r));let l=o&&t.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}this.dispatch({type:"sessions/used",sessionId:o});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(t,s=String(t||"").length){const n=String(t||""),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(t){const s=this.getState().ui.prompt||"";this.setPrompt(s,t)}insertPromptText(t){const s=this.getState().ui,n=Rt(s.prompt,s.promptCursor,t);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(t){this.insertPromptText(t)}deletePromptChar(){const t=this.getState().ui,s=Zt(t.prompt,t.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const t=this.getState().ui,s=tS(t.prompt,t.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(t){const s=this.getState().ui;this.setPrompt(s.prompt,Fe(s.prompt,s.promptCursor+t))}movePromptCursorWord(t){const s=this.getState().ui;this.setPrompt(s.prompt,Iu(s.prompt,s.promptCursor,t))}movePromptCursorVertical(t){const s=this.getState().ui,n=sS(s.prompt,s.promptCursor,t);if(n!==s.promptCursor){this.setPrompt(s.prompt,n);return}t<0&&this.selectPreviousPendingPrompt()||t>0&&this.selectNextPendingPrompt()||this.setPrompt(s.prompt,n)}getCurrentLayout(t={}){const s=this.getState().ui.layout||{},n=this.getState().ui,r=t.prompt??n.prompt;return en({width:t.width??s.viewportWidth??120,height:t.height??s.viewportHeight??40},t.paneAdjust??s.paneAdjust??0,t.promptRows??n.promptRows??Cs(r),t.sessionPaneAdjust??s.sessionPaneAdjust??0,t.activityPaneAdjust??s.activityPaneAdjust??0,t.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(t=this.getCurrentLayout()){const s=t.fullscreenPane===F.SESSIONS?t.bodyHeight:t.sessionPaneHeight;return Math.max(3,s-2)}setViewport(t={}){const s=Math.max(40,Number(t.width)||120),n=Math.max(18,Number(t.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=bt(o,i);l!==o&&this.setFocus(l)}setFocus(t){this.dispatch({type:"ui/focus",focusRegion:bt(t,this.getCurrentLayout()),requestedFocusRegion:t})}focusNext(){const t=this.getCurrentLayout(),s=bt(this.getState().ui.focusRegion,t),n=Ii(t);this.setFocus(hs(n,s,1))}focusPrev(){const t=this.getCurrentLayout(),s=bt(this.getState().ui.focusRegion,t),n=Ii(t);this.setFocus(hs(n,s,-1))}focusLeft(){const t=this.getCurrentLayout(),s=bt(this.getState().ui.focusRegion,t);this.setFocus(Wm(s,t))}focusRight(){const t=this.getCurrentLayout(),s=bt(this.getState().ui.focusRegion,t);this.setFocus(qm(s,t))}adjustPaneSplit(t){const s=this.getState().ui.layout||{},n=s.viewportWidth??120,r=Math.max(-n,Math.min(n,(s.paneAdjust||0)+t));this.dispatch({type:"ui/paneAdjust",paneAdjust:r});const i=this.getCurrentLayout({paneAdjust:r}),o=this.getState().ui.focusRegion,l=bt(o,i);l!==o&&this.setFocus(l)}adjustSessionPaneSplit(t){const s=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,i=Math.max(-r,Math.min(r,(s.sessionPaneAdjust||0)+t));this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:i});const o=this.getCurrentLayout({sessionPaneAdjust:i}),l=this.getState().ui.focusRegion,c=bt(l,o);c!==l&&this.setFocus(c)}adjustActivityPaneSplit(t){const s=this.getState().ui.layout||{},r=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,i=Math.max(-r,Math.min(r,(s.activityPaneAdjust||0)+t));this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:i});const o=this.getCurrentLayout({activityPaneAdjust:i}),l=this.getState().ui.focusRegion,c=bt(l,o);c!==l&&this.setFocus(c)}resizeFocusedPane(t){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===F.SESSIONS||s===F.CHAT){const l=hd(r),c=Os+1,d=Math.min(gd(i,r),r-gr-1),u=s===F.CHAT?-t:t,p=o(n.sessionPaneAdjust,u,c-l,d-l);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:p})}else if(s===F.INSPECTOR||s===F.ACTIVITY){const l=Math.max(Ns,Math.floor(r*fd)),c=Ns+1,d=r-Yn-1,u=s===F.INSPECTOR?-t:t,p=o(n.activityPaneAdjust,u,c-l,d-l);this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:p})}}getActiveSequenceCompletedTurns(){const t=this.getState(),s=t.sessions.activeSessionId;if(!s)return[];const n=t.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(t){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+t));this.dispatch({type:"ui/sequenceSelectedTurn",turn:s[r]})}toggleSequenceTurnExpanded(){const t=this.getActiveSequenceCompletedTurns();if(t.length===0)return;let s=Number(this.getState().ui.sequenceSelectedTurn);t.includes(s)||(s=t[t.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 t=this.getState().ui.inspectorTab,s=hs(wt,t,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const t=hs(wt,this.getState().ui.inspectorTab,-1);this.dispatch({type:"ui/inspectorTab",inspectorTab:t}),this.ensureInspectorData(t).catch(()=>{})}cycleInspectorTab(){this.nextInspectorTab()}toggleStatsView(){const t=["session","fleet","users"],s=this.getState().ui.statsViewMode,n=t.includes(s)?t.indexOf(s):0,r=t[(n+1)%t.length];this.setStatsViewMode(r)}setStatsViewMode(t){this.dispatch({type:"ui/statsViewMode",statsViewMode:t}),this.getState().ui.inspectorTab==="stats"&&this.ensureInspectorData("stats").catch(()=>{})}async selectInspectorTab(t){wt.includes(t)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:t}),await this.ensureInspectorData(t).catch(()=>{}))}async moveSession(t){const s=this.getState(),n=us(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+t)),l=n[o].sessionId;this.navigateToSession(l)}navigateToSession(t){t&&(this.getState().sessions.activeSessionId!==t&&(this.dispatch({type:"sessions/selected",sessionId:t}),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(t).catch(()=>{})},pS))}getSessionPageSize(){const t=this.getCurrentLayout(),s=t.fullscreenPane===F.SESSIONS?t.bodyHeight:t.sessionPaneHeight;return Math.max(1,s-3)}async moveSessionPage(t){const s=this.getSessionPageSize();await this.moveSession(s*t)}inspectorUsesBottomScroll(){return nS.has(this.getState().ui.inspectorTab)}paneUsesStickyBottomFollow(t,s=this.getState()){return t==="chat"||t==="activity"?!0:t==="inspector"?s.ui.inspectorTab==="logs":!1}isPaneFollowingBottom(t,s=this.getState()){return this.paneUsesStickyBottomFollow(t,s)?s.ui.followBottom?.[t]!==!1:!1}getPaneVisualScrollOffset(t,s=this.getState()){const n=this.getPaneMaxScrollOffset(t,s),r=Math.max(0,Math.min(Number(s.ui.scroll?.[t])||0,n));return this.isPaneFollowingBottom(t,s)?Math.max(0,n-r):r}applyPaneVisualScrollOffset(t,s,n={},r=this.getState()){const i=this.getPaneMaxScrollOffset(t,r),o=n.fromViewport?Math.max(0,Number(s)||0):Math.max(0,Math.min(Number(s)||0,i));if(this.paneUsesStickyBottomFollow(t,r)){const l=n.followBottom!==void 0?!!n.followBottom:n.atBottom!==void 0?!!n.atBottom:o>=i;return this.dispatch({type:"ui/followBottom",pane:t,followBottom:l}),this.dispatch({type:"ui/scroll",pane:t,offset:l?0:o}),o}return this.dispatch({type:"ui/scroll",pane:t,offset:o}),o}updatePaneScrollFromViewport(t,s,n={}){const r=this.getState();if(this.paneUsesStickyBottomFollow(t,r)){this.applyPaneVisualScrollOffset(t,s,{...n,fromViewport:!0},r);return}this.scrollPaneTo(t,s)}expandActiveSession(){const t=this.getState().sessions.activeSessionId;t&&this.dispatch({type:"sessions/expand",sessionId:t})}collapseActiveSession(){const t=this.getState().sessions.activeSessionId;t&&this.dispatch({type:"sessions/collapse",sessionId:t})}scrollPane(t,s){const n=this.getState(),r=this.getPaneMaxScrollOffset(t,n);if(this.paneUsesStickyBottomFollow(t,n)){const l=this.getPaneVisualScrollOffset(t,n),c=Math.max(0,Math.min(l-s,r));this.applyPaneVisualScrollOffset(t,c,{followBottom:c>=r},n),t==="chat"&&s>0?l<=0?this.handleChatTopHistoryScrollIntent(c).catch(()=>{}):c<=0&&this.armChatTopHistoryLoad():t==="chat"&&s<0&&this.disarmChatTopHistoryLoad();return}const i=Math.max(0,Math.min(Number(n.ui.scroll?.[t])||0,r)),o=Math.max(0,Math.min(i+s,r));this.dispatch({type:"ui/scroll",pane:t,offset:o}),t==="chat"&&s>0?i>=r?this.handleChatTopHistoryScrollIntent(o).catch(()=>{}):o>=r&&this.armChatTopHistoryLoad():t==="chat"&&s<0&&this.disarmChatTopHistoryLoad()}scrollPaneTo(t,s){const n=this.getState(),r=this.getPaneMaxScrollOffset(t,n),i=Math.max(0,Math.min(Number(s)||0,r));if(this.paneUsesStickyBottomFollow(t,n)){this.applyPaneVisualScrollOffset(t,i,{followBottom:i>=r},n),t==="chat"&&(r>0&&i<=0?this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad());return}this.dispatch({type:"ui/scroll",pane:t,offset:i}),t==="chat"&&(r>0&&i>=r?this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad())}armChatTopHistoryLoad(){const t=this.getState().sessions.activeSessionId;t&&(this.chatTopHistoryLoadArmed=!0,this.chatTopHistoryLoadSessionId=t)}disarmChatTopHistoryLoad(){this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}async handleChatTopHistoryScrollIntent(t,s={}){const r=this.getState().sessions.activeSessionId;if(r){if(!s.force&&(!this.chatTopHistoryLoadArmed||this.chatTopHistoryLoadSessionId!==r)){this.armChatTopHistoryLoad();return}await this.maybeAutoExpandActiveHistory(t,{pages:vb,preserveDomAnchor:s.preserveDomAnchor===!0,onLoadStarted:s.onLoadStarted,force:!0})}}artifactPreviewOwnsActivitySlot(t=this.getState()){return t.ui.inspectorTab==="files"&&!!t.files?.selectedArtifactId}focusIsArtifactList(t=this.getState()){return t.ui.focusRegion===F.INSPECTOR&&t.ui.inspectorTab==="files"}getScrollablePaneForFocus(){const t=this.getState(),s=t.ui.focusRegion;return s===F.CHAT?"chat":s===F.ACTIVITY?this.artifactPreviewOwnsActivitySlot(t)?"filePreview":"activity":s===F.INSPECTOR?this.getState().ui.inspectorTab==="files"?"filePreview":"inspector":null}scrollCurrentPane(t){const s=this.getScrollablePaneForFocus();if(!s)return;if(this.paneUsesStickyBottomFollow(s)){this.scrollPane(s,t);return}const n=s==="inspector"&&this.inspectorUsesBottomScroll(),r=s==="inspector"||s==="filePreview";this.scrollPane(s,r&&!n?-t:t)}scrollCurrentPaneToTop(){const t=this.getScrollablePaneForFocus();if(!t)return;if(this.paneUsesStickyBottomFollow(t)){this.scrollPaneTo(t,0);return}const s=t==="inspector"&&this.inspectorUsesBottomScroll();if(t==="chat"||t==="activity"||s){this.scrollPaneTo(t,Number.MAX_SAFE_INTEGER);return}this.scrollPaneTo(t,0)}scrollCurrentPaneToBottom(){const t=this.getScrollablePaneForFocus();if(!t)return;if(this.paneUsesStickyBottomFollow(t)){this.applyPaneVisualScrollOffset(t,Number.MAX_SAFE_INTEGER,{followBottom:!0});return}const s=t==="inspector"&&this.inspectorUsesBottomScroll();if(t==="chat"||t==="activity"||s){this.scrollPaneTo(t,0);return}this.scrollPaneTo(t,Number.MAX_SAFE_INTEGER)}async expandActiveHistory(){const t=this.getState().sessions.activeSessionId;t&&await this.expandSessionHistory(t)}getActiveChatRenderMetrics(t=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=xa(t,n),o=[...Ca(t,n),...br(t)],l=Math.min(Math.max(0,Math.floor(r*.34)),Ss(o,n)),c=Ss(i,n);return{contentWidth:n,contentHeight:Math.max(1,r-l),totalLines:c}}getActivityRenderMetrics(t=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=t.sessions.activeSessionId,o={sessions:{activeSessionId:i,byId:i?{[i]:t.sessions.byId[i]||null}:{}},history:{bySessionId:i?new Map([[i,t.history.bySessionId.get(i)||null]]):new Map}},l=Pa(o);return{contentWidth:n,contentHeight:r,totalLines:Ss(l.lines,n)}}getInspectorRenderMetrics(t=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=t.sessions.activeSessionId,i=r&&t.orchestration.bySessionId?.[r]||null,o={branding:t.branding,sessions:{activeSessionId:r,byId:t.sessions.byId,flat:t.sessions.flat},history:{bySessionId:t.history.bySessionId},orchestration:{bySessionId:r&&i?{[r]:i}:{}},logs:t.logs,sessionStats:t.sessionStats,fleetStats:t.fleetStats,ui:{inspectorTab:t.ui.inspectorTab,statsViewMode:t.ui.statsViewMode},executionHistory:t.executionHistory},l=Vt(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:Ss(u,n),totalLines:Ss(p,n)}}getFilePreviewRenderMetrics(t=this.getState()){const s=this.getCurrentLayout();if((s.rightHidden||s.inspectorHidden)&&!t.files?.fullscreen)return{contentWidth:20,contentHeight:1,totalLines:0};const n=t.ui.inspectorTab==="files"&&!!t.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=t.sessions.activeSessionId,d=c&&t.sessions.byId[c]||null,u={sessions:{activeSessionId:c,byId:c&&d?{[c]:d}:{},flat:t.sessions.flat},files:{bySessionId:t.files.bySessionId,fullscreen:!!t.files.fullscreen,selectedArtifactId:t.files.selectedArtifactId,filter:t.files.filter},ui:{scroll:{filePreview:t.ui.scroll.filePreview}}},p=Ma(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:Ss(p.previewLines,l)}}getPaneMaxScrollOffset(t,s=this.getState()){if(!t)return 0;if(t==="chat"){const n=this.getActiveChatRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(t==="activity"){const n=this.getActivityRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(t==="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(t==="filePreview"){const n=this.getFilePreviewRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}return 0}async maybeAutoExpandActiveHistory(t,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)>=Wi){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:c,totalLines:d}=this.getActiveChatRenderMetrics(n),u=Math.max(0,d-c);if(t<u)return}const l=this.expandSessionHistory(r,{requestedScrollOffset:t,autoTriggered:!0,pages:s.pages,preserveDomAnchor:s.preserveDomAnchor===!0,eventTypes:hm});s.onLoadStarted?.(),await l}async expandSessionHistory(t,s={}){if(!t)return;if(this.sessionHistoryExpansionLoads.has(t))return this.sessionHistoryExpansionLoads.get(t);const n=this.getState(),r=n.history.bySessionId.get(t),i=Math.max(Ne,Number(r?.loadedEventLimit??Ne)||Ne),o=Ne,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=t===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||qs([],{requestedLimit:i});for(let y=0;y<f;y+=1){const v=Array.isArray(m?.events)&&m.events.length>0?Number(m.events[0]?.seq||0):0;if(!m?.hasOlderEvents||v<=1){m={...m,hasOlderEvents:!1};break}if(Number(m.loadedEventCount||0)>=Wi)break;const S=await this.transport.getSessionEventsBefore(t,v,o,h);if(!Array.isArray(S)||S.length===0){m={...m,hasOlderEvents:!1};break}const w=qs(S,{requestedLimit:o}),E=[...w.events||[],...m?.events||[]],I=new Map((m?.chat||[]).map(C=>[C.id,C])),T=qs(E,{requestedLimit:E.length});if(m={...m,chat:xs([...T.chat.map(C=>({...I.get(C.id),...C})),...(m?.chat||[]).filter(C=>C.liveTurn||C.optimistic)]),activity:[...w.activity||[],...m?.activity||[]],events:E,lastSeq:m?.lastSeq||m?.events?.[m?.events?.length-1]?.seq||S[S.length-1]?.seq||0,loadedEventLimit:E.length,loadedEventCount:E.length,hasOlderEvents:S.length>=o&&Number(S[0]?.seq||0)>1},!m.hasOlderEvents)break}}else{const y=Dm(i);if(y<=i){this.dispatch({type:"ui/status",text:r?.hasOlderEvents?`Already showing a large recent history window (${i} events)`:"Already showing the oldest loaded history"});return}const v=await this.transport.getSessionEvents(t,void 0,y);m={...qs(v,{requestedLimit:y}),lastSeq:v[v.length-1]?.seq||0}}m=xl(m,this.getState().history.bySessionId.get(t),t),this.dispatch({type:"history/set",sessionId:t,history:m});for(const y of m?.events||[])this.reconcileOutboxAgainstEvent(t,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(),v=this.getActiveChatRenderMetrics(y).totalLines,S=Math.max(0,v-u);S>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:d+S})}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(t)});return this.sessionHistoryExpansionLoads.set(t,p),p}async cancelActiveSession({confirmed:t=!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(!t){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(!t){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(!t){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(t){const s=this.getState().ui.modal;!s||s.type!=="confirm"||this.dispatch({type:"ui/modal",modal:{...s,extras:{...s.extras||{},...t||{}}}})}async regenerateActiveSession({confirmed:t=!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(!t){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 t=await this.transport.listModels({groupByProvider:!0});return(Array.isArray(t)?t:Array.isArray(t?.providers)?t.providers:Array.isArray(t?.models)?t.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(t){return this.dispatch({type:"ui/status",text:`Could not load distiller models: ${t?.message||String(t)}`}),[]}}async stopActiveSessionTurn(){const t=this.getState(),s=t.sessions.activeSessionId;if(!s)return;const n=t.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 t=this.getState(),s=t.sessions.activeSessionId;if(!s)return;const n=t.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(t.sessions.pinnedIds)&&t.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 t=this.getState(),s=!t.sessions.selectMode;if(this.dispatch({type:"sessions/selectMode",enabled:s}),s){const n=t.sessions.activeSessionId;n&&t.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 t=this.getState(),s=t.sessions.activeSessionId;s&&(t.sessions.selectMode||this.dispatch({type:"sessions/selectMode",enabled:!0}),this.dispatch({type:"sessions/selectToggle",sessionId:s}))}setSessionSelection(t){const s=Array.isArray(t)?t:[];this.dispatch({type:"sessions/selectSet",sessionIds:s})}clearSessionSelection(){this.dispatch({type:"sessions/selectClear"})}async completeActiveSession(t="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,t),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:t}),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,t),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:t=!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(!t){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||Fn(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(!t){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(!t){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(!t){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(t){switch(t){case L.REFRESH:await this.refreshSessions();return;case L.NEW_SESSION:await this.openNewSessionFlow();return;case L.OPEN_MODEL_PICKER:await this.openModelPicker();return;case L.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case L.OPEN_THEME_PICKER:this.openThemePicker();return;case L.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case L.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case L.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case L.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case L.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case L.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case L.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case L.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case L.CLOSE_MODAL:this.closeModal();return;case L.MODAL_PREV:this.moveModalSelection(-1);return;case L.MODAL_NEXT:this.moveModalSelection(1);return;case L.MODAL_PANE_PREV:this.moveModalPane(-1);return;case L.MODAL_PANE_NEXT:this.moveModalPane(1);return;case L.MODAL_CONFIRM:await this.confirmModal();return;case L.SEND_PROMPT:await this.sendPrompt();return;case L.FOCUS_NEXT:this.focusNext();return;case L.FOCUS_PREV:this.focusPrev();return;case L.FOCUS_LEFT:this.focusLeft();return;case L.FOCUS_RIGHT:this.focusRight();return;case L.FOCUS_PROMPT:this.setFocus(F.PROMPT);return;case L.FOCUS_SESSIONS:this.setFocus(F.SESSIONS);return;case L.MOVE_SESSION_UP:await this.moveSession(-1);return;case L.MOVE_SESSION_DOWN:await this.moveSession(1);return;case L.EXPAND_SESSION:this.expandActiveSession();return;case L.COLLAPSE_SESSION:this.collapseActiveSession();return;case L.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case L.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case L.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case L.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case L.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case L.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case L.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case L.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case L.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case L.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case L.OPEN_HELP:this.openHelpModal();return;case L.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case L.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case L.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case L.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case L.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case L.OPEN_LOG_FILTER:this.openLogFilter();return;case L.OPEN_FILES_FILTER:this.openFilesFilter();return;case L.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case L.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case L.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case L.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case L.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case L.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case L.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case L.SCROLL_UP:this.scrollCurrentPane(1);return;case L.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case L.PAGE_UP:if(this.getState().ui.focusRegion===F.SESSIONS){await this.moveSessionPage(-1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(-10);return}this.scrollCurrentPane(10);return;case L.PAGE_DOWN:if(this.getState().ui.focusRegion===F.SESSIONS){await this.moveSessionPage(1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(10);return}this.scrollCurrentPane(-10);return;case L.EXPAND_HISTORY:await this.expandActiveHistory();return;case L.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case L.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case L.CANCEL_SESSION:await this.cancelActiveSession();return;case L.STOP_TURN:await this.stopActiveSessionTurn();return;case L.DONE_SESSION:await this.completeActiveSession();return;case L.DELETE_SESSION:await this.deleteActiveSession();return;case L.REGENERATE_SESSION:await this.regenerateActiveSession();return;case L.PIN_SESSION:this.togglePinActiveSession();return;case L.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case L.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case L.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case L.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case L.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case L.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case L.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case L.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case L.OPEN_WORKSPACE:this.openWorkspace();return;case L.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case L.ADMIN_SHOW_GHCP:this.setAdminSection("providers");return;case L.ADMIN_SHOW_PACKAGES:this.setAdminSection("packages");return;case L.ADMIN_SHOW_WORKERS:this.setAdminSection("workers");return;case L.ADMIN_WORKERS_REFRESH:await this.refreshAdminWorkers();return;case L.ADMIN_PACKAGES_REFRESH:await this.refreshAdminAgentPackages();return;case L.ADMIN_PACKAGES_NEXT:await this.stepAdminPackageSelection(1);return;case L.ADMIN_PACKAGES_PREV:await this.stepAdminPackageSelection(-1);return;case L.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case L.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case L.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case L.ADMIN_CLEAR_GHCP_KEY:await this.clearAdminGhcpKey();return;default:return}}async exportExecutionHistory(){const t=this.getState().sessions.activeSessionId;if(!t){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(t);s?.filename&&(await this.ensureFilesForSession(t,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:t,filename:s.filename}),this.dispatch({type:"files/selectGlobal",artifactId:`${t}/${s.filename}`}),await this.ensureFilePreview(t,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 qi(e=""){return String(e||"").replace(/\s+/g," ").trim()}const yS=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],bS=24,SS=32,vS=6,Gl=30,wS=56,ii=.4,ES=1.4,kS=2;function Au(e=[]){const t=Math.max(0,...e.map(h=>h.length));if(t<=0)return null;const s=e[0]||[],n=Math.max(1,e.length-1),r=Array.from({length:t},()=>({max:0,longestToken:0,spaceCells:0}));for(let h=0;h<e.length;h+=1){const g=e[h];for(let b=0;b<t;b+=1){const y=qi(g[b]||"");y.length>r[b].max&&(r[b].max=y.length),h>0&&/\s/.test(y)&&(r[b].spaceCells+=1);for(const v of y.split(/\s+/))v.length>r[b].longestToken&&(r[b].longestToken=v.length)}}let i=-1,o=0;for(let h=0;h<t;h+=1){const g=r[h];if(g.max<bS||g.spaceCells/n<.4)continue;const y=qi(s[h]||"").toLowerCase(),v=yS.some(w=>y.includes(w))?60:0,S=g.max+v;S>o&&(o=S,i=h)}if(i<0)return null;const l=r.map((h,g)=>g===i?0:Math.max(vS,Math.min(h.max+2,SS),h.longestToken+2)),c=l.reduce((h,g)=>h+g,0),d=r[i],u=Math.max(Gl,Math.min(d.max*.45,wS,Math.max(Gl,c*ES))),p=l.map((h,g)=>g===i?u:h),m=p.reduce((h,g)=>h+g,0);if(m>0&&p[i]/m<ii){const h=m-p[i];p[i]=h*(ii/(1-ii))}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+kS)}ch`}:null}const wr=0;function pt(e,t){if(Object.is(e,t))return!0;if(!e||!t||typeof e!="object"||typeof t!="object")return!1;const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const r of s)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}function ai(){try{const e=globalThis?.process,t=e?.memoryUsage;if(typeof t?.rss=="function"){const s=Number(t.rss());return Number.isFinite(s)&&s>0?s:null}if(typeof t=="function"){const s=Number(t.call(e)?.rss);return Number.isFinite(s)&&s>0?s:null}}catch{}return null}function IS(e){if(!Number.isFinite(e)||e<=0)return null;const t=Math.round(e/(1024*1024));return[{text:"rss ",color:"gray"},{text:`${t}M`,color:"white",bold:!0}]}function xS(e){const t=e?.principal;if(!t)return null;const s=t.displayName||t.email||t.subject||null;return s?e?.authorization?.role==="admin"||Array.isArray(t.roles)&&t.roles.includes("admin")?`(*) ${s}`:s:null}function AS(e,t=null,s=null){const n=[],r=typeof s=="string"?s.trim():"";r&&n.push({text:r,color:"yellow",bold:!0}),Array.isArray(e)&&e.length>0&&(n.length>0&&n.push({text:" ",color:"gray"}),n.push(...e));const i=typeof t=="string"?t.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 NS(e=2e3){const[t,s]=a.useState(()=>ai());return a.useEffect(()=>{if(ai()==null)return;const n=()=>{const i=ai();i!=null&&s(o=>o===i?o:i)};n();const r=setInterval(n,e);return()=>clearInterval(r)},[e]),a.useMemo(()=>IS(t),[t])}function Gs(e,t){return e&&t?{[e]:t}:{}}function Wl(e){return typeof e=="string"?{text:e,color:"white"}:e}function gn(e,t,s,n,r,i){const o=(t.tabs||wt).map(p=>({text:p===t.activeTab?`[${p}] `:`${p} `,color:p===t.activeTab?"magenta":"gray",bold:p===t.activeTab})),l=(t.lines||[]).map(Wl),c=(t.stickyLines||[]).map(Wl),d=t.activeTab==="sequence"?[o,...c]:[],u=t.activeTab==="sequence"?l:[o,...l];return a.createElement(e.Panel,{title:t.title,color:"magenta",focused:s.focused,width:n,height:r,stickyLines:d,marginBottom:wr,lines:u,scrollOffset:s.inspectorScroll,scrollMode:t.activeTab==="sequence"||t.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:t.activeTab==="sequence"?"Sequence":"Inspector",frame:i})}function ql(e,t){const s=String(e||"");return t<=0?"":s.length<=t?s:t===1?s.slice(0,1):`${s.slice(0,t-1)}...`}a.memo(function({controller:t,maxRows:s,width:n,height:r,frame:i,versionLabel:o=null}){const l=yt(),c=NS(),d=ee(t,h=>({sessions:h.sessions,mode:h.connection?.mode||"local",brandingTitle:h.branding?.title||"PilotSwarm",focused:h.ui.focusRegion==="sessions",identityLabel:xS(h.auth)}),pt),u=a.useMemo(()=>AS(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(()=>Fi(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?Md(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:wr,lines:f,paneId:"sessions",paneLabel:"Sessions",frame:i})});a.memo(function({controller:t,width:s,height:n,frame:r}){const i=yt(),o=ee(t,S=>{const w=S.sessions.activeSessionId;return{activeSessionId:w,activeSession:w&&S.sessions.byId[w]||null,activeHistory:w&&S.history.bySessionId.get(w)||null,activeOutbox:w&&S.outbox?.bySessionId?.[w]||null,authPrincipal:S.auth?.principal||null,branding:S.branding,connectionError:S.connection.error,connectionMode:S.connection.mode,chatScroll:S.ui.scroll.chat,followBottom:S.ui.followBottom?.chat!==!1,focused:S.ui.focusRegion==="chat"}},pt),l=Math.max(20,s-4),c=a.useMemo(()=>{const S=new Map;return o.activeSessionId&&o.activeHistory&&S.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:Gs(o.activeSessionId,o.activeSession)},history:{bySessionId:S},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(()=>eu(c,{width:l}),[l,c]),u=_c(!!d?.animateTitleRight),p=a.useMemo(()=>$c(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"}]:xa(c,l),[o.branding.splash,o.connectionError,l,c,m]),h=String(o.activeSession?.status||"").toLowerCase()==="running",g=sa(h),b=a.useMemo(()=>m?[]:br(c,{spinnerFrame:g,maxWidth:l}),[c,m,g,l]),y=a.useMemo(()=>m?[]:Ca(c,l),[c,m,l]),v=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:v,scrollOffset:o.chatScroll,scrollMode:o.followBottom?"bottom":"top",paneId:"chat",paneLabel:"Chat",frame:r})});const CS=a.memo(function({controller:t,width:s,height:n,shellTitle:r,focused:i=!1,frame:o,showFullscreenTitle:l=!1,embedded:c=!1}){const d=yt(),u=ee(t,O=>({activeSessionId:O.sessions.activeSessionId,activeSession:O.sessions.activeSessionId&&O.sessions.byId[O.sessions.activeSessionId]||null,sessionsFlat:O.sessions.flat,filesBySessionId:O.files.bySessionId,filesFullscreen:!!O.files.fullscreen,selectedArtifactId:O.files.selectedArtifactId,filesFilter:O.files.filter,filePreviewScroll:O.ui.scroll.filePreview}),pt),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(()=>Ma(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)),v=Math.max(5,g-y-1);const S=8;if(v<S){const O=S-v;y=Math.max(5,y-O),v=Math.max(5,g-y-1)}const w=Math.max(1,y-2),E=Math.max(0,f.selectedIndex-Math.floor(w/2)),I=!c&&o?{x:o.x+2,y:o.y+2,width:p,height:y}:null,T=!c&&o?{x:o.x+2,y:o.y+2+y+1,width:p,height:v}:null,C=wt.map(O=>({text:O==="files"?`[${O}] `:`${O} `,color:O==="files"?"magenta":"gray",bold:O==="files"})),k=a.createElement(d.Column,{width:p},a.createElement(d.Lines,{lines:[C]}),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:I}),a.createElement(d.Panel,{title:f.previewTitle,color:"gray",focused:!1,width:p,height:v,lines:f.previewLines,scrollOffset:f.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:T}));return c?k:a.createElement(d.Panel,{title:h,color:"magenta",focused:i,width:s,height:n,marginBottom:wr,paneId:"inspector",paneLabel:"Inspector",frame:o},k)}),TS=a.memo(function({controller:t,width:s,height:n,frame:r,meta:i}){const o=yt(),l=Math.max(20,s-4),c=ee(t,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null}),pt),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Gs(c.activeSessionId,c.activeSession)},ui:{inspectorTab:"files"}}),[c.activeSession,c.activeSessionId]),u=a.useMemo(()=>Vt(d,{width:l}),[l,d]);return a.createElement(o.Panel,{title:u.title,color:"magenta",focused:i.focused,width:s,height:n,marginBottom:wr,paneId:"inspector",paneLabel:"Inspector",frame:r},a.createElement(CS,{controller:t,width:s,height:n,frame:r,focused:i.focused,embedded:!0}))}),PS=a.memo(function({controller:t,width:s,height:n,frame:r,meta:i}){const o=yt(),l=Math.max(20,s-4),c=ee(t,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}),pt),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Gs(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(()=>Vt(d,{width:l,sequenceExpansion:{expandedTurns:c.expandedTurns||[],selectedTurn:c.selectedTurn??null}}),[l,d,c.expandedTurns,c.selectedTurn]);return gn(o,u,i,s,n,r)}),MS=a.memo(function({controller:t,width:s,height:n,frame:r,meta:i}){const o=yt(),l=Math.max(20,s-4),c=ee(t,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,logs:p.logs}),pt),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Gs(c.activeSessionId,c.activeSession)},logs:c.logs,ui:{inspectorTab:"logs"}}),[c.activeSession,c.activeSessionId,c.logs]),u=a.useMemo(()=>Vt(d,{width:l}),[l,d]);return gn(o,u,i,s,n,r)}),_S=a.memo(function({controller:t,width:s,height:n,frame:r,meta:i}){const o=yt(),l=Math.max(20,s-4),c=ee(t,p=>({activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,executionHistory:p.executionHistory}),pt),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Gs(c.activeSessionId,c.activeSession)},executionHistory:c.executionHistory,ui:{inspectorTab:"history"}}),[c.activeSession,c.activeSessionId,c.executionHistory]),u=a.useMemo(()=>Vt(d,{width:l}),[l,d]);return gn(o,u,i,s,n,r)}),$S=a.memo(function({controller:t,width:s,height:n,frame:r,meta:i}){const o=yt(),l=Math.max(20,s-4),c=ee(t,p=>({activeSessionId:p.sessions.activeSessionId,sessionsById:p.sessions.byId,sessionsFlat:p.sessions.flat,histories:p.history.bySessionId}),pt),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(()=>Vt(d,{width:l}),[l,d]);return gn(o,u,i,s,n,r)}),RS=a.memo(function({controller:t,width:s,height:n,frame:r,meta:i}){const o=yt(),l=Math.max(20,s-4),c=ee(t,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}),pt),d=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:Gs(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(()=>Vt(d,{width:l}),[l,d]);return gn(o,u,i,s,n,r)});a.memo(function({controller:t,width:s,height:n,frame:r}){const i=ee(t,o=>({inspectorTab:o.ui.inspectorTab,inspectorScroll:o.ui.scroll.inspector,inspectorFollowBottom:o.ui.followBottom?.inspector!==!1,focused:o.ui.focusRegion==="inspector"}),pt);return i.inspectorTab==="files"?a.createElement(TS,{controller:t,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="sequence"?a.createElement(PS,{controller:t,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="logs"?a.createElement(MS,{controller:t,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="history"?a.createElement(_S,{controller:t,width:s,height:n,frame:r,meta:i}):i.inspectorTab==="stats"?a.createElement(RS,{controller:t,width:s,height:n,frame:r,meta:i}):a.createElement($S,{controller:t,width:s,height:n,frame:r,meta:i})});a.memo(function({controller:t,width:s,height:n,maxLines:r,frame:i}){const o=yt(),l=ee(t,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}},pt),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?tu(d):Pa(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:t,rows:s}){const n=yt(),r=ee(t,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")}},pt);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:t}){const s=yt(),n=ee(t,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}),pt),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(()=>Og(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:ql(i.left,d),right:ql(i.right,c)})});const LS="modulepreload",OS=function(e){return"/"+e},zl={},Nu=function(t,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=OS(d),d in zl)return;zl[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":LS,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 t().catch(i)})};function Cu({line:e}){const[t,s]=a.useState(!1);return a.createElement("details",{className:"ps-system-notice ps-chat-call","data-call-id":e.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"},e.category||"Tool"),a.createElement("span",{className:"ps-system-notice-summary-text"},e.text),e.status?a.createElement("span",{className:`ps-chat-call-status${e.status==="Failed"?" is-failed":""}`},e.status):null),t?a.createElement("div",{className:"ps-system-notice-body"},e.time?a.createElement("div",{className:"ps-chat-call-time"},e.time):null,a.createElement("pre",{className:"ps-chat-call-payload"},e.body)):null)}const X=a.createElement,Lt=e=>e?"On":"Off",oi=e=>typeof e=="string"&&/^[1-9]\d{0,18}$/.test(e)&&BigInt(e)<=9223372036854775807n,Kl=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function FS(e,t=[],s=Date.now()){const n=t.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=Kl(l)&&l.protocolVersion===1&&typeof l.initialized=="boolean"&&Array.isArray(l.supportedKeys)&&l.supportedKeys.every(f=>typeof f=="string")&&Kl(l.appliedRevisions);let p="unknown";d&&u&&oi(e.revision)&&(l.supportedKeys.includes(e.featureKey)?l.initialized?oi(l.appliedRevisions[e.featureKey])&&(p=BigInt(l.appliedRevisions[e.featureKey])>=BigInt(e.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&&oi(l.appliedRevisions[e.featureKey])?l.appliedRevisions[e.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 DS(e,t){return t||!e.eligible||e.unknown===e.eligible?"Settings delivery: status unavailable":`Settings delivery: ${e.updated} of ${e.eligible} reporting workers updated.${e.unknown?` Status unavailable for ${e.unknown}.`:""}${e.unsupported?` ${e.unsupported} do not support this feature.`:""}${e.refreshErrors?` ${e.refreshErrors} reported a refresh problem.`:""}`}function Vl(e,t){return`${Lt(e)} ${t?"by default. Users can choose On or Off.":"for everyone. Personal settings do not apply."}`}function li({legend:e,name:t,value:s,options:n,disabled:r,onChange:i}){return X("fieldset",{className:"ps-feature-choice-group",disabled:r},X("legend",null,e),X("div",{className:"ps-feature-choices"},n.map(o=>X("label",{className:`ps-feature-choice${s===o.value?" is-selected":""}`,key:o.value},X("input",{type:"radio",name:t,value:o.value,checked:s===o.value,onChange:()=>i(o.value)}),X("span",null,o.label)))))}function BS({flag:e,mode:t,busy:s,saving:n,controller:r,workers:i,workersError:o,isAdmin:l,userName:c}){const d=a.useId(),u=r.getFeatureDraft?.(e.featureKey),p=u!==void 0,m=p&&(u.needsReview||u.expectedRevision!==e.revision),f=m&&u.needsReview&&u.expectedRevision===e.revision,h=e.cluster?.enabled??e.defaultEnabled,g=e.cluster?.allowUserOverride??e.defaultAllowUserOverride,b=t!=="cluster"&&!g,y=e.user?String(e.user.enabled):"inherit",v=p?u.values===null?"inherit":String(u.values.enabled):y,S=p?u.values??{enabled:e.defaultEnabled,allowUserOverride:e.defaultAllowUserOverride}:{enabled:h,allowUserOverride:g},w=t==="mine"?"you":c,E=t==="mine"?"Your":`${c}’s`,I=t==="cluster"?`${Lt(h)} ${g?"by default":"for everyone"}`:`${Lt(e.effective)} for ${w}`,T=t==="cluster"?g?"Users can choose On or Off.":"Personal settings do not apply.":b?"Required by the cluster.":e.user?t==="mine"?"Using your choice.":"Using the saved personal choice.":"Following the cluster setting.",C=FS(e,i),k=e.featureKey==="copilot.native_tasks",O=t==="cluster"?h:e.effective,N=l&&k&&O&&!o&&C.eligible>0&&C.incapable===C.eligible,R=s||!e.supported;let H=null;return p&&(t==="cluster"?H=`${u.values===null?"Restore the default policy. ":""}${Vl(S.enabled,S.allowUserOverride)}${!g&&S.allowUserOverride?" Previously saved personal choices will apply again.":""}`:b?H=`${E} future preference will ${v==="inherit"?"follow the cluster setting":`be ${Lt(v==="true")}`}. ${Lt(h)} still applies while the cluster requires it.`:H=`${Lt(v==="inherit"?h:v==="true")} for ${w}. ${v==="inherit"?"Following the cluster setting.":"Using the personal choice."}`),X("section",{className:"ps-feature-flag","data-feature-key":e.featureKey,"aria-labelledby":`${d}-title`},X("div",{className:"ps-feature-flag-heading"},X("h3",{id:`${d}-title`},e.displayName),p?X("span",{className:"ps-feature-unsaved"},"Unsaved changes"):null),X("p",{className:"ps-feature-description"},k?"Lets Copilot delegate short tasks in the same session workspace. On permits use; Copilot decides when to use native tasks.":e.description),X("div",{className:"ps-feature-saved"},X("span",{className:"ps-feature-label"},"Saved setting"),X("strong",{className:`ps-feature-value${(t==="cluster"?h:e.effective)?" is-on":""}`},I),X("p",{className:"ps-feature-explanation"},T),t!=="cluster"?X("p",{className:"ps-feature-context"},`Cluster setting: ${Lt(h)}. Personal settings ${g?"allowed":"not allowed"}.`):null,b?X("p",{className:"ps-feature-retained"},`Saved future preference: ${y==="inherit"?"Use cluster setting":Lt(e.user.enabled)}. This will apply if personal settings are allowed again.`):null),e.supported?null:X("p",{role:"status"},"This server does not support changing this feature."),e.reason==="requires_native_tasks"?X("p",{className:"ps-feature-blocker",role:"status"},"Base Agent V2 is currently Off because it requires Native Copilot tasks. The Base V2 preference is saved and will apply when native tasks are enabled for the same scope."):null,N?X("p",{className:"ps-feature-blocker",role:"status"},`The saved setting is On, but none of the ${C.eligible} reporting workers is configured for native tasks. Native tasks cannot run on those workers.`):null,X("div",{className:"ps-feature-editor"},t==="cluster"?[X(li,{key:"enabled",legend:"Cluster setting",name:`${d}-cluster`,value:String(S.enabled),disabled:R,options:[{value:"false",label:"Off"},{value:"true",label:"On"}],onChange:x=>r.setFeatureDraft(e.featureKey,{...S,enabled:x==="true"})}),X(li,{key:"override",legend:"Personal settings",name:`${d}-override`,value:String(S.allowUserOverride),disabled:R,options:[{value:"true",label:"Allowed"},{value:"false",label:"Not allowed"}],onChange:x=>r.setFeatureDraft(e.featureKey,{...S,allowUserOverride:x==="true"})})]:X(li,{legend:b?"Preference for when personal settings are allowed":t==="mine"?"Your choice":`${c}’s choice`,name:`${d}-user`,value:v,disabled:R,options:[{value:"inherit",label:`Use cluster setting (currently ${Lt(h)})`},{value:"true",label:t==="mine"?"On for me":"On for this user"},{value:"false",label:t==="mine"?"Off for me":"Off for this user"}],onChange:x=>r.setFeatureDraft(e.featureKey,x==="inherit"?null:{enabled:x==="true"})})),p?X("div",{className:"ps-feature-preview",role:"status"},X("strong",null,"After saving: "),H):null,m?X("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,X("div",{className:"ps-feature-actions"},X("button",{type:"button",className:"ps-mini-button ps-feature-save",disabled:R||!p||m,onClick:()=>r.saveFeatureDraft(e.featureKey)},n&&p?"Saving…":b?"Save future preference":"Save changes"),X("button",{type:"button",className:"ps-mini-button",disabled:s||!p,onClick:()=>r.discardFeatureDraft(e.featureKey)},"Discard changes"),m?X("button",{type:"button",className:"ps-mini-button",disabled:s||f,onClick:()=>r.reviewFeatureDraft(e.featureKey)},"Review latest settings"):null),l?X("p",{className:"ps-feature-delivery",role:"status"},DS(C,o)):null,X("details",{className:"ps-feature-details"},X("summary",null,"Technical details"),X("p",null,X("code",null,e.featureKey),` · Saved revision ${e.revision}`),X("p",null,"Workers normally check for settings changes within 20 seconds. Settings delivery does not confirm that each session has refreshed its tools."),k?X("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&&k?X("p",null,o||!C.eligible||C.capabilityUnknown===C.eligible?"Native task support: status unavailable.":`Native task support: ${C.capable} of ${C.eligible} reporting workers configured; ${C.incapable} configured Off; ${C.capabilityUnknown} unknown.`):null,l&&(C.stale||C.draining||C.other)?X("p",null,`Excluded from current delivery counts: ${C.stale} stale or undated reports; ${C.draining} draining workers; ${C.other} other worker reports.`):null,l?X("ul",{className:"ps-feature-worker-list"},C.reports.map(x=>X("li",{key:x.workerNodeId},`${x.workerNodeId}: ${x.eligible?{updated:"settings received",pending:"waiting for latest settings",loading:"loading settings",unsupported:"feature unsupported",unknown:"status unavailable"}[x.delivery]:x.phase==="draining"?"draining; excluded":x.recent?"not reporting ready; excluded":"stale or undated report; status unavailable"}${x.eligible&&x.revision?`; revision ${x.revision}`:""}${x.eligible&&k?`; native task configuration ${x.capability==="sync"?"On":x.capability==="off"?"Off":"unknown"}`:""}${x.refreshError?"; settings refresh problem":""}`))):null,t==="cluster"?X("div",{className:"ps-feature-defaults"},X("p",null,`Default policy: ${Vl(e.defaultEnabled,e.defaultAllowUserOverride)}`),X("button",{type:"button",className:"ps-mini-button",disabled:R||!e.cluster,onClick:()=>r.setFeatureDraft(e.featureKey,null)},"Preview default policy"),X("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 HS({controller:e,features:t={},isAdmin:s,workers:n=[],workersError:r=null}){const i=t.mode||"mine",[o,l]=a.useState(t.userQuery||""),c=t.users?.find(p=>p.userId===t.userId),d=c?.displayName||c?.email||c?.subject||(t.userId?`user ${t.userId}`:"this user"),u=t.saving||t.loading;return X("section",{className:"ps-feature-flags-panel","aria-label":"Feature flags"},X("header",{className:"ps-feature-flag-heading"},X("h2",null,"Feature flags"),X("button",{type:"button",className:"ps-mini-button",disabled:u,onClick:()=>e.refreshFeatureFlags()},"Refresh settings")),X("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=e.getFeatureDraftCount?.(p.mode)||0;return X("button",{type:"button",key:p.mode,role:"tab","aria-selected":i===p.mode,disabled:t.saving,className:"ps-mini-button",onClick:()=>e.selectFeatureScope(p.mode)},p.label,m?X("span",{className:"ps-feature-unsaved"},`${m} unsaved`):null)})),i==="users"&&s?X("div",{className:"ps-feature-user"},X("form",{onSubmit:p=>{p.preventDefault(),e.searchFeatureUsers(o)}},X("label",null,"Find user ",X("input",{type:"search",value:o,"aria-label":"Find feature settings user",placeholder:"Name, email or identity",onChange:p=>l(p.target.value)})),X("button",{className:"ps-mini-button",disabled:t.usersLoading||t.saving},"Search")),X("label",null,"User ",X("select",{"aria-label":"Feature settings user",value:t.userId??"",disabled:t.saving,onChange:p=>e.selectFeatureScope("users",p.target.value?Number(p.target.value):null)},X("option",{value:""},"Select a user"),(t.users||[]).map(p=>X("option",{key:p.userId,value:p.userId},`${p.displayName||p.email||p.subject}${p.displayName&&p.email?` — ${p.email}`:""}${t.selectedUserOutsideResults&&p.userId===t.userId?" (current selection)":""}`)))),t.selectedUserOutsideResults?X("p",{className:"ps-feature-explanation"},"Current selection kept while you search."):null,c?X("p",{className:"ps-feature-user-identity"},X("strong",null,d),c.email?X("span",null,c.email):null):t.userId?X("p",null,`Selected user ID: ${t.userId}`):null,t.users?.length>=500?X("p",null,"Showing the first 500 users. Refine your search to find another user."):null):null,t.error?X("p",{role:"alert"},t.error):null,t.metadataError?X("p",{role:"status"},t.metadataError):null,s&&r?X("p",{role:"status"},"Worker reports could not be refreshed. Settings delivery status is unavailable."):null,t.notice?X("p",{role:"status"},t.notice):null,t.loading?X("p",{role:"status"},"Loading feature settings…"):null,(i==="mine"||s?t.data?.flags||[]:[]).map(p=>X(BS,{key:`${i}:${t.userId}:${p.featureKey}`,flag:p,mode:i,busy:u,saving:t.saving,controller:e,workers:n,workersError:r,isAdmin:s,userName:d})),!t.loading&&t.data?.flags?.length===0?X("p",null,"No feature definitions are published."):null)}const zi=new Set(["completed","failed","cancelled","interrupted"]),US={starting:"◷",running:"◷",waiting:"Ⅱ",completed:"✓",failed:"!",cancelled:"■",interrupted:"↯"};function jS(e,t){const s=e.durationMs??(e.startedAt?(e.completedAt||t)-e.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 GS=a.memo(function({group:t,colors:s}){const[n,r]=a.useState(!1),[i,o]=a.useState(Date.now),l=t.tasks.some(p=>!zi.has(p.status));a.useEffect(()=>{if(!l)return;const p=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(p)},[l]);const c=t.tasks.reduce((p,m)=>{const f=fr[m.status]||"Unknown";return p[f]=(p[f]||0)+1,p},{}),d=Object.entries(c).map(([p,m])=>`${m} ${p.toLowerCase()}`).join(" · "),u=n?t.tasks:t.tasks.slice(0,3);return a.createElement("section",{className:"ps-native-tasks","aria-label":"Native tasks","data-task-group":t.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=>a.createElement(WS,{key:p.id,task:p,colors:s,now:i})),t.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 ${t.tasks.length-3} more tasks`):null)});function WS({task:e,colors:t,now:s}){const n=["failed","cancelled","interrupted"].includes(e.status),[r,i]=a.useState(!zi.has(e.status)||n),o=a.useRef(!1),l=a.useRef(null),c=a.useRef(!0),d=a.useMemo(()=>(e.calls||[]).map(Yc),[e.calls]);a.useLayoutEffect(()=>{r&&l.current&&c.current&&(l.current.scrollTop=l.current.scrollHeight)},[r,d.length]),a.useEffect(()=>{(n||!o.current)&&i(!zi.has(e.status)||n)},[e.status,n]);const u=e.error||e.result||e.preview||(e.status==="completed"?"Task completed.":""),p=jS(e,s),m=e.profile==="swarm-explore"?"Explore":e.profile==="swarm-task"?"Task":"Native task";return a.createElement("details",{className:"ps-native-task","data-task-id":e.id,"data-status":e.status,open:r,onToggle:f=>{f.target===f.currentTarget&&i(f.currentTarget.open)},style:{"--ps-native-task-accent":t[e.status]||t.running}},a.createElement("summary",{onClick:()=>{o.current=!0},onKeyDown:f=>{["Enter"," "].includes(f.key)&&(o.current=!0)}},a.createElement("span",{className:"ps-native-task-mark","aria-hidden":!0},US[e.status]||"?"),a.createElement("span",{className:"ps-native-task-main"},a.createElement("span",{className:"ps-native-task-title"},a.createElement("span",{className:"ps-native-task-profile"},m),e.title==="Native task"?"Working on delegated request":e.title),u?a.createElement("span",{className:"ps-native-task-preview"},u.replace(/\s+/g," ").slice(0,240)):null),a.createElement("span",{className:"ps-native-task-meta"},a.createElement("span",{className:"ps-native-task-status"},e.telemetryStale?"Reconnecting":fr[e.status]||e.status),a.createElement("span",null,[p,`${e.toolCalls||0} ${e.toolCalls===1?"call":"calls"}`].filter(Boolean).join(" · "))),a.createElement("span",{className:"ps-native-task-chevron","aria-hidden":!0},"›")),a.createElement("div",{className:"ps-native-task-detail",onClick:()=>{o.current=!0}},a.createElement("div",{className:"ps-native-task-scope"},[e.model,e.reasoningEffort,"Same worker"].filter(Boolean).join(" · ")),d.length?a.createElement("div",{ref:l,className:"ps-native-task-calls",role:"region","aria-label":`Tool calls for ${e.title}`,tabIndex:0,onScroll:f=>{const h=f.currentTarget;c.current=h.scrollHeight-h.scrollTop-h.clientHeight<=24},onWheel:f=>{o.current=!0,f.deltaY<0&&(c.current=!1)},onTouchStart:()=>{o.current=!0,c.current=!1},onFocus:()=>{o.current=!0}},d.map(f=>a.createElement(Cu,{key:f.callKey,line:f}))):a.createElement("p",{className:"ps-native-task-scope"},e.toolCalls?"Tool details are not available in this recording.":"Waiting for task activity…"),e.result||e.error?a.createElement("p",{className:"ps-native-task-result"},e.error||e.result):null,e.recentActivity?.length&&!e.calls?.length?a.createElement("ul",{className:"ps-native-task-activity"},e.recentActivity.map((f,h)=>a.createElement("li",{key:h},f.message))):null))}const qS=920,Tu=7,zS=19,Ua=.24,Pu=16,Mu=8,ja=224,KS=190,VS=48,Ct=16,Ys=200,_u=.5,Mt=_u,$u=56,Ru=84,YS=700,XS=5e3,QS=new Set(["low","medium","high","xhigh"]),ZS=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],JS=["pilotswarm_theme","pilotswarm_session_owner_filter"],ev={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"Duroxide Event History",files:"Files",stats:"Stats"},Yl={sequence:qw,logs:Kw,nodes:Vw,history:Zw,files:Jw,stats:e0};function tv(e,t,s){const n=Array.isArray(e)?e.filter(Boolean):[];if(n.length===0)return t;const r=n.indexOf(t),o=((r===-1?0:r)+s+n.length)%n.length;return n[o]}function sv(e){return typeof e?.transport?.uploadArtifactFromFile=="function"}function nv(e){return typeof e?.transport?.uploadArtifactFromPath=="function"}function rv(e){return typeof e?.transport?.listArtifacts=="function"}function iv(e){return typeof e?.transport?.deleteArtifact=="function"}function av(e){return typeof e?.transport?.openPathInDefaultApp=="function"}const ov="Session link copied to clipboard",Lu="Artifact link copied to clipboard",lv=140,cv="Only people with access can open this link.";function Ou(e){return!e||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(e)}`}function Er(e,t,{fullscreen:s=!0}={}){const n=Ou(e);return!n||!t?n:`${n}&artifact=${encodeURIComponent(t)}${s?"&view=full":""}`}let kr=[];function fE(e){kr=Array.isArray(e)?e:[]}function or(e){const t=yu(Da(e,kr));navigator?.clipboard?.writeText&&navigator.clipboard.writeText(t).catch(()=>{})}function Fu({url:e,keyPrefix:t,copied:s,onCopy:n}){const r=Da(e,kr),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:e,onFocus:i}),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>n(t,e)},s===t?"Copied":"Copy"));const o=`${t}:all`;return a.createElement("div",{className:"ps-link-origins"},r.map((l,c)=>{const d=`${t}:${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,yu(r))},s===o?"Copied all":"Copy all")))}async function dv(e,t){try{const s=e.transport;if(typeof s?.getSessionAccess=="function"&&((await s.getSessionAccess(t))?.visibility||"private")==="private"){const r=typeof s.listSessionShares=="function"?await s.listSessionShares(t).catch(()=>[]):[];return!Array.isArray(r)||r.length===0}}catch{}return!1}function uv(){if(!(typeof window>"u")){try{for(const e of ZS)window.localStorage.removeItem(e)}catch{}try{for(const e of JS)document.cookie=`${e}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function cs(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},s={};if(Ae(t,"sessionSortMode")&&(s.sessionSortMode=ln(t.sessionSortMode)),Ae(t,"sessionUsedAt")&&(s.sessionUsedAt=Td(t.sessionUsedAt)),Ae(t,"moa")&&(s.moa=cn(t.moa)),typeof t.themeId=="string"&&t.themeId.trim()&&(s.themeId=t.themeId.trim()),typeof t.sessionDetailCollapsed=="boolean"&&(s.sessionDetailCollapsed=t.sessionDetailCollapsed),t.agentPickerUsage&&typeof t.agentPickerUsage=="object"&&!Array.isArray(t.agentPickerUsage)){const n={};for(const[i,o]of Object.entries(t.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 t.touchScale=="boolean"&&(s.touchScale=t.touchScale),typeof t.touchScaleMobile=="boolean"&&(s.touchScaleMobile=t.touchScaleMobile),Ae(t,"sessionOwnerFilter")&&t.sessionOwnerFilter&&typeof t.sessionOwnerFilter=="object"){const n=t.sessionOwnerFilter;s.sessionOwnerFilter=Ae(n,"includeShared")?n:{...n,includeShared:!0}}if(Ae(t,"layoutAdjustments")&&(s.layoutAdjustments=pa(t.layoutAdjustments)),Ae(t,"pinnedSessionIds")&&(s.pinnedSessionIds=Jn(t.pinnedSessionIds)),Ae(t,"sessionOrder")&&(s.sessionOrder=ma(t.sessionOrder)),Ae(t,"collapsedSessionIds")&&(s.collapsedSessionIds=pv(t.collapsedSessionIds)),Ae(t,"activeSessionId")){const n=t.activeSessionId==null?null:String(t.activeSessionId).trim();s.activeSessionId=n||null}return(t.rightPaneMode==="canvas"||t.rightPaneMode==="panes")&&(s.rightPaneMode=t.rightPaneMode),Ae(t,"desktopPanes")&&t.desktopPanes&&typeof t.desktopPanes=="object"&&(s.desktopPanes={canvasOpen:t.desktopPanes.canvasOpen===!0,diagnosticsOpen:t.desktopPanes.diagnosticsOpen===!0,zen:t.desktopPanes.zen===!0}),Ae(t,"canvasPrefs")&&(s.canvasPrefs=fa(t.canvasPrefs)),Ae(t,"sessionViews")&&(s.sessionViews=Ad(t.sessionViews)),s}function Ir(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches}function lr(){return Ir()?"touchScaleMobile":"touchScale"}function cr(){return Ir()?"touchScale":"touchScaleMobile"}function pv(e){if(e instanceof Set){const n=[];for(const r of e){const i=String(r||"").trim();i&&n.push(i)}return n.sort(),n}if(!Array.isArray(e))return[];const t=new Set,s=[];for(const n of e){const r=String(n||"").trim();!r||t.has(r)||(t.add(r),s.push(r))}return s.sort(),s}function Ae(e,t){return!!(e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,t))}function Xl(e){return{...e.ui,...e.ui.layout,ownerFilter:e.sessions.ownerFilter,pinnedIds:e.sessions.pinnedIds,manualOrder:e.sessions.manualOrder,sessionSortMode:e.sessions.sortMode,sessionUsedAt:e.sessions.usedAt,collapsedSessionIds:e.sessions.collapsedIds,activeSessionId:e.sessions.activeSessionId,canvasPrefs:e.canvas?.prefs}}function ci(e,t=null,s=null,n=null){return cs({...e.moa?{moa:e.moa}:{},themeId:e.themeId,[lr()]:e.touchScale,sessionDetailCollapsed:e.sessionDetailCollapsed,sessionOwnerFilter:e.ownerFilter,layoutAdjustments:{paneAdjust:e.paneAdjust,sessionPaneAdjust:e.sessionPaneAdjust,portalSessionColumnAdjust:e.portalSessionColumnAdjust,activityPaneAdjust:e.activityPaneAdjust,canvasPaneAdjust:e.canvasPaneAdjust,diagnosticsPaneAdjust:e.diagnosticsPaneAdjust,diagnosticsSplitAdjust:e.diagnosticsSplitAdjust},pinnedSessionIds:e.pinnedIds,sessionOrder:e.manualOrder,sessionSortMode:e.sessionSortMode,sessionUsedAt:e.sessionUsedAt,collapsedSessionIds:e.collapsedSessionIds,activeSessionId:e.activeSessionId,...Ir()?{...s==="canvas"||s==="panes"?{rightPaneMode:s}:{},...n&&typeof n=="object"?{desktopPanes:n}:{}}:{rightPaneMode:e.canvasOpen?"canvas":"panes",desktopPanes:{canvasOpen:e.canvasOpen===!0,diagnosticsOpen:e.diagnosticsOpen===!0,zen:e.canvasZen===!0}},canvasPrefs:e.canvasPrefs,sessionViews:e.sessionViews,...typeof t=="boolean"?{[cr()]:t}:{},...e.agentPickerUsage&&typeof e.agentPickerUsage=="object"&&Object.keys(e.agentPickerUsage).length>0?{agentPickerUsage:e.agentPickerUsage}:{}})}function Ql(e,t=null,s=null){return cs({...e?.ui?.moa?{moa:e.ui.moa}:{},themeId:e?.ui?.themeId,[lr()]:e?.ui?.touchScale,sessionDetailCollapsed:e?.ui?.sessionDetailCollapsed,sessionOwnerFilter:ar(e?.auth?.principal??null),layoutAdjustments:e?.ui?.layout,pinnedSessionIds:e?.sessions?.pinnedIds,sessionOrder:e?.sessions?.manualOrder,sessionSortMode:e?.sessions?.sortMode,sessionUsedAt:e?.sessions?.usedAt,collapsedSessionIds:e?.sessions?.collapsedIds,activeSessionId:e?.sessions?.activeSessionId,...Ir()?s==="canvas"||s==="panes"?{rightPaneMode:s}:{}:{rightPaneMode:e?.ui?.rightPaneMode,desktopPanes:{canvasOpen:e?.ui?.canvasOpen===!0,diagnosticsOpen:e?.ui?.diagnosticsOpen===!0,zen:e?.ui?.canvasZen===!0}},canvasPrefs:e?.canvas?.prefs,...typeof t=="boolean"?{[cr()]:t}:{}})}function mv(e,t){const s=cs(e),n=cs(t);return cs({...Ae(s,"moa")?{moa:s.moa}:{},themeId:Ae(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:Ae(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:Ae(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:Ae(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,sessionSortMode:s.sessionSortMode??n.sessionSortMode,sessionUsedAt:s.sessionUsedAt??n.sessionUsedAt,sessionOrder:Ae(s,"sessionOrder")?s.sessionOrder:n.sessionOrder,...Ae(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...Ae(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...Ae(s,"desktopPanes")?{desktopPanes:s.desktopPanes}:{},...Ae(s,"sessionViews")?{sessionViews:s.sessionViews}:{},...Ae(s,"rightPaneMode")?{rightPaneMode:s.rightPaneMode}:{},...Ae(s,"canvasPrefs")?{canvasPrefs:s.canvasPrefs}:{},...Ae(s,lr())?{touchScale:s[lr()]}:{},...Ae(s,"sessionDetailCollapsed")?{sessionDetailCollapsed:s.sessionDetailCollapsed}:{},...Ae(s,"agentPickerUsage")?{agentPickerUsage:s.agentPickerUsage}:{}})}const Tn=new WeakMap;async function fv(e,t){if(typeof e?.transport?.setCurrentUserProfileSettings!="function")return null;const n=(Tn.get(e)||Promise.resolve()).catch(()=>{}).then(()=>e.transport.setCurrentUserProfileSettings({settings:cs(t)}));Tn.set(e,n);try{return await n}finally{Tn.get(e)===n&&Tn.delete(e)}}function Ga(e){return rv(e)?wt:wt.filter(t=>t!=="files")}function Ve(e,t){if(Object.is(e,t))return!0;if(!e||!t||typeof e!="object"||typeof t!="object")return!1;const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const r of s)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}function $s(e,t,s){return Math.max(t,Math.min(s,e))}const Hn=120,Wa=640,qa=320;function Ki(e){const t=Math.max(0,Number(e)||0),s=Math.max(0,t-Pu-Mu*2),n=s*Ua,r=Math.max(0,s-ja);return{minAdjust:-n,maxAdjust:r-n}}function hv(e,t){const s=Ki(e),n=Math.max(0,Number(e)||0),i=Math.max(0,n-Pu-Mu*2)*Ua;return $s(i+(Number(t)||0),0,i+s.maxAdjust)}function gv(e){return e<=VS?"hidden":e<=KS?"compact":"wrap"}function Du(e){const t=Number(e?.ui?.promptRows);return Number.isFinite(t)&&t>0?t:Cs(e?.ui?.prompt||"")}function xr(e){return en({width:e.ui.layout?.viewportWidth??120,height:e.ui.layout?.viewportHeight??40},e.ui.layout?.paneAdjust??0,Du(e),e.ui.layout?.sessionPaneAdjust??0)}function yv(e,t,s=!1){return Math.max(20,e-(s?6:4))}function Bu({slack:e=1,debounceMs:t=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)-e);n(y=>y===b?y:b)},d=()=>{l.timer&&window.clearTimeout(l.timer),l.timer=window.setTimeout(c,t)};l.frame=requestAnimationFrame(c),l.observer=new ResizeObserver(d);try{l.observer.observe(o,{box:"content-box"})}catch{l.observer.observe(o)}},[e,t]);return[s,i]}function rt(e){const t=[],s=n=>{const r=String(n||"");return!r.includes("\\n")||r.includes(`
93
- `)?r:r.replace(/\\n/g,`
94
- `)};for(const n of e||[]){if(n?.kind==="chatCall"||n?.callPreview!==void 0){t.push(n);continue}if(n?.kind==="assistantPreview"||n?.kind==="nativeTasks"){t.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 Oc(i.text||""))t.push({kind:"runs",runs:o,preserve:!0,splashVariant:i.variant});continue}if(n?.kind==="markdownTable"||n?.kind==="cardStart"||n?.kind==="cardEnd"||n?.kind==="imageAttachments"){t.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)t.push({kind:"runs",runs:[{...i,text:c}]});continue}t.push({kind:"runs",runs:[{...i,text:o}]});continue}t.push({kind:"runs",runs:r.map(i=>({...i,text:s(i?.text||"")}))});continue}if(Array.isArray(n)){t.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)t.push({kind:"text",...n,text:o});continue}t.push({kind:"text",...n,text:r});continue}t.push({kind:"text",...n})}return t}function je(e,t){if(t)return e?.tui?.[t]||e?.terminal?.[t]||e?.page?.[t]||t}function Hu(e=[]){return e.map(t=>String(t?.text||"")).join("")}function Zl(e){return Array.isArray(e)?Hu(e):String(e||"")}function Jl(e,t=40){if(!Array.isArray(e)){const i=String(e||"");return[{text:i.length>t?`${i.slice(0,t-1)}…`:i,color:"white",bold:!0}]}const s=[],n=i=>/^[\s·—-]+$/.test(String(i?.text||""));let r=Math.max(8,t);for(const i of e){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:e}function bv(e){typeof document>"u"||(e?document.documentElement.dataset.psTouch="1":delete document.documentElement.dataset.psTouch)}function Sv(e){const t=Pt(e);if(!t||typeof document>"u")return;const s=document.documentElement;s.style.setProperty("--ps-page-background",t.page.background),s.style.setProperty("--ps-page-foreground",t.page.foreground),s.style.setProperty("--ps-surface",t.tui.surface),s.style.setProperty("--ps-background",t.tui.background),s.style.setProperty("--ps-foreground",t.tui.foreground),s.style.setProperty("--ps-muted",t.tui.gray),s.style.setProperty("--ps-border",t.tui.border||t.tui.gray),s.style.setProperty("--ps-selection-background",t.tui.selectionBackground),s.style.setProperty("--ps-selection-foreground",t.tui.selectionForeground),s.style.setProperty("--ps-highlight-background",t.tui.activeHighlightBackground),s.style.setProperty("--ps-highlight-foreground",t.tui.activeHighlightForeground),s.style.setProperty("--ps-modal-backdrop",t.page.modalBackdrop),s.style.setProperty("--ps-modal-background",t.page.modalBackground),s.style.setProperty("--ps-modal-border",t.page.modalBorder),s.style.setProperty("--ps-modal-foreground",t.page.modalForeground),s.style.setProperty("--ps-modal-muted",t.page.modalMuted),s.style.setProperty("--ps-modal-selected-background",t.page.modalSelectedBackground),s.style.setProperty("--ps-modal-selected-border",t.page.modalSelectedBorder),s.style.setProperty("--ps-modal-selected-foreground",t.page.modalSelectedForeground),s.style.setProperty("--ps-accent",t.tui.cyan),s.style.setProperty("--ps-success",t.tui.green),s.style.setProperty("--ps-warning",t.tui.yellow),s.style.setProperty("--ps-danger",t.tui.red),s.dataset.psTheme=t.id}function ec(e,t=!1){const[s,n]=a.useState({width:0,height:0});return a.useLayoutEffect(()=>{if(t)return;const r=e.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)}},[e,t]),s}function vv(e){const t=Math.max(320,e.width||window.innerWidth||1280),s=Math.max(320,e.height||window.innerHeight||800);return{width:Math.max(40,Math.floor(t/Tu)),height:Math.max(18,Math.floor(s/zS))}}function za(e){if(!e)return 0;const t=Math.max(0,e.scrollHeight-e.clientHeight);return Math.max(0,t-e.scrollTop)}function wv(e){return za(e)<=_u}function Ev(e,t,s,n=!1){if(!e)return 0;const r=Math.max(0,e.scrollHeight-e.clientHeight);if(n)return Math.max(0,Math.min(e.scrollTop,r));const i=Math.max(0,Number(t)||0)*Ct;return s==="bottom"?Math.max(0,r-i):Math.min(r,i)}function kv(e){return e?e.kind==="runs"?e.runs?.map(t=>t?.text||"").join("")||"":e.kind==="assistantPreview"?`assistant:${e.previewKey||e.messageId||e.id||""}`:`${e.kind||"text"}:${e.text||e.value||e.id||""}`:""}function tc(e,t=!1){return(t?e.slice(-8):e.slice(0,8)).map(kv).join("␞")}function Iv(e,t,s,n,r,i,{stickyBottom:o=!1,historyPullEnabled:l=!1,historySessionId:c=null}={}){const d=a.useMemo(()=>rt(t),[t]),u=a.useRef(null),p=a.useRef({scrollMode:n,scrollOffset:s}),m=a.useRef(null),f=a.useRef(null);a.useEffect(()=>()=>{f.current=null},[]);const[h,g]=a.useState(0),[b,y]=a.useState(null);a.useEffect(()=>{g(0)},[c]);const v=a.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),S=a.useRef({width:null,height:null}),[w,E]=a.useState(0);a.useLayoutEffect(()=>{const P=e.current;if(!P||typeof ResizeObserver>"u")return;S.current={width:P.clientWidth,height:P.clientHeight};const _=new ResizeObserver(()=>{const $={width:P.clientWidth,height:P.clientHeight},B=S.current;$.width===B.width&&$.height===B.height||(S.current=$,E(j=>j+1))});return _.observe(P),()=>_.disconnect()},[e]),a.useLayoutEffect(()=>{const P=e.current;if(!P)return;const _=p.current,$=tc(d),B=tc(d,!0),j=m.current;let W=f.current;const A=i.getState().sessions.activeSessionId;W&&W.sessionId!==A&&(f.current=null,W=null);const G=i.getState().history.bySessionId.get(A)?.events?.[0]?.seq,D=W&&!W.applied&&G<W.oldestSeq;let Y=null;if(D){const be=W.anchor,Q=be?.element.isConnected&&be.element.textContent===be.text?be.element:[...P.children].find(ge=>ge.textContent===be?.text),ce=Q?Q.getBoundingClientRect().top-be.top:P.scrollHeight-W.height;Y=Math.max(0,Math.min(P.scrollHeight-P.clientHeight,P.scrollTop+ce-Ct)),W.applied=!0,W.target=Y,W.releaseAt=performance.now()+Ys}const J=v.current,te=typeof performance<"u"?performance.now():Date.now(),Z=J.touching||te-(J.lastUserScrollAt||0)<YS,ne=J.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-J.lastDispatchedOffset)<2,ae=o&&n==="top"&&_?.scrollMode==="top"&&_?.scrollOffset===s,oe=!W&&o&&j?.lastLine===B&&j?.firstLine!==$&&P.scrollHeight>j.scrollHeight&&(ae||P.scrollTop<=Mt);if(!D&&!oe&&Z&&n===_?.scrollMode&&(s===_?.scrollOffset||ne)){p.current={scrollMode:n,scrollOffset:s},m.current={firstLine:$,lastLine:B,scrollHeight:P.scrollHeight};return}const ve=D?Y:oe?Math.max(0,Math.min(P.scrollTop+(P.scrollHeight-j.scrollHeight),P.scrollHeight-P.clientHeight)):Ev(P,s,n,ae);if(Math.abs(P.scrollTop-ve)>Mt){const be={target:ve};u.current=be,P.scrollTop=ve,window.requestAnimationFrame(()=>{u.current===be&&(u.current=null)})}if((D||oe)&&r&&typeof i.updatePaneScrollFromViewport=="function"){const be=Math.max(0,ve)/Ct;v.current.lastDispatchedOffset=be,i.updatePaneScrollFromViewport(r,be,{atBottom:!1})}p.current={scrollMode:n,scrollOffset:s},m.current={firstLine:$,lastLine:B,scrollHeight:P.scrollHeight}},[d,e,n,s,o,w]);const I=Nv(P=>{i.dispatch({type:"ui/scroll",pane:r,offset:P})}),T=a.useCallback(()=>{const P=e.current;if(!P||!r)return;const _=f.current;if(_?.applied&&performance.now()<=_.releaseAt&&P.scrollTop<_.target){P.scrollTop=_.target,_.releaseAt=performance.now()+Ys;return}_?.applied&&performance.now()>_.releaseAt&&(f.current=null);const $=u.current;if($){if(Math.abs(P.scrollTop-$.target)<=Mt)return;u.current=null}v.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const B=Math.max(0,P.scrollHeight-P.clientHeight);if(B<=0)return;if(o&&typeof i.updatePaneScrollFromViewport=="function"){const W=Math.max(0,P.scrollTop)/Ct;v.current.lastDispatchedOffset=W,i.updatePaneScrollFromViewport(r,W,{atBottom:wv(P)}),r==="chat"&&P.scrollTop<=Mt&&i.armChatTopHistoryLoad?.();return}const j=n==="bottom"?Math.max(0,B-P.scrollTop):Math.max(0,P.scrollTop);v.current.lastDispatchedOffset=j/Ct,I(j/Ct),r==="chat"&&n==="bottom"&&P.scrollTop<=Mt&&i.armChatTopHistoryLoad?.()},[i,I,r,e,n,o]),C=a.useCallback(()=>{const P=e.current,_=i.getState(),$=_.sessions.activeSessionId;if(!P||!$||!l||f.current)return;const B=P.getBoundingClientRect().top,j=[...P.children].find(G=>G.textContent?.trim()&&G.getBoundingClientRect().bottom>B+6),W={sessionId:$,oldestSeq:_.history.bySessionId.get($)?.events?.[0]?.seq,height:P.scrollHeight,applied:!1,anchor:j?{element:j,text:j.textContent,top:j.getBoundingClientRect().top}:null};f.current=W;const A=i.handleChatTopHistoryScrollIntent?.((P.scrollHeight-P.clientHeight)/Ct,{force:!0,preserveDomAnchor:!0,onLoadStarted:()=>y($)});Promise.resolve(A).catch(()=>{}).finally(()=>{if(y(D=>D===$?null:D),f.current!==W)return;i.getState().history.bySessionId.get($)?.events?.[0]?.seq<W.oldestSeq?E(D=>D+1):f.current=null})},[i,l,e]),k=a.useCallback(P=>{const _=e.current;if(!_||r!=="chat"||!P.deltaY||P.ctrlKey)return;const $=f.current;if($&&P.deltaY>0)f.current=null;else if($){if(!$.applied||performance.now()<=$.releaseAt){$.releaseAt=performance.now()+Ys,P.preventDefault();return}f.current=null}P.deltaY>=0||_.scrollTop>Mt||(P.preventDefault(),C())},[r,e,C]),O=a.useRef({startY:null,distance:0}),N=a.useCallback(P=>{v.current.touching=!0,f.current?.applied&&(f.current=null);const _=e.current;O.current={startY:l&&b!==c&&r==="chat"&&_?.scrollTop<=Mt?P.touches?.[0]?.clientY??null:null,distance:0}},[l,c,b,r,e]),R=a.useCallback(()=>{v.current.touching=!1,v.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now(),f.current?.applied&&(f.current.releaseAt=performance.now()+Ys);const P=O.current.distance;O.current={startY:null,distance:0},g(0),P>=$u&&e.current?.scrollTop<=Mt&&C()},[e,C]),H=a.useCallback(()=>{v.current.touching=!1,O.current={startY:null,distance:0},g(0)},[]),x=a.useCallback(P=>{const _=e.current,$=O.current;if(!_||r!=="chat"||P.touches?.length!==1)return;if(f.current){f.current.releaseAt=performance.now()+Ys,P.preventDefault();return}if($.startY==null||_.scrollTop>Mt)return;const B=P.touches?.[0]?.clientY;B!=null&&($.distance=Math.min(Ru,Math.max(0,B-$.startY)),g($.distance),$.distance>0&&P.preventDefault())},[r,e]);return a.useEffect(()=>{const P=e.current;if(P)return P.addEventListener("wheel",k,{passive:!1}),P.addEventListener("touchmove",x,{passive:!1}),()=>{P.removeEventListener("wheel",k),P.removeEventListener("touchmove",x)}},[e,k,x]),{normalizedLines:d,onScroll:T,onTouchStart:N,onTouchEnd:R,onTouchCancel:H,topPullDistance:h,loadingOlderHistory:b===c}}function Je({runs:e,theme:t}){return a.createElement(a.Fragment,null,(e||[]).map((s,n,r)=>{const i=n>0&&!!dr(r[n-1]?.href),o={color:je(t,s.color),backgroundColor:je(t,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=dr(l);if(d)return a.createElement(Vu,{key:n,artifactRef:d,style:o});const u=i?qu(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 Uu({line:e,theme:t}){const[s,n]=a.useState(!1),r=String(e?.body||"").trim(),i=`ps-system-notice${e?.liveReasoning||e?.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:je(t,e?.color)||"var(--ps-muted)"}},a.createElement("span",{className:"ps-system-notice-summary-text"},e?.text||"System notice")),r&&s?a.createElement("div",{className:"ps-system-notice-body"},a.createElement(Za,{content:r,theme:t})):null)}function xv({calls:e}){const t=e[e.length-1]||{},s=t.status==="Called"||t.status==="Started",n=e.some(f=>f.status==="Failed"),[r,i]=a.useState(s),o=a.useRef(null),l=a.useRef(!0),c=new Set(e.map(f=>f.category||"Tool")),d=c.size===1&&c.has("Tool")?`${e.length} tool ${e.length===1?"call":"calls"}`:c.size===1&&c.has("Agent")?`${e.length} agent ${e.length===1?"activity":"activities"}`:`${e.length} activities`,u=String(t.text||t.category||"activity").split(" — ")[0],p=s?"Working":n?"Failed":"Done",m=`${t.callKey||""}:${t.status||""}:${String(t.body||"").length}`;return a.useLayoutEffect(()=>{const f=o.current;r&&f&&l.current&&(f.scrollTop=f.scrollHeight)},[r,e.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:t.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=za(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()},e.map(f=>a.createElement(Cu,{key:f.callKey,line:f}))),a.createElement("div",{className:"ps-activity-run-footer"},`Showing ${e.length} ${e.length===1?"entry":"entries"} · Scroll for earlier activity`))}function Av({line:e,theme:t}){const s=String(e?.canvasActionPayload||"").trim(),n=e?.canvasActionName||"action",r=String(e?.canvasActionDetail||"").trim(),i=String(e?.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:je(t,"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 Nv(e){const t=a.useRef(0),s=a.useRef(null),n=a.useRef(e);return n.current=e,a.useEffect(()=>()=>{t.current&&cancelAnimationFrame(t.current)},[]),a.useCallback((...r)=>{s.current=r,!t.current&&(t.current=requestAnimationFrame(()=>{t.current=0;const i=s.current;s.current=null,i&&n.current(...i)}))},[])}const ct=a.memo(function({line:t,theme:s,className:n=""}){const r=n?`ps-line ${n}`:"ps-line";return t?t.kind==="systemNotice"?a.createElement(Uu,{line:t,theme:s}):t.canvasAction?a.createElement(Av,{line:t,theme:s}):t.kind==="runs"?a.createElement("div",{className:r},a.createElement(Je,{runs:t.runs,theme:s})):a.createElement("div",{className:r,style:{color:je(s,t.color),backgroundColor:je(s,t.backgroundColor),fontWeight:t.bold?700:400,textDecoration:t.underline?"underline":"none"}},t.text||" "):a.createElement("div",{className:r}," ")});function mt(e){return e?e.kind==="runs"?Hu(e.runs):String(e.text||""):""}function ju(e,t,s,n){const r=a.useRef(!1);return a.useLayoutEffect(()=>{const i=e.current;if(!i||!s)return;const o=Math.max(0,i.scrollHeight-i.clientHeight),l=Math.min(o,Math.max(0,Number(t)||0)*Ct);Math.abs(i.scrollTop-l)>2&&(r.current=!0,i.scrollTop=l,window.requestAnimationFrame(()=>{r.current=!1}))},[e,t,s]),a.useCallback(i=>{if(r.current)return;const o=e.current;!o||!s||i&&i.target!==o||o.scrollHeight<=o.clientHeight||n.dispatch({type:"ui/scroll",pane:s,offset:Math.max(0,o.scrollTop)/Ct})},[n,s,e])}const Cv={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"},Tv=new Set(["diff","patch","udiff"]),Pv=/\.(patch|diff)$/i,Ka=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,Va=/\.(png|jpe?g|gif|webp|avif|bmp|svg|ico)$/i,Mv={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 _v(e){const t=/\.([a-z0-9]+)$/i.exec(String(e||""));return t&&Mv[t[1].toLowerCase()]||null}const $v={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 Rv(e){const t=String(e||"");if(!/^---[ \t]*\r?\n/.test(t))return t;const s=/\r?\n---[ \t]*(\r?\n|$)/.exec(t.slice(3));return s?t.slice(3+s.index+s[0].length):t}const Lv=/\.(html?|xhtml)$/i;function Gu(e,t){return Lv.test(String(e||""))?!0:/^(text\/html|application\/xhtml\+xml)$/i.test(String(t||"").trim().split(";")[0])}const Ov=/\.(csv|tsv)$/i;function Wu(e,t){return Ov.test(String(e||""))?!0:/^text\/(csv|tab-separated-values)$/i.test(String(t||"").trim())}const di=2e3;function Fv(e){const t=String(e??"");return/[\t\n\r"]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function Dv({content:e,filename:t}){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),Nu(()=>import("./papaparse.min-Dk5F4KnO.js").then(E=>E.p),[]).then(E=>{if(w)return;const I=E.default||E,T=/\.tsv$/i.test(String(t||""))?" ":"",C=I.parse(String(e||"").trim(),{delimiter:T,skipEmptyLines:"greedy"});n({rows:C.data||[],errors:C.errors||[]})}).catch(()=>{w||n({rows:null,errors:[{message:"parser unavailable"}]})}),()=>{w=!0}},[e,t]),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 I=window.getSelection();if(!I)return;const T=!!(w.compareDocumentPosition(E)&Node.DOCUMENT_POSITION_PRECEDING),C=document.createRange();C.setStartBefore(T?E:w),C.setEndAfter(T?w:E),I.removeAllRanges(),I.addRange(C)},[]),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,I=window.getSelection();if(!E||!I)return;w.preventDefault(),w.stopPropagation();const T=document.createRange();T.selectNodeContents(E),I.removeAllRanges(),I.addRange(T)},[]),m=a.useCallback(w=>{const E=i.current,I=window.getSelection();if(!E||!I||I.rangeCount===0)return;const T=I.getRangeAt(0),C=new Map;for(const k of E.querySelectorAll("th,td")){if(!T.intersectsNode(k))continue;const O=k.parentElement;C.has(O)||C.set(O,[]),C.get(O).push(Fv(k.textContent))}C.size!==0&&(w.clipboardData.setData("text/plain",Array.from(C.values(),k=>k.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(e||"")));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>di,v=y?h.slice(0,di):h,S=[];return y&&S.push(`showing first ${di} of ${h.length} rows`),s.errors.length&&S.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,v.map((w,E)=>a.createElement("tr",{key:`r${E}`},b.map((I,T)=>a.createElement("td",{key:`c${T}`},String(w[T]??""))))))),S.length?a.createElement("div",{className:"ps-csv-status"},S.join(" · ")):null)}function Ya(e){const t=/\.([A-Za-z0-9]+)$/.exec(String(e||""));return t&&$v[t[1].toLowerCase()]||null}function Xa(e,t){return Pv.test(String(e||""))?!0:/^text\/x-(patch|diff)$/i.test(String(t||"").trim())}function qu(e){const t=String(e??"");if(t.startsWith(Mn))return t.slice(Mn.length);const s=Mn.trimStart();return t.startsWith(s)?t.slice(s.length):t}function dr(e){const t=/^artifact:\/\/([^/]+)\/(.+)$/i.exec(String(e||"").trim());if(!t)return null;try{return{sessionId:t[1],filename:decodeURIComponent(t[2])}}catch{return{sessionId:t[1],filename:t[2]}}}const Vi=a.createContext(null);function zu(e){const t=String(e||""),s=(/\.([A-Za-z0-9]+)$/.exec(t)?.[1]||"").toLowerCase();return Gu(t)?{kind:"page",type:"HTML",noun:"Page"}:Xa(t)?{kind:"diff",type:s.toUpperCase()||"DIFF",noun:"Diff"}:Va.test(t)?{kind:"image",type:s.toUpperCase(),noun:"Image"}:Wu(t)?{kind:"table",type:s.toUpperCase(),noun:"Table"}:/\.md$/i.test(t)?{kind:"doc",type:"MD",noun:"Document"}:Ya(t)?{kind:"code",type:s.toUpperCase(),noun:"Code"}:{kind:"file",type:s.toUpperCase()||"FILE",noun:"File"}}function Ku(e){const t=String(e||"").replace(/\.[A-Za-z0-9]+$/,""),n=(t.replace(/[-_ ]?\d{6,8}$/,"")||t).replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):String(e||"Artifact")}function Bv({kind:e}){const t={fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},s=e==="page"?[a.createElement("rect",{key:"w",x:2.5,y:3.5,width:15,height:13,rx:2,...t}),a.createElement("path",{key:"b",d:"M2.5 7.5h15",...t}),a.createElement("circle",{key:"d",cx:5.2,cy:5.5,r:.7,fill:"currentColor",stroke:"none"})]:e==="image"?[a.createElement("rect",{key:"f",x:2.5,y:3.5,width:15,height:13,rx:2,...t}),a.createElement("path",{key:"m",d:"M2.5 13l4-4 4 3.5 3-2.5 3.5 3",...t})]:e==="table"?[a.createElement("rect",{key:"f",x:2.5,y:3.5,width:15,height:13,rx:2,...t}),a.createElement("path",{key:"g",d:"M2.5 8h15M8 8v8.5M2.5 12.5h15",...t})]:[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",...t}),a.createElement("path",{key:"c",d:"M11.5 2.5V7H16",...t}),e==="diff"?a.createElement("path",{key:"t",d:"M7 11h6M10 8.5v5",...t}):a.createElement("path",{key:"t",d:"M7 10.5h6M7 13.5h4",...t})];return a.createElement("svg",{className:"ps-artifact-card-glyph",viewBox:"0 0 20 20","aria-hidden":"true"},s)}function Vu({artifactRef:e}){const t=a.useContext(Vi),s=zu(e.filename),n=a.useCallback(r=>{r.preventDefault(),r.stopPropagation(),Hv(t,e.sessionId,e.filename)},[t,e.sessionId,e.filename]);return a.createElement("button",{type:"button",className:`ps-artifact-card is-${s.kind}`,onClick:n,title:`Open ${e.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"},Ku(e.filename)),a.createElement("span",{className:"ps-artifact-card-meta"},`${s.noun} · ${s.type}`)),a.createElement("span",{className:"ps-artifact-card-open"},"Open"))}function Hv(e,t,s){if(!e?.revealArtifact)return;if(e.openChatArtifact){Promise.resolve(e.openChatArtifact(t,s)).catch(()=>{});return}const n=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;Promise.resolve(n?e.revealArtifact(t,s,{fullscreen:!0}):e.revealArtifact(t,s,{pane:!0})).catch(()=>{})}function Yu(e){return Tv.has(String(e||"").trim().toLowerCase())}const Uv=/^(?: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 jv(e){return Uv.test(e)?"meta":e.startsWith("@@")?"hunk":e.startsWith("+")?"add":e.startsWith("-")?"del":"context"}const Gv={add:"green",del:"red",hunk:"cyan",meta:"gray"};function Qa(e,t){return String(e||"").replace(/\n$/,"").split(`
100
- `).map((n,r)=>{const i=jv(n),o=Gv[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:je(t,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 Xu(e){return String(e||"").trim().toLowerCase()==="mermaid"}const sc={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 Wv(e){const t={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(e){case"python":return[t,d,o,l,r,i];case"shell":return[t,o,l,r,i];case"sql":return[n,l,o,r,i];case"yaml":return[t,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 qv={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},zv=2e4,Jt=new Map,Kv=120;function Vv(e,t){const s=`${t||""}\0${e}`,n=Jt.get(s);if(n)return Jt.delete(s),Jt.set(s,n),n;const r=Yv(e,t);return Jt.set(s,r),Jt.size>Kv&&Jt.delete(Jt.keys().next().value),r}function Yv(e,t){const s=Cv[String(t||"").trim().toLowerCase()]||"default",n=sc[s]||sc.js,r=Wv(s),i=[];let o=0,l=0;const c=d=>{d>l&&i.push({type:"plain",text:e.slice(l,d)})};for(;o<e.length;){let d=null;for(const p of r){p.re.lastIndex=o;const m=p.re.exec(e);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=e.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(e.length),i}function Bs(e,t,s){const n=String(e||"");if(!n||n.length>zv)return n;let r;try{r=Vv(n,t)}catch{return n}return r.map((i,o)=>{const l=qv[i.type];return l?a.createElement("span",{key:`t:${o}`,className:`ps-code-token is-${i.type}`,style:{color:je(s,l)||void 0}},i.text):a.createElement(a.Fragment,{key:`t:${o}`},i.text)})}let Pn=null;function Xv(){return Pn||(Pn=Nu(()=>import("./mermaid.core-1gBc6FeB.js").then(e=>e.bp),[]).then(e=>e.default||e).catch(e=>{throw Pn=null,e})),Pn}function Qv(e,t){return e.initialize({startOnLoad:!1,securityLevel:"strict",theme:t?"default":"dark",fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"}),e}let nc=0,rc=Promise.resolve();function Zv(e){const t=rc.then(e,e);return rc=t.then(()=>{},()=>{}),t}function Qu({code:e,theme:t,fallback:s}){const[n,r]=a.useState(null),[i,o]=a.useState(!1),[l,c]=a.useState(""),d=a.useMemo(()=>hf(t),[t]);return a.useEffect(()=>{let u=!0;const p=String(e||"").trim();if(p)return o(!1),Xv().then(m=>Zv(async()=>{if(!u)return;Qv(m,d),nc+=1;const f=`ps-mermaid-${nc}`;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}},[e,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 Tt(e,t,s="md"){const n=ia(e);return n.map((r,i)=>{const o=`${s}:${i}`;if(i>0&&n[i-1]?.type==="link"&&dr(n[i-1]?.href)){const l=qu(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"},Tt(r.text,t,`${o}:strong`));if(r.type==="em")return a.createElement("em",{key:o,className:"ps-md-em"},Tt(r.text,t,`${o}:em`));if(r.type==="link"){const l=dr(r.href);return l?a.createElement(Vu,{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:je(t,"cyan")}},r.text):a.createElement("span",{key:o,style:{color:je(t,"cyan")}},r.text)}return a.createElement(a.Fragment,{key:o},r.text)})}function Zu(e=[],t=0){return Array.from({length:t},(s,n)=>(Array.isArray(e)?e:[]).map(i=>qi(i?.[n]||"")).filter(Boolean).join(" / ")||null)}function ic(e="",t=""){const s=String(e||"");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(t||""))}function ac(e=""){return String(e||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function Jv(e=""){const s=String(e||"").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=ac(i);r+=2;const m=[];for(;r<s.length&&s[r].includes("|")&&s[r].trim();)m.push(ac(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])&&!ic(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()&&!ic(s[r],s[r+1]||"");)u.push(s[r].trim()),r+=1;n.push({type:"paragraph",text:u.join(" ")})}return n}function Za({content:e,theme:t}){const s=a.useMemo(()=>Jv(e),[e]);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}`},Tt(n.text,t,`heading:${r}`));if(n.type==="code"){const i=Yu(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?Qa(n.content,t):Bs(n.content,n.language,t))));return Xu(n.language)?a.createElement(Qu,{key:`block:${r}`,code:n.content,theme:t,fallback:o}):o}if(n.type==="blockquote")return a.createElement("blockquote",{key:`block:${r}`,className:"ps-md-quote"},Tt(n.text,t,`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"},Tt(o,t,`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?Au([n.header,...n.rows]):null,c=!!l,d=l?l.flexIndex:-1,u=h=>h===d?"is-flex-column":null,p=Zu([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},Tt(h,t,`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"},Tt(b,t,`table:${r}:${g}:${y}`)))))))))}return a.createElement("p",{key:`block:${r}`,className:"ps-md-paragraph"},Tt(n.text,t,`para:${r}`))}))}function ui({controller:e,title:t,color:s,focused:n,scrollOffset:r=0,paneKey:i,theme:o,className:l="",focusRegion:c=null,children:d}){const u=a.useRef(null),p=ju(u,r,i,e),m=a.useCallback(()=>{const f=Ja(i,c);f&&e?.setFocus&&e.setFocus(f)},[e,i,c]);return a.createElement(Yt,{title:t,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 ew({controller:e,title:t,color:s,focused:n,scrollOffset:r=0,paneKey:i,theme:o,content:l,focusRegion:c=null}){const d=a.useCallback(()=>{const m=Ja(i,c);m&&e?.setFocus&&e.setFocus(m)},[e,i,c]),u=a.useRef(null),p=ju(u,r,i,e);return a.createElement(Yt,{title:t,color:s,focused:n,theme:o},a.createElement("div",{ref:u,className:"ps-scroll-panel ps-markdown-scroll",onScroll:p,onMouseDown:d},a.createElement(Za,{content:l,theme:o})))}function Ju(e){const t=Number(e);if(!Number.isFinite(t)||t<0)return"Unknown size";if(t<1024)return`${Math.round(t)} B`;if(t<1024*1024){const n=t/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=t/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function oc({title:e,color:t,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(Ju(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=Ka.test(String(i||""))||Va.test(String(r||"")),[h,g]=a.useState(null);return a.useEffect(()=>{if(g(null),!f||!d||!u||!r)return;let b=!1;return ap(d,u,r).then(y=>{b||g(y)}).catch(()=>{b||g("error")}),()=>{b=!0}},[f,d,u,r]),a.createElement(Yt,{title:e,color:t,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=Er(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 tw=260,sw=28;function nw(e,t,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}t&&(c.current=null,d.current+=1,l(d.current))},[n,t]),a.useEffect(()=>{const m=e.current;if(!t||!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)<sw||(f&&clearTimeout(f),f=setTimeout(()=>{f=null,c.current=Math.round(m.getBoundingClientRect().width)||b,d.current+=1,l(d.current)},tw))}});return h.observe(m),()=>{f&&clearTimeout(f),h.disconnect()}},[e,t]);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 pi=1024;function ep({fitWidth:e,setFitWidth:t}){return a.createElement(Se,{icon:e?"1:1":"⤢",label:e?"Actual size":"Fit page to width",active:e,onClick:()=>t(!e)})}const es=[.5,.67,.8,.9,1,1.1,1.25,1.5,1.75,2,2.5,3];function ur({zoom:e,setZoom:t}){const s=n=>{const r=es.findIndex(l=>Math.abs(l-e)<.005),i=r===-1?es.indexOf(1):r,o=es[Math.min(es.length-1,Math.max(0,i+n))];t(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:e<=es[0]+.001,title:"Zoom out (artifact only)","aria-label":"Zoom out"},"−"),a.createElement("button",{type:"button",className:"ps-html-zoom-level",onClick:()=>t(1),title:"Reset zoom to 100%","aria-label":`Zoom ${Math.round(e*100)} percent, click to reset`},`${Math.round(e*100)}%`),a.createElement("button",{type:"button",className:"ps-html-zoom-btn",onClick:()=>s(1),disabled:e>=es[es.length-1]-.001,title:"Zoom in (artifact only)","aria-label":"Zoom in"},"+"))}function tp({mode:e,setMode:t}){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${e===s?" is-active":""}`,"aria-pressed":e===s,onClick:()=>t(s)},s==="rendered"?"Rendered":"Source")))}function sp(e){const[t,s]=a.useState({width:0,height:0});return a.useLayoutEffect(()=>{const n=e.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()},[e]),t}function np(e,t,s,n=!1){const r=e?.transport?.api?.downloadArtifactResponse;return typeof r!="function"?Promise.reject(new Error("artifact download unavailable")):r.call(e.transport.api,t,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 rw({controller:e,sessionId:t,filename:s,contentType:n,sizeBytes:r,theme:i,color:o="cyan",focused:l=!1,title:c=null,chromeless:d=!1}){const u=ee(e,x=>x.files.htmlViewMode||"rendered"),p=a.useCallback(x=>{e.dispatch({type:"files/htmlViewMode",mode:x})},[e]),[m,f]=a.useState(null),[h,g]=a.useState(null),b=a.useRef(null),y=ee(e,x=>!!x.files.htmlFitWidth),v=a.useCallback(x=>{e.dispatch({type:"files/htmlFitWidth",enabled:x})},[e]),S=sp(b),w=y&&S.width>0&&S.width<pi?S.width/pi:1,E=w<1,I=ee(e,x=>Number(x.files.htmlZoom)||1),T=a.useCallback(x=>{e.dispatch({type:"files/htmlZoom",zoom:x})},[e]),C=E?w*I:I,k=nw(b,u==="rendered"&&!E,`${t}/${s}`,I);a.useEffect(()=>{if(f(null),g(null),u!=="rendered"||!e||!t||!s)return;let x=!1,P=null;return np(e,t,s).then(_=>{if(P=_,x){URL.revokeObjectURL(_);return}f(_)}).catch(_=>{x||g(_?.message||String(_))}),()=>{x=!0,P&&URL.revokeObjectURL(P)}},[e,t,s,u]);const O=Er(t,s),N=d?null:a.createElement(a.Fragment,null,a.createElement(tp,{mode:u,setMode:p}),u==="rendered"?a.createElement(ep,{fitWidth:y,setFitWidth:v}):null,u==="rendered"?a.createElement(ur,{zoom:I,setZoom:T}):null,O?a.createElement(Se,{icon:"↗",label:"Open in a new tab",onClick:()=>{try{window.open(O,"_blank","noopener")}catch{}}}):null),R=u==="source"?a.createElement(iw,{controller:e,sessionId:t,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?[k.live,k.pending].filter((x,P,_)=>x!==null&&_.indexOf(x)===P).map(x=>a.createElement("iframe",{key:`frame:${x}`,className:`ps-html-preview-frame${x===k.live?"":" is-staging"}`,style:E?{flex:"none",width:`${pi}px`,height:`${Math.max(1,Math.round(S.height/C))}px`,transform:`scale(${C})`,transformOrigin:"top left"}:I!==1&&S.width>0?{flex:"none",width:`${Math.max(1,Math.round(S.width/I))}px`,height:`${Math.max(1,Math.round(S.height/I))}px`,transform:`scale(${I})`,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:()=>k.promote(x)})):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,Ju(r)].filter(Boolean).join(" • ")):null),H=u==="rendered"?a.createElement("div",{ref:b,className:`ps-html-preview-host${E||I!==1?" is-fitting":""}`},R):R;return a.createElement(Yt,{title:c,color:o,focused:l,theme:i,actions:N,className:"ps-html-preview"},H)}function iw({controller:e,sessionId:t,filename:s,theme:n}){const[r,i]=a.useState(null),[o,l]=a.useState(null);return a.useEffect(()=>{i(null),l(null);const c=e?.transport?.api?.downloadArtifactResponse;if(typeof c!="function"||!t||!s){l("artifact download unavailable");return}let d=!1;return c.call(e.transport.api,t,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}},[e,t,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,Bs(r,"html",n))))}function Un(e){const t=String(e||"").trim();return t.startsWith("┌")&&t.endsWith("┐")}function mi(e){const t=String(e||"").trim();return t.startsWith("└")&&t.endsWith("┘")}function aw(e){const t=String(e||"").trim();return t.startsWith("├")&&t.endsWith("┤")}function rn(e){const t=String(e||"").trim();return t.startsWith("│")&&t.endsWith("│")}function ow(e){const t=String(mt(e)||"").trim();return Un(t)?t.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function lw(e){if(e?.kind==="runs"&&Array.isArray(e.runs)&&e.runs.length>=3)return String(e.runs[1]?.text||"").replace(/\s+$/u,"");const t=mt(e);return rn(t)?String(t).slice(1,-1).replace(/\s+$/u,""):String(t||"")}function cw(e=[]){const t=(e||[]).map(s=>({...s}));return t.length===0?t:(t[0].text=String(t[0].text||"").replace(/^\s+/,""),t[t.length-1].text=String(t[t.length-1].text||"").replace(/\s+$/,""),t.filter((s,n)=>String(s.text||"").length>0||t.length===1||n===0))}function lc(e,{fallbackColor:t=null}={}){return e?.kind==="runs"&&Array.isArray(e.runs)&&e.runs.length>=3?cw(e.runs.slice(1,-1)):[{text:mt(e).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:t}]}function dw(e){const t=String(e||"").trim();return rn(t)?t.slice(1,-1).split("│").map(s=>s.trim()):[]}function uw(e="",t=""){const s=String(e||"").trimEnd(),n=String(t||"").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 pw(e=[]){const t=(Array.isArray(e)?e:[e]).map(s=>String(s||"").trim()).filter(Boolean);return t.length===0?"":t.slice(1).reduce((s,n)=>uw(s,n)?`${s}${n}`:`${s} ${n}`,t[0])}function cc(e=[]){const t=Math.max(0,...e.map(s=>s.length));return Array.from({length:t},(s,n)=>pw(e.map(r=>String(r[n]||"").trim()).filter(Boolean)))}function rp(e=[]){const t=[];for(let s=0;s<e.length;){const n=e[s];if(n?.kind==="nativeTasks"){t.push({type:"nativeTasks",group:n.group}),s+=1;continue}if(n?.kind==="chatCall"||n?.callPreview!==void 0){const i=[];for(;s<e.length;){const o=e[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}t.push({type:"chatCallGroup",groupKey:i[0]?.callKey,calls:i});continue}if(n?.kind==="assistantPreview"){t.push({type:"assistantPreview",line:n}),s+=1;continue}if(n?.preserve){const i=n.splashVariant||null,o=[];for(;s<e.length&&e[s]?.preserve&&(e[s].splashVariant||null)===i;)o.push(e[s]),s+=1;t.push({type:"preserve",lines:o,splashVariant:i});continue}if(n?.kind==="cardStart"){const i=[];for(s+=1;s<e.length&&e[s]?.kind!=="cardEnd";)i.push(e[s]),s+=1;s<e.length&&(s+=1),s<e.length&&mt(e[s]).trim().length===0&&(s+=1),t.push({type:"card",cardKey:n.cardKey||null,headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:rp(i)});continue}if(n?.kind==="imageAttachments"){t.push({type:"imageAttachments",sessionId:n.sessionId||null,attachments:Array.isArray(n.attachments)?n.attachments:[]}),s+=1;continue}if(n?.kind==="markdownTable"){t.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=mt(n);if(Un(r)&&r.includes("┬")){const i=[],o=[];let l=[],c=!0;for(s+=1;s<e.length;){const d=e[s],u=mt(d);if(mi(u)){if(l.length>0){const p=cc(l);p.length>0&&(c?i.push(p):o.push(p))}s+=1;break}if(aw(u)){if(l.length>0){const p=cc(l);p.length>0&&(c?i.push(p):o.push(p))}l=[],c=!1,s+=1;continue}if(rn(u)){const p=dw(u);p.length>0&&l.push(p)}s+=1}t.push({type:"table",headerRows:i,bodyRows:o});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&Un(r)){const i=ow(n),o=[];for(s+=1;s<e.length;){const l=e[s],c=mt(l);if(mi(c)){s+=1;break}rn(c)?o.push(lw(l)):o.push(mt(l)),s+=1}s<e.length&&mt(e[s]).trim().length===0&&(s+=1),t.push({type:"code",language:i||"text",content:o.join(`
106
- `)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&Un(r)){const i=lc(n),o=n.runs[0]?.color||"gray",l=[];for(s+=1;s<e.length;){const c=e[s],d=mt(c);if(mi(d)){s+=1;break}rn(d)?l.push(lc(c)):l.push(c?.kind==="runs"?c.runs:[{text:mt(c),color:c?.color||null}]),s+=1}s<e.length&&mt(e[s]).trim().length===0&&(s+=1),t.push({type:"card",headerRuns:i,bodyLines:l,borderColor:o});continue}t.push({type:"line",line:n}),s+=1}return t}function ip({lines:e,theme:t,controller:s=null}){const n=a.useMemo(()=>rp((e||[]).filter(r=>!r?.canvasUpdate)),[e]);return a.createElement(op,{blocks:n,theme:t,controller:s})}const _t=new Map,mw=60;function ap(e,t,s){const n=`${t}/${s}`,r=_t.get(n);if(r)return _t.delete(n),_t.set(n,r),r;const i=e?.transport?.api?.downloadArtifactResponse;if(typeof i!="function")return Promise.reject(new Error("artifact download unavailable"));const o=i.call(e.transport.api,t,s).then(async l=>{if(!l?.ok)throw new Error(`download failed (${l?.status})`);const c=await l.blob(),d=_v(s),u=d&&!Ka.test(c.type)?new Blob([c],{type:d}):c;return URL.createObjectURL(u)}).catch(l=>{throw _t.get(n)===o&&_t.delete(n),l});for(_t.set(n,o);_t.size>mw;){const[l,c]=_t.entries().next().value;_t.delete(l),Promise.resolve(c).then(d=>URL.revokeObjectURL(d)).catch(()=>{})}return o}function fw({controller:e,sessionId:t,attachments:s}){const[n,r]=a.useState({});return a.useEffect(()=>{if(!e||!t)return;let i=!1;for(const o of s){const l=o?.filename;l&&ap(e,t,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}},[e,t,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 hw=a.memo(function({content:t,width:s,theme:n,controller:r}){const i=a.useMemo(()=>rt(ds(t,{width:s,tableMode:"sentinel"})),[t,s]);return a.createElement(ip,{lines:i,theme:n,controller:r})}),gw=a.memo(function({line:t,theme:s,controller:n}){const[r,i]=a.useState(t.text==="Agent update"),[o,l]=a.useState(!t.liveStartedAt||Date.now()-t.liveStartedAt>=200),c=a.useRef(null),d=a.useRef(null),u=a.useRef(!0),p=a.useRef(null),m=r||t.final;a.useLayoutEffect(()=>{t.text==="Agent update"&&i(!0)},[t.text]),m&&(p.current=t);const f=p.current;return a.useEffect(()=>{if(t.final||o)return;const h=setTimeout(()=>l(!0),Math.max(0,Math.min(200,200-(Date.now()-t.liveStartedAt))));return()=>clearTimeout(h)},[t.final,t.liveStartedAt,o]),a.useLayoutEffect(()=>{if(!m||t.final)return;const h=()=>{const b=c.current;b&&t.isLive&&u.current&&(b.scrollTop=b.scrollHeight)};h();const g=new ResizeObserver(h);return d.current&&g.observe(d.current),()=>g.disconnect()},[m,t.final,t.isLive,f]),!t.final&&!o?null:a.createElement("details",{className:`ps-system-notice ps-assistant-preview${t.final?" is-final":""}`,open:m,onToggle:h=>{h.target===h.currentTarget&&!t.final&&i(h.currentTarget.open)}},a.createElement("summary",{className:"ps-system-notice-summary ps-canvas-action-summary",tabIndex:t.final?-1:void 0,onClick:h=>{t.final&&h.preventDefault()}},t.final?a.createElement(Je,{runs:t.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"},t.text),t.statusText?a.createElement("span",{className:"ps-preview-status"},t.statusText):null)),a.createElement("div",{ref:c,className:"ps-assistant-preview-viewport",tabIndex:m&&!t.final?0:void 0,role:t.final?void 0:"region","aria-label":t.final?void 0:t.text,onScroll:h=>{t.final||(h.stopPropagation(),u.current=za(h.currentTarget)<=24)},onWheel:h=>{t.final||(h.stopPropagation(),h.deltaY<0&&(u.current=!1))},onTouchStart:h=>{t.final||(h.stopPropagation(),u.current=!1)},onTouchMove:h=>{t.final||h.stopPropagation()},onTouchEnd:h=>{t.final||h.stopPropagation()},onKeyDown:h=>{!t.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(Uu,{key:"reasoning",line:{text:t.isLive?"Thinking":"Thought",body:f.reasoningText,streamReasoning:!0},theme:s}):null,f?.body?a.createElement(hw,{key:"message",content:f.body,width:f.width,theme:s,controller:n}):null,f?.truncated&&t.isLive?a.createElement("div",{className:"ps-preview-status"},"Preview paused — the full answer will appear when complete."):null)))});function op({blocks:e,theme:t,controller:s=null}){return a.createElement(a.Fragment,null,(e||[]).map((n,r)=>{if(n.type==="nativeTasks")return a.createElement(GS,{key:n.group.id,group:n.group,colors:{starting:je(t,"cyan"),running:je(t,"cyan"),waiting:je(t,"yellow"),completed:je(t,"green"),failed:je(t,"red"),cancelled:je(t,"gray"),interrupted:je(t,"yellow")}});if(n.type==="chatCallGroup")return a.createElement(xv,{key:n.groupKey,calls:n.calls});if(n.type==="assistantPreview")return a.createElement(gw,{key:n.line.previewKey,line:n.line,theme:t,controller:s});if(n.type==="imageAttachments")return a.createElement(fw,{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(ct,{key:`preserve:${r}:${l}`,line:o,theme:t,className:"ps-line-preserve"})))}if(n.type==="code"){const i=Yu(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?Qa(n.content||"",t):Bs(n.content||"",n.language,t))));return Xu(n.language)?a.createElement(Qu,{key:`code:${r}`,code:n.content||"",theme:t,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":je(t,n.borderColor)||"var(--ps-border)"}},a.createElement("header",{className:"ps-chat-card-header"},a.createElement(Je,{runs:n.headerRuns,theme:t})),a.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?a.createElement(op,{blocks:n.blocks,theme:t,controller:s}):(n.bodyLines||[]).map((i,o)=>a.createElement("div",{key:`card:${r}:line:${o}`,className:"ps-chat-card-line"},a.createElement(Je,{runs:i,theme:t})))));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?Au([...i,...o]):null,u=!!d,p=d?d.flexIndex:-1,m=b=>b===p?"is-flex-column":null,f=Zu(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},(v,S)=>a.createElement("th",{key:`th:${y}:${S}`,className:m(S)||void 0},Tt(b[S]||"",t,`chat-table:${r}:head:${y}:${S}`)))))):null,a.createElement("tbody",null,o.map((b,y)=>a.createElement("tr",{key:`tbody:${y}`},Array.from({length:l},(v,S)=>a.createElement("td",{key:`td:${y}:${S}`,className:m(S)||void 0,"data-label":f[S]||void 0},a.createElement("span",{className:"ps-table-cell-value"},Tt(b[S]||"",t,`chat-table:${r}:${y}:${S}`)))))))))}return a.createElement(ct,{key:`line:${r}`,line:n.line,theme:t})}))}function Yt({title:e,titleRight:t=null,color:s="gray",focused:n=!1,actions:r=null,children:i,theme:o,className:l=""}){const c=je(o,s),d=!!((Array.isArray(e)?e.length>0:String(e??"").trim())||t||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(e)?a.createElement(Je,{runs:e,theme:o}):Zl(e)),t||r?a.createElement("div",{className:"ps-panel-header-right"},t?a.createElement("div",{className:"ps-panel-title-right"},Array.isArray(t)?a.createElement(Je,{runs:t,theme:o}):Zl(t)):null,r?a.createElement("div",{className:"ps-panel-actions"},r):null):null):null,a.createElement("div",{className:"ps-panel-body"},i))}function yw({lines:e,theme:t,controller:s}){return a.createElement("div",{className:"ps-nodemap"},(e||[]).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(Je,{runs:i,theme:t});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 bw({lines:e,theme:t,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&&QS.has(f.toLowerCase())?m.length-2:m.length-1;return m[Math.max(0,h)]||m[0]||"unknown"};return a.createElement(a.Fragment,null,e.map((u,p)=>{const m=u?.kind==="runs"&&Array.isArray(u.runs)?u.runs.find(T=>T?.completedTurn!=null)?.completedTurn:null,f=m!=null?s.get(Number(m)):null;if(!f)return a.createElement(ct,{key:`line:${p}`,line:u,theme:t});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)",v=d(h.model),S=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)}`,I=[["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(([,T])=>T!=null&&T!=="");return a.createElement(a.Fragment,{key:`seq:${p}`},a.createElement(ct,{line:u,theme:t}),a.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>i(g)},a.createElement("span",{className:"ps-sequence-turn-caret"},b?"v":">"),a.createElement("span",{className:"ps-sequence-turn-rule"},"--- "),a.createElement("span",{className:"ps-sequence-turn-key"},"Mod: "),a.createElement("span",{className:"ps-sequence-turn-model"},v),a.createElement("span",{className:"ps-sequence-turn-rule"}," ("),a.createElement("span",{className:"ps-sequence-turn-key"},"tok: "),a.createElement("span",{className:"ps-sequence-turn-tokens"},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"},S),a.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),b?a.createElement("div",{className:"ps-sequence-turn-details"},I.map(([T,C])=>a.createElement("div",{key:T},a.createElement("span",{className:"ps-sequence-turn-detail-label"},`${T}: `),a.createElement("span",null,String(C))))):null)}))}const Sw={chat:"chat",activity:"activity",inspector:"inspector",filePreview:"inspector"};function Ja(e,t=null){return t||Sw[String(e||"")]||null}function Ar({title:e,titleRight:t=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:v=!1,historyPullEnabled:S=!1,historySessionId:w=null,renderBody:E=null,focusRegion:I=null,panelRef:T=null,ariaLive:C=null}){const k=ee(m,Q=>Q.ui.themeId),O=Pt(k),N=a.useRef(null),R=a.useCallback(Q=>{N.current=Q,typeof T=="function"?T(Q):T&&(T.current=Q)},[T]),H=a.useRef(null),x=a.useRef(!1),{normalizedLines:P,onScroll:_,onTouchStart:$,onTouchEnd:B,onTouchCancel:j,topPullDistance:W,loadingOlderHistory:A}=Iv(N,i,d,u,p,m,{stickyBottom:v,historyPullEnabled:S,historySessionId:w}),G=a.useMemo(()=>rt(o),[o]),D=a.useMemo(()=>rt(l),[l]),Y=f.includes("is-preserve")&&h.includes("has-preserved-sticky"),J=`${p}:${e}`;a.useEffect(()=>{const Q=()=>{N.current&&(N.current.scrollLeft=0),H.current&&(H.current.scrollLeft=0)};Q();const ce=typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{Q()}):null;return()=>{ce!=null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(ce)}},[J]);const te=a.useCallback(()=>{const Q=Ja(p,I);Q&&m?.setFocus&&m.setFocus(Q)},[m,p,I]),Z=a.useCallback((Q,ce)=>{!Q||!ce||Math.abs((ce.scrollLeft||0)-(Q.scrollLeft||0))<=1||(x.current=!0,ce.scrollLeft=Q.scrollLeft,window.requestAnimationFrame(()=>{x.current=!1}))},[]),[ne,ae]=a.useState({up:!1,down:!1}),oe=a.useCallback(Q=>{if(!Q)return;const ce=Q.scrollHeight-Q.scrollTop-Q.clientHeight>4,ge=Q.scrollTop>4;ae(Qe=>Qe.up===ce&&Qe.down===ge?Qe:{up:ce,down:ge})},[]),ve=a.useCallback(Q=>{_(),oe(Q.currentTarget),!(!Y||x.current)&&Z(Q.currentTarget,H.current)},[_,Y,Z,oe]);a.useEffect(()=>{oe(N.current)},[oe,P,D,G]),a.useEffect(()=>{const Q=N.current;if(!Q||typeof ResizeObserver>"u")return;const ce=new ResizeObserver(()=>oe(Q));return ce.observe(Q),()=>ce.disconnect()},[oe,N]);const be=a.useCallback(Q=>{!Y||x.current||Z(Q.currentTarget,N.current)},[Y,Z]);return a.createElement(Yt,{title:e,titleRight:t,color:s,focused:n,actions:r,theme:O,className:h},typeof g=="function"?g({topPullDistance:W,loadingOlderHistory:A}):g,G.length>0?a.createElement("div",{ref:H,className:`ps-panel-sticky${Y?" is-scroll-sync":""}`,onScroll:be},G.map((Q,ce)=>a.createElement(ct,{key:`sticky:${ce}`,line:Q,theme:O}))):null,a.createElement("div",{ref:R,className:`ps-scroll-panel ${f}${ne.down?" is-scrolled-down":""}${ne.up?" is-scrolled-up":""}`.trim(),"data-session-scroll":I==="sessions"?"1":void 0,"aria-live":C||void 0,"aria-atomic":C?"false":void 0,onScroll:ve,onMouseDown:te,onTouchStart:$,onTouchEnd:B,onTouchCancel:j},typeof E=="function"?E(P,O):y?a.createElement(ip,{lines:P,theme:O,controller:m}):P.map((Q,ce)=>a.createElement(ct,{key:`line:${ce}`,line:Q,theme:O}))),D.length>0||c?a.createElement("div",{className:`ps-panel-bottom-sticky${c?" is-reserved":""}`},D.map((Q,ce)=>a.createElement(ct,{key:`bottom-sticky:${ce}`,line:Q,theme:O}))):null,b)}const fi="—";function vw(e,t){const s=typeof e?.waitReason=="string"&&e.waitReason.trim()?kw(e.waitReason):null;if(!s)return null;const n=String(t||"");return n==="waiting"||n.startsWith("waiting on")||n==="input_required"?s:null}const ww=10,Ew=72;function kw(e,t=ww,s=Ew){const n=String(e??"").replace(/\s+/gu," ").trim();if(!n)return"";let i=n.split(" ").slice(0,t).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 Iw(e){return e?.cronActive===!0?"On wake":"Waiting"}function xw({session:e,childCount:t=0,pause:s=null,controller:n=null,collapsed:r=!1,onToggle:i=null,onOpenBudget:o=null}){const l=(S,w,E="")=>{const I=w==null||w===""?fi:String(w),T=I===fi;return a.createElement("div",{className:`ps-session-detail-field${E?` ${E}`:""}${T?" is-none":""}`,key:S},a.createElement("span",{className:"ps-session-detail-label"},S),a.createElement("span",{className:"ps-session-detail-value",title:I},I))},c=e?.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?`${se(c.currentTokens)} / ${se(c.tokenLimit)} · ${u}%`:null;let m=null;e&&!e.isGroup&&(m="off",e.cronActive===!0&&(m=e.cronKind==="wall-clock"?`next ${tr(e.cronNextFireAt)}`:typeof e.cronInterval=="number"?`every ${as(e.cronInterval)}`:"on"));const f=e?.model?e.reasoningEffort&&!String(e.model).includes(String(e.reasoningEffort))?`${e.model}:${e.reasoningEffort}`:e.model:null,h=e?e.visibility==="shared_write"?"shared · write":e.visibility==="shared_read"?"shared · read":"private":null,g=e?.isGroup?e.memberCount==null?null:String(e.memberCount):t>0?String(t):null,b=dh(e),y=vw(e,b?.status),v=!s&&!y?null:a.createElement("div",{className:`ps-session-detail-pause${s?" is-paused":""}`},a.createElement("span",{className:"ps-session-detail-label"},s?"Paused":Iw(e)),a.createElement("span",{className:"ps-session-detail-why",...!s&&typeof e?.waitReason=="string"&&e.waitReason.trim()?{title:e.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||(S=>n.openBudget(S)))(s.provider?{provider:s.provider}:{}).catch(()=>{})},s.provider?`Open ${s.provider}`:"Open providers and budgets"):null));if(r){const S=[];return p&&S.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&&S.push(a.createElement("span",{key:"updated",className:"ps-session-detail-mark"},`${b.relative} (${b.status})`)),(s||y)&&S.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"},e?.title||fi),a.createElement("span",{className:"ps-session-detail-marks"},S)),v)}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",e?.title,"is-title"),l("ID",e?.sessionId,"is-id"),l("Owner",e?.owner?Z0(e.owner):null),l("Model",f),l("Context",p,u!=null&&u>=85?"is-hot":u!=null&&u>=70?"is-warm":""),l("Cron",m,e?.cronActive===!0?"is-armed":""),l("Agent",e?.agentId),l("Updated",b?`${b.relative} (${b.status})`:null),l("Children",g),l("Access",h),v)}function lp(e){const t=()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(e).matches:!1,[s,n]=a.useState(t);return a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),i=o=>n(o.matches);return n(r.matches),r.addEventListener?.("change",i),()=>r.removeEventListener?.("change",i)},[e]),s}function Aw(){return lp("(pointer: coarse)")}const cp=13,dp=11,up=1.5,Nw=7;function Cw(e){return cp+(e-1)*dp+up/2-Nw/2}const Tw=a.memo(function({row:t,theme:s,structuredRows:n,mobile:r,onRowClick:i,setRef:o,drag:l}){const c=Math.max(0,t.depth),d=a.useMemo(()=>{if(c<1)return;const v=Array.from({length:c},(S,w)=>w);return{backgroundImage:v.map(()=>"linear-gradient(var(--ps-rail), var(--ps-rail))").join(", "),backgroundSize:v.map(()=>`${up}px 100%`).join(", "),backgroundPosition:v.map(S=>`${cp+S*dp}px 0`).join(", "),backgroundRepeat:"no-repeat"}},[c]),u=a.useCallback(v=>o(t.sessionId,v),[o,t.sessionId]),p=a.useCallback(v=>i(v,t),[i,t]),m=t.groupId||null,f=!!(l?.dragging&&l.overGroupId&&m===l.overGroupId),h=f&&!!t.isGroup,g=!!(l?.dragging&&l.insertBeforeId===t.sessionId),b=!!(l?.dragging&&l.insertAfterId&&l.insertAfterId===t.sessionId),y=a.useCallback(v=>{if(l?.onPointerDown&&v.button===0){if(v.currentTarget?.setPointerCapture&&v.pointerId!=null)try{v.currentTarget.setPointerCapture(v.pointerId)}catch{}l.onPointerDown(v,t)}},[l,t]);return a.createElement("button",{type:"button",ref:u,className:`ps-list-button ps-session-list-button${t.active?" is-selected":""}${t.selected?" is-multiselected":""}${t.pinned?" is-pinned":""}${f?" is-drop-zone":""}${h?" is-drop-target":""}${g?" is-insert-before":""}${b?" is-insert-after":""}${t.depth>0?" is-nested":""}`,style:d,tabIndex:t.active?0:-1,"aria-selected":t.active?"true":"false","data-session-id":t.sessionId,"data-group-row":t.isGroup?"1":void 0,"data-group-id":t.isGroup?t.groupId||"":void 0,"data-drop-group":m||void 0,"data-order-container":t.orderContainer??void 0,"data-orderable":t.orderable?"1":void 0,onPointerDown:y,onClick:p,onContextMenu:v=>{v.ctrlKey&&(v.preventDefault(),i(v,t))}},a.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:c>0?`${Cw(c)}px`:"0px"}},a.createElement(Pw,{row:t,theme:s,structured:n,showInlineDetail:r})))});function dc(e,t){if(!Array.isArray(e))return{statusColor:null,rest:e};let s=null;const n=[];for(const r of e)if(r?.role!=="depth"&&r?.role!=="selection"){if(r?.role==="status"){s=je(t,r.color)||null;continue}n.push(r)}return{statusColor:s,rest:n}}function uc({color:e,node:t=!1}){return a.createElement("span",{className:`ps-session-status-dot${t?" is-node":""}`,style:e?t?{borderColor:e}:{background:e}:void 0})}function Yi({badge:e,size:t="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]),!e)return null;const o=e.isMine?`${e.name} (you)`:e.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-${t}${e.isMine?" is-mine":""}`,"data-owner-hue":String(e.hue??0),"aria-label":o,onMouseEnter:l,onMouseLeave:c,onFocus:l,onBlur:c},e.initials),s&&typeof document<"u"?Hs.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 pc(e){return Array.isArray(e)?e.filter(t=>!t?.ownerChip):e}function Pw({row:e,theme:t,structured:s=!1,showInlineDetail:n=!1}){if(!(s&&Array.isArray(e.titleRuns))){if(!Array.isArray(e.runs))return e.text;const f=dc(pc(e.runs),t);return a.createElement(a.Fragment,null,f.statusColor?a.createElement(uc,{color:f.statusColor,node:e.depth>0}):null,a.createElement(Yi,{badge:e.ownerBadge}),a.createElement(Sc,{mark:e.canvasMark}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(Je,{runs:f.rest,theme:t})))}const i=pc(e.titleRuns),o=dc(i.filter(f=>f?.role!=="collapseBadge"),t),l=i.filter(f=>f?.role==="collapseBadge"),c=l.length>0,d=Array.isArray(e.ctxRuns)?e.ctxRuns:[],u=d.length>0,p=Array.isArray(e.detailRuns)?e.detailRuns:Array.isArray(e.selectedMetaRuns)?e.selectedMetaRuns:[],m=n&&e.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(uc,{color:o.statusColor,node:e.depth>0}):null,a.createElement(Yi,{badge:e.ownerBadge}),a.createElement(Sc,{mark:e.canvasMark}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(Je,{runs:o.rest,theme:t}))),c?a.createElement("div",{className:"ps-session-row-badge"},a.createElement(Je,{runs:l,theme:t})):null,u?a.createElement("div",{className:"ps-session-row-ctx"},a.createElement(Je,{runs:d,theme:t})):null),m?a.createElement("div",{className:"ps-session-row-detail"},a.createElement(Je,{runs:p,theme:t})):null)}function Mw(e){const t=a.useRef(e),s=a.useRef(null),n=a.useMemo(()=>{try{return JSON.stringify(e)}catch{return null}},[e]);return(n===null||s.current!==n)&&(s.current=n,t.current=e),t.current}const mc=10,_w=1.6;function $w(e,t){return Math.abs(e)<mc&&Math.abs(t)<mc?null:Math.abs(e)>Math.abs(t)*_w?"x":"y"}function Rw(e,t=!0){a.useEffect(()=>{const s=e.current;if(!s||!t)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,v=b.clientY-r;if(l===null){const E=d("y");if(!E&&!d("x")){l="done";return}if(E&&g.cancelable&&g.preventDefault(),l=$w(y,v),l===null)return;if(!d(l)||!g.cancelable){l="done";return}i=b.clientX,o=b.clientY,c=!0}g.cancelable&&g.preventDefault();const S=b.clientX-i,w=b.clientY-o;l==="x"?s.scrollLeft-=S: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)}},[e,t])}const Lw=a.memo(function({query:t="",onQuery:s,matchCount:n=0,mobile:r=!1,expanded:i=!1,onOpen:o,onClose:l,triggerRef:c,listRef:d=null}){const[u,p]=a.useState(t),m=a.useRef(null),f=a.useRef(t),h=a.useRef(!1),g=a.useRef(s);g.current=s;const b=()=>{clearTimeout(m.current),m.current=null},y=I=>{b(),f.current=I,g.current?.(I)},v=I=>{b(),h.current||(m.current=setTimeout(()=>y(I),150))};a.useEffect(()=>()=>clearTimeout(m.current),[]),a.useEffect(()=>{t!==f.current&&(b(),f.current=t,p(t))},[t]);const S=a.useRef(null),w=()=>{u||t?(p(""),y("")):l?.()},E=u!==t?"Searching…":u?`${n} ${n===1?"match":"matches"}`:"";return a.createElement("div",{className:`ps-session-search${i?" is-open":""}`,"data-session-search":"true"},r?a.createElement("button",{type:"button",className:"ps-session-search-trigger",ref:c,"aria-expanded":i,"aria-label":"Search sessions",title:"Search sessions",onClick:o},a.createElement(hc)):null,a.createElement("div",{className:"ps-session-search-fields"},a.createElement(hc),a.createElement("input",{ref:S,type:"text",inputMode:"search","aria-label":"Find a session",placeholder:"Find a session…",value:u,onChange:I=>{const T=I.target.value;p(T),v(T)},onCompositionStart:()=>{h.current=!0,b()},onCompositionEnd:I=>{h.current=!1,v(I.currentTarget.value)},onKeyDown:I=>{if(I.key==="Escape"){I.preventDefault(),w();return}I.key==="ArrowDown"&&(I.preventDefault(),u!==t&&y(u),requestAnimationFrame(()=>d?.current?.querySelector?.(".ps-session-list-button")?.focus({preventScroll:!0})))}}),E?a.createElement("span",{className:"ps-session-search-count",role:"status","aria-live":"polite"},E):null,u?a.createElement("button",{type:"button",className:"ps-session-search-clear","aria-label":u?"Clear session search":"Close session search",title:u?"Clear":"Close",onClick:w},"×"):null))}),Ow=Object.freeze([]);function Xi({controller:e,actions:t=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=lp("(max-width: 920px)"),[m,f]=a.useState(!1),h=p&&m,g=a.useRef(null),b=a.useRef(null),y=a.useRef(null),v=Aw(),S=u||v;Rw(y,S);const w=ee(e,U=>U.ui.themeId),E=Pt(w),I=ee(e,U=>!!U.ui.sessionDetailCollapsed),T=a.useRef(new Map),C=ee(e,U=>({branding:U.branding,activeSessionId:U.sessions.activeSessionId,sessionsById:U.sessions.byId,sessionsFlat:U.sessions.flat,filterQuery:U.sessions.filterQuery||"",ownerFilter:U.sessions.ownerFilter,pinnedIds:U.sessions.pinnedIds,manualOrder:U.sessions.manualOrder,sortMode:U.sessions.sortMode,sortSnapshot:U.sessions.sortSnapshot,selectedIds:U.sessions.selectedIds,selectMode:U.sessions.selectMode,auth:U.auth,connectionMode:U.connection?.mode||"local",modalOpen:!!U.ui.modal,focused:U.ui.focusRegion==="sessions",listDeselected:!!U.sessions.listDeselected,canvasBySessionId:U.canvas?.bySessionId,canvasPrefs:U.canvas?.prefs,budgetPaused:U.budget?.paused}),Ve),k=i?{...C,activeSessionId:i.sessionId,filterQuery:i.query||"",selectedIds:Ow,selectMode:!1,focused:!0,listDeselected:!i.sessionId}:C,O=a.useMemo(()=>us({sessions:{activeSessionId:k.activeSessionId,byId:k.sessionsById,flat:k.sessionsFlat,filterQuery:k.filterQuery,ownerFilter:k.ownerFilter,pinnedIds:k.pinnedIds,manualOrder:k.manualOrder,sortMode:k.sortMode,sortSnapshot:k.sortSnapshot,selectedIds:k.selectedIds,selectMode:k.selectMode,listDeselected:k.listDeselected},auth:k.auth,connection:{mode:k.connectionMode},branding:k.branding,canvas:{bySessionId:k.canvasBySessionId,prefs:k.canvasPrefs},budget:{paused:k.budgetPaused}}),[k.activeSessionId,k.auth,k.branding,k.budgetPaused,k.canvasBySessionId,k.canvasPrefs,k.connectionMode,k.filterQuery,k.listDeselected,k.ownerFilter,k.pinnedIds,k.manualOrder,k.sortMode,k.sortSnapshot,k.selectedIds,k.selectMode,k.sessionsById,k.sessionsFlat]),N=Mw(O),R=a.useRef({top:0,left:0,restore:!1}),H=a.useRef(null);H.current={query:k.filterQuery,setQuery:i?i.onQuery:U=>e.setSessionFilterQuery(U)};const x=a.useCallback(U=>{const q=String(U||""),le=String(H.current?.query||""),he=y.current;!le.trim()&&q.trim()&&he?R.current={top:he.scrollTop,left:he.scrollLeft,restore:!1}:le.trim()&&!q.trim()&&(R.current.restore=!0),H.current?.setQuery?.(q)},[]),P=a.useCallback(()=>{f(!1),x(""),requestAnimationFrame(()=>b.current?.focus({preventScroll:!0}))},[x]);a.useLayoutEffect(()=>{const U=g.current;if(!h||!U)return;const q=window.visualViewport,le=()=>{U.style.top=`${(q?.offsetTop||0)+8}px`,U.style.left=`${(q?.offsetLeft||0)+8}px`,U.style.width=`${(q?.width||window.innerWidth)-16}px`,U.style.height=`${(q?.height||window.innerHeight)-16}px`};return le(),U.showModal(),U.querySelector("input")?.focus({preventScroll:!0}),q?.addEventListener("resize",le),q?.addEventListener("scroll",le),window.addEventListener("resize",le),()=>{q?.removeEventListener("resize",le),q?.removeEventListener("scroll",le),window.removeEventListener("resize",le),U.close()}},[h]),a.useEffect(()=>{p||f(!1)},[p]),a.useLayoutEffect(()=>{k.filterQuery||!R.current.restore||!y.current||(y.current.scrollTop=R.current.top,y.current.scrollLeft=R.current.left,R.current.restore=!1)},[N,k.filterQuery]);const _=k.filterQuery?N.reduce((U,q)=>U+(q.searchMatch?1:0),0):0,$=k.activeSessionId&&k.sessionsById[k.activeSessionId]||null,B=k.activeSessionId&&N.find(U=>U.sessionId===k.activeSessionId)||null,[j,W]=a.useState(!1),[A,G]=a.useState(null),D=a.useRef(!1),Y=["modelPicker","reasoningEffortPicker","contextTierPicker"],J=ee(e,U=>Y.includes(U.ui.modal?.type));a.useEffect(()=>{!J&&D.current&&(D.current=!1,W(!0))},[J]),a.useEffect(()=>{d?.(j||!!A||J)},[j,A,J,d]);const te=()=>{D.current=!0,W(!1),e.openSwitchModelPicker(()=>{D.current=!1}).then(()=>{!Y.includes(e.getState().ui.modal?.type)&&D.current&&(D.current=!1,W(!0))}).catch(U=>{D.current=!1,W(!0),e.dispatch({type:"ui/status",text:U?.message||String(U)||"Failed to switch model"})})},Z=k.auth?.principal||null,ne=k.auth?.authorization?.role,ae=ne==="admin"||ne==="anonymous",oe=ae&&k.auth?.adminScope!=="cluster",ve=!!($?.owner&&Z&&String($.owner.provider)===String(Z.provider)&&String($.owner.subject)===String(Z.subject)),be=!!($&&!$.isGroup&&($.isSystem?ae:oe||ve)),Q=Array.isArray(k.selectedIds)?k.selectedIds.length:0,ce=Q>1,ge=!!($?.isGroup&&!ce),Qe=!!($&&!$.isSystem&&($.isGroup||!$.parentSessionId&&!$.groupId)),$e=!!($&&Array.isArray(k.pinnedIds)&&k.pinnedIds.includes($.sessionId)),it=!!($?.isGroup&&Number($.memberCount||0)===0),Ye=ce?Array.isArray(k.selectedIds)&&k.selectedIds.some(U=>{const q=k.sessionsById[U];return q&&!q.isSystem&&!q.isGroup}):$?.isGroup?!0:!!$,It=Q>0,V=!!($&&!k.listDeselected&&!$.isSystem&&!$.isGroup&&!$.parentSessionId),me=It?k.selectedIds.filter(U=>{const q=k.sessionsById[U];return q&&!q.isSystem&&!q.isGroup&&!q.parentSessionId}):V?[$.sessionId]:[],Be=`ps-session-pane${s?` ${s}`:""}`,ke=a.useRef(null);ke.current={rows:N,viewState:k,controller:e,selection:i,searchOverlay:h,closeSearch:P};const[de,Re]=a.useState({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),Ie=a.useRef(null),et=a.useRef(null),z=a.useCallback(()=>{et.current!=null&&(cancelAnimationFrame(et.current),et.current=null)},[]),M=a.useCallback(()=>{let U=y.current;for(;U&&U!==document.body;){const q=window.getComputedStyle(U).overflowY;if(/(auto|scroll|overlay)/.test(q)&&U.scrollHeight-U.clientHeight>1)return U;U=U.parentElement}return null},[]),K=a.useCallback((U,q)=>{const ie=M();if(!ie){z();return}const Ce=ie.getBoundingClientRect();let xe=0;if(q<Ce.top+48?xe=-14*Math.min(1,(Ce.top+48-q)/48):q>Ce.bottom-48&&(xe=14*Math.min(1,(q-(Ce.bottom-48))/48)),Ie.current&&(Ie.current.autoScrollStep=xe),!Ie.current){z();return}if(et.current!=null)return;const He=()=>{const tt=Ie.current;if(!tt||!tt.autoScrollStep){z();return}ie.scrollTop+=tt.autoScrollStep,et.current=requestAnimationFrame(He)};et.current=requestAnimationFrame(He)},[M,z]),re=a.useCallback(U=>{const q=Ie.current;if(Ie.current=null,z(),Re({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),!(!U||!q?.started||q.ids.length===0)){if(q.intent==="reorder"){e.dispatch({type:"sessions/reorder",sessionId:q.ids[0],beforeSessionId:q.beforeSessionId});return}q.intent!=="file"&&q.intent!=="unfile"||e.moveSessionsToGroup(q.overGroupId,q.ids).catch(le=>{e.dispatch({type:"ui/status",text:`Move failed: ${le?.message||le}`})})}},[e,z]),ye=a.useCallback((U,q)=>typeof U!="number"||typeof q!="number"?null:(document.elementFromPoint(U,q)?.closest?.("[data-drop-group]")||null)?.getAttribute("data-drop-group")||null,[]),Me=a.useCallback((U,q,le,he)=>{if(typeof U!="number"||typeof q!="number"||le==null)return;const ie=Array.from(document.querySelectorAll(`[data-order-container="${CSS.escape(le)}"][data-orderable="1"]`));if(ie.length===0)return;for(const He of ie){const tt=He.getBoundingClientRect();if(q<tt.top+tt.height/2)return{before:He.getAttribute("data-session-id")||null,after:null}}const xe=ie[ie.length-1]?.getAttribute("data-session-id")||null;return{before:null,after:xe&&xe!==he?xe:null}},[]),We=a.useCallback((U,q,le)=>{const he=ye(U,q);if(le?.isGroup){const He=le.ids.length===1?Me(U,q,le.container,le.ids[0]):void 0;return He===void 0?{kind:"none",overGroupId:null,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:He.before,after:He.after}}const ie=le?.ownGroupId||null;if(he&&he!==ie)return{kind:"file",overGroupId:he,before:void 0,after:null};if(!he&&ie)return{kind:"unfile",overGroupId:null,before:void 0,after:null};const xe=le?.orderable&&le.ids.length===1?Me(U,q,le.container,le.ids[0]):void 0;return xe===void 0?{kind:he?"file":"none",overGroupId:he,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:xe.before,after:xe.after}},[ye,Me]);a.useEffect(()=>{if(!de.dragging)return;const U=ie=>{const Ce=Ie.current;if(!Ce)return;const xe=We(ie.clientX,ie.clientY,Ce);Ce.intent=xe.kind,Ce.overGroupId=xe.overGroupId,Ce.beforeSessionId=xe.before,K(ie.clientX,ie.clientY),document.body.classList.toggle("ps-drop-ok",xe.kind==="file"),Re(He=>({...He,intent:xe.kind,overGroupId:xe.overGroupId,insertBeforeId:xe.before,insertAfterId:xe.after,x:ie.clientX,y:ie.clientY}))},q=ie=>{const Ce=Ie.current;if(Ce&&typeof ie?.clientX=="number"){const xe=We(ie.clientX,ie.clientY,Ce);Ce.intent=xe.kind,Ce.overGroupId=xe.overGroupId,Ce.beforeSessionId=xe.before}re(!0)},le=()=>re(!1),he=ie=>{ie.key==="Escape"&&re(!1)};return window.addEventListener("pointermove",U),window.addEventListener("pointerup",q),window.addEventListener("pointercancel",le),window.addEventListener("keydown",he),document.body.classList.add("ps-dragging-sessions"),()=>{window.removeEventListener("pointermove",U),window.removeEventListener("pointerup",q),window.removeEventListener("pointercancel",le),window.removeEventListener("keydown",he),document.body.classList.remove("ps-dragging-sessions"),document.body.classList.remove("ps-drop-ok")}},[de.dragging,re,We,K]);const at=a.useMemo(()=>({dragging:de.dragging,overGroupId:de.overGroupId,insertBeforeId:de.insertBeforeId,insertAfterId:de.insertAfterId,onPointerDown:(U,q)=>{if(q.isSystem||!q.orderable&&!q.isGroup&&q.depth>0)return;const le=U.clientX,he=U.clientY,ie={row:q,startX:le,startY:he,started:!1,ids:[],overGroupId:null,beforeSessionId:void 0,orderable:!!q.orderable,container:q.orderContainer??null,isGroup:!!q.isGroup,ownGroupId:q.groupId||null,intent:"none",autoScrollStep:0},Ce=He=>{if(ie.started||Math.hypot(He.clientX-le,He.clientY-he)<5)return;ie.started=!0;const tt=ke.current.viewState,Bt=Array.isArray(tt.selectedIds)?tt.selectedIds:[],Xt=Bt.includes(q.sessionId)&&Bt.length>1?Bt:[q.sessionId],Tr=tt.sessionsById||{};ie.ids=Xt,Ie.current=ie,Re({dragging:!0,ids:Xt,titles:Xt.map(yn=>Tr[yn]?.title||String(yn).slice(0,8)).slice(0,3),overGroupId:null,x:He.clientX,y:He.clientY})},xe=()=>{window.removeEventListener("pointermove",Ce),window.removeEventListener("pointerup",xe)};window.addEventListener("pointermove",Ce),window.addEventListener("pointerup",xe)}}),[de.dragging,de.overGroupId,de.insertBeforeId,de.insertAfterId]),qe=a.useCallback((U,q)=>{const{rows:le,viewState:he,controller:ie,selection:Ce}=ke.current;if(ke.current.searchOverlay&&!q.isGroup){Ce?Ce.onSelect(q.sessionId):(ie.setFocus("sessions"),ie.loadSession(q.sessionId).catch(()=>{})),ke.current.closeSearch();return}if(Ce){(q.isGroup||q.hasChildren&&q.active)&&ie.dispatch({type:q.collapsed?"sessions/expand":"sessions/collapse",sessionId:q.sessionId}),q.isGroup||Ce.onSelect(q.sessionId);return}if(U.metaKey||U.ctrlKey){U.preventDefault(),he.selectMode||ie.dispatch({type:"sessions/selectMode",enabled:!0}),ie.dispatch({type:"sessions/selectToggle",sessionId:q.sessionId}),ie.setFocus("sessions");return}if(U.shiftKey&&he.activeSessionId){U.preventDefault();const He=le.map(Xt=>Xt.sessionId),tt=He.indexOf(he.activeSessionId),Bt=He.indexOf(q.sessionId);if(tt>=0&&Bt>=0){const[Xt,Tr]=tt<=Bt?[tt,Bt]:[Bt,tt],yn=He.slice(Xt,Tr+1),Ap=Array.from(new Set([...he.selectedIds||[],...yn]));ie.setSessionSelection(Ap),ie.setFocus("sessions");return}}if(q.hasChildren&&q.active){ie.dispatch({type:q.collapsed?"sessions/expand":"sessions/collapse",sessionId:q.sessionId}),ie.setFocus("sessions");return}he.selectMode&&ie.dispatch({type:"sessions/selectClear"}),ie.setFocus("sessions"),q.sessionId===he.activeSessionId?ie.dispatch({type:"sessions/listReselect"}):q.active||ie.loadSession(q.sessionId).catch(()=>{})},[]),xt=a.useCallback((U,q)=>{U&&(q?T.current.set(U,q):T.current.delete(U))},[]),we=a.useRef(null),ze=`${k.activeSessionId||""}${k.focused?1:0}${k.modalOpen?1:0}`;a.useEffect(()=>{if(k.modalOpen||!k.focused||!k.activeSessionId){we.current=null;return}const U=T.current.get(k.activeSessionId);if(!U||we.current===ze)return;we.current=ze;const q=document.activeElement,le=!!(q&&(q.tagName==="INPUT"||q.tagName==="TEXTAREA"||q.tagName==="SELECT"||q.isContentEditable));k.focused&&q!==U&&!le&&U.focus({preventScroll:!0})},[ze,k.activeSessionId,k.focused,k.modalOpen,k.sessionsFlat]);const At=a.createElement(a.Fragment,null,!o&&ce?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."},`${Q} selected`):null,!o&&(ce?a.createElement(Se,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>e.handleCommand(L.CLEAR_SESSION_SELECTION).catch(()=>{})}):a.createElement(Se,{className:"ps-mini-button ps-pin-icon",icon:a.createElement(s0),onClick:()=>e.handleCommand(L.PIN_SESSION).catch(()=>{}),disabled:!Qe,active:$e,label:Qe?$e?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"})),!o&&a.createElement(Se,{className:"ps-mini-button",icon:me.length>1?a.createElement("span",{className:"ps-icon-badge"},a.createElement(yc),a.createElement("span",{className:"ps-icon-badge__count"},String(me.length))):a.createElement(yc),onClick:()=>e.handleCommand(L.OPEN_MOVE_TO_GROUP).catch(()=>{}),label:me.length>1?`Move ${me.length} selected sessions to a group`:me.length===1?"Move this session to a group":"New group"}),a.createElement(Se,{className:"ps-mini-button",icon:a.createElement(pp),onClick:()=>{if($?.isGroup){e.handleCommand(L.OPEN_RENAME_SESSION).catch(()=>{});return}W(!0)},disabled:!be&&!ge||ce,label:ce?"Disabled while multiple sessions are selected":$?.isSystem?"System sessions are managed by administrators":$?.isGroup?"Rename folder":be?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(Se,{className:"ps-mini-button",icon:a.createElement(t0),onClick:()=>{const U=$?.sessionId;if(!U)return;const q=Ou(U);q&&(or(q),G({url:q,warn:!1}),dv(e,U).then(le=>{G(he=>he&&he.url===q?{...he,warn:le}:he)}).catch(()=>{}))},disabled:!$||$.isGroup||ce,label:"Copy link — copy a direct link to this session"}),a.createElement(Se,{className:"ps-mini-button",icon:a.createElement($?.isSystem?Gw:Qi),onClick:()=>e.handleCommand($?.isGroup?L.DELETE_SESSION:L.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!Ye,label:ce?`Terminate ${Q} selected sessions (Mark Completed, Cancel, or Delete)`:$?.isGroup?it?"Delete this empty group":"This group cannot be deleted yet":$?.isSystem?"Restart this system session (complete, terminate, or hard delete)":"Terminate — mark completed, cancel, or delete this session"}),t),Cr=de.dragging?a.createElement("div",{className:"ps-drag-ghost",style:{left:`${de.x}px`,top:`${de.y}px`}},a.createElement("div",{className:`ps-drag-ghost__stack${de.ids.length>1?" is-collection":""}`},de.ids.length>1?a.createElement("span",{className:"ps-drag-ghost__count"},String(de.ids.length)):null,a.createElement("span",{className:"ps-drag-ghost__title"},de.ids.length>1?`${de.ids.length} sessions`:de.titles[0]||"session")),a.createElement("div",{className:"ps-drag-ghost__hint"},de.intent==="file"?"Release to file here":de.intent==="unfile"?"Release to remove from folder":de.intent==="reorder"?"Release to move here":"Release to cancel")):null,pe=o?l?Hs.createPortal(a.createElement("div",{className:"ps-moa-control-actions",onClick:c},At),l):null:a.createElement(Yt,{title:[{text:h?"Find a session":"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:k.focused,theme:E,actions:h?a.createElement(Se,{label:"Close session search",icon:"×",onClick:P}):i?a.createElement(a.Fragment,null,i.onCreate?a.createElement(Se,{className:"ps-mini-button",icon:a.createElement(mp),label:"Create New Session",onClick:i.onCreate}):null,t):At,className:Be},a.createElement("div",{ref:y,onKeyDown:i?U=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(U.key)||U.altKey||U.ctrlKey||U.metaKey)return;const q=[...y.current.querySelectorAll(".ps-session-list-button")],le=q.indexOf(U.target.closest(".ps-session-list-button")),he=U.key==="Home"?0:U.key==="End"?q.length-1:Math.max(0,Math.min(q.length-1,le+(U.key==="ArrowUp"?-1:1))),ie=q[he];ie&&(U.preventDefault(),U.stopPropagation(),ie.dataset.sessionId&&i.onSelect(ie.dataset.sessionId),ie.focus())}:void 0,className:`ps-action-list ps-session-list${de.dragging?" is-dragging":""}`,onClick:U=>{U.target instanceof Element&&U.target.closest(".ps-session-list-button")||(i?i.onSelect(null):e.dispatch({type:"sessions/listDeselect"}))}},N.length===0?a.createElement("div",{className:"ps-empty-state"},k.filterQuery?`No sessions matched "${k.filterQuery}".`:"No sessions yet."):N.map(U=>a.createElement(Tw,{key:U.sessionId,row:U,theme:E,structuredRows:n,mobile:u,onRowClick:qe,setRef:xt,drag:i||S||k.sortMode!=="saved"?null:at}))),a.createElement("div",{className:"ps-session-find-controls",onPointerDown:U=>{p&&U.button===0&&U.target.closest?.("button")&&U.currentTarget.contains(document.activeElement)&&document.activeElement?.matches("input")&&U.preventDefault()}},a.createElement("div",{className:"ps-session-sort-controls"},a.createElement("div",{className:"ps-session-sort-modes",role:"group","aria-label":"Session sort order"},...[["used","Recently used","M12 8v4l3 2",!0],["updated","Recently updated","M3 12h4l3-7 4 14 3-7h4"],["saved","Saved order","M6 3h12v18l-6-4-6 4Z"]].map(([U,q,le,he])=>a.createElement(Se,{key:U,label:q,className:"ps-session-sort-button",active:(k.sortMode||"saved")===U,pressed:(k.sortMode||"saved")===U,icon:a.createElement("svg",{viewBox:"0 0 24 24",width:18,height:18,fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},he?a.createElement("circle",{cx:12,cy:12,r:9}):null,a.createElement("path",{d:le})),onClick:()=>e.dispatch({type:"sessions/sortMode",mode:U})}))),a.createElement(Se,{label:"Refresh session order",className:"ps-session-sort-refresh",icon:a.createElement("svg",{viewBox:"0 0 24 24",width:18,height:18,fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},a.createElement("path",{d:"M20 7v5h-5M20 12a8 8 0 1 0-2 5M20 7v5"})),onClick:async()=>{try{await e.refreshSessions(),e.dispatch({type:"sessions/refreshSort"})}catch{e.dispatch({type:"ui/status",text:"Could not refresh sessions. Try again."})}}})),a.createElement(Lw,{query:k.filterQuery,onQuery:x,matchCount:_,mobile:p,expanded:h,onOpen:()=>f(!0),onClose:P,triggerRef:b,listRef:y})),!h&&(r===null?!u:r)?a.createElement(xw,{session:$,childCount:B?.childCount||0,pause:B?.pause||null,controller:e,collapsed:I,onToggle:()=>e.dispatch({type:"ui/sessionDetailCollapsed",collapsed:!I})}):null);return a.createElement(a.Fragment,null,Cr,h?null:pe,a.createElement("dialog",{ref:g,className:"ps-session-search-overlay","aria-label":"Find a session",onCancel:U=>{U.preventDefault(),P()},onKeyDownCapture:U=>{U.key==="Escape"&&(U.preventDefault(),U.stopPropagation(),P())},onClick:U=>{U.target===U.currentTarget&&P()}},h?pe:null),j&&$&&!$.isGroup?a.createElement(r0,{controller:e,sessionId:$.sessionId,initialTitle:$.title||"",allowSharing:!o,currentModel:$.model||"",currentReasoningEffort:$.reasoningEffort||"",principal:k.auth?.principal||null,onClose:()=>W(!1),onSwitchModel:te,onChanged:()=>{}}):null,A?a.createElement(Fw,{url:A.url,warn:A.warn,onCopyAgain:()=>{or(A.url),e.dispatch({type:"ui/status",text:ov})},onClose:()=>G(null)}):null)}function Fw({url:e,warn:t,onCopyAgain:s,onClose:n}){const[r,i]=a.useState(""),o=Da(e,kr).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(Fu,{url:e,keyPrefix:"session",copied:r,onCopy:l}),t?a.createElement("div",{className:"ps-link-warn"},cv):null))}const fc={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function De({children:e}){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"},e)}function pp(){return a.createElement(De,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 eo(){return a.createElement(De,null,a.createElement("path",{d:"M21 4H3l7.2 8.5V19l3.6 2v-8.5L21 4z"}))}function hc(){return a.createElement(De,null,a.createElement("circle",{cx:"11",cy:"11",r:"7"}),a.createElement("path",{d:"m20 20-4-4"}))}function mp(){return a.createElement(De,null,a.createElement("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),a.createElement("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))}function Dw(){return a.createElement(De,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 Bw(){return a.createElement(De,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 fp(){return a.createElement(De,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 Hw(){return a.createElement(De,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 Uw(){return a.createElement(De,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 jw(){return a.createElement(De,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 Gw(){return a.createElement(De,null,a.createElement("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"}),a.createElement("path",{d:"M21 3v5h-5"}))}function Ww(){return a.createElement(De,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 hp(){return a.createElement(De,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 qw(){return a.createElement(De,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 zw(){return a.createElement(De,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 gc(){return a.createElement(De,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 Kw(){return a.createElement(De,null,a.createElement("path",{d:"M4 17l6-6-6-6"}),a.createElement("line",{x1:"12",y1:"19",x2:"20",y2:"19"}))}function Vw(){return a.createElement(De,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 Yw="M12 2.3 20.4 7.15v9.7L12 21.7 3.6 16.85V7.15Z",Xw="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",Qw="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 Zw(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":"true"},a.createElement("path",{d:Yw,strokeWidth:"1.9",strokeLinejoin:"round"}),a.createElement("path",{d:Xw,fill:"currentColor",stroke:"none",fillRule:"evenodd"}),a.createElement("path",{d:Qw,fill:"currentColor",stroke:"none"}))}function Jw(){return a.createElement(De,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 e0(){return a.createElement(De,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 t0(){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 Qi(){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 yc(){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 s0(){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 n0(){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 gp(e,t,s){const[n,r]=a.useState({access:null,loading:!1}),i=a.useCallback(()=>{if(!t||s||typeof e.transport.getSessionAccess!="function"){r({access:null,loading:!1});return}let o=!1;return r(l=>({...l,loading:!0})),e.transport.getSessionAccess(t).then(l=>{o||r({access:l,loading:!1})}).catch(()=>{o||r({access:null,loading:!1})}),()=>{o=!0}},[e,t,s]);return a.useEffect(()=>{let o;const l=setTimeout(()=>{o=i()},lv);return()=>{clearTimeout(l),typeof o=="function"&&o()}},[i]),{access:n.access,loading:n.loading,reload:i}}function r0({controller:e,sessionId:t,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([]),[v,S]=a.useState([]),[w,E]=a.useState("private"),[I,T]=a.useState(""),[C,k]=a.useState("write"),[O,N]=a.useState([]),[R,H]=a.useState(!1),[x,P]=a.useState(null);a.useEffect(()=>{let V=!1;return e.transport.getSessionAccess(t).then(me=>{!V&&me&&(f(me),E(me.visibility||"private"))}).catch(()=>{}),d&&typeof e.transport.listKnownUsers=="function"&&e.transport.listKnownUsers({limit:500}).then(me=>{V||N(Array.isArray(me)?me:[])}).catch(()=>{}),()=>{V=!0}},[e,t,d]);const _=a.useCallback(()=>{e.transport.listSessionShares(t).then(V=>{const me=Array.isArray(V)?V:[];y(me),S(me)}).catch(()=>{y([]),S([])})},[e,t]);a.useEffect(()=>{d&&_()},[_,d]);const $=async V=>{H(!0),P(null);try{await V(),c?.()}catch(me){P(me?.message||String(me))}finally{H(!1)}},B=()=>$(async()=>{await e.transport.renameSession(t,h.trim())}),j=V=>{const me=V.trim().toLowerCase();if(!me)return null;const Be=O.find(ke=>ke.displayName&&ke.displayName.toLowerCase()===me||ke.email&&ke.email.toLowerCase()===me||ke.subject&&ke.subject.toLowerCase()===me);return Be||{provider:i?.provider||"dev",subject:V.trim(),email:null,displayName:null}},W=V=>`${V.provider}${V.subject}`,A=V=>{const me=W(V);S(Be=>[...Be.filter(ke=>W(ke)!==me),{provider:V.provider,subject:V.subject,email:V.email??null,displayName:V.displayName??null,access:C}]),T("")},G=()=>{const V=j(I);V&&A(V)},D=V=>{const me=W(V);S(Be=>Be.filter(ke=>W(ke)!==me))},Y=new Set(v.map(W)),J=m?.owner?`${m.owner.provider}${m.owner.subject}`:null,te=I.trim().toLowerCase(),Z=te?O.filter(V=>{const me=W(V);return me===J||Y.has(me)?!1:V.displayName&&V.displayName.toLowerCase().includes(te)||V.email&&V.email.toLowerCase().includes(te)||V.subject&&V.subject.toLowerCase().includes(te)}).slice(0,25):[],ne=!!m?.canManage,ae=m?.visibility||"private",oe=new Set(v.map(V=>`${W(V)}:${V.access}`)),ve=new Set(b.map(V=>`${W(V)}:${V.access}`)),be=oe.size!==ve.size||[...oe].some(V=>!ve.has(V)),Q=ne&&(w!==ae||be),ce=()=>$(async()=>{w!==ae&&await e.transport.setSessionVisibility(t,w);const V=new Map(b.map(de=>[W(de),de])),me=new Map(v.map(de=>[W(de),de]));for(const[de,Re]of me){const Ie=V.get(de);(!Ie||Ie.access!==Re.access)&&await e.transport.grantSessionShare(t,{provider:Re.provider,subject:Re.subject,email:Re.email??null,displayName:Re.displayName??null},Re.access)}for(const[de,Re]of V)me.has(de)||await e.transport.revokeSessionShare(t,{provider:Re.provider,subject:Re.subject});const Be=await e.transport.listSessionShares(t).catch(()=>null);Array.isArray(Be)&&(y(Be),S(Be));const ke=await e.transport.getSessionAccess(t).catch(()=>null);ke&&(f(ke),E(ke.visibility||"private")),e.dispatch({type:"ui/status",text:"Access updated."})}),ge=l||(()=>{o(),e.openSwitchModelPicker().catch(V=>{e.dispatch({type:"ui/status",text:V?.message||String(V)||"Failed to switch model"})})}),Qe=n?r?`${n}:${r}`:n:"—",$e=[{id:"general",label:"General"},...d&&ne?[{id:"access",label:"Access"}]:[]],it=$e.some(V=>V.id===u)?u:"general",Ye=typeof e.transport?.regenerateSession=="function",It=V=>V.stopPropagation();return a.createElement("div",{className:"ps-share-overlay",onClick:o},a.createElement("div",{className:"ps-share-modal",onClick:It},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"},$e.map(V=>a.createElement("button",{key:V.id,type:"button",role:"tab","aria-selected":it===V.id?"true":"false",className:`ps-manage-tab${it===V.id?" is-active":""}`,onClick:()=>p(V.id)},V.label))),a.createElement("div",{className:"ps-share-modal-body"},it==="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:R,onChange:V=>g(V.target.value),onKeyDown:V=>{V.key==="Enter"&&B()}}),a.createElement("button",{className:"ps-mini-button",disabled:R||!h.trim(),onClick:B},"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"},Qe),a.createElement("button",{className:"ps-mini-button",disabled:R,onClick:ge},"Switch model…")),Ye?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:R,onClick:()=>{o(),e.handleCommand(L.REGENERATE_SESSION).catch(()=>{})}},a.createElement(n0),a.createElement("span",null,"Regenerate context…")))):null):null,it==="access"&&ne?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(V=>a.createElement("label",{key:V,className:`ps-share-radio${w===V?" is-active":""}`},a.createElement("input",{type:"radio",name:"visibility",checked:w===V,disabled:R,onChange:()=>E(V)}),a.createElement("span",{className:"ps-share-radio-glyph"},fc[V].glyph),a.createElement("span",null,fc[V].label),a.createElement("span",{className:"ps-share-radio-hint"},V==="private"?"only you and admins":V==="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."),v.length===0?a.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):v.map(V=>a.createElement("div",{key:`${V.provider}/${V.subject}`,className:"ps-share-grant-row"},a.createElement("span",{className:"ps-share-grant-name"},V.displayName||V.subject),a.createElement("span",{className:"ps-share-grant-access"},`can ${V.access}`),a.createElement("button",{className:"ps-mini-button",disabled:R,onClick:()=>D(V)},"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:I,disabled:R,autoComplete:"off",onChange:V=>T(V.target.value),onKeyDown:V=>{V.key==="Enter"&&G()}}),a.createElement("select",{className:"ps-share-add-select",value:C,disabled:R,onChange:V=>k(V.target.value)},a.createElement("option",{value:"read"},"can read"),a.createElement("option",{value:"write"},"can write")),a.createElement("button",{className:"ps-mini-button",disabled:R||!I.trim(),onClick:G},"Add")),Z.length>0?a.createElement("div",{className:"ps-share-suggestions"},Z.map(V=>a.createElement("button",{key:`${V.provider}/${V.subject}`,type:"button",className:"ps-share-suggestion",disabled:R,onClick:()=>A(V)},a.createElement("span",{className:"ps-share-suggestion-name"},V.displayName||V.subject),V.email?a.createElement("span",{className:"ps-share-suggestion-email"},V.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),it==="access"&&ne?a.createElement("div",{className:"ps-manage-apply-bar is-footer"},a.createElement("span",{className:"ps-share-section-sub"},Q?"Unsaved access changes.":"No changes to apply."),a.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:R||!Q,onClick:ce},"Apply")):null,x?a.createElement("div",{className:"ps-share-error"},x):null))}function hE({controller:e,onReadOnlyFocus:t=null,mobile:s=!1,compact:n=!1,autoFocus:r=!s}){const i=ee(e,d=>d.ui.modal),o=ee(e,d=>d.sessions.byId[d.sessions.activeSessionId]),{access:l}=gp(e,o?.sessionId,o?.isGroup),c=o?.serviceKind||l?.canWrite===!1;return a.useLayoutEffect(()=>{c&&!i&&t?.()},[c,i,t]),!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(vp,{controller:e,mobile:s,compact:n,autoFocus:r,active:!0}))}function gE({controller:e}){const t=ee(e,c=>c),s=t.sessions.byId[t.sessions.activeSessionId],n=sa(s?.status==="running"),i=br(t,{spinnerFrame:n,maxWidth:120})[0]?.map(c=>c.text||"").join("")||(s?String(s.status||"idle").replace(/^./,c=>c.toUpperCase()):""),o=Jd(t),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 i0(){return a.createElement(De,null,a.createElement("path",{d:"M12 19V5m-5 5 5-5 5 5"}))}function a0(){return a.createElement(De,null,a.createElement("path",{d:"M20.5 12a8.5 8.5 0 1 1-8.5-8.5"}))}function o0({loading:e,manual:t,pullDistance:s,onManualLoad:n}){const r=s>=$u,i=e?"Loading earlier messages…":t?"Load older messages":r?"Release to load earlier messages":"Pull for earlier messages";return a.createElement("div",{className:`ps-history-load${e?" is-loading":""}${t?" is-manual":""}${r?" is-ready":""}`,style:s>0?{"--ps-history-pull":`${Math.min(s,Ru)}px`}:void 0,role:"status","aria-live":"polite"},a.createElement("span",{className:"ps-history-track","aria-hidden":"true"},a.createElement("span",{className:"ps-history-tick is-first"}),a.createElement("span",{className:"ps-history-tick is-second"}),a.createElement("span",{className:"ps-history-marker"},e?a.createElement(a0):a.createElement(i0),e?a.createElement("span",{className:"ps-history-text-spinner"},["|","/","—","\\"].map((o,l)=>a.createElement("span",{key:l},o))):null)),t&&!e?a.createElement("button",{type:"button",className:"ps-mini-button ps-load-older-button",onClick:n},i):a.createElement("span",{className:"ps-history-label"},i))}function Zi({controller:e,mobile:t=!1,fullWidth:s=!1,showComposer:n=!0,onEnterZen:r=null,activityInHeader:i=!1}){const o=ee(e,$=>$.ui.themeId),l=Pt(o),c=ee(e,$=>{const B=$.sessions.activeSessionId,j=xr($),W=s||t?j.totalWidth:j.leftWidth,A=Math.max(20,W-4);return{activeSessionId:B,activeHistory:B&&$.history.bySessionId.get(B)||null,activeOutbox:B&&$.outbox?.bySessionId?.[B]?$.outbox.bySessionId[B]:pr,branding:$.branding,connection:$.connection,sessionsById:$.sessions.byId,sessionsFlat:$.sessions.flat,inspectorTab:$.ui.inspectorTab,activeSessionIsGroup:!!(B&&$.sessions.byId[B]?.isGroup),activeSessionStatus:B?String($.sessions.byId[B]?.status||"").toLowerCase():"",focused:$.ui.focusRegion==="chat",scroll:$.ui.scroll.chat,followBottom:$.ui.followBottom?.chat!==!1,authPrincipal:$.auth?.principal||null,contentWidth:A}},Ve),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]=Bu(),m=u??c.contentWidth,f=a.useMemo(()=>eu(d,{width:m}),[d,m]),h=_c(!!f.animateTitleRight),g=a.useMemo(()=>$c(f.titleRight,f.animateTitleRight?h:""),[h,f.animateTitleRight,f.titleRight]),[b,y]=a.useState(null),v=!!(c.activeHistory?.hasOlderEvents&&Number(c.activeHistory?.loadedEventCount||0)>=Wi),S=a.useMemo(()=>xa(d,m,{tableMode:"sentinel"}),[d,m]),w=sa(c.activeSessionStatus==="running"),I=a.useMemo(()=>br(d,{spinnerFrame:w,maxWidth:m}),[d,w,m]),T=a.useMemo(()=>Ca(d,m,{tableMode:"sentinel"}),[d,m]),C=a.useMemo(()=>I.length>0?[...T,...I]:T,[T,I]),k=a.useMemo(()=>i&&T.length?[...S,...T]:S,[i,S,T]),{access:O}=gp(e,c.activeSessionId,c.activeSessionIsGroup),N=ee(e,Mh,Ve),R=n&&!c.activeSessionIsGroup,H=!!c.sessionsById?.[c.activeSessionId]?.serviceKind,x=H||!!O&&O.canWrite===!1,P=R?a.createElement("div",{className:"ps-chat-composer"},x?a.createElement("div",{className:"ps-composer-readonly"},H?"⚗ Service session — runtime machinery. Its transcript is a read-only trace; it does not accept messages.":`You have view access to this session. Ask ${O.owner?.displayName||O.owner?.email||"the owner"} for write access to participate.`):a.createElement(vp,{controller:e,mobile:t,active:!0})):null,_=!!(c.activeSessionId&&c.sessionsById[c.activeSessionId]);return N&&!_?a.createElement(Yt,{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:()=>e.setNavigationIntent(N.sessionId)},"Retry"):null)):a.createElement(Ar,{controller:e,title:t?Jl(f.title,28):f.title,titleRight:t&&g?Jl(g,18):g,actions:t&&r?a.createElement(Se,{className:"ps-mini-button",icon:a.createElement(fp),label:"Enter mobile zen",onClick:r}):null,color:f.color,focused:c.focused,lines:k,bottomStickyLines:i?pr:C,reserveBottomSticky:!i,scrollOffset:c.scroll,scrollMode:c.followBottom?"bottom":"top",stickyBottom:!0,paneKey:"chat",historySessionId:c.activeSessionId,historyPullEnabled:!!(c.activeHistory?.hasOlderEvents&&!v),ariaLive:"polite",className:"is-wrapped",panelClassName:"ps-chat-panel",panelRef:p,bottomContent:P,topContent:({topPullDistance:$,loadingOlderHistory:B})=>{const j=B||b===c.activeSessionId;return!v&&$<=0&&!j?null:a.createElement(o0,{loading:j,manual:v,pullDistance:j?0:$,onManualLoad:()=>{const W=c.activeSessionId;y(W),e.handleCommand(L.EXPAND_HISTORY).catch(()=>{}).finally(()=>y(A=>A===W?null:A))}})},structuredBlocks:!0,renderBody:null})}function l0({controller:e,onClose:t}){const s=ee(e,g=>g.ui.themeId),n=Pt(s),r=ee(e,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:e.canStepArtifactPreview(-1),canNext:e.canStepArtifactPreview(1)}},Ve),i=zu(r.filename),o=ee(e,g=>g.files.htmlViewMode||"rendered"),l=ee(e,g=>!!g.files.htmlFitWidth),c=a.useCallback(g=>{e.dispatch({type:"files/htmlFitWidth",enabled:g})},[e]),d=a.useCallback(g=>{e.dispatch({type:"files/htmlViewMode",mode:g})},[e]),u=ee(e,g=>Number(g.files.htmlZoom)||1),p=a.useCallback(g=>{e.dispatch({type:"files/htmlZoom",zoom:g})},[e]),m=a.useCallback(g=>{e.stepArtifactPreview(g).catch(()=>{})},[e]),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(),t())}},[t,m]),h=Er(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(tp,{mode:o,setMode:d}):null,i.kind==="page"&&o==="rendered"?a.createElement(ep,{fitWidth:l,setFitWidth:c}):null,i.kind==="page"&&o==="rendered"?a.createElement(ur,{zoom:u,setZoom:p}):null,a.createElement("span",{className:"ps-artifact-pane-heading"},a.createElement("span",{className:"ps-artifact-pane-name",title:r.filename},Ku(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&&(or(h),e.dispatch({type:"ui/status",text:Lu}))},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:()=>e.handleCommand(L.DOWNLOAD_SELECTED_FILE).catch(()=>{}),title:"Download","aria-label":"Download"},a.createElement(hp)),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn is-close",onClick:t,title:"Close (Esc)","aria-label":"Close artifact"},"✕"))),a.createElement("div",{className:"ps-artifact-pane-body"},a.createElement(Nr,{controller:e,focused:!1,previewOnly:!0,chromeless:!0,theme:n})))}function c0({controller:e,visible:t=!0}){const[s,n]=a.useState(!1),r=a.useCallback(()=>n(i=>!i),[]);return a.useEffect(()=>{t||n(!1)},[t]),a.createElement("div",{className:`ps-mobile-canvas-layer${s?" is-maximized":""}${t?"":" is-hidden"}`,...t?{}:{inert:!0,"aria-hidden":"true"}},a.createElement(bp,{controller:e,mobile:!0,visible:t,focusOnPromote:!0,maximized:s,onToggleMaximized:r}))}function d0({controller:e}){const t=ee(e,o=>{const l=o.files.selectedArtifactId||"";return{filename:l?l.slice(l.indexOf("/")+1):"",origin:o.files.previewOrigin||null,canPrev:e.canStepArtifactPreview(-1),canNext:e.canStepArtifactPreview(1)}},Ve),s=!!Ya(t.filename)||Xa(t.filename),[n,r]=a.useState(!1);a.useEffect(()=>{r(!1)},[t.filename]);const i=a.useCallback(o=>{e.stepArtifactPreview(o).catch(()=>{})},[e]);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:()=>e.closeArtifactPreview().catch(()=>{}),"aria-label":t.origin==="chat"?"Close, back to chat":"Close, back to artifacts"},"✕"),a.createElement("span",{className:"ps-artifact-overlay-title"},t.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:!t.canPrev,onClick:()=>i(-1),"aria-label":"Previous artifact"},"‹"),a.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!t.canNext,onClick:()=>i(1),"aria-label":"Next artifact"},"›")),a.createElement("div",{className:`ps-artifact-overlay-body${n?" is-content-width":""}`},a.createElement(Nr,{controller:e,focused:!0,mobile:!0,previewOnly:!0,nativeScroll:!0})))}const u0=140;function p0(e,t,s,n){let r=e;!e||Math.abs(t-e.width)>2?r={width:t,height:s}:s>e.height&&(r={width:e.width,height:s});const i=s<=r.height-u0;return{baseline:r,takeover:i&&n}}function m0(e,t=".ps-prompt-input"){const[s,n]=a.useState(!1);return a.useEffect(()=>{if(!e||typeof window>"u"||!window.visualViewport){n(!1);return}const r=window.visualViewport;let i={width:r.width,height:r.height},o=0;const l=()=>{o=0;const d=!!document.activeElement?.matches?.(t),u=p0(i,r.width,r.height,d);i=u.baseline,n(u.takeover)},c=()=>{o||(o=requestAnimationFrame(l))};return l(),r.addEventListener("resize",c),window.addEventListener("focusin",c),window.addEventListener("focusout",c),()=>{o&&cancelAnimationFrame(o),r.removeEventListener("resize",c),window.removeEventListener("focusin",c),window.removeEventListener("focusout",c)}},[e,t]),e?s:!1}function f0({controller:e,layout:t="split",onEnterZen:s}){const n=a.createElement(Xi,{controller:e,panelClassName:"ps-mobile-session-pane"});return t==="chat"?a.createElement("div",{className:"ps-mobile-workspace is-chat-only"},a.createElement("div",{className:"ps-mobile-chat-pane"},a.createElement(Zi,{controller:e,mobile:!0,fullWidth:!0,onEnterZen:s}))):t==="sessions"?a.createElement("div",{className:"ps-mobile-workspace is-sessions-only"},a.createElement(Xi,{controller:e,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(Zi,{controller:e,mobile:!0,fullWidth:!0,onEnterZen:s})))}function yp(){const e={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,...e}),a.createElement("path",{d:"M5.5 11.5l3-3.5 2.5 2.5 3.5-4",...e}),a.createElement("path",{d:"M7 17.5h6M10 14.5v3",...e}))}function bc(){const e={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",...e}),a.createElement("path",{d:"M6.2 10.3h7.6",...e}),a.createElement("path",{d:"M7.6 6.5a2.4 2.4 0 0 1 4.8 0",...e}),a.createElement("path",{d:"M8 4.4 6.9 2.9M12 4.4l1.1-1.5",...e}),a.createElement("path",{d:"M6.3 8.6 3.8 7.4M6.2 10.6H3.6M6.3 12.6 3.8 13.9",...e}),a.createElement("path",{d:"M13.7 8.6 16.2 7.4M13.8 10.6h2.6M13.7 12.6l2.5 1.3",...e}))}function Sc({mark:e}){if(e!=="canvas"&&e!=="unseen")return null;const t=e==="unseen",s={fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("span",{className:`ps-session-canvas-mark${t?" is-unseen":""}`,title:t?"Canvas updated since you last viewed it":"This session has a canvas","aria-label":t?"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}),t?a.createElement("circle",{cx:12.4,cy:4.6,r:2.4,fill:"currentColor",stroke:"none"}):null))}function vc(){const e={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",...e}),a.createElement("path",{d:"M7 13l-1.8 1.8a2.8 2.8 0 01-4-4l3-3a2.8 2.8 0 014 0",...e}),a.createElement("path",{d:"M13 7l1.8-1.8a2.8 2.8 0 014 4l-3 3a2.8 2.8 0 01-4 0",...e}))}const h0=[{id:"session",label:"Session access"},{id:"public",label:"Anyone with link"}];function g0({controller:e,sessionId:t,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),[v,S]=a.useState(null),[w,E]=a.useState(!1),I=e.transport,T=`${window.location.origin}/?session=${encodeURIComponent(t)}&view=canvas&slot=${s}&max=1${w?"&show_chrome=false":""}`,C=(_,$)=>a.createElement(Fu,{url:_,keyPrefix:$,copied:m,onCopy:R}),k=a.useCallback(()=>{I.getCanvasShareLink?.(t,s).then(_=>i(_||{exists:!1})).catch(_=>{i({exists:!1}),p(_?.message||String(_))}),typeof I.readCanvasKv=="function"&&I.readCanvasKv(t,s,{limit:1}).then(_=>{y(_?.policy||"owner"),S(_?.me||null)}).catch(()=>{y(null),S(null)})},[I,t,s]);a.useEffect(()=>{k()},[k]);const O=v?.relation==="owner"||v?.relation==="admin",N=_=>{d(!0),p(""),I.setCanvasKvAccess(t,s,_).then(()=>y(_)).catch($=>p($?.message||String($))).finally(()=>d(!1))},R=(_,$)=>{navigator.clipboard?.writeText($).then(()=>{f(_),window.setTimeout(()=>f(""),1500)}).catch(()=>p("Could not reach the clipboard — copy the link manually."))},H=_=>{d(!0),p(""),I.resetCanvasShareLink(t,s).then(({token:$})=>{l(`${window.location.origin}/?canvasShare=${encodeURIComponent($)}`),i({exists:!0})}).catch($=>p($?.message||String($))).finally(()=>d(!1))},x=()=>{d(!0),p(""),I.removeCanvasShareLink(t,s).then(()=>{l(null),i({exists:!1})}).catch(_=>p(_?.message||String(_))).finally(()=>d(!1))},P=a.createElement("div",{className:"ps-canvas-share-overlay",onClick:n},a.createElement("div",{className:"ps-canvas-share-dialog",onClick:_=>_.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"},h0.map(_=>a.createElement("button",{key:_.id,type:"button",role:"tab","aria-selected":h===_.id?"true":"false",className:`ps-manage-tab${h===_.id?" is-active":""}`,onClick:()=>g(_.id)},_.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."),C(T,"session"),a.createElement("label",{className:"ps-canvas-share-check"},a.createElement("input",{type:"checkbox",checked:w,onChange:_=>E(_.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||!O,onChange:_=>N(_.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."),O?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,C(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:()=>H(r?.exists)},r?.exists?"Reset link":"Create link"),r?.exists?a.createElement("button",{type:"button",className:"ps-mini-button",disabled:c,onClick:x},"Remove link"):null))),u?a.createElement("div",{className:"ps-canvas-share-error"},u):null));return typeof document<"u"&&document.body?Hs.createPortal(P,document.body):P}function hi({controller:e,view:t,compact:s=!1}){const n=Array.isArray(t.slots)?t.slots:[];if(n.length<=1)return null;const r=n.map(c=>c.slot),i=Math.max(0,r.indexOf(t.slot)),o=c=>{const d=r[(i+c+r.length)%r.length];e.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:t.slot,onChange:c=>e.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 wc(){const e={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,...e}),a.createElement("rect",{x:8.2,y:3.4,width:9.6,height:13.2,rx:1,...e}))}function Ec(){const e={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",...e}))}function kc(){const e={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",...e}))}function y0({controller:e,sessionId:t,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,v]=a.useState(null),[S,w]=a.useState(0),E=a.useRef({live:null,staging:null}),I=a.useRef({rev:0,used:!1}),T=a.useRef(null),C=a.useRef(null),k=a.useRef(null),O=sp(T),N=a.useRef(null),R=a.useRef(r);R.current=r;const H=a.useRef(i);H.current=i,a.useEffect(()=>{if(!e||!t)return;const _=$=>{const B=C.current,j=$.data;if(!j||typeof j!="object"||!$.source)return;const W=!!(B&&$.source===B.contentWindow),A=!!(k.current&&$.source===k.current.contentWindow);if(!(!W&&!A)){if(j.type==="moa-panel-key"){W&&document.activeElement===B&&["Tab","Escape"].includes(j.key)&&p.current?.(j.key,j.backwards===!0);return}if(j.type==="canvas-action"){if(!W)return;e.submitCanvasAction(t,j,s).then(G=>{G&&G.ok===!1&&typeof console<"u"&&console.warn(`canvas action rejected: ${G.reason}`)}).catch(()=>{});return}if(j.type==="canvas-kv"){const G=j.id,D=e.transport,Y=$.source,J=ne=>{try{Y.postMessage(ne,"*")}catch{}},te=(ne,ae="ERROR")=>J({type:"canvas-kv-result",id:G,ok:!1,error:String(ne?.message||ne||"failed"),code:ne?.code||ae});if(typeof D?.readCanvasKv!="function"){te("the canvas KV store is not available on this deployment","UNAVAILABLE");return}const Z=String(j.op||"");if(!W&&(Z==="put"||Z==="delete")){te("the canvas is still loading; retry the write in a moment","NOT_READY");return}if(Z==="ready"||Z==="list"){D.readCanvasKv(t,s,{prefix:j.prefix??null,limit:j.limit??null,after:j.after??null}).then(ne=>J({type:Z==="ready"?"canvas-kv-ready":"canvas-kv-result",id:G,ok:!0,entries:ne?.entries??[],nextAfter:ne?.nextAfter??null,me:ne?.me??null,canWrite:!!ne?.me?.canWrite,policy:ne?.policy??"owner"})).catch(te);return}if(Z==="get"){D.readCanvasKv(t,s,{key:j.key}).then(ne=>J({type:"canvas-kv-result",id:G,ok:!0,entry:ne?.entries?.[0]??null})).catch(te);return}if(Z==="put"||Z==="delete"){const ne=Z==="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}:{}};D.writeCanvasKv(t,s,[ne]).then(ae=>{const oe=ae?.results?.[0]??{ok:!1,error:"no result"};J({type:"canvas-kv-result",id:G,ok:!!oe.ok,key:oe.key,rev:oe.rev,capped:oe.capped,error:oe.error,code:oe.code})}).catch(te);return}te(`unknown canvas-kv op ${Z}`,"INVALID_REQUEST")}}};return window.addEventListener("message",_),()=>window.removeEventListener("message",_)},[e,t,s]),a.useEffect(()=>{if(!(!e||!t||typeof e.subscribeCanvasKv!="function"))return e.subscribeCanvasKv(t,_=>{if(!_||Number(_.slot)!==Number(s))return;const $=C.current?.contentWindow;if(!$)return;const B=j=>{try{$.postMessage({type:"canvas-kv-change",key:_.key,rev:_.rev,op:_.op,...j?{v:j.v,by:j.by,at:j.at}:{}},"*")}catch{}};if(_.op==="delete"){B(null);return}if(_.value&&typeof _.value=="object"){B({v:_.value.v,by:_.value.by,at:_.value.at});return}e.transport?.readCanvasKv?.(t,s,{key:_.key}).then(j=>B(j?.entries?.[0]??null)).catch(()=>{})})},[e,t,s]),a.useEffect(()=>{if(!e||!t||!n)return;let _=!1,$=null;return np(e,t,s<=1?"canvas.html":`canvas${s}.html`,m).then(B=>{if(_){URL.revokeObjectURL(B);return}E.current.staging&&E.current.staging!==E.current.live&&URL.revokeObjectURL(E.current.staging),E.current.staging=B,v(null),b({url:B,rev:n})}).catch(()=>{if(!_){if(I.current.rev!==n&&(I.current={rev:n,used:!1}),!I.current.used){I.current.used=!0,$=setTimeout(()=>{_||w(B=>B+1)},1500);return}v({rev:n})}}),()=>{_=!0,$&&clearTimeout($)}},[e,t,s,n,S,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),v(null)},[t]);const x=a.useCallback(_=>{if(!_||E.current.staging!==_.url)return;const $=E.current.live;E.current.live=_.url,E.current.staging=null,$&&$!==_.url&&URL.revokeObjectURL($),h(_),b(j=>j&&j.url===_.url?null:j);const B=T.current;if(B){const j=B.getBoundingClientRect(),W=R.current||1;N.current={w:Math.round(j.width/W),h:Math.round(j.height/W)}}if(e&&t&&H.current&&e.dispatch({type:"canvas/viewed",sessionId:t,slot:s,rev:_.rev}),o&&H.current)try{C.current?.focus({preventScroll:!0})}catch{}},[e,t,o]);a.useEffect(()=>{if(!(!f||!l||c===null)){try{C.current?.contentWindow?.postMessage({type:"canvas-data",data:c,dataRev:l},"*"),d&&C.current?.contentWindow?.postMessage({type:"canvas-patch",patch:d,dataRev:l},"*")}catch{}e&&t&&H.current&&e.dispatch({type:"canvas/viewed",sessionId:t,slot:s,dataRev:l})}},[f,l,c,d,e,t]),a.useEffect(()=>{if(i&&f&&e&&t&&(e.dispatch({type:"canvas/viewed",sessionId:t,slot:s,rev:f.rev,...l?{dataRev:l}:{}}),o))try{C.current?.focus({preventScroll:!0})}catch{}},[i,f,e,t,o,l]),a.useEffect(()=>{if(!f||!i)return;const _=r||1,$=Math.round((O.width||0)/_),B=Math.round((O.height||0)/_);if(!$||!B)return;const j=N.current;if(j){if(!(j.w<220||j.h<170))return;const G=Math.abs(j.w-$),D=Math.abs(j.h-B);if(G<=2&&D<=2||G<=2&&D/Math.max(1,j.h)<.15)return}const W=setTimeout(()=>{N.current={w:$,h:B},w(A=>A+1)},350);return()=>clearTimeout(W)},[O.width,O.height,r,f,i]);const P=r!==1&&O.width>0?{flex:"none",width:`${Math.max(1,Math.round(O.width/r))}px`,height:`${Math.max(1,Math.round(O.height/r))}px`,transform:`scale(${r})`,transformOrigin:"top left"}:void 0;return a.createElement("div",{ref:T,className:"ps-html-preview-host is-fitting"},[f,g].filter(Boolean).map(_=>a.createElement("iframe",{key:`canvas:${_.rev}:${_.url}`,ref:_===f?($=>{C.current=$}):($=>{k.current=$}),className:`ps-html-preview-frame${_===f?"":" is-staging"}`,style:P,src:_.url,title:"Session canvas",sandbox:"allow-scripts allow-popups allow-popups-to-escape-sandbox",allow:"autoplay *",referrerPolicy:"no-referrer",onLoad:_===g?()=>x(_):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:()=>{I.current={rev:0,used:!1},v(null),w(_=>_+1)}},"Retry")):null)}const b0=160;function bp({controller:e,mobile:t=!1,visible:s=!0,focusOnPromote:n=!1,maximized:r=!1,onToggleMaximized:i=null}){const o=ee(e,Aa,Ve),l=ee(e,b=>Number(b.files.htmlZoom)||1),c=a.useCallback(b=>{e.dispatch({type:"files/htmlZoom",zoom:b})},[e]);a.useEffect(()=>{if(!s||!o.sessionId)return;const b=setTimeout(()=>{e.ensureCanvasSnapshot(o.sessionId).catch(()=>{})},b0);return()=>clearTimeout(b)},[e,o.sessionId,s]);const d=ee(e,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 v=document.getElementById("ps-toolbar-canvas-slot");v?f(v):b=requestAnimationFrame(y)};return y(),()=>cancelAnimationFrame(b)},[r]),a.useCallback(()=>{e.dispatch({type:"ui/canvasOpen",open:!1,sessionId:o.sessionId,manual:!0})},[e,o.sessionId]);const h=t&&(o.exists||r),g=t?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(hi,{controller:e,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(vc)):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?kc:Ec)):null):null:r?m?Hs.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(hi,{controller:e,view:o,compact:!0}),o.exists?a.createElement(ur,{zoom:l,setZoom:c}):null,a.createElement("button",{type:"button",className:`ps-artifact-pane-btn${d?" is-active":""}`,onClick:()=>{e.dispatch({type:"ui/canvasMaximized",on:!1}),e.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(wc)),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn ps-toolbar-canvas-restore",onClick:()=>e.dispatch({type:"ui/canvasMaximized",on:!1}),title:"Back to the workspace","aria-label":"Restore canvas"},a.createElement(kc))),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(yp)),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(hi,{controller:e,view:o})),a.createElement("span",{className:"ps-artifact-pane-actions"},o.exists?a.createElement(ur,{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(vc)):null,a.createElement("button",{type:"button",className:`ps-artifact-pane-btn${d?" is-active":""}`,onClick:()=>e.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(wc)),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>e.dispatch({type:"ui/canvasMaximized",on:!0}),title:"Full screen — hide chat and sessions","aria-label":"Full screen canvas"},a.createElement(Ec))));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(y0,{key:`slot:${o.slot}`,controller:e,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(g0,{controller:e,sessionId:o.sessionId,slot:o.slot,onClose:()=>p(!1)}):null)}function Sp({activeTab:e,controller:t}){const s=a.useMemo(()=>Ga(t),[t]);return a.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>a.createElement(Se,{key:n,icon:Yl[n]?a.createElement(Yl[n]):"•",label:ev[n]||n,active:e===n,onClick:()=>{t.setFocus("inspector"),t.selectInspectorTab(n).catch(()=>{})}})))}function Nr({controller:e,focused:t,mobile:s=!1,previewOnly:n=!1,nativeScroll:r=!1,chromeless:i=!1}){const o=ee(e,x=>x.ui.themeId),l=Pt(o),c=a.useRef(null),d=ee(e,x=>{const P=x.sessions.activeSessionId,_=xr(x),$=s||x.files.fullscreen?x.ui.layout?.viewportWidth??120:_.rightWidth;return{activeSessionId:P,sessionsById:x.sessions.byId,sessionsFlat:x.sessions.flat,filesBySessionId:x.files.bySessionId,filesFilter:x.files.filter,selectedArtifactId:x.files.selectedArtifactId,markedIds:x.files.markedIds||[],previewOrigin:x.files.previewOrigin||null,focused:t,previewScroll:x.ui.scroll.filePreview,fullscreen:!!x.files.fullscreen,contentWidth:Math.max(20,$-4),canBrowserUpload:sv(e),canPathUpload:nv(e),canDeleteArtifacts:iv(e),canOpenLocally:av(e)}},Ve),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(()=>Ma(u,{listWidth:Math.max(18,d.contentWidth-4),previewWidth:Math.max(18,d.contentWidth-4),showHints:!1}),[u,d.contentWidth]),m=a.useMemo(()=>rs(u),[u]),f=m.length>0,h=a.useCallback(x=>{const P=Array.isArray(x)?x.filter(Boolean):[];P.length!==0&&e.uploadArtifactFiles(P).catch(()=>{})},[e]),g=a.useCallback(()=>{if(d.canBrowserUpload&&c.current){c.current.click();return}d.canPathUpload&&e.handleCommand(L.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[e,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(Se,{icon:a.createElement(Qi),label:`Delete ${b.size} marked`,onClick:()=>e.deleteMarkedArtifacts().catch(()=>{})}):null,a.createElement(Se,{icon:"✕",label:"Clear marks",onClick:()=>e.clearArtifactMarks()})):null,a.createElement("input",{ref:c,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:x=>{h(Array.from(x.currentTarget.files||[])),x.currentTarget.value=""}}),a.createElement(Se,{icon:a.createElement(Ww),label:"Upload",onClick:g,disabled:!d.canBrowserUpload&&!d.canPathUpload}),a.createElement(Se,{icon:a.createElement(hp),label:"Download",onClick:()=>e.handleCommand(L.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!f}),a.createElement(Se,{icon:"🔗",label:"Copy link to this artifact",onClick:()=>{const x=Er(p.selectedSessionId,p.selectedFilename);x&&(or(x),e.dispatch({type:"ui/status",text:Lu}))},disabled:!f||!p.selectedFilename}),d.canDeleteArtifacts?a.createElement(Se,{icon:a.createElement(Qi),label:"Delete",onClick:()=>e.handleCommand(L.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,d.canOpenLocally?a.createElement(Se,{icon:"↗",label:"Open locally",onClick:()=>e.handleCommand(L.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!f}):null,a.createElement(Se,{icon:a.createElement(eo),label:"Filter",onClick:()=>e.handleCommand(L.OPEN_FILES_FILTER).catch(()=>{})}),a.createElement(Se,{icon:a.createElement(d.fullscreen?Hw:fp),label:d.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>e.handleCommand(L.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),v=a.useRef(null);a.useEffect(()=>{const x=v.current;x&&typeof x.scrollIntoView=="function"&&x.scrollIntoView({block:"nearest"})},[p.selectedIndex,d.selectedArtifactId]);const S=m.length===0?rt(p.listBodyLines||[]).map((x,P)=>a.createElement(ct,{key:`empty:${P}`,line:x,theme:l})):m.map((x,P)=>a.createElement("button",{key:x.id,type:"button",ref:P===p.selectedIndex?v:null,className:`ps-list-button${P===p.selectedIndex?" is-selected":""}`+(b.has(x.id)?" is-marked":""),onClick:_=>{if(e.setFocus("inspector"),_.metaKey||_.ctrlKey){e.toggleArtifactMark(x);return}if(_.shiftKey){e.markArtifactRange(x);return}e.clearArtifactMarks(),e.selectFileBrowserItem(x).then(()=>{s&&e.handleCommand(L.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})}).catch(()=>{})}},a.createElement(ct,{line:rt([p.listBodyLines?.[P]])[0],theme:l}))),w=!p.previewLoading&&!p.previewError,E=w&&Xa(p.selectedFilename,p.previewContentType)&&!p.previewIsBinary&&!!p.previewContent,I=w&&(Ka.test(String(p.previewContentType||""))||Va.test(String(p.selectedFilename||""))),T=w&&!p.previewIsBinary&&!E&&p.previewRenderMode!=="markdown"&&p.previewContent?Ya(p.selectedFilename):null,C=n?"activity":null,k=r?null:"filePreview",O=w&&!p.previewIsBinary&&Wu(p.selectedFilename,p.previewContentType)&&!!p.previewContent,R=w&&!p.previewIsBinary&&Gu(p.selectedFilename,p.previewContentType)?a.createElement(rw,{controller:e,sessionId:p.selectedSessionId,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,theme:l,color:"cyan",focused:!1,title:null,chromeless:i}):O?a.createElement(ui,{controller:e,title:null,color:"cyan",focused:!1,theme:l,paneKey:k,scrollOffset:d.previewScroll,className:"ps-csv-preview",focusRegion:C},a.createElement(Dv,{content:p.previewContent,filename:p.selectedFilename})):I?a.createElement(oc,{title:null,color:"cyan",focused:!1,theme:l,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,source:p.previewSource,uploadedAt:p.previewUploadedAt,controller:e,sessionId:p.selectedSessionId}):T?a.createElement(ui,{controller:e,title:null,color:"cyan",focused:!1,theme:l,paneKey:k,scrollOffset:d.previewScroll,className:"ps-diff-preview",focusRegion:C},a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,Bs(p.previewContent,T,l)))):E?a.createElement(ui,{controller:e,title:null,color:"cyan",focused:!1,theme:l,paneKey:k,scrollOffset:d.previewScroll,className:"ps-diff-preview",focusRegion:C},a.createElement("pre",{className:"ps-md-code-pre is-diff"},a.createElement("code",null,Qa(p.previewContent,l)))):p.previewRenderMode==="markdown"&&!p.previewLoading&&!p.previewError?a.createElement(ew,{controller:e,title:null,color:"cyan",focused:!1,scrollOffset:d.previewScroll,paneKey:k,theme:l,focusRegion:C,content:Rv(p.previewContent||"")}):p.previewIsBinary&&!p.previewLoading&&!p.previewError?a.createElement(oc,{title:null,color:"cyan",focused:!1,theme:l,filename:p.selectedFilename,contentType:p.previewContentType,sizeBytes:p.previewSizeBytes,source:p.previewSource,uploadedAt:p.previewUploadedAt,controller:e,sessionId:p.selectedSessionId}):a.createElement(Ar,{controller:e,title:null,color:"cyan",focused:!1,lines:p.previewLines,scrollOffset:d.previewScroll,scrollMode:"top",paneKey:k,focusRegion:C,className:"is-preview is-wrapped"}),H=d;return n?R:a.createElement(Yt,{title:H.fullscreen?p.fullscreenTitle:s&&p.panelTitleMobile?p.panelTitleMobile:p.panelTitle,color:"magenta",focused:H.focused,actions:y,theme:l},a.createElement(Sp,{activeTab:"files",controller:e}),H.fullscreen?R:a.createElement("div",{className:"ps-files-grid is-list-only"},a.createElement("div",{className:"ps-action-list ps-files-list"},S)))}function Xs({controller:e,mobile:t=!1,panelClassName:s="",extraActions:n=null}){const r=ee(e,b=>{const y=xr(b),v=b.ui.inspectorTab,S=t?b.ui.layout?.viewportWidth??120:y.rightWidth;return{inspectorTab:v,statsViewMode:b.ui.statsViewMode,adminWorkers:b.admin?.workers,nodeMapSelectedNode:b.ui.nodeMapSelectedNode,activeSessionId:b.sessions.activeSessionId,sessionsById:b.sessions.byId,sessionsFlat:b.sessions.flat,historyBySessionId:b.history.bySessionId,sessionStats:b.sessionStats,fleetStats:b.fleetStats,connection:b.connection,orchestrationBySessionId:b.orchestration.bySessionId,executionHistoryBySessionId:b.executionHistory?.bySessionId||{},executionHistoryFormat:b.executionHistory?.format||"pretty",logs:b.logs,files:b.files,focused:b.ui.focusRegion==="inspector",scroll:b.ui.scroll.inspector,followBottom:b.ui.followBottom?.inspector!==!1,logsTailing:b.logs.tailing,filesFullscreen:!!b.files.fullscreen,contentWidth:yv(S,v,t)}},Ve),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]=Bu(),c=o??r.contentWidth,d=a.useMemo(()=>Vt(i,{width:c}),[i,c]),u=a.useMemo(()=>{const b=r.activeSessionId&&r.historyBySessionId?.get(r.activeSessionId)||null,y=new Map;for(const v of b?.events||[]){if(v?.eventType!=="session.turn_completed")continue;const S=Number(v?.data?.turnIndex??v?.data?.iteration);Number.isFinite(S)&&y.set(S,v)}return y},[r.activeSessionId,r.historyBySessionId]),p=a.useCallback((b,y)=>a.createElement(bw,{lines:b,theme:y,completionByTurn:u}),[u]),m=a.useCallback((b,y)=>a.createElement(yw,{lines:b,theme:y,controller:e}),[e]);a.useEffect(()=>{if(r.inspectorTab!=="nodes")return;e.ensureInspectorData("nodes");const b=window.setInterval(()=>{e.ensureInspectorData("nodes")},1e4);return()=>window.clearInterval(b)},[e,r.inspectorTab]);const f=a.useRef(null);if(a.useEffect(()=>{if(t)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 v=window.getComputedStyle(y),S=document.createElement("span");S.style.cssText="position:absolute;visibility:hidden;white-space:pre;",S.style.fontFamily=v.fontFamily,S.style.fontSize=v.fontSize,S.style.fontWeight=v.fontWeight,S.style.letterSpacing=v.letterSpacing,S.textContent="0".repeat(100),y.parentElement.appendChild(S);const w=S.getBoundingClientRect().width/100||8;S.remove();const E=window.getComputedStyle(b),I=b.clientWidth-(parseFloat(E.paddingLeft)||0)-(parseFloat(E.paddingRight)||0);if(!(I>50))return;const C=Math.floor(I/w)+6,k=e.getState().ui.layout?.viewportWidth??120;if(Math.abs(C-k)<=2)return;e.dispatch({type:"ui/viewport",width:C,height:null})}catch{}}),()=>{f.current&&cancelAnimationFrame(f.current)}},[e,t,r.inspectorTab,r.activeSessionId]),r.inspectorTab==="files"&&!d.disabled)return a.createElement(Nr,{controller:e,focused:r.focused,mobile:t});const h=[];if(r.inspectorTab==="logs")h.push(a.createElement(Se,{key:"tail",icon:r.logsTailing?"■":"⇣",label:r.logsTailing?"Stop tailing":"Tail (follow)",active:r.logsTailing,onClick:()=>e.handleCommand(L.TOGGLE_LOG_TAIL).catch(()=>{})})),h.push(a.createElement(Se,{key:"filter",icon:a.createElement(eo),label:"Filter",onClick:()=>e.handleCommand(L.OPEN_LOG_FILTER).catch(()=>{})}));else if(r.inspectorTab==="history")h.push(a.createElement(Se,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>e.handleCommand(L.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),h.push(a.createElement(Se,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>e.handleCommand(L.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(Se,{key:`stats-view:${y}`,icon:b[y],label:`${y.replace(/^./u,v=>v.toUpperCase())} stats`,active:r.statsViewMode===y,onClick:()=>e.setStatsViewMode(y)}))}const g=n?h.concat(n):h;return a.createElement(Ar,{controller:e,title:d.title,color:"magenta",focused:r.focused,actions:g,topContent:a.createElement(Sp,{activeTab:d.activeTab,controller:e}),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 gi({controller:e,panelClassName:t="",extraActions:s=null}){const n=ee(e,l=>{const c=l.sessions.activeSessionId,d=xr(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}},Ve),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?tu(i):Pa(i,n.maxLines),[r,i,n.maxLines]);return a.createElement(Ar,{controller:e,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${t?` ${t}`:""}`})}const pr=Object.freeze([]);function Ic(e){const t=Number(e)||0;return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function vp({controller:e,mobile:t,compact:s=!1,active:n=!0,onAfterSend:r=null,autoFocus:i=!0}){const o=ee(e,N=>{const R=N.sessions.activeSessionId,H=R&&N.sessions.byId[R]||null,x=R&&N.outbox?.bySessionId?.[R]?N.outbox.bySessionId[R]:[];return{value:N.ui.prompt,cursor:N.ui.promptCursor,focused:N.ui.focusRegion==="prompt",modalOpen:!!N.ui.modal,answerMode:!!H?.pendingQuestion?.question,canStopTurn:zd(H),hasOutbox:x.length>0,hasPendingOutbox:x.some(P=>P?.phase==="pending"),pendingCount:x.filter(P=>P?.phase==="pending").length,editingPending:N.ui.promptEdit?.sessionId===R,selectedOutboxPhase:N.ui.promptEdit?.sessionId===R&&N.ui.promptEdit?.phase||null,promptAttachments:N.ui.promptAttachments||pr}},Ve),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=t&&!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 R=l.current;R&&(!N&&R.scrollHeight<=R.clientHeight||(R.style.height="0px",R.style.height=`${R.scrollHeight+2}px`))},[]);a.useLayoutEffect(()=>{const N=String(o.value||"").length,R=N<=g.current;g.current=N,b(R||N===0)},[b,o.value,h]),a.useEffect(()=>{const N=()=>b(!0);window.addEventListener("resize",N);const R=l.current,H=R&&typeof ResizeObserver<"u"?new ResizeObserver(()=>b(!0)):null;return H&&R&&H.observe(R),()=>{window.removeEventListener("resize",N),H?.disconnect()}},[b]);const y=typeof e.transport?.supportsPromptImageAttachments=="function"&&e.transport.supportsPromptImageAttachments()&&typeof e.transport?.uploadArtifactFromFile=="function",v=y?o.promptAttachments.filter(N=>N?.kind==="image"):pr,S=a.useRef(new Map);a.useEffect(()=>{const N=S.current,R=new Set(v.map(H=>H.file));for(const[H,x]of N)R.has(H)||(URL.revokeObjectURL(x),N.delete(H));for(const H of v)if(H.file&&!N.has(H.file))try{N.set(H.file,URL.createObjectURL(H.file))}catch{}},[v]),a.useEffect(()=>()=>{for(const N of S.current.values())URL.revokeObjectURL(N);S.current.clear()},[]);const w=a.useCallback(N=>{if(!y)return 0;const R=Array.from(N||[]).filter(x=>x&&typeof x.type=="string"&&x.type.startsWith("image/"));return R.length===0?0:e.addPendingImageFiles(R)?.accepted||0},[e,y]);a.useEffect(()=>{const N=l.current;if(!(!n||o.modalOpen||!o.focused||!N)){if(document.activeElement!==N){if(!i||typeof i=="function"&&!i()||t)return;try{N.focus({preventScroll:!0})}catch{N.focus()}}N.value===o.value&&N.selectionStart!==o.cursor&&N.setSelectionRange(o.cursor,o.cursor)}},[n,t,i,o.cursor,o.value,o.focused,o.modalOpen]);const E=a.useCallback(()=>{e.handleCommand(L.SEND_PROMPT).catch(()=>{}).finally(()=>{r?.()})},[e,r]),[I,T]=a.useState(!1),C=a.useCallback(()=>{T(!0),e.handleCommand(L.STOP_TURN).catch(()=>{}).finally(()=>T(!1))},[e]),k=a.useCallback(()=>{if(e.getState().ui.promptEdit){typeof e.cancelSelectedOutboxPrompt=="function"?e.cancelSelectedOutboxPrompt().catch(()=>{}):e.cancelSelectedPendingPrompt();return}typeof e.cancelLatestQueuedOutbox=="function"&&e.cancelLatestQueuedOutbox().catch(()=>{})},[e]),O=o.editingPending||o.hasPendingOutbox&&!o.value.trim()?"⇪":o.hasOutbox?"+":"❯";return a.createElement("div",{className:`ps-prompt-shell${s?" is-compact":""}${t?" 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))}}:{}},v.length>0?a.createElement("div",{className:"ps-prompt-attachments"},v.map((N,R)=>{const H=N.file?S.current.get(N.file):null;return a.createElement("div",{key:`attach:${R}:${N.filename}`,className:"ps-attach-chip",title:`${N.filename} · ${Ic(N.sizeBytes)}`},H?a.createElement("img",{className:"ps-attach-thumb",src:H,alt:N.filename}):a.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),a.createElement("div",{className:"ps-attach-size"},Ic(N.sizeBytes)),a.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${N.filename}`,"aria-label":`Remove attachment ${N.filename}`,onClick:()=>e.removePendingImageAttachment(R)},"✕"))})):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:t?"enter":"send",onFocus:()=>e.setFocus("prompt"),onSelect:N=>e.setPromptCursor(N.currentTarget.selectionStart||0),onChange:N=>e.setPrompt(N.currentTarget.value,N.currentTarget.selectionStart||N.currentTarget.value.length),onPaste:y?N=>{const H=Array.from(N.clipboardData?.items||[]).filter(x=>x.kind==="file"&&x.type.startsWith("image/")).map(x=>x.getAsFile()).filter(Boolean);H.length>0&&w(H)>0&&N.preventDefault()}:void 0,onKeyDown:N=>{if(N.key==="Tab"&&!N.shiftKey&&e.acceptPromptReferenceAutocomplete()){N.preventDefault();return}if(N.key==="Escape"&&o.editingPending){if(N.preventDefault(),f){e.exitPendingPromptEdit({restoreDraft:!0});return}k();return}N.key==="Enter"&&!N.shiftKey&&!N.metaKey&&!t&&(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:k},p?"Delete":"Cancel"):null,o.canStopTurn||I?a.createElement("button",{type:"button",className:`ps-stop-button${I?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:I,onPointerDown:N=>N.preventDefault(),onClick:C},"■"):null,a.createElement("button",{type:"button",className:`ps-send-button${t?" 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},O)))}const S0=1e3;function Se({icon:e,label:t,onClick:s,disabled:n=!1,active:r=!1,pressed:i=void 0,className:o="ps-toolbar-button"}){const[l,c]=a.useState(null),d=a.useRef(null),u=a.useRef(null),p=a.useRef(null),m=a.useRef(!1);a.useLayoutEffect(()=>{if(!l||!u.current||!d.current)return;const C=u.current,k=window.visualViewport,O=()=>{const N=k?.offsetLeft||0,R=k?.offsetTop||0,H=k?.width||window.innerWidth,x=k?.height||window.innerHeight,P=6,_=d.current.getBoundingClientRect();C.style.width="max-content",C.style.maxWidth=`${Math.min(220,H-2*P)}px`,C.style.maxHeight=`${x-2*P}px`;const $=C.getBoundingClientRect();let B=l.placement==="below";!B&&_.top-$.height-P<R&&(B=!0),B&&_.bottom+$.height+P>R+x&&_.top-$.height-P>=R&&(B=!1);const j=Math.max(N+P,Math.min(_.left+_.width/2-$.width/2,N+H-$.width-P)),W=Math.max(R+P,Math.min(B?_.bottom+P:_.top-$.height-P,R+x-$.height-P));C.style.transform="none",C.style.left=`${j}px`,C.style.top=`${W}px`};return O(),k?.addEventListener("resize",O),k?.addEventListener("scroll",O),window.addEventListener("resize",O),()=>{k?.removeEventListener("resize",O),k?.removeEventListener("scroll",O),window.removeEventListener("resize",O)}},[l]);const f=(C=!1)=>{const k=d.current;if(!k||typeof window>"u")return;const O=k.getBoundingClientRect(),N=C?O.top-44<0:O.bottom+44<window.innerHeight;c({x:O.left+O.width/2,y:N?O.bottom+6:O.top-6,placement:N?"below":"above"})},h=a.useRef(null),g=a.useRef(null),b=C=>{C.pointerType==="mouse"&&(clearTimeout(p.current),clearTimeout(h.current),p.current=setTimeout(f,S0))},y=C=>{C.pointerType==="mouse"&&(clearTimeout(p.current),clearTimeout(h.current),c(null))},v=C=>{C.pointerType!=="mouse"&&(m.current=!1,g.current={x:C.clientX,y:C.clientY},clearTimeout(p.current),clearTimeout(h.current),p.current=setTimeout(()=>{m.current=!0,f(!0)},450))},S=C=>{if(C.pointerType==="mouse"||!g.current)return;const k=C.clientX-g.current.x,O=C.clientY-g.current.y;k*k+O*O>100&&(g.current=null,clearTimeout(p.current),c(null))},w=C=>{C.pointerType!=="mouse"&&(g.current=null,clearTimeout(p.current),m.current?(clearTimeout(h.current),h.current=setTimeout(()=>c(null),3e3),setTimeout(()=>{m.current=!1},250)):c(null))};a.useEffect(()=>()=>{clearTimeout(p.current),clearTimeout(h.current)},[]);const E=C=>{if(m.current){m.current=!1,C.preventDefault?.();return}n||s?.(C)},I=C=>{C.preventDefault?.()},T=l&&typeof document<"u"&&document.body?Hs.createPortal(a.createElement("span",{ref:u,className:`ps-icon-tooltip is-${l.placement}`,role:"tooltip",style:{left:`${l.x}px`,top:`${l.y}px`}},t),document.body):null;return a.createElement("button",{ref:d,type:"button",className:`${o} ps-icon-button${r?" is-active":""}`,onClick:E,disabled:n,"aria-label":t,"aria-pressed":i,onPointerEnter:b,onPointerLeave:y,onPointerDown:v,onPointerMove:S,onPointerUp:w,onPointerCancel:w,onContextMenu:I},a.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},e),T)}function xc({controller:e,mobile:t,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(t?null:document.getElementById("ps-header-toolbar-slot"))},[t]);const u=ee(e,x=>!!x.admin?.visible),p=ee(e,x=>!!(x.admin?.profile?.isAdmin||x.auth?.authorization?.role==="admin")),m=p?"admin console":"settings",f=ee(e,x=>!!x.ui?.budgetOpen),h=ee(e,Aa,Ve),g=ee(e,x=>x?.ui?.diagnosticsOpen===!0),b=ee(e,x=>x?.ui?.canvasMaximized===!0),y=ee(e,x=>!!(x?.files?.paneOpen&&x?.files?.selectedArtifactId)),v=[{key:"new",icon:a.createElement(mp),label:"New session — choose model and agent",onClick:()=>e.handleCommand(L.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:a.createElement(eo),label:"Filter sessions",onClick:()=>e.handleCommand(L.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:a.createElement(Bw),label:"Theme",onClick:()=>e.handleCommand(L.OPEN_THEME_PICKER).catch(()=>{})},{key:"canvas",icon:a.createElement(yp),label:(t?n:h.mode==="canvas"&&!y)?"Hide the canvas":"Show canvas",onClick:()=>{if(t){r&&r();return}e.dispatch({type:"ui/canvasOpen",open:h.mode!=="canvas",sessionId:h.sessionId,manual:!0})},active:t?n:h.mode==="canvas"&&!y,badge:t?h.exists&&(h.latestRev>(h.lastViewedRev||0)||(h.latestDataRev||0)>(h.lastViewedDataRev||0))&&!n:h.unseen,loadedDot:h.exists},{key:"budget",icon:a.createElement(jw),label:f?"Close budget":"Budget — providers, limits and usage",onClick:()=>{f?e.closeBudget():e.openBudget().catch(()=>{})},active:f},...t?[]:[{key:"diagnostics",icon:a.createElement(bc),label:g?"Hide diagnostics":"Show diagnostics (inspector and activity)",onClick:()=>e.dispatch({type:"ui/diagnosticsOpen"}),active:g}],...t?[]:[{key:"admin",icon:a.createElement(Uw),label:u?`Close ${m}`:p?"Admin console":"Settings",onClick:()=>e.handleCommand(u?L.CLOSE_ADMIN_CONSOLE:L.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:u}],...t?[]:[{key:"workspace",icon:a.createElement(gc),label:"Workspace — sessions, chat and panels",onClick:()=>e.handleCommand(L.OPEN_WORKSPACE).catch(()=>{}),active:!s?.active&&!u&&!f}]];s&&v.push({key:"moa",icon:a.createElement(zw),label:s.returnTo?"Back to MoA — Master of Agents":"Master of Agents",active:s.active,disabled:!s.loaded,onClick:()=>{e.dispatch({type:"ui/canvasMaximized",on:!1}),e.handleCommand(L.OPEN_WORKSPACE).catch(()=>{}),s.open()}});const S=x=>{const P=a.createElement(Se,{key:x.badge?void 0:x.key,icon:x.icon,label:x.label,onClick:x.onClick,disabled:!!x.disabled,active:!!x.active});return x.badge||x.loadedDot?a.createElement("span",{key:x.key,className:"ps-canvas-toggle"},P,x.loadedDot?a.createElement("span",{className:"ps-canvas-loaded-dot","aria-hidden":"true"}):null,x.badge?a.createElement("span",{className:"ps-canvas-badge","aria-hidden":"true"}):null):P};if(t){const x={split:"Main — sessions and chat (tap for chat only)",chat:"Main — chat only (tap for sessions only)",sessions:"Main — sessions only (tap for both)"},P=i==="inspector"||i==="activity",_=i==="inspector"?"activity":"inspector",$=[{id:"workspace",icon:gc,label:x[l]||x.split,focus:"chat"},{id:_,icon:bc,active:P,label:P?i==="inspector"?"Diagnostics — inspector (tap for activity)":"Diagnostics — activity (tap for inspector)":"Diagnostics — inspector and activity",focus:_}];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"},v.filter(B=>B.key!=="moa").map(S)),a.createElement("div",{className:"ps-toolbar-row-actions is-panes"},...v.filter(B=>B.key==="moa").map(S),$.map(B=>a.createElement(Se,{key:B.id==="workspace"?"workspace":"diagnostics",icon:a.createElement(B.icon),label:B.label,active:B.active??i===B.id,onClick:()=>{o&&o(B.id,B.focus)}})))))}const w=s?.active?"moa":u?"admin":f?"budget":"workspace",E=["new","filter"],I=["canvas","diagnostics"],T=["workspace","moa","budget","admin"],C=x=>(!b||x.key==="canvas")&&!(s?.active&&["workspace","budget","admin"].includes(x.key))?x:{...x,onClick:(...P)=>(e.dispatch({type:"ui/canvasMaximized",on:!1}),s?.active&&["workspace","budget","admin"].includes(x.key)&&s.leave(),x.onClick?.(...P))},k=x=>x.map(P=>v.find(_=>_.key===P)).filter(Boolean).map(C).map(S),O=x=>a.createElement("span",{key:x,className:"ps-toolbar-divider","aria-hidden":"true"}),N=w==="workspace"?[...k(E),...k(I)]:[],R=[...k(T),O("mode-divider"),...k(["theme"])],H=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"},R),a.createElement("span",{className:"ps-toolbar-signout-slot",id:"ps-toolbar-signout-slot"})));return c?Hs.createPortal(H,c):H}function Ws(e){try{e.currentTarget?.setPointerCapture?.(e.pointerId)}catch{}}function v0({controller:e,paneAdjust:t=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)/Tu),m=p-u.appliedCells;m&&(e.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")}},[e,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(),Ws(i),s.current={startX:i.clientX,appliedCells:0},r(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{t&&e.adjustPaneSplit(-t)},onKeyDown:i=>{if(i.key==="ArrowLeft"){i.preventDefault(),e.handleCommand(L.GROW_RIGHT_PANE).catch(()=>{});return}i.key==="ArrowRight"&&(i.preventDefault(),e.handleCommand(L.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 w0({controller:e,portalSessionColumnAdjust:t=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=$s(c.startAdjust+(l.clientX-c.startX),c.minAdjust,c.maxAdjust);e.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")}},[e,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(),Ws(i);const o=i.currentTarget.closest(".ps-workspace-main-grid"),l=Ki(o?.getBoundingClientRect?.().width);s.current={startX:i.clientX,startAdjust:Number(t)||0,minAdjust:l.minAdjust,maxAdjust:l.maxAdjust},r(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>{e.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:0})},onKeyDown:i=>{const o=i.currentTarget.closest(".ps-workspace-main-grid"),l=Ki(o?.getBoundingClientRect?.().width),c=d=>{const u=$s((Number(t)||0)+d,l.minAdjust,l.maxAdjust);e.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 E0({controller:e,canvasPaneAdjust:t=0,diagnosticsPaneAdjust:s=0}){const n=a.useRef(null),[r,i]=a.useState(!1),o=(c,d)=>({canvas:Wa+(Number(c)||0),diag:qa+(Number(d)||0)}),l=(c,d)=>{const u=o(c,d);if(u.canvas<Hn||u.diag<Hn){e.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),e.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:0}),e.dispatch(u.canvas<Hn?{type:"ui/canvasOpen",open:!1,manual:!0}:{type:"ui/diagnosticsOpen",open:!1});return}e.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:c}),e.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;e.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:p.startCanvas+m}),e.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=e.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)}},[e,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(),Ws(c),n.current={startX:c.clientX,startCanvas:Number(t)||0,startDiag:Number(s)||0},i(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{e.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),e.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(t)||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 k0({controller:e,sessionId:t,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&&e.dispatch({type:"canvas/zenRail",sessionId:t,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)}},[e,r,t]),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(),Ws(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(),e.dispatch({type:"canvas/zenRail",sessionId:t,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 I0({controller:e,target:t,adjust:s=0}){const n=a.useRef(null),[r,i]=a.useState(!1),o=t==="canvas"?"ui/canvasPaneAdjust":"ui/diagnosticsPaneAdjust",l=t==="canvas"?"canvasPaneAdjust":"diagnosticsPaneAdjust",c=t==="canvas"?Wa:qa,d=u=>{if(c+u<Hn){e.dispatch({type:o,[l]:0}),e.dispatch(t==="canvas"?{type:"ui/canvasOpen",open:!1,manual:!0}:{type:"ui/diagnosticsOpen",open:!1});return}e.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);e.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((e.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)}},[e,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(),Ws(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-ja)},i(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>e.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 x0({controller:e,splitAdjust:t=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=$s(c.start+(l.clientY-c.startY),c.minAdjust,c.maxAdjust);e.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")}},[e,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(),Ws(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}=ko(l,c);s.current={startY:i.clientY,start:$s(Number(t)||0,d,u),minAdjust:d,maxAdjust:u},r(!0),document.body.classList.add("is-resizing-pane-y")},onDoubleClick:()=>e.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}=ko(l,c);e.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:$s((Number(t)||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 A0=[{value:"day",label:"Daily"},{value:"week",label:"Weekly"},{value:"month",label:"Monthly"}],Ac={day:"Daily",week:"Weekly",month:"Monthly"},N0={plain:"",amber:" warn",red:" over",idle:""};function C0(e){const t=Math.abs(Number(e)||0),[s,n]=t>=1e9?["B",1e9]:t>=1e6?["M",1e6]:t>=1e3?["K",1e3]:["",1],r=t/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 T0(e){const t=String(e??"").trim().replace(/[,_\s]/g,"").toUpperCase();if(!t)return null;const s=/^(\d+(?:\.\d+)?)([KMB])?$/.exec(t);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 Ji(e){return e?`resets ${e}`:"no reset recorded"}function P0(e,t,s){return`${e} ${e===1?t:s}`}function M0(e,t,s=[]){if(!t?.name)return[];const n=new Map;for(const r of e){if(!(r.catalogKind==="runtime_provider"?r.providerId===t.name:r.catalogKind==="provider_type"?r.providerId===t.typeId:r.providerId===t.name||r.providerId===t.typeId))continue;const o=`${t.name}:${r.modelName}`;n.set(o,{qualifiedName:o,modelName:r.modelName})}for(const r of s)r.providerName!==t.name||r.rowKind!=="model"||!String(r.scope||"").startsWith(`${t.name}:`)||n.set(r.scope,{qualifiedName:r.scope,modelName:r.scope.slice(t.name.length+1)});return[...n.values()]}function _0(e){return(Array.isArray(e)?e:Array.isArray(e?.providers)?e.providers:Array.isArray(e?.models)?e.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 wp({title:e,subtitle:t,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 v=y[0],S=y[y.length-1];b.shiftKey&&document.activeElement===v?(b.preventDefault(),S.focus()):!b.shiftKey&&document.activeElement===S&&(b.preventDefault(),v.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":e,ref:m,tabIndex:-1},a.createElement("div",{className:"ps-budget-sheet-top"},a.createElement("div",{className:"ps-budget-sheet-title"},e),t?a.createElement("div",{className:"ps-budget-sheet-sub"},t):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 lt({label:e,hint:t,children:s}){return a.createElement("div",{className:"ps-budget-field",role:"group","aria-label":e},a.createElement("span",{className:"ps-budget-label"},e),s,t?a.createElement("span",{className:"ps-budget-field-hint"},t):null)}function is({value:e,options:t,onChange:s,label:n=null}){return a.createElement("div",{className:"ps-budget-seg",role:"group","aria-label":n||void 0},t.map(r=>a.createElement("button",{key:r.value,type:"button","aria-pressed":e===r.value?"true":"false",className:`ps-budget-seg-btn${e===r.value?" is-on":""}`,onClick:()=>s(r.value)},r.label)))}function $0(e){const t=e.known?N0[e.tone]||"":" idle";return a.createElement(a.Fragment,null,a.createElement("span",{className:`ps-budget-pct${t}`},e.usedLabel),e.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${e.uncapped?" is-inf":""}`},`/ ${e.quotaLabel}`))}function R0(e){if(!e.split)return a.createElement("span",{className:"ps-budget-split"},"—");const t="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 ",se(e.split.input)),a.createElement("span",null,"out ",se(e.split.output)),a.createElement("span",{title:t},"cache r ",se(e.split.cacheRead)),a.createElement("span",{title:t},"w ",se(e.split.cacheWrite)))}function L0(e,t,s){const n=e.kind==="model"?`${e.providerName} · ${e.label}`:e.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} · ${t.label} — ${r}. It ${Ji(s.resetsLabel)}.${i}${o}`}function O0({controller:e,view:t,defaults:s=null}){const n=a.useCallback((l,c="*")=>{e.selectBudgetProvider(l,c).catch(()=>{})},[e]),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),t.columns.map(c=>a.createElement("td",{key:c.id,className:"ps-budget-grid-num","data-period":c.label,title:L0(l,c,l.cells[c.id])},$0(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"}),t.columns.map(c=>a.createElement("td",{key:c.id,className:"ps-budget-grid-num is-split","data-period":c.label},R0(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${t.providerCount>0?` · ${t.providerCount}`:""}`),a.createElement("label",{className:"ps-budget-toggle"},a.createElement("input",{type:"checkbox",checked:t.overall,onChange:()=>e.setBudgetOverall()}),a.createElement("span",null,t.overallLabel))),t.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"},t.usageHeading)),a.createElement("tr",null,t.columns.map(l=>a.createElement("th",{key:l.id,className:"ps-budget-grid-h is-num",scope:"col"},l.label)))),a.createElement("tbody",null,t.rows.flatMap(l=>l.selected?[i(l),o(l)]:[i(l)]))))}function F0({controller:e,view:t}){const s=t.series,n=t.selected,r={className:"ps-budget-chart-pane","data-range-days":String(t.rangeDays)},[i,o]=a.useState(null),[l,c]=a.useState(0);a.useEffect(()=>{if(!i||typeof ResizeObserver>"u")return;const S=()=>{const E=Math.round(i.getBoundingClientRect().width);c(I=>Math.abs(E-I)<1?I:E)},w=new ResizeObserver(S);return w.observe(i),S(),()=>w.disconnect()},[i]);const d=s.days,u=d.length,p=a.useMemo(()=>{const E=l-(u-1)*5,I=l>0?Math.floor(E/30):7,T=Math.max(1,Math.min(7,I)),C=Math.max(1,Math.ceil(u/T)),k=new Set;for(let O=u-1;O>=0;O-=C)k.add(O);return k},[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"},` · ${t.usageHeading.toLowerCase()}, by day`)),a.createElement("div",{className:"ps-budget-chart-range"},a.createElement(is,{value:t.rangeDays,options:t.rangeOptions,label:"Chart range",onChange:S=>e.setBudgetRangeDays(S).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=C0(f),b=d.filter(S=>S.tokens>0).length,y=s.quotaPct==null?null:Math.max(0,Math.min(96,100-s.quotaPct)),v=a.createElement("div",{className:"ps-budget-xaxis"},a.createElement("div",{className:"ps-budget-xaxis-spacer"}),a.createElement("div",{className:"ps-budget-tl-x",ref:o},d.map((S,w)=>a.createElement("span",{key:S.dayUtc,className:p.has(w)?"is-tick":void 0},p.has(w)?S.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(S=>a.createElement("div",{key:`t${S}`,className:"ps-budget-ytick",style:{top:`${(1-S)*100}%`}},g(f*S))):null),a.createElement("div",{className:"ps-budget-plot"},f>0?h.map(S=>a.createElement("div",{key:`g${S}`,className:"ps-budget-gridline",style:{top:`${(1-S)*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(S=>a.createElement("div",{key:S.dayUtc,className:`ps-budget-tl-col${S.tokens===0?" is-idle":""}${s.quotaTokens!=null&&S.tokens>s.quotaTokens?" is-over":""}`,title:`${S.label} · ${S.tokens?`${S.tokens.toLocaleString("en-US")} tokens · ${P0(S.turns,"turn","turns")}`:"no usage"}`},a.createElement("div",{className:"ps-budget-tl-bar",style:{height:S.tokens===0?"2px":`${Math.max(1,S.pct)}%`}})))),s.empty?a.createElement("div",{className:"ps-budget-noaxis"},`No token usage on ${n.subject} in this range.`):null)),v,a.createElement("div",{className:"ps-budget-xaxis-title"},`Daily totals · UTC · ${s.rangeLabel.toLowerCase()}`),a.createElement("div",{className:"ps-budget-legend"},a.createElement("span",null,`Peak ${s.peakLabel} tokens/day`),a.createElement("span",null,`${b} of ${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 D0({view:e}){const t=e.systemSpend;if(!t)return null;const s=n=>String(n||"").startsWith(`${e.selectedProvider}:`)?String(n).slice(e.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"},t.rangeLabel)),t.loading&&!t.loaded?a.createElement("div",{className:"ps-budget-empty"},"Reading system spend…"):null,t.error?a.createElement("div",{className:"ps-budget-empty is-error",role:"alert"},t.error):null,t.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,t.tokensLabel),a.createElement("span",null,"tokens")),a.createElement("div",{className:"ps-budget-system-stat"},a.createElement("strong",null,se(t.turns)),a.createElement("span",null,t.turns===1?"turn":"turns")),t.turns>0?a.createElement("div",{className:"ps-budget-system-stat"},a.createElement("strong",null,se(Math.round(t.tokens/t.turns))),a.createElement("span",null,"tokens / turn")):null),t.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,t.models.map(n=>{const r=t.tokens>0?n.tokens/t.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"},se(n.turns)))}))):a.createElement("div",{className:"ps-budget-sub"},"No system spend in this range.")):null)}function B0({row:e,rawRows:t,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=e.class==="shared",h=e.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"),[v,S]=a.useState(p),[w,E]=a.useState(m==="*"?"all":"model"),[I,T]=a.useState(m==="*"?"":m),[C,k]=a.useState("");a.useEffect(()=>{!I&&s[0]&&T(s[0].qualifiedName)},[s,I]);const O=t.find(K=>K.providerName===e.providerName&&K.rowKind!=="model")||null,N=w==="model"?I||s[0]?.qualifiedName||"":null,R=w==="model"?t.find(K=>K.providerName===e.providerName&&K.rowKind==="model"&&K.scope===N)||null:O,H=R?.periods?.[v]||null,x=H?.quotaTokens??null,P=R?Number(H?.usedTokens)||0:null,_=P!=null,$=e.cells[v]?.resetsLabel||null,B=Ac[v]||v,j=N||"all models";a.useEffect(()=>{k(x==null?"":Number(x).toLocaleString("en-US"))},[x,v,N]);const W=T0(C),A=!!W&&(w!=="model"||!!N),G=x!=null,D=Number.isFinite(e.allowancePct)?e.allowancePct:100,Y=W==null||D>=100?W:Math.max(1,Math.floor(W*D/100)),J=Number(H?.yourUsedTokens),te=_&&W!==null&&P>=W,Z=!te&&W!==null&&Y!==W&&Number.isFinite(J)&&J>=Y,ne=Number.isFinite(e.allowancePct)?e.allowancePct:100,[ae,oe]=a.useState(String(ne)),ve=Number(String(ae).trim()),be=Number.isFinite(ve)&&ve>=1&&ve<=100&&Math.floor(ve)===ve,Q=["day","week","month"].map(K=>({id:K,label:Ac[K],tokens:O?.periods?.[K]?.quotaTokens??null})).filter(K=>K.tokens!=null),ce=!!e.hold,[ge,Qe]=a.useState(ce?"release":"forever"),[$e,it]=a.useState(""),Ye=(()=>{if(ge!=="until"||!$e)return null;const K=new Date($e);return Number.isNaN(K.getTime())?null:K.toISOString()})(),It=!!Ye&&Date.parse(Ye)<=Date.now(),V=ge!=="until"||!!Ye&&!It,me=ge!=="until"?null:It?"That time has already passed. A hold has to end in the future.":$e&&!Ye?"That is not a time this can read.":null,Be={limit:"Limits",allowance:"Allowance",hold:"Hold"},ke={limit:G?"Replace limit":"Save limit",allowance:"Save allowance",hold:ge==="release"?"Release hold":"Place hold"},de={limit:"Limits are enforced.",allowance:"Applies to everyone.",hold:"Stops new turns."},Re=b==="limit"?A:b==="allowance"?be:b==="hold"?V:!0,Ie=()=>{b==="limit"?A&&u("limit",{period:v,model:N,tokens:W}):b==="allowance"?be&&u("allowance",{pct:ve}):b==="hold"&&u("hold",ge==="release"?{release:!0,untilUtc:null}:{release:!1,untilUtc:Ye})},et=a.createElement(a.Fragment,null,a.createElement(lt,{label:"Time period",hint:"One limit per period and scope."},a.createElement(is,{value:v,onChange:S,options:A0,label:"Time period"})),a.createElement(lt,{label:"Applies to"},a.createElement(is,{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:I,onChange:K=>T(K.target.value)},s.length===0?a.createElement("option",{value:""},n?"Loading models…":r?"Model catalog unavailable":"No models listed for this provider"):s.map(K=>a.createElement("option",{key:K.qualifiedName,value:K.qualifiedName},K.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(lt,{label:"Tokens",hint:W?`= ${W.toLocaleString("en-US")} tokens.`:C.trim()?"A whole number of tokens: 20,000,000 or 20M.":"Remove the limit to uncap."},a.createElement("input",{className:`ps-budget-input${C&&!W?" is-invalid":""}`,value:C,"aria-label":"Tokens",placeholder:"20,000,000 or 20M",onChange:K=>k(K.target.value),onKeyDown:K=>{K.key==="Enter"&&Ie()}})),a.createElement("div",{className:"ps-budget-consequences"},a.createElement("div",null,`${B} · ${j} — `,_?a.createElement(a.Fragment,null,a.createElement("strong",null,`${P.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.")),$?a.createElement("div",{className:"ps-budget-sub"},`Resets ${$}.`):null),G?a.createElement("div",{className:"ps-budget-note is-warn"},`Replaces the existing ${se(x)} token limit.`):null,a.createElement("div",{className:`ps-budget-note${te||Z?" is-warn":""}`},"Current spend counts. Saving does not reset usage.",te?` ${P.toLocaleString("en-US")} already meets ${W.toLocaleString("en-US")}, so sessions on ${e.providerName} pause on their next turn${$?` — until this period ${Ji($)}`:""}.`:Z?` At ${D}% each that is ${Y.toLocaleString("en-US")} per person, which you have already spent — so sessions pause on their next turn${$?` — until this period ${Ji($)}`:""}.`:""),G?a.createElement("div",null,a.createElement("button",{type:"button",className:"ps-mini-button is-danger",disabled:l,onClick:()=>u("removeLimit",{period:v,model:N})},`Remove the ${B} · ${j} limit`),a.createElement("div",{className:"ps-budget-note"},"Usage history is kept.")):null),z=a.createElement(a.Fragment,null,a.createElement(lt,{label:"Share per person",hint:be?ve>=100?"100% removes the per-person ceiling.":`Each person may use up to ${ve}% of each limit, per period.`:"A whole number from 1 to 100."},a.createElement("input",{className:`ps-budget-input${ae&&!be?" is-invalid":""}`,value:ae,"aria-label":"Share per person, as a percentage",inputMode:"numeric",placeholder:"20",onChange:K=>oe(K.target.value),onKeyDown:K=>{K.key==="Enter"&&be&&Ie()}})),a.createElement("div",{className:"ps-budget-consequences"},Q.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,Q.map(K=>a.createElement("div",{key:K.id},`${K.label} · ${se(K.tokens)} → `,a.createElement("strong",null,be?`${se(Math.floor(K.tokens*ve/100))} per person`:"—"))),a.createElement("div",{className:"ps-budget-note"},"The provider limit still caps total spend.")),be&&ve<ne?a.createElement("div",{className:"ps-budget-note is-warn"},"Users already past the new ceiling pause on their next turn."):null)),M=a.createElement(a.Fragment,null,a.createElement(lt,{label:"What to do"},a.createElement(is,{value:ge,onChange:Qe,label:"What to do",options:[...ce?[{value:"release",label:"release it"}]:[],{value:"forever",label:"hold until released"},{value:"until",label:"hold until a time"}]})),ge==="until"?a.createElement(lt,{label:"Ends at",hint:me||"Sessions resume at this time."},a.createElement("input",{className:`ps-budget-input${$e&&!V?" is-invalid":""}`,"aria-label":"The hold ends at",type:"datetime-local",value:$e,onChange:K=>it(K.target.value)})):null,ce?a.createElement("div",{className:"ps-budget-consequences"},a.createElement("div",null,`This provider is on hold: it ${e.hold.label}.`)):null,a.createElement("div",{className:`ps-budget-note${ge==="release"?"":" is-warn"}`},ge==="release"?`Releasing wakes every session waiting on ${e.providerName}. A session still over a limit stays paused for that reason instead.`:`Every session on ${e.providerName} pauses on its next turn. Messages sent to them are kept and answered when the hold lifts.`));return a.createElement(wp,{title:Be[b],subtitle:`${e.providerName}${f?" · shared":""}`,confirmLabel:ke[b]||"",danger:b==="hold"&&ge==="release",busy:l,disabled:!Re,error:c,onCancel:d,onConfirm:ke[b]?Ie:null,cancelLabel:ke[b]?"Cancel":"Done",footNote:de[b]},g.length>1?a.createElement(lt,{label:"What to change"},a.createElement(is,{value:b,onChange:y,options:g,label:"What to change"})):null,b==="limit"?et:null,b==="allowance"?z:null,b==="hold"?M:null)}function H0({types:e,existingNames:t,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||e[0]?.id||""),[y,v]=a.useState(""),[S,w]=a.useState(""),[E,I]=a.useState(s&&d),T=a.useRef(null);a.useEffect(()=>{T.current?.focus()},[]),a.useEffect(()=>{!g&&e[0]&&b(e[0].id)},[e,g]);const C=f.trim(),k=!m&&t.some(j=>j.toLowerCase()===C.toLowerCase()),O=C!==""&&!/^[A-Za-z0-9._-]+$/.test(C),N=C.length>64,R=e.find(j=>j.id===g)?.usesWorkloadIdentity===!0,H=R,x=H?!0:E,P=!!C&&!k&&!O&&!N&&!!g&&(R||!!y.trim())&&(!H||s),_=/github/i.test(g),$=()=>{if(!P)return;const j={name:C,type:g,shared:x,credentials:R?{kind:"workloadIdentity"}:_?{githubToken:y.trim()}:{apiKey:y.trim()},baseUrl:S.trim()||null};v(""),l(j)},B=()=>{v(""),o()};return a.createElement(wp,{title:m?`Update key for ${C}`:_?"Add GitHub Copilot provider":"Add model provider",subtitle:x?"Shared":"Personal",confirmLabel:m?"Update key":"Add provider",busy:n,disabled:!P,error:r,onCancel:B,onConfirm:$,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(lt,{label:"Name",hint:k?"A provider with that name already exists, and names are unique across the cluster.":N?`Too long: ${C.length} characters, and a name may be at most 64.`:O?'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:T,className:`ps-budget-input${m?" is-static":""}${(k||O||N)&&C?" 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"&&P&&$()}})),a.createElement(lt,{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)}},e.length===0?a.createElement("option",{value:""},"No provider types are listed on this deployment"):e.map(j=>a.createElement("option",{key:j.id,value:j.id},j.id)))),R?a.createElement(lt,{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(lt,{label:m?_?"New GitHub Copilot token":"New API key":_?"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?_?"New GitHub Copilot token":"New API key":_?"GitHub Copilot token":"API key",value:y,placeholder:"Paste token",onChange:j=>{i?.(),v(j.target.value)},onKeyDown:j=>{j.key==="Enter"&&P&&$()}})),m?null:a.createElement(lt,{label:"Base URL",hint:"Optional."},a.createElement("input",{className:"ps-budget-input",value:S,placeholder:"https://…","aria-label":"Base URL",onChange:j=>w(j.target.value)})),H&&!m?a.createElement(lt,{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(lt,{label:"Access"},a.createElement(is,{value:E?"shared":"mine",onChange:j=>I(j==="shared"),label:"Access",options:[{value:"shared",label:"Shared"},{value:"mine",label:"Only me"}]})):null)}function U0(e){const t=e.budget||{};return[!!e.ui?.budgetOpen,t.loading,t.refreshing,t.loaded,t.error,t.grid,t.paused,t.overall,t.selectedProvider,t.selectedScope,t.missingProvider,t.series,t.tab,t.summary,e.auth?.authorization?.role,e.admin?.profile]}const Nc=["#5b8def","#e8833a","#3fb27f","#c95d63","#8f6fd8","#2fa8bf","#c9a227","#d1699e","#7a9a3b","#8a8a8a"],ea=e=>Nc[e%Nc.length];function j0({view:e,included:t}){const l=e.agents.filter(b=>t.has(b.agent)).map(b=>b.agent),c=e.dayKeys.map(b=>{const y=e.daily.get(b)||new Map;return l.reduce((v,S)=>v+(y.get(S)||0),0)}),d=Math.max(0,...c)||1,u=180,p=b=>u-b/d*u,m=Math.max(1,e.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"},Te(b*d)))),e.dayKeys.map((b,y)=>{const v=e.daily.get(b)||new Map,S=58+y*f+(f-h)/2;let w=0;const E=l.map((T,C)=>{const k=v.get(T)||0;if(k<=0)return null;const O=8+p(w);w+=k;const N=8+p(w);return a.createElement("rect",{key:T,x:S,y:N,width:h,height:Math.max(.5,O-N-.5),fill:ea(e.agents.findIndex(R=>R.agent===T))})}),I=`${b}: ${Te(w)} tokens
107
- `+l.map(T=>[T,v.get(T)||0]).filter(([,T])=>T>0).sort((T,C)=>C[1]-T[1]).map(([T,C])=>`${T}: ${Te(C)}`).join(`
108
- `);return a.createElement("g",{key:b,className:"ps-summary-chart__bar"},a.createElement("title",null,I),E,y%g===0||y===m-1?a.createElement("text",{x:S+h/2,y:204,className:"ps-summary-chart__day",textAnchor:"middle"},b.slice(5)):null)}))}const Cc={agent:(e,t)=>e.agent.localeCompare(t.agent),turns:(e,t)=>t.turns-e.turns,sessions:(e,t)=>t.sessions-e.sessions,total:(e,t)=>t.total-e.total,perTurn:(e,t)=>t.perTurn-e.perTurn,cacheRead:(e,t)=>t.cacheRead-e.cacheRead};function G0(e){const t=e.budget?.agents||{},s=e.budget?.summary||{};return[t.loading,t.error,t.fetchedAt,s.days,s.preset,(s.providers||[]).join(","),(e.budget?.grid||[]).length]}function W0({controller:e}){const t=ee(e,G0,Ve),s=a.useMemo(()=>Rg(e.getState()),[e,t]),n=a.useMemo(()=>ru(e.getState()),[e,t]);a.useEffect(()=>{!s.loaded&&!s.loading&&!s.error&&e.loadUsageAgents().catch(()=>{})},[e]);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 I=new Set(E);return I.has(w)?I.delete(w):I.add(w),I}),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(Cc[o]||Cc.total),[s,o]),y=w=>e.setUsageSummaryFilter({days:w}).catch(()=>{}),v=({preset:w,providers:E})=>e.setUsageSummaryFilter({preset:w,providers:E}).catch(()=>{}),S=(w,E,I)=>a.createElement("th",{key:E,title:I||"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(kp,{view:n,onChange:v}),a.createElement("div",{className:"ps-budget-seg",role:"group","aria-label":"Window"},Ep.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 · ${Te(s.windowTotal)} tokens · untick a row below to slice the chart`)),s.loaded||s.windowTotal>0?a.createElement(j0,{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:ea(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"})),S("agent","Agent"),a.createElement("th",{title:"Distinct model names this agent ran in the window"},"Models"),S("turns","Turns"),S("sessions","Sessions"),S("total","Total"),S("perTurn","Tok/turn","Window average: total tokens over ledger turns"),S("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:ea(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"},Te(w.total)),a.createElement("td",null,Te(Math.round(w.perTurn))),a.createElement("td",null,Te(w.cacheRead)),a.createElement("td",null,Te(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(Ip,{values:s.dayKeys.map(E=>{const I=w.daily.find(T=>T.day===E);return I&&Number(I.total)||0})})))))))))}const Ep=[14,30,90],q0=[{id:"all",label:"All providers"},{id:"shared",label:"Shared providers"},{id:"users",label:"User providers"}];function z0(e){if(e.preset==="all")return"All providers";if(e.preset==="shared")return"Shared providers";if(e.preset==="users")return"User providers";const t=e.selectedProviders.length;return t===0?"No providers":t===1?e.selectedProviders[0]:`${t} providers`}function kp({view:e,onChange:t}){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"?[]:e.providers.filter(u=>d==="shared"?u.class==="shared":u.class!=="shared").map(u=>u.name),o=new Set(e.preset==="all"?e.providers.map(d=>d.name):e.preset==="custom"?e.selectedProviders:i(e.preset)),l=d=>{t({preset:d,providers:i(d)}),n(!1)},c=d=>{const u=new Set(o);u.has(d)?u.delete(d):u.add(d),t({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)},z0(e)," ",a.createElement("span",{"aria-hidden":"true"},"▾")),s?a.createElement("div",{className:"ps-summary-picker__menu",role:"listbox","aria-label":"Providers"},q0.map(d=>a.createElement("button",{key:d.id,type:"button",role:"option","aria-selected":e.preset===d.id,className:`ps-summary-picker__preset${e.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:()=>t({preset:"custom",providers:[]})},"Clear all"),e.providers.length===0?a.createElement("div",{className:"ps-summary-picker__empty"},"No providers to choose from."):e.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 Te(e){return se(Number(e)||0)}function K0({series:e}){const o=e.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,e.length),f=662/m,h=Math.max(3,f*.66),g=[0,.25,.5,.75,1].map(y=>({f:y,label:Te(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, ${e.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))),e.map((y,v)=>{const S=58+v*f+(f-h)/2,w=Math.min(y.input,y.cacheRead),E=Math.min(y.input-w,y.cacheWrite),I=y.input-w-E,T=I+w,C=y.input,k=C+y.output,O=8+u,N=8+p(I),R=8+p(T),H=8+p(C),x=8+p(k),P=`${y.day}: ${Te(y.total)} tokens · in ${Te(y.input)} (cache r ${Te(y.cacheRead)} · w ${Te(y.cacheWrite)}) · out ${Te(y.output)} · ${y.turns} turns`;return a.createElement("g",{key:y.day,className:"ps-summary-chart__bar"},a.createElement("title",null,P),a.createElement("rect",{x:S,y:N,width:h,height:Math.max(0,O-N),className:"is-in"}),a.createElement("rect",{x:S,y:R,width:h,height:Math.max(0,N-R),className:"is-cache"}),a.createElement("rect",{x:S,y:H,width:h,height:Math.max(0,R-H),className:"is-cache-w"}),a.createElement("rect",{x:S,y:x,width:h,height:Math.max(0,H-x),className:"is-out"}),v%b===0||v===m-1?a.createElement("text",{x:S+h/2,y:184,className:"ps-summary-chart__day",textAnchor:"middle"},y.day.slice(5)):null)}))}function Ip({values:e}){const t=Math.max(0,...e);return a.createElement("span",{className:"ps-summary-spark","aria-hidden":"true",style:{gridAutoColumns:e.length>30?"2px":"4px"}},e.map((s,n)=>a.createElement("i",{key:n,style:{height:`${t>0?Math.max(s>0?8:0,s/t*100):0}%`}})))}function yi({label:e,w:t}){return a.createElement("div",{className:"ps-summary-kpi"},a.createElement("div",{className:"ps-summary-kpi__label"},e),a.createElement("div",{className:"ps-summary-kpi__value"},Te(t.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 ",Te(t.input)),a.createElement("span",null,a.createElement("i",{className:"ps-summary-dot is-cache"}),"cache r ",Te(t.cacheRead)),a.createElement("span",null,a.createElement("i",{className:"ps-summary-dot is-cache-w"}),"w ",Te(t.cacheWrite)),a.createElement("span",null,a.createElement("i",{className:"ps-summary-dot is-out"}),"out ",Te(t.output)),a.createElement("span",null,`· ${t.turns} turns`)))}function V0(e){const t=e.budget?.summary||{};return[t.loading,t.error,t.fetchedAt,t.days,t.preset,(t.providers||[]).join(","),(e.budget?.grid||[]).length]}function Y0({controller:e}){const t=ee(e,V0,Ve),s=a.useMemo(()=>ru(e.getState()),[e,t]);a.useEffect(()=>{!s.loaded&&!s.loading&&!s.error&&e.loadUsageSummary().catch(()=>{})},[e]);const n=l=>e.setUsageSummaryFilter({days:l}).catch(()=>{}),r=({preset:l,providers:c})=>e.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(kp,{view:s,onChange:r}),a.createElement("div",{className:"ps-budget-seg",role:"group","aria-label":"Window"},Ep.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(yi,{label:"Today (UTC)",w:s.windows.day}),a.createElement(yi,{label:"Last 7 days",w:s.windows.week}),a.createElement(yi,{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} · ${Te(s.windowTotal)} tokens`),null),s.windowTotal>0||s.loaded?a.createElement(K0,{series:s.series}):null,i.length>1?a.createElement("div",{className:"ps-summary__muted"},"By charge: ",i.map((l,c)=>`${c?" · ":""}${l.chargeClass} ${Te(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,Te(l.input)),a.createElement("td",null,Te(l.output)),a.createElement("td",null,Te(l.cacheRead)),a.createElement("td",null,Te(l.cacheWrite)),a.createElement("td",{className:"is-total"},Te(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(Ip,{values:l.sparkline})))))))))}function X0({controller:e}){const t=ee(e,U0,Ve),s=a.useMemo(()=>Lg(e.getState()),[e,t]),n=a.useMemo(()=>e.getState().budget?.grid||[],[e,t]),[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 e.transport.getDefaults=="function"&&Promise.resolve(e.transport.getDefaults()).then(B=>g(B||null)).catch(()=>{})},[e]);a.useEffect(()=>{let B=!0;return l(!0),Promise.resolve().then(()=>{if(typeof e.transport.listModels!="function")throw new Error("Model catalog unavailable");return e.transport.listModels()}).then(j=>{B&&(i(_0(j)),d(!1))}).catch(()=>{B&&d(!0)}).finally(()=>{B&&l(!1)}),typeof e.transport.listProviders=="function"&&Promise.resolve(e.transport.listProviders()).then(j=>{if(!B)return;const W=new Map;for(const A of j?.providers||[])W.set(A.name,A.typeId||"");f(W)}).catch(()=>{}),b(),()=>{B=!1}},[e,b,u]),a.useEffect(()=>{const B=e.getState().budget||{};!B.loaded&&!B.loading&&!B.error&&e.loadProviderTable().catch(()=>{})},[e]),a.useEffect(()=>{const B=setInterval(()=>{e.refreshProviderTable().catch(()=>{})},6e4);return()=>clearInterval(B)},[e]),a.useEffect(()=>{const B=j=>{if(j.key!=="Escape")return;const W=j.target,A=W&&W.tagName;A==="SELECT"||A==="INPUT"||A==="TEXTAREA"||e.getState().ui.modal||document.querySelector(".ps-budget-sheet")||(j.preventDefault(),j.stopPropagation(),e.closeBudget())};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[e]);const[y,v]=a.useState(null),[S,w]=a.useState(!1),[E,I]=a.useState(null),T=a.useRef(null),C=B=>{T.current=typeof document<"u"?document.activeElement:null,I(null),w(!1),v(B)},k=a.useCallback(()=>{v(null),I(null),w(!1);const B=T.current;T.current=null,B&&typeof B.focus=="function"&&document.contains(B)&&B.focus()},[]),O=async(B,{keepOpen:j=!1,onDone:W=null}={})=>{w(!0),I(null);const A=await B();if(w(!1),!A||A.ok!==!0){I(A?.error||"The change was refused.");return}j||k(),W&&W(A.result||null)},N=B=>e.dispatch({type:"ui/status",text:B}),R=s.selected,H=s.selectedProviderRow,x=R?M0(r,{name:R.providerName,typeId:m.get(R.providerName)||""},n):[];let P=null;y?.kind==="edit"&&H&&(P=a.createElement(B0,{row:H,rawRows:n,models:x,isAdmin:s.isAdmin,modelsLoading:o,modelsError:c,onRetryModels:()=>p(B=>B+1),initialPeriod:y.period||"day",initialScope:y.scope||"*",busy:S,error:E,onCancel:k,onRun:(B,j)=>{const W=R.providerName;if(B==="limit")return O(()=>e.setProviderLimit({provider:W,...j}),{onDone:A=>{const G=Number(A?.seededTokens)||0;N(G>0?`Limit saved. This period had already spent ${se(G)} tokens, and they count against it.`:"Limit saved. This period has spent nothing against it yet.")}});if(B==="removeLimit")return O(()=>e.removeProviderLimit({provider:W,...j}),{onDone:()=>N(`That period no longer caps ${W}.`)});if(B==="allowance")return O(()=>e.setProviderAllowance({provider:W,pct:j.pct}),{onDone:()=>N(j.pct>=100?`Everyone shares the whole of ${W} again.`:`Each person may now use up to ${j.pct}% of each of ${W}'s limits.`)});if(B==="hold")return O(()=>e.setProviderHold({provider:W,...j}),{onDone:()=>{if(j.release){N(`The hold on ${W} is released. Sessions waiting on it wake up.`);return}const A=(e.getState().budget?.grid||[]).find(D=>D.providerName===W&&D.rowKind!=="model"),G=A?.holdIndefinite===!0||(A?.holdUntilUtc?Date.parse(A.holdUntilUtc)>Date.now():!1);N(G?`${W} is on hold. No new turn runs against it until it is released.`:`${W} is NOT on hold: the time given has already passed.`)}})}}));const _=a.createElement("div",{className:"ps-budget-head"},a.createElement("div",{className:"ps-budget-headline"},a.createElement("span",{className:"ps-budget-coin","aria-hidden":"true"},"◎"),a.createElement("h2",{className:"ps-budget-h"},"Providers & Budgets"),a.createElement("span",{className:"ps-budget-sub"},"Usage and limits")),a.createElement("div",{className:"ps-budget-head-actions"},a.createElement(Se,{icon:"↻",label:"Refresh providers and budgets",className:"ps-mini-button",disabled:s.loading||s.refreshing,onClick:()=>e.refreshProviderTable().catch(()=>{})})));let $;return s.failed?$=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:()=>e.loadProviderTable().catch(()=>{})},"Try again")),a.createElement("div",{className:"ps-budget-sub"},s.error)):s.loading&&!s.loaded?$=a.createElement("div",{className:"ps-budget-empty"},"Reading providers and budgets…"):$=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&&e.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:()=>{e.closeBudget(),e.openAdminConsole()}},"Open Model Providers")):null,a.createElement("div",{className:`ps-budget-body${s.refreshing?" is-refreshing":""}`},a.createElement(O0,{controller:e,view:s,defaults:h}),a.createElement("div",{className:"ps-budget-actions"},a.createElement(Se,{icon:a.createElement(pp),label:"Edit usage policy",className:"ps-mini-button",disabled:!H||!H.manageable,onClick:()=>C({kind:"edit",scope:R?.kind==="model"?R.scope:"*"})}),a.createElement("span",{className:"ps-budget-sub"},R?R.providerName:"No provider selected")),a.createElement("div",{className:"ps-budget-foot ps-budget-sub"},"Manage providers and defaults in Admin Console."),R?a.createElement(F0,{controller:e,view:s}):null,R?a.createElement(D0,{view:s}):null)),a.createElement("div",{className:"ps-budget-surface"},_,a.createElement("div",{className:"ps-budget-tabs",role:"tablist"},[["providers","Providers"],["summary","Cluster summary"],["agents","Agents"]].map(([B,j])=>a.createElement("button",{key:B,type:"button",role:"tab","aria-selected":(e.getState().budget?.tab||"providers")===B,className:`ps-budget-tab${(e.getState().budget?.tab||"providers")===B?" is-on":""}`,onClick:()=>e.setBudgetTab(B)},j))),(e.getState().budget?.tab||"providers")==="summary"?a.createElement("div",{className:"ps-budget"},a.createElement(Y0,{controller:e})):e.getState().budget?.tab==="agents"?a.createElement("div",{className:"ps-budget"},a.createElement(W0,{controller:e})):a.createElement("div",{className:"ps-budget"},$),P)}function ta({controller:e}){const t=ee(e,y=>y.ui.themeId),s=ee(e,y=>!!y.ui.touchScale),n=Pt(t),r=ee(e,y=>({rawModal:y.ui.modal,themePicker:Hy(y),modelPicker:py(y),reasoningEffortPicker:fy(y),contextTierPicker:hy(y),sessionAgentPicker:my(y),sessionGroupPicker:gy(y),sessionGroupName:by(y),artifactPicker:ky(y),logFilter:wy(y),filesFilter:Ey(y),historyFormat:By(y),renameSession:yy(y),sessionOwnerFilter:vy(y),artifactUpload:Sy(y),confirm:Uy(y),logsFilter:y.logs.filter,filesFilterState:y.files.filter,historyFormatState:y.executionHistory?.format||"pretty"}),Ve),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 v=y.querySelector(".ps-list-button.is-selected");v&&typeof v.scrollIntoView=="function"&&v.scrollIntoView({block:"nearest"})},[i?.type,i?.selectedIndex,r.themePicker?.selectedRowIndex,r.modelPicker?.selectedRowIndex,r.reasoningEffortPicker?.selectedRowIndex,r.contextTierPicker?.selectedRowIndex,r.sessionAgentPicker?.selectedRowIndex,r.sessionGroupPicker?.selectedRowIndex,r.artifactPicker?.selectedRowIndex,r.sessionOwnerFilter?.selectedRowIndex,r.logFilter?.selectedRowIndex,r.filesFilter?.selectedRowIndex,r.historyFormat?.selectedRowIndex]),!i)return null;const m=()=>e.handleCommand(L.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=>e.dispatch({type:"ui/touchScale",enabled:y.target.checked})}),a.createElement("span",null,"Mobile")),h=(y,v="Apply",S=null,w=null)=>{const E=Array.isArray(y.rows)?y.rows:[],I=Array.isArray(y.rowItemIndexes)?y.rowItemIndexes:null,T=i.type==="modelPicker"||i.type==="reasoningEffortPicker"||i.type==="contextTierPicker"||i.type==="sessionAgentPicker",C=I&&I.length===E.length?E.map((k,O)=>{const N=I[O],R=Array.isArray(k)?k:rt([k])[0]?.runs||[{text:k?.text||"",color:k?.color}];if(N==null||N<0)return a.createElement("div",{key:`row:${O}`,className:"ps-line ps-modal-list-heading-line"},a.createElement(Je,{runs:R,theme:n}));const H=i.items?.[N];return a.createElement("button",{key:H?.id||`row:${O}`,type:"button",className:`ps-list-button ps-modal-list-button${N===i.selectedIndex?" is-selected":""}${T?" is-hanging":""}${H?.disabled?" is-disabled":""}`,onClick:()=>{e.dispatch({type:"ui/modalSelection",index:N})}},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Je,{runs:R,theme:n})))}):(i.items||[]).flatMap((k,O,N)=>{const R=a.createElement("button",{key:k.id||O,type:"button",className:`ps-list-button ps-modal-list-button${O===i.selectedIndex?" is-selected":""}${T?" is-hanging":""}${k?.disabled?" is-disabled":""}`,onClick:()=>e.dispatch({type:"ui/modalSelection",index:O})},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Je,{runs:Array.isArray(E?.[O])?E[O]:rt([E?.[O]])[0]?.runs||[{text:E?.[O]?.text||"",color:E?.[O]?.color}],theme:n})));return k?.group&&k.group!==N[O-1]?.group?[a.createElement("div",{key:`group:${k.group}`,className:"ps-modal-list-group","aria-hidden":"true"},k.group),R]:[R]});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: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"},"✕")),w,a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:c,className:"ps-modal-list"},C),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),rt(y.detailsLines||[]).map((k,O)=>a.createElement(ct,{key:`detail:${O}`,line:k,theme:n,className:"ps-modal-detail-line"})))),a.createElement("div",{className:"ps-modal-footer"},S,a.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>e.handleCommand(L.MODAL_CONFIRM).catch(()=>{})},v))))};if(i.type==="confirm"&&r.confirm){const y=!!i.alert,v=!y&&i.action==="deleteSession",S=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)),S?a.createElement("div",{className:"ps-modal-body",style:{padding:"0 20px 12px",display:"flex",flexDirection:"column",gap:10}},a.createElement("label",{style:{color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8}},"Distillation",a.createElement("select",{className:"ps-modal-input",style:{flex:"1",padding:"4px 8px"},value:w.distillMode||"llm",onChange:E=>e.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(Q0,{controller:e,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=>e.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 ${v?"is-danger":"is-primary"}`,onClick:()=>e.handleCommand(L.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"]],v=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:S=>e.setAgentPickerQuery(S.target.value),onKeyDown:S=>{["ArrowUp","ArrowDown","Enter","Escape","Tab"].includes(S.key)||S.stopPropagation()}}),a.createElement("div",{className:"ps-agent-picker-sorts",role:"group","aria-label":"Sort agents"},y.map(([S,w,E])=>a.createElement("button",{key:S,type:"button",className:`ps-agent-picker-sort${(i.sort||"used")===S?" is-on":""}`,title:E,"aria-pressed":(i.sort||"used")===S?"true":"false",onClick:()=>e.setAgentPickerSort(S)},w))));return h(r.sessionAgentPicker,"Create Session",null,v)}if(i.type==="sessionGroupPicker"&&r.sessionGroupPicker)return h(r.sessionGroupPicker,"Move");if(i.type==="artifactPicker"&&r.artifactPicker)return h(r.artifactPicker,r.artifactPicker.confirmLabel||"Open / Download");if(i.type==="sessionOwnerFilter"&&r.sessionOwnerFilter){const y=r.sessionOwnerFilter,v=Array.isArray(y.rows)?y.rows:[],S=d.trim().toLowerCase(),w=I=>{const T=v?.[I];return(Array.isArray(T)?T:rt([T])[0]?.runs||[]).map(k=>k?.text||"").join("")||String(T?.text||"")},E=(i.items||[]).map((I,T)=>T).filter(I=>{if(!S)return!0;const T=(i.items||[])[I]||{};return`${w(I)} ${T.label||""} ${T.description||""}`.toLowerCase().includes(S)});return a.createElement("div",{className:"ps-modal-backdrop",onClick:m},a.createElement("div",{className:"ps-modal is-list",onClick:I=>I.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:I=>u(I.currentTarget.value),onKeyDown:I=>{I.key==="Escape"&&d&&(I.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(I=>(T=>a.createElement("button",{key:T.id||I,type:"button",className:`ps-list-button ps-modal-list-button${I===i.selectedIndex?" is-selected":""}`,onClick:()=>e.toggleSessionOwnerFilter(I)},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(Je,{runs:Array.isArray(v?.[I])?v[I]:rt([v?.[I]])[0]?.runs||[{text:v?.[I]?.text||"",color:v?.[I]?.color}],theme:n}))))((i.items||[])[I]||{}))),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),rt(y.detailsLines||[]).map((I,T)=>a.createElement(ct,{key:`detail:${T}`,line:I,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=>e.setRenameSessionValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),e.handleCommand(L.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},rt(r.renameSession.helpLines||[]).map((y,v)=>a.createElement(ct,{key:`help:${v}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>e.handleCommand(L.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=>e.setSessionGroupNameValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),e.handleCommand(L.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},rt(r.sessionGroupName.helpLines||[]).map((y,v)=>a.createElement(ct,{key:`help:${v}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>e.handleCommand(L.MODAL_CONFIRM).catch(()=>{})},r.sessionGroupName.mode==="rename"?"Rename":"Create and Move"))));if(i.type==="terminatePicker"){const y=Number(i.bulkCount)>1,v=!!i.systemRestart,S=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.`:v?`How should "${S}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${S}"? Choose an action; you'll be asked to confirm.`,I=T=>()=>{e.pickTerminateAction(T).catch(()=>{})};return a.createElement("div",{className:"ps-modal-backdrop",onClick:m},a.createElement("div",{className:"ps-modal is-narrow",onClick:T=>T.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:I("regenerate")},"Regenerate Context"):null,a.createElement("button",{type:"button",className:"ps-modal-button is-primary",style:{width:"100%",justifyContent:"flex-start"},onClick:I("complete")},y?`Mark ${w} Completed`:v?"Complete & Restart":"Mark Completed"),a.createElement("button",{type:"button",className:"ps-modal-button",style:{width:"100%",justifyContent:"flex-start"},onClick:I("cancel")},y?`Cancel ${w} Sessions`:v?"Terminate & Restart":"Cancel Session"),a.createElement("button",{type:"button",className:"ps-modal-button is-danger",style:{width:"100%",justifyContent:"flex-start"},onClick:I("delete")},y?`Hard Delete ${w} Sessions`:v?"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=>e.setArtifactUploadValue(y.currentTarget.value,y.currentTarget.selectionStart||y.currentTarget.value.length),autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},rt(r.artifactUpload.helpLines||[]).map((y,v)=>a.createElement(ct,{key:`help:${v}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:m},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>e.handleCommand(L.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,v)=>{const S=i.type==="filesFilter"?r.filesFilterState?.[y.id]||y.options?.[0]?.id:i.type==="historyFormat"?r.historyFormatState:r.logsFilter?.[y.id]||y.options?.[0]?.id;return a.createElement("div",{key:y.id||v,className:"ps-filter-column"},a.createElement("div",{className:"ps-filter-title"},y.label),(y.options||[]).map(w=>a.createElement("button",{key:w.id,type:"button",className:`ps-filter-option${w.id===S?" is-selected":""}`,onClick:()=>{e.dispatch({type:"ui/modalSelection",index:v}),i.type==="historyFormat"?e.dispatch({type:"executionHistory/format",format:w.id}):i.type==="filesFilter"?(e.dispatch({type:"files/filter",filter:{[y.id]:w.id}}),e.ensureFilesForScope(w.id).catch(()=>{})):e.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 Q0({controller:e,extras:t}){const s=Array.isArray(t.distillerModelOptions)?t.distillerModelOptions:[],n=s.find(d=>d.qualifiedName===t.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=>e.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:t.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:t.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:t.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 yE({controller:e}){const t=ee(e,s=>s.ui.modal);return xp(e,!1,!t),a.createElement(ta,{controller:e})}function xp(e,t,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=e.getState().ui.modal,c=Ga(e),d=e.getState().ui.inspectorTab,u=e.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=tv(c,d,g);e.selectInspectorTab(b).catch(()=>{})};if(!o&&m){r.preventDefault(),e.handleCommand(L.OPEN_THEME_PICKER).catch(()=>{});return}if(!o&&f){r.preventDefault(),e.handleCommand(L.OPEN_MODEL_PICKER).catch(()=>{});return}if(l&&!o){if(r.key==="Escape"||l.type==="confirm"&&r.key==="n"){r.preventDefault(),e.handleCommand(L.CLOSE_MODAL).catch(()=>{});return}if(r.key==="Enter"||l.type==="confirm"&&r.key==="y"){r.preventDefault(),e.handleCommand(L.MODAL_CONFIRM).catch(()=>{});return}if(r.key==="Tab"&&r.shiftKey){r.preventDefault(),e.handleCommand(L.MODAL_PANE_PREV).catch(()=>{});return}if(r.key==="Tab"){r.preventDefault(),e.handleCommand(L.MODAL_PANE_NEXT).catch(()=>{});return}if(r.key==="ArrowUp"||r.key==="k"){r.preventDefault(),e.handleCommand(L.MODAL_PREV).catch(()=>{});return}(r.key==="ArrowDown"||r.key==="j")&&(r.preventDefault(),e.handleCommand(L.MODAL_NEXT).catch(()=>{}));return}if(l&&o&&i instanceof HTMLElement&&i.dataset.modalSearch==="true"){if(r.key==="Escape"){r.preventDefault(),e.handleCommand(L.CLOSE_MODAL).catch(()=>{});return}if(r.key==="Enter"){r.preventDefault(),e.handleCommand(L.MODAL_CONFIRM).catch(()=>{});return}if(r.key==="ArrowUp"){r.preventDefault(),e.handleCommand(L.MODAL_PREV).catch(()=>{});return}if(r.key==="ArrowDown"){r.preventDefault(),e.handleCommand(L.MODAL_NEXT).catch(()=>{});return}return}if(!o){if(r.key==="r"&&p&&u!=="prompt"){r.preventDefault(),e.handleCommand(L.REFRESH).catch(()=>{});return}if(r.key==="n"&&p){r.preventDefault(),e.handleCommand(L.NEW_SESSION).catch(()=>{});return}if(u==="inspector"&&d==="files"&&(r.key==="u"&&p||(r.ctrlKey||r.metaKey)&&r.key.toLowerCase()==="a")){r.preventDefault(),e.handleCommand(L.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(u==="inspector"&&d==="files"&&r.key==="a"&&p){r.preventDefault(),e.handleCommand(L.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&d==="files"&&r.key==="x"&&p){r.preventDefault(),e.handleCommand(L.DELETE_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&d==="files"&&r.key==="o"&&p){r.preventDefault(),e.handleCommand(L.OPEN_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&d==="files"&&r.key==="f"&&p){r.preventDefault(),e.handleCommand(L.OPEN_FILES_FILTER).catch(()=>{});return}if(u==="inspector"&&d==="stats"&&r.key==="f"&&p){r.preventDefault(),e.handleCommand(L.TOGGLE_STATS_VIEW).catch(()=>{});return}if(u==="inspector"&&d==="files"&&r.key==="v"&&p){r.preventDefault(),e.handleCommand(L.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(u==="inspector"&&d==="logs"&&r.key==="t"&&p){r.preventDefault(),e.handleCommand(L.TOGGLE_LOG_TAIL).catch(()=>{});return}if(u==="inspector"&&d==="logs"&&r.key==="f"&&p){r.preventDefault(),e.handleCommand(L.OPEN_LOG_FILTER).catch(()=>{});return}if(u==="inspector"&&d==="history"&&r.key==="f"&&p){r.preventDefault(),e.handleCommand(L.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(u==="inspector"&&d==="history"&&r.key==="r"&&p){r.preventDefault(),e.handleCommand(L.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(u==="inspector"&&d==="history"&&r.key==="a"&&p){r.preventDefault(),e.handleCommand(L.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(r.key==="a"&&p){r.preventDefault(),e.handleCommand(L.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(r.key==="p"&&p){r.preventDefault(),e.handleCommand(L.FOCUS_PROMPT).catch(()=>{});return}if(r.key==="c"&&p){r.preventDefault(),e.handleCommand(L.CANCEL_SESSION).catch(()=>{});return}if(r.key==="d"&&p){r.preventDefault(),e.handleCommand(L.DONE_SESSION).catch(()=>{});return}if(r.key==="D"&&r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey){r.preventDefault(),e.handleCommand(L.DELETE_SESSION).catch(()=>{});return}if(r.key==="m"&&p&&u==="inspector"){r.preventDefault(),h(1);return}if(r.key==="["&&p){r.preventDefault(),e.handleCommand(L.GROW_LEFT_PANE).catch(()=>{});return}if(r.key==="]"&&p){r.preventDefault(),e.handleCommand(L.GROW_RIGHT_PANE).catch(()=>{});return}if(r.key==="{"&&p){r.preventDefault(),e.handleCommand(L.SHRINK_SESSION_PANE).catch(()=>{});return}if(r.key==="}"&&p){r.preventDefault(),e.handleCommand(L.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(),e.handleCommand(L.MOVE_SESSION_UP).catch(()=>{});return}if(u==="sessions"&&(r.key==="ArrowDown"||r.key==="j")){r.preventDefault(),e.handleCommand(L.MOVE_SESSION_DOWN).catch(()=>{});return}if(u==="sessions"&&r.ctrlKey&&r.key.toLowerCase()==="g"&&!r.metaKey&&!r.altKey){r.preventDefault(),e.handleCommand(L.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(u==="sessions"&&(r.key==="PageUp"||r.ctrlKey&&r.key.toLowerCase()==="u")){r.preventDefault(),e.handleCommand(L.PAGE_UP).catch(()=>{});return}if(u==="sessions"&&(r.key==="PageDown"||r.ctrlKey&&r.key.toLowerCase()==="d")){r.preventDefault(),e.handleCommand(L.PAGE_DOWN).catch(()=>{});return}if(u==="sessions"&&r.key==="t"&&p){r.preventDefault(),e.handleCommand(L.OPEN_RENAME_SESSION).catch(()=>{});return}if(!t&&(r.key==="PageUp"||r.ctrlKey&&r.key.toLowerCase()==="u")){r.preventDefault(),e.handleCommand(L.PAGE_UP).catch(()=>{});return}if(!t&&(r.key==="PageDown"||r.ctrlKey&&r.key.toLowerCase()==="d")){r.preventDefault(),e.handleCommand(L.PAGE_DOWN).catch(()=>{});return}if(!t&&r.key==="g"&&p){r.preventDefault(),e.handleCommand(L.SCROLL_TOP).catch(()=>{});return}if(!t&&r.key==="G"&&r.shiftKey&&!r.metaKey&&!r.ctrlKey&&!r.altKey){r.preventDefault(),e.handleCommand(L.SCROLL_BOTTOM).catch(()=>{});return}if(u!=="prompt"&&r.key==="h"&&p){r.preventDefault(),e.handleCommand(L.FOCUS_LEFT).catch(()=>{});return}if(u!=="prompt"&&r.key==="l"&&p){r.preventDefault(),e.handleCommand(L.FOCUS_RIGHT).catch(()=>{});return}if(!t&&u==="inspector"&&d==="files"&&(r.key==="ArrowUp"||r.key==="k")){r.preventDefault(),e.handleCommand(L.MOVE_FILE_UP).catch(()=>{});return}if(!t&&u==="inspector"&&d==="files"&&(r.key==="ArrowDown"||r.key==="j")){r.preventDefault(),e.handleCommand(L.MOVE_FILE_DOWN).catch(()=>{});return}if(!t&&(r.key==="ArrowUp"||r.key==="k")){r.preventDefault(),e.handleCommand(L.SCROLL_UP).catch(()=>{});return}if(!t&&(r.key==="ArrowDown"||r.key==="j")){r.preventDefault(),e.handleCommand(L.SCROLL_DOWN).catch(()=>{});return}!t&&r.key==="Escape"&&(r.preventDefault(),e.handleCommand(L.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e,t,s])}function Z0(e){if(!e)return"Unknown user";const t=String(e.displayName||"").trim(),s=String(e.email||"").trim();if(t&&s&&t.toLowerCase()!==s.toLowerCase())return`${t} <${s}>`;if(t)return t;if(s)return s;const n=String(e.provider||"").trim(),r=String(e.subject||"").trim();return[n,r].filter(Boolean).join(":")||"user"}function J0({controller:e,mobile:t=!1}){const s=ee(e,$t,Ve),n=ee(e,x=>x.admin.features),r=ee(e,x=>x.admin.workers),i=ee(e,x=>x.auth?.authorization?.role),o=s.packages||{},l=s.section==="packages",c=s.section==="workers",d=s.section==="features",u=a.createElement(HS,{controller:e,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,v]=a.useState(()=>{const x={wsWidth:440,treePct:44,navWidth:240};try{return{...x,...JSON.parse(window.localStorage.getItem("ps-admin-ws-layout")||"{}")}}catch{return x}}),S=a.useCallback(x=>{v(P=>{const _={...P,...x};_.wsWidth=Math.min(900,Math.max(300,Math.round(_.wsWidth))),_.treePct=Math.min(85,Math.max(15,_.treePct)),_.navWidth=Math.min(420,Math.max(170,Math.round(_.navWidth??240)));try{window.localStorage.setItem("ps-admin-ws-layout",JSON.stringify(_))}catch{}return _})},[]),w=a.useCallback(x=>{x.preventDefault(),document.body.style.cursor="col-resize";const P=x.clientX,_=y.navWidth??240,$=j=>S({navWidth:_+(j.clientX-P)}),B=()=>{window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",B),window.removeEventListener("pointercancel",B),document.body.style.cursor=""};window.addEventListener("pointermove",$),window.addEventListener("pointerup",B),window.addEventListener("pointercancel",B)},[y.navWidth,S]);a.useCallback(()=>{e.closeAdminConsole()},[e]);const E=a.useCallback(()=>{m(null),h(!1),b(null),e.dismissAdminModelProviderMutationError()},[e]),I=a.useCallback(async x=>{h(!0),b(null);const P=p?.update?await e.updateAdminProviderCredential({name:x.name,credentials:x.credentials,shared:x.shared===!0}):await e.createAdminProvider(x);if(h(!1),!P?.ok){b(P?.error||`The provider key could not be ${p?.update?"updated":"created"}.`);return}E()},[E,e,p]),T=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),C=a.createElement(oE,{controller:e,view:s,sheetOpen:!!p,onAddPersonal:()=>{e.dismissAdminModelProviderMutationError(),m({shared:!1,github:!0})},onAddShared:()=>{e.dismissAdminModelProviderMutationError(),m({shared:!0,github:!1})},onUpdatePersonal:x=>{e.dismissAdminModelProviderMutationError(),m({update:x,shared:x.class==="shared"})}}),k=a.createElement(eE,{controller:e,view:s}),O=a.createElement(tE,{controller:e,view:s}),N=l&&o.selectedName?a.createElement(nE,{controller:e,view:s,layout:y,onLayout:S}):null,R=o.addDialog?.open?a.createElement(aE,{controller:e,dialog:o.addDialog}):null,H=p?a.createElement(H0,{types:s.modelProviders?.providerTypes||[],existingNames:[...s.modelProviders?.sharedProviders||[],...s.modelProviders?.myProviders||[]].map(x=>x.name),isAdmin:s.isAdmin,initialShared:p.shared,updateProvider:p.update||null,initialType:p.github?(s.modelProviders?.providerTypes||[]).find(x=>/github/i.test(x.id))?.id||"":p.update?.typeId||"",initialName:p.update?.name||"",busy:f,error:g,onDirty:()=>b(null),onCancel:E,onConfirm:I}):null;if(t){let x;return l&&o.selectedName?x=a.createElement("div",{className:"ps-admin-mobile-stack"},a.createElement("button",{type:"button",className:"ps-mini-button ps-admin-back",onClick:()=>e.selectAdminPackage(null)},"← All packages"),O,N):l?x=k:c?x=a.createElement("div",{className:"ps-admin-mobile-stack"},k,a.createElement(Tc,{controller:e,view:s})):x=a.createElement("div",{className:"ps-admin-mobile-stack"},k,d?u:C),a.createElement("div",{className:"ps-admin-console is-mobile"},T,s.loadError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,x,R,H)}return a.createElement("div",{className:"ps-admin-console is-workspace"},T,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"},k,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?O:c?a.createElement(Tc,{controller:e,view:s}):d?u:C),N),R,H)}function Tc({controller:e,view:t}){const s=t.workers||{},n=s.rows||[],r=s.counts||{};return a.useEffect(()=>{const i=window.setInterval(()=>{e.refreshAdminWorkers()},25e3);return()=>window.clearInterval(i)},[e]),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:()=>e.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 eE({controller:e,view:t}){const s=t.packages||{};return a.createElement("nav",{className:"ps-admin-tree"},a.createElement("div",{className:"ps-admin-tree__label"},"Settings"),(t.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"?()=>e.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"?(e.setAdminSection("providers"),e.setAdminModelProviderPage("mine")):n.id==="sharedProviders"?(e.setAdminSection("providers"),e.setAdminModelProviderPage("shared")):n.id==="features"?e.setAdminSection("features"):e.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(Yi,{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,t.section==="packages"?a.createElement("button",{type:"button",className:"ps-admin-tree__add",onClick:()=>e.openAdminAddPackage()},"+ Add package"):null)}function tE({controller:e,view:t}){const s=t.packages||{},n=s.detail;if(!s.selectedName)return a.createElement("div",{className:"ps-admin-detail is-empty"},a.createElement("h3",null,"Packages"),a.createElement("p",{className:"ps-admin-console__hint"},s.empty?"No packages yet. Add reusable skills, tools, MCP integrations, or authored agent workflows from a repo or folder — or use `pilotswarm agents push ./my-kit`.":"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.`)&&e.runAdminPackageAction("delete")},i=(c,d)=>()=>e.runAdminPackageAction(c,d),o=n.actionPending,l=async()=>{try{await e.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(sE,{controller:e,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:()=>e.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 e.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 sE({controller:e,detail:t,pending:s}){const[n,r]=a.useState(""),[i,o]=a.useState([]);a.useEffect(()=>{if(!t.canManage||typeof e.transport.listKnownUsers!="function")return;let m=!1;return e.transport.listKnownUsers({limit:500}).then(f=>{m||o(Array.isArray(f)?f:[])}).catch(()=>{}),()=>{m=!0}},[e,t.canManage]);const l=new Set(t.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(""),e.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"),t.editors.length?a.createElement("div",{className:"ps-admin-detail__chips"},t.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,t.canManage?a.createElement("button",{type:"button",className:"ps-chip-remove","aria-label":`Remove editor ${m.label}`,disabled:!!s,onClick:()=>e.runAdminPackageAction("revokeEditor",{provider:m.provider,subject:m.subject})},"×"):null))):a.createElement("p",{className:"ps-admin-console__hint"},t.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."),t.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 nE({controller:e,view:t,layout:s=null,onLayout:n=null}){const r=ee(e,p=>p.ui.themeId),i=Pt(r),o=t.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=v=>m(g,v.clientX-f,v.clientY-h),y=()=>{window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),document.body.style.cursor=""};window.addEventListener("pointermove",b),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)},[s,n]),d=a.useCallback(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?` · ${t.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"?()=>e.toggleAdminPackageDir(p.path):()=>e.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(iE,{file:o.file,theme:i}):null)):null}function rE(e){const t=/^---\n([\s\S]*?)\n---\n?/.exec(e||"");if(!t)return{meta:null,body:e||""};const s=t[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:e||""}:{meta:s,body:(e||"").slice(t[0].length)}}function iE({file:e,theme:t}){const s=e.language||"text",n=e.truncated?a.createElement("div",{className:"ps-admin-tree__hint"},"… truncated preview"):null;if(s==="markdown"){const{meta:r,body:i}=rE(e.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(Za,{content:i,theme:t}),n)}if(s==="json"){let r=e.text||"";if(!e.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,Bs(r,"json",t))),n)}return a.createElement("div",{className:"ps-admin-ws__doc"},a.createElement("pre",{className:`ps-admin-ws__code lang-${s}`},a.createElement("code",null,Bs(e.text||"",s,t))),n)}function aE({controller:e,dialog:t}){const s=ee(e,p=>p.docs?.agentPackageGuideUrl||null),n=p=>m=>e.setAdminAddPackageField(p,m.target.value),r=[["repo","GitHub / Azure DevOps"],["upload","Upload folder"]],i=t.kind==="repo"||t.kind==="github"||t.kind==="ado",o=a.useRef(null),[l,c]=a.useState(!1),d=2*1024*1024,u=p=>{if(p.preventDefault(),!(l||t.submitting)){if(t.kind==="upload"){const m=o.current;if(!m?.files?.length){e.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){e.failAdminAddPackage("The chosen folder has no uploadable files.");return}if(h>d){e.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,v)=>{const S=new FileReader;S.onerror=()=>v(new Error(`could not read ${b}`)),S.onload=()=>y({path:b,contentBase64:String(S.result).split(",",2)[1]||""}),S.readAsDataURL(g)}))).then(g=>e.submitAdminUploadPackage(g,t.scope)).catch(g=>e.failAdminAddPackage(g?.message||"Could not read the chosen folder.")).finally(()=>c(!1));return}e.submitAdminAddPackage().catch(()=>{})}};return a.createElement("div",{className:"ps-modal-backdrop",onClick:()=>e.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,t.updateName?`Update ${t.updateName}`:"Add package"),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>e.closeAdminAddPackage()},"✕")),a.createElement("div",{className:"ps-admin-add__body"},a.createElement("p",{className:"ps-admin-console__hint"},"Packages can contain reusable skills, tools, MCP integrations, and authored agent workflows. No agent is required."),a.createElement("div",{className:"ps-admin-add__tabs"},r.map(([p,m])=>a.createElement("button",{key:p,type:"button",className:`ps-admin-add__tab${t.kind===p?" is-on":""}`,onClick:()=>e.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:t.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:t.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:t.scope==="shared",disabled:!!t.updateName,onChange:()=>e.setAdminAddPackageField("scope","shared")})," Shared — everyone can use it"),a.createElement("label",null,a.createElement("input",{type:"radio",name:"pkg-scope",checked:t.scope==="user",disabled:!!t.updateName,onChange:()=>e.setAdminAddPackageField("scope","user")})," User — only you see it")),t.updateName?a.createElement("p",{className:"ps-admin-console__hint"},`Publishes a new version of ${t.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 a 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"),t.progress&&!t.error?a.createElement("p",{className:"ps-admin-add__progress"},t.progress):null,t.error?a.createElement("pre",{className:"ps-admin-add__error",role:"alert"},t.error):null),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>e.closeAdminAddPackage(),disabled:t.submitting},"Cancel"),a.createElement("button",{type:"submit",className:"ps-primary-button",disabled:t.submitting||l},l?"Reading folder…":t.submitting?"Importing…":t.updateName?"Import & update":"Import & publish"))))}function bi(e){return e?.configured?.model||""}function Si({label:e,hint:t,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"},e),a.createElement("select",{className:"ps-budget-input",value:s,disabled:r,"aria-label":e,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}`))),t?a.createElement("span",{className:"ps-admin-console__hint"},t):null)}function Pc({providers:e,isAdmin:t,personal:s,busy:n,onSystemUse:r,onUpdate:i,onDelete:o}){return e.length?a.createElement("div",{className:"ps-admin-provider-list"},e.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&&t?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||t)&&!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(Se,{icon:a.createElement(Dw),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 oE({controller:e,view:t,onAddPersonal:s,onAddShared:n,onUpdatePersonal:r,sheetOpen:i=!1}){const o=t.modelProviders||{},l=!!o.mutation?.pending,c=bi(o.systemSessionDefault),[d,u]=a.useState(c),[p,m]=a.useState(""),[f,h]=a.useState(null);a.useEffect(()=>{u(c)},[c]);const g=(C,k)=>C.find(O=>O.qualifiedName===k)||null,b=(C,k,O)=>{e.setAdminModelDefault(C,g(k,O))},y=C=>{window.confirm(`Delete ${C.name}? Sessions using it will wait until that provider name exists again.`)&&e.deleteAdminProvider(C.name,{shared:C.class==="shared"})},v=async()=>{h(null);const C=await e.setAdminSystemModelDefault(g(o.systemChoices||[],d),{restartDisposition:p||null});C?.ok&&h(C.result?.restart||{requested:!1})},S=(o.systemAgentRoutes||[]).filter(C=>!C.override),w=o.page==="shared"&&t.isAdmin,E=a.createElement("div",{className:"ps-admin-provider-heading"},a.createElement("h3",null,"Model Providers"),a.createElement(Se,{icon:"↻",label:"Refresh model providers",className:"ps-mini-button",disabled:o.loading,onClick:()=>e.refreshAdminModelProviders()})),I=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(Pc,{providers:o.myProviders||[],isAdmin:t.isAdmin,personal:!0,busy:l,onSystemUse:(C,k)=>e.setAdminProviderSystemUse(C,k),onUpdate:r,onDelete:y})),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement(Si,{label:"My Session Default",hint:`Effective: ${o.mySessionDefault?.effective?.model||"none"}.`,value:bi(o.mySessionDefault),choices:o.userChoices||[],disabled:l,emptyLabel:"Use cluster default",onChange:C=>b("user",o.userChoices||[],C)}))),T=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(Pc,{providers:o.sharedProviders||[],isAdmin:!0,personal:!1,busy:l,onSystemUse:()=>{},onDelete:y,onUpdate:r})),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement(Si,{label:"Cluster Session Default",hint:`Effective: ${o.clusterSessionDefault?.effective?.model||"none"}.`,value:bi(o.clusterSessionDefault),choices:o.clusterChoices||[],disabled:l,emptyLabel:"Use first shared provider",onChange:C=>b("cluster",o.clusterChoices||[],C)})),a.createElement("div",{className:"ps-admin-provider-block"},a.createElement("h4",null,"System Session Default"),a.createElement(Si,{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(is,{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"},`${S.length} agent${S.length===1?"":"s"} inherit this default.`),a.createElement("button",{type:"button",className:"ps-primary-button",disabled:l,onClick:v},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(C=>a.createElement("div",{key:C.agentId,className:"ps-admin-override-row"},a.createElement("div",{className:"ps-admin-override-row__agent"},a.createElement("strong",null,C.title),a.createElement("span",null,C.effectiveModel||"blocked"),a.createElement("small",null,C.override?"override":"system default")),a.createElement("select",{className:"ps-budget-input",value:C.override?.model||"",disabled:l,"aria-label":`Model override for ${C.title}`,onChange:k=>{const O=g(o.systemChoices||[],k.target.value);O?e.setAdminSystemAgentModel(C.agentId,O):e.clearAdminSystemAgentModel(C.agentId)}},a.createElement("option",{value:""},"Inherit system default"),(o.systemChoices||[]).map(k=>a.createElement("option",{key:k.qualifiedName,value:k.qualifiedName},`${k.provider} · ${k.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?T:I)}function bE({transport:e,mode:t="remote",branding:s=null,docs:n=null}={}){uv();const r=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches,i=fb(db,Ci({mode:t,branding:s,docs:n}));return i.dispatch({type:"ui/touchScale",enabled:r}),new gS({store:i,transport:e})}function SE({controller:e,suspended:t=!1,moa:s=null}){const n=a.useRef(null),r=a.useRef(null),i=ec(n,t),o=ec(r,t),l=vv(i);a.useEffect(()=>{const z=()=>{try{const re=document.createElement("span");re.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const ye=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");if(ye){const qe=window.getComputedStyle(ye);re.style.fontFamily=qe.fontFamily,re.style.fontSize=qe.fontSize,re.style.fontWeight=qe.fontWeight,re.style.letterSpacing=qe.letterSpacing}re.textContent="0".repeat(100),(ye?.parentElement||document.body).appendChild(re);const Me=re.getBoundingClientRect().width/100||8;re.remove();const We=document.documentElement.clientWidth||window.innerWidth,at=document.documentElement.clientHeight||window.innerHeight;e.dispatch({type:"ui/viewport",width:Math.floor(We/Me),height:Math.floor(at/Ct)})}catch{}};z();let M;const K=()=>{clearTimeout(M),M=setTimeout(z,150)};return window.addEventListener("resize",K),window.addEventListener("orientationchange",K),()=>{clearTimeout(M),window.removeEventListener("resize",K),window.removeEventListener("orientationchange",K)}},[e]);const[c,d]=a.useState("split"),u=ee(e,z=>({moa:z.ui.moa,themeId:z.ui.themeId,touchScale:!!z.ui.touchScale,sessionDetailCollapsed:!!z.ui.sessionDetailCollapsed,agentPickerUsage:z.ui.agentPickerUsage,ownerFilter:z.sessions.ownerFilter,pinnedIds:z.sessions.pinnedIds,manualOrder:z.sessions.manualOrder,sessionSortMode:z.sessions.sortMode,sessionUsedAt:z.sessions.usedAt,collapsedSessionIds:z.sessions.collapsedIds,activeSessionId:z.sessions.activeSessionId||null,revealedCreatedSessionId:z.ui.revealedCreatedSessionId||null,promptRows:Du(z),rightPaneMode:z.ui.rightPaneMode||"panes",canvasOpen:z.ui.canvasOpen===!0,diagnosticsOpen:z.ui.diagnosticsOpen===!0,canvasMaximized:z.ui.canvasMaximized===!0,canvasZen:z.ui.canvasZen===!0,canvasPrefs:z.canvas?.prefs,activeSessionIsGroup:!!(z.sessions.activeSessionId&&z.sessions.byId[z.sessions.activeSessionId]?.isGroup),paneAdjust:z.ui.layout?.paneAdjust??0,sessionPaneAdjust:z.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:z.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:z.ui.layout?.activityPaneAdjust??0,canvasPaneAdjust:z.ui.layout?.canvasPaneAdjust??0,diagnosticsPaneAdjust:z.ui.layout?.diagnosticsPaneAdjust??0,diagnosticsSplitAdjust:z.ui.layout?.diagnosticsSplitAdjust??0,sessionViews:z.ui.sessionViews,focusRegion:z.ui.focusRegion,requestedFocusRegion:z.ui.requestedFocusRegion,inspectorTab:z.ui.inspectorTab,filesFullscreen:!!z.files.fullscreen,selectedArtifactId:z.files.selectedArtifactId||null,artifactPaneOpen:!!z.files.paneOpen,adminVisible:!!z.admin?.visible,budgetOpen:!!z.ui?.budgetOpen}),Ve),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),v=a.useRef(!1),S=a.useRef(0),w=a.useRef(0),E=a.useRef(null),I=a.useRef(null),[T,C]=a.useState("workspace"),k=(i.width||window.innerWidth||0)<qS,N=u.activeSessionIsGroup?0:u.promptRows;xp(e,k,t);const R=a.useRef(u.revealedCreatedSessionId);a.useEffect(()=>{R.current!==u.revealedCreatedSessionId&&(R.current=u.revealedCreatedSessionId,!(!u.revealedCreatedSessionId||u.activeSessionId!==u.revealedCreatedSessionId)&&(k&&(C("workspace"),d("chat")),s?.active&&s.leave()))},[u.revealedCreatedSessionId,u.activeSessionId,k,s]),a.useEffect(()=>{e.dispatch({type:"ui/sessionViewDevice",device:k?"mobile":"desktop"})},[e,k]);const H=m0(k&&T==="workspace"&&!u.adminVisible);a.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-kb-takeover",H),()=>document.body.classList.remove("ps-kb-takeover")},[H]),a.useEffect(()=>{H&&e.applyPaneVisualScrollOffset?.("chat",0,{followBottom:!0})},[H,e]);const x=ee(e,Aa,Ve),P=T==="canvas",_=a.useRef("workspace"),[$,B]=a.useState(!1),[j,W]=a.useState(!1);a.useEffect(()=>{C(z=>z==="canvas"?_.current||"workspace":z),B(!1),W(!1)},[x.sessionId]),a.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-canvas-lock",!!(k&&P)),()=>document.body.classList.remove("ps-canvas-lock")},[k,P]);const A=a.useCallback(()=>{T!=="canvas"&&(_.current=T),C("canvas"),B(!0),e.dispatch({type:"ui/rightPaneMode",mode:"canvas",sessionId:x.sessionId})},[e,T,x.sessionId]),G=a.useCallback(()=>{C(_.current||"workspace"),e.dispatch({type:"ui/rightPaneMode",mode:"panes",sessionId:x.sessionId,manual:!0})},[e,x.sessionId]),D=a.useRef(x.flipSeq);a.useEffect(()=>{x.flipSeq!==D.current&&(D.current=x.flipSeq,k&&A())},[x.flipSeq,k,A]);const Y=a.useCallback(()=>{if(P){G();return}A()},[P,G,A]);a.useEffect(()=>{let z=!0;p.current=!1,m.current=null,E.current=null,I.current=Ql(e.getState()),b.current&&(clearTimeout(b.current),b.current=null),y.current&&(clearInterval(y.current),y.current=null),v.current=!1,S.current=0;const M=e.transport;if(typeof M?.getCurrentUserProfile!="function"||typeof M?.setCurrentUserProfileSettings!="function")return p.current=!0,()=>{z=!1};const K=async()=>{if(!z||v.current)return;v.current=!0;const re=w.current;try{const ye=await M.getCurrentUserProfile();if(!z)return;ye&&typeof ye.isAdmin=="boolean"&&!e.getState().admin?.profile&&e.dispatch({type:"admin/profile/loaded",profile:ye});const Me=cs(ye?.profileSettings);typeof Me[cr()]=="boolean"&&(f.current=Me[cr()]),(Me.rightPaneMode==="canvas"||Me.rightPaneMode==="panes")&&(h.current=Me.rightPaneMode),Me.desktopPanes&&(g.current=Me.desktopPanes),I.current=Ql(e.getState(),f.current,h.current,g.current);const We=mv(ye?.profileSettings,I.current),at=JSON.stringify(We),qe=ci(Xl(e.getState()),f.current,h.current,g.current),xt=JSON.stringify(qe),we=p.current&&m.current!=null&&xt!==m.current,ze=re!==w.current||!!b.current||S.current||we||e.getState().ui.moaDirty===!0;if(!ze&&E.current!==at&&(e.dispatch({type:"profileSettings/apply",settings:We}),E.current=at),!p.current||!ze){const At=ci(Xl(e.getState()),f.current,h.current,g.current);m.current=JSON.stringify(At)}p.current=!0}catch{if(!z)return;p.current=!0}finally{v.current=!1}};return K().catch(()=>{}),y.current=setInterval(()=>{K().catch(()=>{})},XS),()=>{z=!1,b.current&&(clearTimeout(b.current),b.current=null),y.current&&(clearInterval(y.current),y.current=null),v.current=!1}},[e]),a.useEffect(()=>{if(!p.current)return;const z=ci(u,f.current,h.current,g.current),M=JSON.stringify(z);m.current!==M&&(m.current=M,w.current+=1,b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{b.current=null,S.current+=1;const K=e.getState().ui.moaRevision;e.dispatch({type:"ui/moaSaveStatus",status:"saving"}),fv(e,z).then(()=>e.dispatch({type:"ui/moaSaveStatus",status:"saved",revision:K})).catch(()=>{m.current=null,e.dispatch({type:"ui/moaSaveStatus",status:"error"})}).finally(()=>{S.current=Math.max(0,S.current-1)})},400))},[e,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.sessionSortMode,u.sessionUsedAt,u.pinnedIds,u.portalSessionColumnAdjust,u.rightPaneMode,u.sessionDetailCollapsed,u.sessionPaneAdjust,u.sessionViews,u.themeId,u.touchScale]),a.useEffect(()=>{Sv(u.themeId),bv(u.touchScale)},[u.themeId,u.touchScale]);const J=a.useRef(null);a.useEffect(()=>{const z=J.current;if(J.current=u.focusRegion,z===null||z===u.focusRegion)return;const M=u.requestedFocusRegion;k&&(u.focusRegion==="inspector"||u.focusRegion==="activity")&&(M==="inspector"||M==="activity")&&C(u.focusRegion)},[k,u.focusRegion,u.requestedFocusRegion]),a.useEffect(()=>{const z=Ga(e);!z.includes(u.inspectorTab)&&z.length>0&&e.selectInspectorTab(z[0]).catch(()=>{})},[e,u.inspectorTab]);const te=a.useMemo(()=>en(l,u.paneAdjust,N,u.sessionPaneAdjust,u.activityPaneAdjust),[l,u.activityPaneAdjust,u.paneAdjust,N,u.sessionPaneAdjust]),Z=u.filesFullscreen&&u.inspectorTab==="files",ne=u.inspectorTab==="files"&&!!u.selectedArtifactId&&!Z,ae=!k&&u.artifactPaneOpen&&!!u.selectedArtifactId&&!Z,oe=!k&&u.canvasOpen&&!Z;a.useEffect(()=>{oe&&W(!0)},[oe,x.sessionId]);const ve=!k&&u.diagnosticsOpen&&!Z&&!ae&&!(u.canvasZen&&u.canvasOpen),be=ae||oe||ve,Q=u.canvasMaximized&&oe,ce=u.canvasZen&&oe&&!ae,ge=Math.max(260,Math.min(720,Number(u.canvasPrefs?.[u.activeSessionId]?.zenRailPx)||380));a.useEffect(()=>{if(t||!Q&&!ce)return;const z=M=>{M.key==="Escape"&&e.dispatch(Q?{type:"ui/canvasMaximized",on:!1}:{type:"ui/canvasZen",on:!1})};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[e,Q,ce,t]);const Qe=Math.max(0,Wa+(Number(u.canvasPaneAdjust)||0)),$e=Math.max(0,qa+(Number(u.diagnosticsPaneAdjust)||0)),it=(oe?Qe:0)+(oe&&ve?1:0)+(ve?$e:0),Ye=a.useCallback(()=>{e.closeArtifactPane().catch(()=>{})},[e]),It=Math.max(0,(i.width||0)*.68),V=o.width||It,me=hv(V,u.portalSessionColumnAdjust),Be=ce?"hidden":gv(me),ke=Be==="hidden"?"0px":`clamp(0px, calc(${Ua*100}% + ${Number(u.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,de=a.createElement("div",{className:`ps-workspace-grid${be?"":" is-right-hidden"}`,style:{gridTemplateColumns:ae?`minmax(0, ${te.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${te.rightWidth}fr)`:ce?`${ge}px var(--ps-resizer-track, 16px) minmax(0, 1fr)`:be?`minmax(0, 1fr) var(--ps-resizer-track, 16px) min(${it}px, calc(100% - var(--ps-resizer-track, 16px) - ${ja}px))`:"minmax(0, 1fr)"}},a.createElement("div",{ref:r,className:`ps-workspace-main-grid is-session-${Be}`,style:{gridTemplateColumns:`${ke} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},Be!=="hidden"?a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},a.createElement(Xi,{controller:e,structuredRows:!0})):null,a.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},a.createElement(w0,{controller:e,portalSessionColumnAdjust:u.portalSessionColumnAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},a.createElement(Zi,{controller:e}))),be?ae?a.createElement(v0,{controller:e,paneAdjust:u.paneAdjust}):ce?a.createElement(k0,{controller:e,sessionId:u.activeSessionId,railPx:ge}):a.createElement(I0,{controller:e,target:oe?"canvas":"diagnostics",adjust:oe?u.canvasPaneAdjust:u.diagnosticsPaneAdjust}):null,a.createElement("div",{className:`ps-workspace-column-host is-split${Q?" has-maximized":""}`},ae?a.createElement("div",{className:"ps-workspace-column is-artifact"},a.createElement(l0,{controller:e,onClose:Ye})):null,j?a.createElement("div",{key:`canvas:${u.activeSessionId||""}`,className:`ps-workspace-column is-artifact ps-canvas-layer${oe&&!ae?"":" is-hidden"}${Q&&oe&&!ae?" is-maximized":""}`,style:oe&&!ae&&ve&&!Q?{flex:`0 0 ${Qe}px`,minWidth:0}:void 0,...oe&&!ae?{}:{inert:!0,"aria-hidden":"true"}},a.createElement(bp,{controller:e,visible:oe&&!ae,maximized:Q})):null,oe&&ve?a.createElement(E0,{controller:e,canvasPaneAdjust:u.canvasPaneAdjust,diagnosticsPaneAdjust:u.diagnosticsPaneAdjust}):null,ve?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)`,...oe?{flex:"1 1 0%",minWidth:0}:null}},a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},a.createElement(Xs,{controller:e,mobile:!1})),a.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},a.createElement(x0,{controller:e,splitAdjust:u.diagnosticsSplitAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},ne?a.createElement(Nr,{controller:e,focused:!1,previewOnly:!0}):a.createElement(gi,{controller:e}))):null)),Re=a.createElement("div",{className:"ps-workspace-full"},a.createElement(Xs,{controller:e,mobile:!1}));let Ie=null;Z&&!k?Ie=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(Xs,{controller:e,mobile:!0})):T==="inspector"?Ie=u.inspectorTab==="nodes"?a.createElement("div",{className:"ps-mobile-pane-fill ps-mobile-node-split"},a.createElement(Xs,{controller:e,mobile:!0}),a.createElement(gi,{controller:e,panelClassName:"ps-mobile-node-detail"})):a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(Xs,{controller:e,mobile:!0})):T==="activity"?Ie=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(gi,{controller:e})):T==="canvas"?Ie=null:Ie=a.createElement(f0,{controller:e,layout:c,onEnterZen:s?.openMobileZen});const et=k&&$?a.createElement(c0,{key:`canvas:${x.sessionId||""}`,controller:e,visible:P}):null;return t?a.createElement(Vi.Provider,{value:e},a.createElement(xc,{controller:e,mobile:!1,moa:s}),a.createElement(ta,{controller:e})):a.createElement(Vi.Provider,{value:e},a.createElement("div",{ref:n,className:"ps-web-shell"},a.createElement(xc,{controller:e,moa:s,mobile:k,canvasPaneOpen:P,onToggleCanvasPane:Y,mobilePane:T,mobileMainLayout:c,onSelectMobilePane:(z,M)=>{z==="workspace"&&T==="workspace"&&d(K=>K==="split"?"chat":K==="chat"?"sessions":"split"),e.closeBudget(),C(z),M&&e.setFocus(M)}}),a.createElement("div",{className:"ps-workspace"},u.adminVisible?a.createElement(J0,{controller:e,mobile:k}):u.budgetOpen?a.createElement(X0,{controller:e}):Z?Re:k?Ie:de,et),k&&Z?a.createElement(d0,{controller:e}):null,a.createElement(ta,{controller:e})))}export{Og as A,Vi as C,lE as M,SE as P,a as R,gE as S,Nu as _,Mp as a,Zi as b,hE as c,yE as d,dE as e,ut as f,Np as g,Xi as h,bE as i,uE as j,Hs as k,Jf as l,Mi as m,cn as n,Mo as o,xw as p,pE as q,Mc as r,us as s,_o as t,ee as u,cE as v,y0 as w,fE as x,Pt as y,mE as z};