pilotswarm 0.5.39 → 0.5.41

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 (83) hide show
  1. package/package.json +2 -2
  2. package/tui/src/node-sdk-transport.js +25 -0
  3. package/ui/core/src/controller.js +34 -8
  4. package/ui/core/src/history.js +5 -1
  5. package/ui/core/src/index.js +1 -0
  6. package/ui/core/src/portal-links.js +46 -0
  7. package/ui/core/src/reducer.js +88 -2
  8. package/ui/core/src/selectors.js +2 -0
  9. package/ui/react/src/web-app.js +358 -36
  10. package/web/README.md +28 -0
  11. package/web/api/canvas-plane.js +116 -0
  12. package/web/api/ws.js +120 -5
  13. package/web/config.js +60 -0
  14. package/web/dist/assets/{abnfDiagram-VRR7QNED-Hsly1fgf.js → abnfDiagram-VRR7QNED-kpxu_PEa.js} +1 -1
  15. package/web/dist/assets/{arc-DiQLL9vM.js → arc-BnVQmtB5.js} +1 -1
  16. package/web/dist/assets/{architectureDiagram-ZJ3FMSHR-B8ry8WNZ.js → architectureDiagram-ZJ3FMSHR-CDynQ_6_.js} +1 -1
  17. package/web/dist/assets/{blockDiagram-677ZJIJ3-Z4PcukIo.js → blockDiagram-677ZJIJ3-BUpYaSDb.js} +1 -1
  18. package/web/dist/assets/{c4Diagram-LMCZKHZV-Cahkc0gc.js → c4Diagram-LMCZKHZV-ZL8eskDB.js} +1 -1
  19. package/web/dist/assets/channel-Bi5A6sHR.js +1 -0
  20. package/web/dist/assets/{chunk-2Q5K7J3B-CtZuWH4J.js → chunk-2Q5K7J3B-o0Nsyp1T.js} +1 -1
  21. package/web/dist/assets/{chunk-32BRIVSS-C0M390-k.js → chunk-32BRIVSS-CH5CSNRP.js} +1 -1
  22. package/web/dist/assets/{chunk-5VM5RSS4-ClvX9u5j.js → chunk-5VM5RSS4-C9wwtPWL.js} +1 -1
  23. package/web/dist/assets/{chunk-EX3LRPZG-BVAet5KG.js → chunk-EX3LRPZG--F9yFbhA.js} +1 -1
  24. package/web/dist/assets/{chunk-JWPE2WC7-BccmZmrr.js → chunk-JWPE2WC7-BPIstyWL.js} +1 -1
  25. package/web/dist/assets/{chunk-MOJQB5TN-BN5MKe94.js → chunk-MOJQB5TN-5Dm2u-0k.js} +1 -1
  26. package/web/dist/assets/{chunk-RYQCIY6F-DfWw-ACP.js → chunk-RYQCIY6F-Dbtf9iQK.js} +1 -1
  27. package/web/dist/assets/{chunk-V7JOEXUC-BgUEoLnN.js → chunk-V7JOEXUC-DrZEBJ5l.js} +1 -1
  28. package/web/dist/assets/{chunk-VR4S4FIN-k1eKfFNA.js → chunk-VR4S4FIN-AqAUynqK.js} +1 -1
  29. package/web/dist/assets/{chunk-XXDRQBXY-DPyV10yR.js → chunk-XXDRQBXY-DQlFaqCy.js} +1 -1
  30. package/web/dist/assets/classDiagram-OUVF2IWQ-D8dCxI54.js +1 -0
  31. package/web/dist/assets/classDiagram-v2-EOCWNBFH-D8dCxI54.js +1 -0
  32. package/web/dist/assets/{cose-bilkent-JH36ORCC-Bt_rpukK.js → cose-bilkent-JH36ORCC-RAtPG1Ou.js} +1 -1
  33. package/web/dist/assets/{cynefin-VYW2F7L2-Z8eMzFMv.js → cynefin-VYW2F7L2-CbeHaUWZ.js} +1 -1
  34. package/web/dist/assets/{cynefinDiagram-TSTJHNR4-BJSNawFi.js → cynefinDiagram-TSTJHNR4-B6paqF5Y.js} +1 -1
  35. package/web/dist/assets/{dagre-VKFMJZFB-D6dNl8jc.js → dagre-VKFMJZFB-DziTBO2K.js} +1 -1
  36. package/web/dist/assets/{diagram-FQU43EPY-Cy1nbGsU.js → diagram-FQU43EPY-CPRUiLcr.js} +1 -1
  37. package/web/dist/assets/{diagram-G47NLZAW-CmrbuA_d.js → diagram-G47NLZAW-CIMVdcL1.js} +1 -1
  38. package/web/dist/assets/{diagram-NH7WQ7WH-PoLNQE2j.js → diagram-NH7WQ7WH-CHPFllxR.js} +1 -1
  39. package/web/dist/assets/{diagram-OA4YK3LP-BZwNFcSV.js → diagram-OA4YK3LP-DwS6unBJ.js} +1 -1
  40. package/web/dist/assets/{diagram-WEI45ONY-pKw0b_fN.js → diagram-WEI45ONY-DKWgkObI.js} +1 -1
  41. package/web/dist/assets/{ebnfDiagram-CCIWWBDH-UNctuQCV.js → ebnfDiagram-CCIWWBDH-zAVWV6-D.js} +1 -1
  42. package/web/dist/assets/{erDiagram-Q63AITRT-DxIETMif.js → erDiagram-Q63AITRT-D0tYX4h0.js} +1 -1
  43. package/web/dist/assets/{flowDiagram-23GEKE2U-C06IdNKV.js → flowDiagram-23GEKE2U-Cfq4I7R0.js} +1 -1
  44. package/web/dist/assets/{ganttDiagram-NO4QXBWP-fU7aGyP1.js → ganttDiagram-NO4QXBWP-wgBAHr5I.js} +1 -1
  45. package/web/dist/assets/{gitGraphDiagram-IHSO6WYX-9UKkPJm6.js → gitGraphDiagram-IHSO6WYX-BTIPX5PR.js} +1 -1
  46. package/web/dist/assets/index-OHj-gGHp.js +24 -0
  47. package/web/dist/assets/index-eTH1FBtN.css +1 -0
  48. package/web/dist/assets/{infoDiagram-FWYZ7A6U-C6F06SQJ.js → infoDiagram-FWYZ7A6U-CRLiQ87D.js} +1 -1
  49. package/web/dist/assets/{ishikawaDiagram-FXEZZL3T-CB-O9NfO.js → ishikawaDiagram-FXEZZL3T-CwzwUis1.js} +1 -1
  50. package/web/dist/assets/{journeyDiagram-5HDEW3XC-B-8MOf-H.js → journeyDiagram-5HDEW3XC-B9pqMeFw.js} +1 -1
  51. package/web/dist/assets/{kanban-definition-HUTT4EX6-DX0XA3hI.js → kanban-definition-HUTT4EX6-CZ5Xky4p.js} +1 -1
  52. package/web/dist/assets/{linear-D60PrjTW.js → linear-BLZ2eH4a.js} +1 -1
  53. package/web/dist/assets/{mermaid.core-bonzwapf.js → mermaid.core-CPN1IVjz.js} +4 -4
  54. package/web/dist/assets/{mindmap-definition-LN4V7U3C-Y-6Dum33.js → mindmap-definition-LN4V7U3C-MdC8d2tc.js} +1 -1
  55. package/web/dist/assets/{papaparse.min-Cas1JfRG.js → papaparse.min-CtrVJupf.js} +1 -1
  56. package/web/dist/assets/{pegDiagram-2B236MQR-_paO0yDw.js → pegDiagram-2B236MQR-B2DqAc-A.js} +1 -1
  57. package/web/dist/assets/{pieDiagram-ENE6RG2P-xT1_Gpn4.js → pieDiagram-ENE6RG2P-C3QAoXZh.js} +1 -1
  58. package/web/dist/assets/pilotswarm-CF1nmpMy.js +97 -0
  59. package/web/dist/assets/{quadrantDiagram-ABIIQ3AL-1usdLFOF.js → quadrantDiagram-ABIIQ3AL-BoUr5qFH.js} +1 -1
  60. package/web/dist/assets/{railroadDiagram-RFXS5EU6-R3lwHOz9.js → railroadDiagram-RFXS5EU6-bZzE4KFN.js} +1 -1
  61. package/web/dist/assets/{requirementDiagram-TGXJPOKE-BL8J1__Z.js → requirementDiagram-TGXJPOKE-B2ENAqLS.js} +1 -1
  62. package/web/dist/assets/{sankeyDiagram-HTMAVEWB-Dz6--0pl.js → sankeyDiagram-HTMAVEWB-AJZ3h46Z.js} +1 -1
  63. package/web/dist/assets/{sequenceDiagram-DBY2YBRQ-CG2Xpkct.js → sequenceDiagram-DBY2YBRQ-QUf0VVE7.js} +1 -1
  64. package/web/dist/assets/{sizeCapture-X5ZJPWSS-BPbYfjxj.js → sizeCapture-X5ZJPWSS-Cv9RcUy6.js} +1 -1
  65. package/web/dist/assets/{stateDiagram-2N3HPSRC-46x_y_aA.js → stateDiagram-2N3HPSRC-hDiye45t.js} +1 -1
  66. package/web/dist/assets/stateDiagram-v2-6OUMAXLB-Bu4ufvaU.js +1 -0
  67. package/web/dist/assets/{swimlanes-5IMT3BWC-SXdMo4zJ.js → swimlanes-5IMT3BWC-hSk_OF85.js} +2 -2
  68. package/web/dist/assets/swimlanesDiagram-G3AALYLV-BTFePb1Y.js +8 -0
  69. package/web/dist/assets/{timeline-definition-FHXFAJF6-CGgT-b38.js → timeline-definition-FHXFAJF6-ccOZEJ5e.js} +1 -1
  70. package/web/dist/assets/{vennDiagram-L72KCM5P-BGS3xBa_.js → vennDiagram-L72KCM5P-Bk5DLH_V.js} +1 -1
  71. package/web/dist/assets/{wardleyDiagram-EHGQE667-m2U3wEZJ.js → wardleyDiagram-EHGQE667-C20AX8ot.js} +1 -1
  72. package/web/dist/assets/{xychartDiagram-FW5EYKEG-DI6tQysg.js → xychartDiagram-FW5EYKEG-DaHqmi-R.js} +1 -1
  73. package/web/dist/index.html +3 -3
  74. package/web/runtime.js +71 -0
  75. package/web/server.js +51 -2
  76. package/web/dist/assets/channel-BHLBPE50.js +0 -1
  77. package/web/dist/assets/classDiagram-OUVF2IWQ-rj9D2TSL.js +0 -1
  78. package/web/dist/assets/classDiagram-v2-EOCWNBFH-rj9D2TSL.js +0 -1
  79. package/web/dist/assets/index-B8nGlHwb.js +0 -24
  80. package/web/dist/assets/index-DtL0lbis.css +0 -1
  81. package/web/dist/assets/pilotswarm-BT6tOknQ.js +0 -96
  82. package/web/dist/assets/stateDiagram-v2-6OUMAXLB-C2tnolSo.js +0 -1
  83. package/web/dist/assets/swimlanesDiagram-G3AALYLV-Dh6Sn__t.js +0 -8
@@ -0,0 +1,97 @@
1
+ function Uc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var yn={exports:{}},Z={};var mr;function zc(){if(mr)return Z;mr=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),r=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),f=Symbol.iterator;function h(k){return k===null||typeof k!="object"?null:(k=f&&k[f]||k["@@iterator"],typeof k=="function"?k:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,S={};function y(k,$,K){this.props=k,this.context=$,this.refs=S,this.updater=K||m}y.prototype.isReactComponent={},y.prototype.setState=function(k,$){if(typeof k!="object"&&typeof k!="function"&&k!=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,k,$,"setState")},y.prototype.forceUpdate=function(k){this.updater.enqueueForceUpdate(this,k,"forceUpdate")};function v(){}v.prototype=y.prototype;function x(k,$,K){this.props=k,this.context=$,this.refs=S,this.updater=K||m}var E=x.prototype=new v;E.constructor=x,g(E,y.prototype),E.isPureReactComponent=!0;var w=Array.isArray;function I(){}var b={H:null,A:null,T:null,S:null},M=Object.prototype.hasOwnProperty;function A(k,$,K){var z=K.ref;return{$$typeof:t,type:k,key:$,ref:z!==void 0?z:null,props:K}}function O(k,$){return A(k.type,$,k.props)}function F(k){return typeof k=="object"&&k!==null&&k.$$typeof===t}function L(k){var $={"=":"=0",":":"=2"};return"$"+k.replace(/[=:]/g,function(K){return $[K]})}var G=/\/+/g;function P(k,$){return typeof k=="object"&&k!==null&&k.key!=null?L(""+k.key):$.toString(36)}function H(k){switch(k.status){case"fulfilled":return k.value;case"rejected":throw k.reason;default:switch(typeof k.status=="string"?k.then(I,I):(k.status="pending",k.then(function($){k.status==="pending"&&(k.status="fulfilled",k.value=$)},function($){k.status==="pending"&&(k.status="rejected",k.reason=$)})),k.status){case"fulfilled":return k.value;case"rejected":throw k.reason}}throw k}function U(k,$,K,z,B){var Q=typeof k;(Q==="undefined"||Q==="boolean")&&(k=null);var V=!1;if(k===null)V=!0;else switch(Q){case"bigint":case"string":case"number":V=!0;break;case"object":switch(k.$$typeof){case t:case e:V=!0;break;case p:return V=k._init,U(V(k._payload),$,K,z,B)}}if(V)return B=B(k),V=z===""?"."+P(k,0):z,w(B)?(K="",V!=null&&(K=V.replace(G,"$&/")+"/"),U(B,$,K,"",function(Y){return Y})):B!=null&&(F(B)&&(B=O(B,K+(B.key==null||k&&k.key===B.key?"":(""+B.key).replace(G,"$&/")+"/")+V)),$.push(B)),1;V=0;var j=z===""?".":z+":";if(w(k))for(var T=0;T<k.length;T++)z=k[T],Q=j+P(z,T),V+=U(z,$,K,Q,B);else if(T=h(k),typeof T=="function")for(k=T.call(k),T=0;!(z=k.next()).done;)z=z.value,Q=j+P(z,T++),V+=U(z,$,K,Q,B);else if(Q==="object"){if(typeof k.then=="function")return U(H(k),$,K,z,B);throw $=String(k),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(k).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return V}function re(k,$,K){if(k==null)return k;var z=[],B=0;return U(k,z,"","",function(Q){return $.call(K,Q,B++)}),z}function he(k){if(k._status===-1){var $=k._result;$=$(),$.then(function(K){(k._status===0||k._status===-1)&&(k._status=1,k._result=K)},function(K){(k._status===0||k._status===-1)&&(k._status=2,k._result=K)}),k._status===-1&&(k._status=0,k._result=$)}if(k._status===1)return k._result.default;throw k._result}var ce=typeof reportError=="function"?reportError:function(k){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof k=="object"&&k!==null&&typeof k.message=="string"?String(k.message):String(k),error:k});if(!window.dispatchEvent($))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",k);return}console.error(k)},Ge={map:re,forEach:function(k,$,K){re(k,function(){$.apply(this,arguments)},K)},count:function(k){var $=0;return re(k,function(){$++}),$},toArray:function(k){return re(k,function($){return $})||[]},only:function(k){if(!F(k))throw Error("React.Children.only expected to receive a single React element child.");return k}};return Z.Activity=d,Z.Children=Ge,Z.Component=y,Z.Fragment=s,Z.Profiler=i,Z.PureComponent=x,Z.StrictMode=n,Z.Suspense=c,Z.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=b,Z.__COMPILER_RUNTIME={__proto__:null,c:function(k){return b.H.useMemoCache(k)}},Z.cache=function(k){return function(){return k.apply(null,arguments)}},Z.cacheSignal=function(){return null},Z.cloneElement=function(k,$,K){if(k==null)throw Error("The argument must be a React element, but you passed "+k+".");var z=g({},k.props),B=k.key;if($!=null)for(Q in $.key!==void 0&&(B=""+$.key),$)!M.call($,Q)||Q==="key"||Q==="__self"||Q==="__source"||Q==="ref"&&$.ref===void 0||(z[Q]=$[Q]);var Q=arguments.length-2;if(Q===1)z.children=K;else if(1<Q){for(var V=Array(Q),j=0;j<Q;j++)V[j]=arguments[j+2];z.children=V}return A(k.type,B,z)},Z.createContext=function(k){return k={$$typeof:o,_currentValue:k,_currentValue2:k,_threadCount:0,Provider:null,Consumer:null},k.Provider=k,k.Consumer={$$typeof:r,_context:k},k},Z.createElement=function(k,$,K){var z,B={},Q=null;if($!=null)for(z in $.key!==void 0&&(Q=""+$.key),$)M.call($,z)&&z!=="key"&&z!=="__self"&&z!=="__source"&&(B[z]=$[z]);var V=arguments.length-2;if(V===1)B.children=K;else if(1<V){for(var j=Array(V),T=0;T<V;T++)j[T]=arguments[T+2];B.children=j}if(k&&k.defaultProps)for(z in V=k.defaultProps,V)B[z]===void 0&&(B[z]=V[z]);return A(k,Q,B)},Z.createRef=function(){return{current:null}},Z.forwardRef=function(k){return{$$typeof:l,render:k}},Z.isValidElement=F,Z.lazy=function(k){return{$$typeof:p,_payload:{_status:-1,_result:k},_init:he}},Z.memo=function(k,$){return{$$typeof:u,type:k,compare:$===void 0?null:$}},Z.startTransition=function(k){var $=b.T,K={};b.T=K;try{var z=k(),B=b.S;B!==null&&B(K,z),typeof z=="object"&&z!==null&&typeof z.then=="function"&&z.then(I,ce)}catch(Q){ce(Q)}finally{$!==null&&K.types!==null&&($.types=K.types),b.T=$}},Z.unstable_useCacheRefresh=function(){return b.H.useCacheRefresh()},Z.use=function(k){return b.H.use(k)},Z.useActionState=function(k,$,K){return b.H.useActionState(k,$,K)},Z.useCallback=function(k,$){return b.H.useCallback(k,$)},Z.useContext=function(k){return b.H.useContext(k)},Z.useDebugValue=function(){},Z.useDeferredValue=function(k,$){return b.H.useDeferredValue(k,$)},Z.useEffect=function(k,$){return b.H.useEffect(k,$)},Z.useEffectEvent=function(k){return b.H.useEffectEvent(k)},Z.useId=function(){return b.H.useId()},Z.useImperativeHandle=function(k,$,K){return b.H.useImperativeHandle(k,$,K)},Z.useInsertionEffect=function(k,$){return b.H.useInsertionEffect(k,$)},Z.useLayoutEffect=function(k,$){return b.H.useLayoutEffect(k,$)},Z.useMemo=function(k,$){return b.H.useMemo(k,$)},Z.useOptimistic=function(k,$){return b.H.useOptimistic(k,$)},Z.useReducer=function(k,$,K){return b.H.useReducer(k,$,K)},Z.useRef=function(k){return b.H.useRef(k)},Z.useState=function(k){return b.H.useState(k)},Z.useSyncExternalStore=function(k,$,K){return b.H.useSyncExternalStore(k,$,K)},Z.useTransition=function(){return b.H.useTransition()},Z.version="19.2.4",Z}var gr;function wa(){return gr||(gr=1,yn.exports=zc()),yn.exports}var Wc=wa();const a=Uc(Wc);var Sn={exports:{}},Me={};var yr;function qc(){if(yr)return Me;yr=1;var t=wa();function e(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var p=2;p<arguments.length;p++)u+="&args[]="+encodeURIComponent(arguments[p])}return"Minified React error #"+c+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function s(){}var n={d:{f:s,r:function(){throw Error(e(522))},D:s,C:s,L:s,m:s,X:s,S:s,M:s},p:0,findDOMNode:null},i=Symbol.for("react.portal");function r(c,u,p){var d=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:d==null?null:""+d,children:c,containerInfo:u,implementation:p}}var o=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return Me.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=n,Me.createPortal=function(c,u){var p=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(e(299));return r(c,u,null,p)},Me.flushSync=function(c){var u=o.T,p=n.p;try{if(o.T=null,n.p=2,c)return c()}finally{o.T=u,n.p=p,n.d.f()}},Me.preconnect=function(c,u){typeof c=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,n.d.C(c,u))},Me.prefetchDNS=function(c){typeof c=="string"&&n.d.D(c)},Me.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var p=u.as,d=l(p,u.crossOrigin),f=typeof u.integrity=="string"?u.integrity:void 0,h=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;p==="style"?n.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:d,integrity:f,fetchPriority:h}):p==="script"&&n.d.X(c,{crossOrigin:d,integrity:f,fetchPriority:h,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},Me.preinitModule=function(c,u){if(typeof c=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var p=l(u.as,u.crossOrigin);n.d.M(c,{crossOrigin:p,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&n.d.M(c)},Me.preload=function(c,u){if(typeof c=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var p=u.as,d=l(p,u.crossOrigin);n.d.L(c,p,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},Me.preloadModule=function(c,u){if(typeof c=="string")if(u){var p=l(u.as,u.crossOrigin);n.d.m(c,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:p,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else n.d.m(c)},Me.requestFormReset=function(c){n.d.r(c)},Me.unstable_batchedUpdates=function(c,u){return c(u)},Me.useFormState=function(c,u,p){return o.H.useFormState(c,u,p)},Me.useFormStatus=function(){return o.H.useHostTransitionStatus()},Me.version="19.2.4",Me}var Sr;function Kc(){if(Sr)return Sn.exports;Sr=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}return t(),Sn.exports=qc(),Sn.exports}var vi=Kc();const Vc=a.createContext(null);function Xe(){const t=a.useContext(Vc);if(!t)throw new Error("useUiPlatform must be used within a UiPlatformProvider");return t}function X(t,e,s=Object.is){const n=a.useRef(e),i=a.useRef(s);n.current=e,i.current=s;const[r,o]=a.useState(()=>e(t.getState())),l=a.useRef(r);return a.useEffect(()=>{l.current=r},[r]),a.useEffect(()=>t.subscribe(c=>{const u=n.current(c);i.current(l.current,u)||(l.current=u,o(u))}),[t]),r}const br=[".  ",".. ","..."],wr=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];function va(t,e=120){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(r=>(r+1)%wr.length)},e);return()=>clearInterval(i)},[t,e]),t?wr[s]:""}function Ea(t,e=360){const[s,n]=a.useState(0);return a.useEffect(()=>{if(!t){n(0);return}const i=setInterval(()=>{n(r=>(r+1)%br.length)},e);return()=>clearInterval(i)},[t,e]),t?br[s]:""}function xa(t,e=""){if(!Array.isArray(t)||t.length===0)return null;if(!e)return t;const s=t[t.length-1]||{};return[...t,{text:e,color:s.color||"gray",bold:!!s.bold,underline:!!s.underline,backgroundColor:s.backgroundColor}]}const N={SESSIONS:"sessions",CHAT:"chat",INSPECTOR:"inspector",ACTIVITY:"activity",PROMPT:"prompt"},et=["sequence","logs","nodes","history","files","stats"],C={REFRESH:"refresh",NEW_SESSION:"newSession",OPEN_MODEL_PICKER:"openModelPicker",OPEN_SWITCH_MODEL_PICKER:"openSwitchModelPicker",OPEN_THEME_PICKER:"openThemePicker",OPEN_RENAME_SESSION:"openRenameSession",OPEN_SESSION_FILTER:"openSessionFilter",OPEN_TERMINATE_PICKER:"openTerminatePicker",OPEN_MOVE_TO_GROUP:"openMoveToGroup",CREATE_SESSION_GROUP:"createSessionGroup",OPEN_ARTIFACT_UPLOAD:"openArtifactUpload",CLOSE_MODAL:"closeModal",MODAL_PREV:"modalPrev",MODAL_NEXT:"modalNext",MODAL_PANE_PREV:"modalPanePrev",MODAL_PANE_NEXT:"modalPaneNext",MODAL_CONFIRM:"modalConfirm",SEND_PROMPT:"sendPrompt",FOCUS_NEXT:"focusNext",FOCUS_PREV:"focusPrev",FOCUS_LEFT:"focusLeft",FOCUS_RIGHT:"focusRight",FOCUS_PROMPT:"focusPrompt",FOCUS_SESSIONS:"focusSessions",MOVE_SESSION_UP:"moveSessionUp",MOVE_SESSION_DOWN:"moveSessionDown",EXPAND_SESSION:"expandSession",COLLAPSE_SESSION:"collapseSession",NEXT_INSPECTOR_TAB:"nextInspectorTab",PREV_INSPECTOR_TAB:"prevInspectorTab",CYCLE_INSPECTOR_TAB:"cycleInspectorTab",GROW_LEFT_PANE:"growLeftPane",GROW_RIGHT_PANE:"growRightPane",GROW_SESSION_PANE:"growSessionPane",SHRINK_SESSION_PANE:"shrinkSessionPane",GROW_FOCUSED_PANE:"growFocusedPane",SHRINK_FOCUSED_PANE:"shrinkFocusedPane",OPEN_ARTIFACT_PICKER:"openArtifactPicker",OPEN_HELP:"openHelp",SEQUENCE_SELECT_PREV:"sequenceSelectPrev",SEQUENCE_SELECT_NEXT:"sequenceSelectNext",TOGGLE_SEQUENCE_TURN:"toggleSequenceTurn",TOGGLE_LOG_TAIL:"toggleLogTail",TOGGLE_STATS_VIEW:"toggleStatsView",OPEN_LOG_FILTER:"openLogFilter",OPEN_FILES_FILTER:"openFilesFilter",MOVE_FILE_UP:"moveFileUp",MOVE_FILE_DOWN:"moveFileDown",DOWNLOAD_SELECTED_FILE:"downloadSelectedFile",DELETE_SELECTED_FILE:"deleteSelectedFile",OPEN_SELECTED_FILE:"openSelectedFile",TOGGLE_FILE_PREVIEW_FULLSCREEN:"toggleFilePreviewFullscreen",TOGGLE_PANE_FULLSCREEN:"togglePaneFullscreen",SCROLL_UP:"scrollUp",SCROLL_DOWN:"scrollDown",PAGE_UP:"pageUp",PAGE_DOWN:"pageDown",EXPAND_HISTORY:"expandHistory",SCROLL_TOP:"scrollTop",SCROLL_BOTTOM:"scrollBottom",DONE_SESSION:"doneSession",CANCEL_SESSION:"cancelSession",STOP_TURN:"stopTurn",DELETE_SESSION:"deleteSession",REGENERATE_SESSION:"regenerateSession",PIN_SESSION:"pinSession",CYCLE_SESSION_VISIBILITY:"cycleSessionVisibility",OPEN_SHARE_SESSION:"openShareSession",TOGGLE_SELECT_MODE:"toggleSelectMode",TOGGLE_SESSION_SELECTION:"toggleSessionSelection",CLEAR_SESSION_SELECTION:"clearSessionSelection",OPEN_HISTORY_FORMAT:"openHistoryFormat",REFRESH_EXECUTION_HISTORY:"refreshExecutionHistory",EXPORT_EXECUTION_HISTORY:"exportExecutionHistory",OPEN_ADMIN_CONSOLE:"openAdminConsole",CLOSE_ADMIN_CONSOLE:"closeAdminConsole",ADMIN_REFRESH_PROFILE:"adminRefreshProfile",ADMIN_SHOW_GHCP:"adminShowGhcp",ADMIN_SHOW_PACKAGES:"adminShowPackages",ADMIN_SHOW_WORKERS:"adminShowWorkers",ADMIN_WORKERS_REFRESH:"adminWorkersRefresh",ADMIN_PACKAGES_REFRESH:"adminPackagesRefresh",ADMIN_PACKAGES_NEXT:"adminPackagesNext",ADMIN_PACKAGES_PREV:"adminPackagesPrev",ADMIN_BEGIN_EDIT_GHCP_KEY:"adminBeginEditGhcpKey",ADMIN_CANCEL_EDIT_GHCP_KEY:"adminCancelEditGhcpKey",ADMIN_SAVE_GHCP_KEY:"adminSaveGhcpKey",ADMIN_CLEAR_GHCP_KEY:"adminClearGhcpKey"};function Mt(t,e,s){const n=t.indexOf(e),r=((n===-1?0:n)+s+t.length)%t.length;return t[r]}function Ei(t){const e=typeof t?.utilization=="number"?t.utilization:typeof t?.tokenLimit=="number"&&t.tokenLimit>0&&typeof t?.currentTokens=="number"?t.currentTokens/t.tokenLimit:null;return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.min(100,Math.round(e*100)))}function Zn(t){return typeof t!="number"||!Number.isFinite(t)||t<0?"?":t>=1e6?`${t>=1e7?Math.round(t/1e6):Math.round(t/1e5)/10}`.replace(/\.0$/,"")+"m":t>=1e3?`${t>=1e5?Math.round(t/1e3):Math.round(t/100)/10}`.replace(/\.0$/,"")+"k":String(Math.round(t))}function Yc(t){const e=Ei(t);return e==null?"gray":e>=85?"red":e>=70?"yellow":"gray"}function Xc(t){if(!t||!(typeof t.tokenLimit=="number"&&t.tokenLimit>0&&typeof t.currentTokens=="number"&&t.currentTokens>=0))return null;const e=Ei(t);return e==null?null:{text:`ctx ${Zn(t.currentTokens)}/${Zn(t.tokenLimit)} ${e}%`,color:Yc(t)}}function Qc(t){const e=t?.compaction;return!e||typeof e!="object"?null:e.state==="running"?{text:"[compacting]",color:"magenta"}:e.state==="failed"?{text:"[compact failed]",color:"red"}:null}function Ia(t){return!t||typeof t!="object"?null:{...t,...t.compaction&&typeof t.compaction=="object"?{compaction:{...t.compaction}}:{}}}function Zc(t){if(t instanceof Date)return t.getTime();const e=new Date(t).getTime();return Number.isFinite(e)?e:Date.now()}function ka(t,e,s={},n={}){if(!e)return null;const i=Ia(t)||{},r=Zc(n.timestamp);return e==="session.usage_info"?typeof s.tokenLimit!="number"||typeof s.currentTokens!="number"||typeof s.messagesLength!="number"?null:(i.tokenLimit=s.tokenLimit,i.currentTokens=s.currentTokens,i.messagesLength=s.messagesLength,i.utilization=s.tokenLimit>0?s.currentTokens/s.tokenLimit:0,typeof s.systemTokens=="number"&&(i.systemTokens=s.systemTokens),typeof s.conversationTokens=="number"&&(i.conversationTokens=s.conversationTokens),typeof s.toolDefinitionsTokens=="number"&&(i.toolDefinitionsTokens=s.toolDefinitionsTokens),typeof s.isInitial=="boolean"&&(i.isInitial=s.isInitial),i):e==="assistant.usage"?(typeof s.inputTokens=="number"&&(i.lastInputTokens=s.inputTokens),typeof s.outputTokens=="number"&&(i.lastOutputTokens=s.outputTokens),typeof s.cacheReadTokens=="number"&&(i.lastCacheReadTokens=s.cacheReadTokens),typeof s.cacheWriteTokens=="number"&&(i.lastCacheWriteTokens=s.cacheWriteTokens),i):e==="session.compaction_start"?(i.compaction={...i.compaction||{},state:"running",startedAt:r,completedAt:void 0,error:void 0},i):e==="session.compaction_complete"?(i.compaction={...i.compaction||{},state:s.success===!1?"failed":"succeeded",completedAt:r,error:typeof s.error=="string"?s.error:void 0,preCompactionTokens:typeof s.preCompactionTokens=="number"?s.preCompactionTokens:void 0,postCompactionTokens:typeof s.postCompactionTokens=="number"?s.postCompactionTokens:void 0,preCompactionMessagesLength:typeof s.preCompactionMessagesLength=="number"?s.preCompactionMessagesLength:void 0,messagesRemoved:typeof s.messagesRemoved=="number"?s.messagesRemoved:void 0,tokensRemoved:typeof s.tokensRemoved=="number"?s.tokensRemoved:void 0,systemTokens:typeof s.systemTokens=="number"?s.systemTokens:void 0,conversationTokens:typeof s.conversationTokens=="number"?s.conversationTokens:void 0,toolDefinitionsTokens:typeof s.toolDefinitionsTokens=="number"?s.toolDefinitionsTokens:void 0,inputTokens:typeof s.compactionTokensUsed?.input=="number"?s.compactionTokensUsed.input:void 0,outputTokens:typeof s.compactionTokensUsed?.output=="number"?s.compactionTokensUsed.output:void 0,cachedInputTokens:typeof s.compactionTokensUsed?.cachedInput=="number"?s.compactionTokensUsed.cachedInput:void 0},typeof s.postCompactionTokens=="number"&&typeof i.tokenLimit=="number"&&i.tokenLimit>0&&(i.currentTokens=s.postCompactionTokens,i.utilization=s.postCompactionTokens/i.tokenLimit),typeof s.preCompactionMessagesLength=="number"&&typeof s.messagesRemoved=="number"&&(i.messagesLength=Math.max(0,s.preCompactionMessagesLength-s.messagesRemoved)),typeof s.systemTokens=="number"&&(i.systemTokens=s.systemTokens),typeof s.conversationTokens=="number"&&(i.conversationTokens=s.conversationTokens),typeof s.toolDefinitionsTokens=="number"&&(i.toolDefinitionsTokens=s.toolDefinitionsTokens),i):null}function Jc(t,e,s={}){const n=t?[{text:`[${t}] `,color:"white"}]:[];return e==="session.compaction_start"?[...n,{text:"[compaction]",color:"magenta"},{text:" started",color:"white"}]:s.success===!1?[...n,{text:"[compaction]",color:"red"},{text:" failed",color:"white"},...typeof s.error=="string"&&s.error?[{text:`: ${s.error}`,color:"red"}]:[]]:[...n,{text:"[compaction]",color:"magenta"},{text:" complete",color:"white"},...typeof s.tokensRemoved=="number"?[{text:` freed ${Zn(s.tokensRemoved)}`,color:"gray"}]:[]]}const Jn=/\{(\/?)([a-z-]+)\}/g,eu={color:null,bold:!1,underline:!1},Fs=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{}]+)/g,vr=/session:\/\/([A-Za-z0-9-]+)/g,Ms=" (press a to download)",tu={black:"black",red:"red",green:"green",yellow:"yellow",blue:"blue",magenta:"magenta",cyan:"cyan",white:"white",gray:"gray",grey:"gray"};function Ps(t){return{color:t.color,bold:t.bold,underline:t.underline}}function su(t,e,s){const n=Ps(t);if(e==="bold")return n.bold=!s,n;if(e==="underline")return n.underline=!s,n;if(e.endsWith("-fg")){const i=e.slice(0,-3);return n.color=s?null:tu[i]||null,n}return n}function xi(t){return String(t||"").replace(Jn,"")}function Aa(t){const e=[],n=String(t||"").split(`
2
+ `);for(const i of n){const r=[];let o=Ps(eu),l=0,c;for(;(c=Jn.exec(i))!==null;){const[u,p,d]=c;c.index>l&&r.push({text:i.slice(l,c.index),...Ps(o)}),o=su(o,d,p==="/"),l=c.index+u.length}(l<i.length||r.length===0)&&r.push({text:i.slice(l),...Ps(o)}),e.push(r),Jn.lastIndex=0}return e}function ge(t){return String(t||"").slice(0,8)}function Ca(t){const e=String(t||"");return e?e.includes(":")?e.split(":").slice(1).join(":"):e:""}let bn=null,wn=null,vn=null,En=null;function nu(){return bn||(bn=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})),bn}function Ta(){return wn||(wn=new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})),wn}function iu(){return vn||(vn=new Intl.DateTimeFormat("en-GB",{month:"short"})),vn}function ru(){return En||(En=new Intl.DateTimeFormat("en-GB",{month:"short",day:"numeric"})),En}function Na(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t);if(Number.isNaN(s.getTime()))return"";if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return Ta().format(s);const i=nu().format(s),r=String(s.getDate()),o=iu().format(s),l=s.getFullYear()===e.getFullYear()?"":String(s.getFullYear()).slice(-2);return`${r}${o}${l} ${i}`}catch{return""}}function Le(t,e=new Date){if(!t)return"";try{const s=t instanceof Date?t:new Date(t),n=Ta().format(s);if(s.getFullYear()===e.getFullYear()&&s.getMonth()===e.getMonth()&&s.getDate()===e.getDate())return n;const r=ru().format(s),o=s.getFullYear()===e.getFullYear()?"":` ${s.getFullYear()}`;return`${r}${o} ${n}`}catch{return""}}function Dt(t){if(typeof t!="number"||!Number.isFinite(t)||t<0)return"?";const e=Math.round(t),s=Math.floor(e/3600),n=Math.floor(e%3600/60),i=e%60;return s>0?`${s}h ${n}m`:n>0?`${n}m ${i}s`:`${i}s`}function Ma(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function ou(t,e,s){const n=t.indexOf(e,s);return n>=0?n:-1}function Ds(t){return/[A-Za-z0-9_]/u.test(String(t||""))}function Er(t,e,s){const n=t[e+s.length]||"";if(!n||/\s/u.test(n))return!1;if(!s.includes("_"))return!0;const i=t[e-1]||"";return!(Ds(i)&&Ds(n))}function au(t,e,s){const n=t[e-1]||"";if(!n||/\s/u.test(n))return!1;if(!s.includes("_"))return!0;const i=t[e+s.length]||"";return!(Ds(n)&&Ds(i))}function xr(t,e,s){let n=s;for(;n<t.length;){const i=t.indexOf(e,n);if(i<0)return-1;if(au(t,i,e))return i;n=i+e.length}return-1}function lu(t){let e=String(t||""),s="";for(;e&&/[.,!?;:]/u.test(e[e.length-1]||"");)s=`${e[e.length-1]}${s}`,e=e.slice(0,-1);return{url:e,trailing:s}}function cu(t,e,s){let n=0;for(;t.slice(s+n,s+n+e.length)===e;)n+=e.length;return n}function os(t,e,s={}){if(!e)return;const n=t[t.length-1];if(n&&n.color===(s.color||null)&&!!n.bold==!!s.bold&&!!n.underline==!!s.underline&&n.backgroundColor===s.backgroundColor&&n.href===s.href){n.text+=e;return}t.push({text:e,color:s.color||null,bold:!!s.bold,underline:!!s.underline,backgroundColor:s.backgroundColor||void 0,href:s.href||void 0})}function ct(t,e){if(e){if(e.type==="text"){const s=t[t.length-1];if(s?.type==="text"){s.text+=e.text||"";return}}t.push(e)}}function Pa(t){return(t||[]).map(e=>e?.text||"").join("")}function Rs(t){return Ke(Pa(t))}function uu(t,e){const s=Math.max(0,Number(e)||0);if(s<=0)return[];const n=[];let i=s;for(const r of t||[]){if(i<=0)break;const o=String(r?.text||"");if(!o)continue;const l=Ss(o,i);l&&(n.push({...r,text:l}),i-=Ke(l))}return n}function Ra(t,e){const s=Math.max(0,Number(e)||0),n=uu(t,s),i=Rs(n),r=Math.max(0,s-i);return r>0&&n.push({text:" ".repeat(r),color:null,bold:!1,underline:!1}),n}function _a(t,e){const s=Math.max(1,Number(e)||1),n=[];let i=[],r=0;function o(){if(i.length===0){n.push([{text:"",color:null,bold:!1,underline:!1}]);return}n.push(i),i=[],r=0}for(const l of t||[]){let c=String(l?.text||"");if(c)for(;c.length>0;){const u=Math.max(1,s-r),p=Ss(c,u);if(!p)break;if(p.length===c.length||Ke(p)<u){i.push({...l,text:p}),r+=Ke(p),c=c.slice(p.length),r>=s&&o();continue}const d=p.lastIndexOf(" ");if(d>0&&(r>0||d>0)){const f=p.slice(0,d+1);i.push({...l,text:f}),r+=Ke(f),c=c.slice(f.length),o()}else i.push({...l,text:p}),r+=Ke(p),c=c.slice(p.length),r>=s&&o()}}return(i.length>0||n.length===0)&&o(),n}function Ir(t,e){return e?(t||[]).map(s=>String(s?.text||"").trim()?{...s,color:e}:{...s}):t}function La(t){if(!t)return t;let e=String(t);for(;;){const s=e.replace(/[*_`]+$/g,"").replace(/[)\]}>!,;:?]+$/g,"").replace(/(\.[A-Za-z0-9]{1,16})\.+$/g,"$1");if(s===e)return e;e=s}}function du(t){const e=String(t||"");return Fs.lastIndex=0,[...e.matchAll(Fs)].map(s=>{const n=s[1],i=La(s[2]);return!n||!i?null:{sessionId:n,filename:i,uri:`artifact://${n}/${i}`}}).filter(Boolean)}function Bt(t){const e=String(t||"");if(!e)return e;Fs.lastIndex=0;const s=e.replace(Fs,(n,i,r,o,l)=>{if(l.slice(Math.max(0,o-2),o)==="](")return n;const c=La(r);return!i||!c?n:`[artifact: ${c}](artifact://${i}/${c})${Ms}`});return vr.lastIndex=0,s.replace(vr,(n,i)=>i?`[session: ${ge(i)}](session://${i})`:n)}function Ii(t=""){const e=String(t||""),s=[];let n=0;for(;n<e.length;){if(e[n]==="`"){const r=cu(e,"`",n),o="`".repeat(r),l=ou(e,o,n+r);if(l>n+r-1){ct(s,{type:"code",text:e.slice(n+r,l)}),n=l+r;continue}}if(e.startsWith("**",n)||e.startsWith("__",n)){const r=e.slice(n,n+2),o=Er(e,n,r)?xr(e,r,n+2):-1;if(o>n+2){ct(s,{type:"strong",text:e.slice(n+2,o)}),n=o+2;continue}}if(e[n]==="["){const r=/^\[([^\]]+)\]\(([^)]+)\)/.exec(e.slice(n));if(r){ct(s,{type:"link",text:r[1],href:r[2]}),n+=r[0].length;continue}}if(e.startsWith("<http://",n)||e.startsWith("<https://",n)){const r=e.indexOf(">",n+1);if(r>n+1){const o=e.slice(n+1,r);ct(s,{type:"link",text:o,href:o}),n=r+1;continue}}if(e.startsWith("http://",n)||e.startsWith("https://",n)){let r=n;for(;r<e.length&&!/\s/u.test(e[r]||"");)r+=1;const{url:o,trailing:l}=lu(e.slice(n,r));if(o){ct(s,{type:"link",text:o,href:o}),l&&ct(s,{type:"text",text:l}),n=r;continue}}if((e[n]==="*"||e[n]==="_")&&e[n+1]!==" "&&e[n-1]!==e[n]&&Er(e,n,e[n])){const r=e[n],o=xr(e,r,n+1);if(o>n+1){ct(s,{type:"em",text:e.slice(n+1,o)}),n=o+1;continue}}let i=e.length;for(const r of["<https://","<http://","https://","http://","**","__","`","[","*","_"]){const o=e.indexOf(r,n+1);o!==-1&&o<i&&(i=o)}ct(s,{type:"text",text:e.slice(n,i)}),n=i}return s.length>0?s:[{type:"text",text:""}]}function pu(t=""){return Ii(t).filter(e=>e?.type==="link"&&/^https?:\/\//i.test(String(e?.href||""))).map(e=>({href:String(e.href||"").trim(),text:String(e.text||e.href||"").trim()})).filter(e=>e.href)}function ps(t){const e=Ii(t),s=[];for(const n of e){if(n.type==="code"){os(s,n.text,{color:"cyan"});continue}if(n.type==="strong"){os(s,n.text,{bold:!0});continue}if(n.type==="em"){os(s,n.text,{underline:!0});continue}if(n.type==="link"){os(s,n.text,{color:"cyan",underline:!0,href:n.href});continue}os(s,n.text)}return s.length>0?s:[{text:"",color:null,bold:!1,underline:!1}]}function Ht(t){return/^\s*\|.*\|\s*$/.test(t)||/^\s*\|?[:\- ]+\|[:\-| ]+\|?\s*$/.test(t)}function jt(t){const e=String(t||"").trim().replace(/^\|/,"").replace(/\|$/,""),s=[];let n="",i=!1;for(const r of e){if(i){n+=r,i=!1;continue}if(r==="\\"){i=!0;continue}if(r==="|"){s.push(n.trim()),n="";continue}n+=r}return s.push(n.trim()),s}function Bs(t){return t.length>0&&t.every(e=>/^:?-+:?$/.test(String(e||"").replace(/\s+/g,"")))}function Ke(t){return Array.from(String(t||"")).length}function Ss(t,e){if(e<=0)return"";let s="",n=0;for(const i of Array.from(String(t||""))){if(n+1>e)break;s+=i,n+=1}return s}function Oa(t,e){const s=String(t||""),n=Math.max(0,e-Ke(s));return s+" ".repeat(n)}function $a(t){return Pa(ps(t))}function fu(t,e){const s=$a(t).replace(/\s+/g," ").trim();if(!s)return[""];const n=s.split(" "),i=[];let r="";const o=l=>{let c=l;for(;Ke(c)>e;){const u=Ss(c,e);if(!u)break;r&&(i.push(r),r=""),i.push(u),c=c.slice(u.length)}return c};for(const l of n){const c=o(l);if(!c)continue;if(!r){r=c;continue}const u=`${r} ${c}`;Ke(u)<=e?r=u:(i.push(r),r=c)}return r&&i.push(r),i.length>0?i:[""]}function hu(t,e){const s=Math.max(1,...t.map(p=>p.length)),n=Math.max(s*3,e-(s*3+1)),i=Array.from({length:s},(p,d)=>Math.max(3,...t.map(f=>Ke(f[d]||"")))),r=Array.from({length:s},(p,d)=>Math.max(3,...t.map(f=>Math.max(0,...String(f[d]||"").split(/\s+/).filter(Boolean).map(h=>Ke(h)))))),o=Array.from({length:s},(p,d)=>Math.max(3,Math.min(Math.max(Ke(t[0]?.[d]||"")||3,r[d]),24)));if(i.reduce((p,d)=>p+d,0)<=n)return i;const c=o.slice();let u=n-c.reduce((p,d)=>p+d,0);if(u<0){const p=Math.max(3,Math.floor(n/s));return c.map((d,f)=>f===s-1?Math.max(3,n-p*(s-1)):p)}for(;u>0;){let p=0,d=-1/0;for(let f=0;f<s;f++){const h=i[f]-c[f];h>d&&(d=h,p=f)}if(d<=0){c[s-1]+=u;break}c[p]+=1,u-=1}return c}function mu(t,e){if(!t||t.length===0)return"";const s=Math.max(1,...t.map(f=>f.length)),i=t.map(f=>Array.from({length:s},(h,m)=>f[m]||"")).map(f=>f.map(h=>$a(h))),r=hu(i,e),o=[],l=`┌${r.map(f=>"─".repeat(f+2)).join("┬")}┐`,c=`├${r.map(f=>"─".repeat(f+2)).join("┼")}┤`,u=`└${r.map(f=>"─".repeat(f+2)).join("┴")}┘`,p=f=>{const h=f.map((g,S)=>fu(g,r[S])),m=Math.max(...h.map(g=>g.length));for(let g=0;g<m;g++){const S=h.map((y,v)=>Oa(y[g]||"",r[v]));o.push(`│ ${S.join(" │ ")} │`)}};o.push(l),p(i[0]),o.push(c);const d=i.slice(1);for(const f of d)p(f);return o.push(u),o.join(`
3
+ `)}function gu(t,e){const s=String(t||"").split(`
4
+ `),n=[];let i=!1;for(let r=0;r<s.length;r++){const o=s[r];if(o.trim().startsWith("```")){i=!i,n.push(o);continue}if(i){n.push(o);continue}const c=s[r+1];if(!Ht(o)||!Ht(c)){n.push(o);continue}const u=jt(o),p=jt(c);if(!Bs(p)||u.length!==p.length){n.push(o);continue}const d=[u];for(r+=1;r+1<s.length&&Ht(s[r+1]);){r+=1;const f=jt(s[r]);Bs(f)||d.push(f)}n.push(mu(d,e))}return n.join(`
5
+ `)}function yu(t,e){const s=String(t||"");if(!s)return[""];const n=[];let i=s;for(;i.length>0;){const r=Ss(i,e);if(!r)break;n.push(r),i=i.slice(r.length)}return n.length>0?n:[""]}function kr(t,e){const s=Math.max(12,e),n=t?` ${String(t).trim()} `:" code ",i=Ss(n,Math.max(1,s-4)),r=Math.max(0,s-i.length-2);return[{text:`┌${i}${"─".repeat(r)}┐`,color:"gray"}]}function Ar(t){return[{text:`└${"─".repeat(Math.max(1,t-2))}┘`,color:"gray"}]}function Cr(t,e){const s=Math.max(8,e),n=Math.max(1,s-2),i=[];for(const r of t){const o=yu(r,n);for(const l of o)i.push([{text:"│",color:"gray"},{text:Oa(l,n),color:"cyan"},{text:"│",color:"gray"}]);o.length===0&&i.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}])}return i.length===0&&i.push([{text:"│",color:"gray"},{text:" ".repeat(n),color:"cyan"},{text:"│",color:"gray"}]),i}function Vt(t,e={}){const s=[],n=Math.max(20,Number(e?.width)||80),i=e.tableMode==="sentinel"?"sentinel":"boxArt",o=(i==="boxArt"?gu(String(t||""),n):String(t||"")).split(`
6
+ `);let l=!1,c="",u=[];for(let p=0;p<o.length;p+=1){const d=o[p],f=d.trim();if(f.startsWith("```")){l?(s.push(kr(c,Math.max(8,n))),s.push(...Cr(u,Math.max(8,n))),s.push(Ar(Math.max(8,n))),l=!1,c="",u=[]):(l=!0,c=f.slice(3).trim(),u=[]);continue}if(l){u.push(d);continue}if(i==="sentinel"&&d&&Ht(d)){const y=o[p+1]||"";if(Ht(y)){const v=jt(d),x=jt(y);if(Bs(x)&&v.length===x.length){const E=[];let w=p+2;for(;w<o.length&&Ht(o[w]);){const I=jt(o[w]);Bs(I)||E.push(I),w+=1}s.push({kind:"markdownTable",header:v,rows:E}),p=w-1;continue}}}if(!d){s.push([{text:"",color:null}]);continue}const h=/^(#{1,6})\s+(.*)$/.exec(d);if(h){s.push([{text:h[2],color:"white",bold:!0}]);continue}const m=/^>\s?(.*)$/.exec(d);if(m){s.push([{text:"> ",color:"gray"},...ps(m[1]).map(y=>({...y,color:y.color||"gray"}))]);continue}const g=/^\s*[-*]\s+(.*)$/.exec(d);if(g){s.push([{text:"• ",color:"gray"},...ps(g[1])]);continue}const S=/^\s*(\d+)\.\s+(.*)$/.exec(d);if(S){s.push([{text:`${S[1]}. `,color:"gray"},...ps(S[2])]);continue}s.push(ps(d))}return l&&(s.push(kr(c,Math.max(8,n))),s.push(...Cr(u,Math.max(8,n))),s.push(Ar(Math.max(8,n)))),s}function Ee({title:t="SYSTEM",timestamp:e="",body:s="",width:n=80,titleColor:i="yellow",borderColor:r="gray",bodyColor:o=null,fitToContent:l=!1,tableMode:c=null}={}){const u=Math.max(l?12:20,Number(n)||(l?12:20)),p=Math.max(1,u-4),d=[{text:` ${String(t||"SYSTEM").toUpperCase()} `,color:i,bold:!0},...e?[{text:` ${String(e)} `,color:"gray"}]:[]];if(c==="sentinel"){const x=Vt(String(s||""),{width:p,tableMode:c}),E=o?x.map(w=>Array.isArray(w)?Ir(w,o):w):x;return[{kind:"cardStart",runs:d,borderColor:r},...E,{kind:"cardEnd"},[{text:"",color:null}]]}const f=Vt(String(s||""),{width:p}),h=f.length>0?f.flatMap(x=>_a(x,p)):[[{text:"",color:null}]],m=o?h.map(x=>Ir(x,o)):h,g=m.reduce((x,E)=>Math.max(x,Rs(E)),0),S=l?Math.min(u,Math.max(12,Rs(d)+3,g+4)):u,y=Math.max(1,S-4),v=Math.max(0,S-Rs(d)-3);return[[{text:"┌─",color:r},...d,{text:`${"─".repeat(v)}┐`,color:r}],...m.map(x=>[{text:"│ ",color:r},...Ra(x,y),{text:" │",color:r}]),[{text:`└${"─".repeat(Math.max(1,S-2))}┘`,color:r}],[{text:"",color:null}]]}const ki="[canvas-action] ",Tr=2048,Nr=8192;function Su(t){let e;try{e=JSON.stringify(t)||""}catch{return 1/0}return typeof TextEncoder<"u"?new TextEncoder().encode(e).length:e.length}function bu(t,e){const s=t?.actions;if(!s||typeof s!="object")return{ok:!1,reason:"the current canvas declares no response contract"};if(!e||typeof e!="object"||e.type!=="canvas-action")return{ok:!1,reason:"not a canvas-action message"};const n=typeof e.action=="string"?e.action:"",i=Object.prototype.hasOwnProperty.call(s,n)?s[n]:null;if(!i||typeof i!="object")return{ok:!1,reason:`action ${JSON.stringify(n)} is not declared by the contract`};const r=e.data===void 0?{}:e.data;if(!r||typeof r!="object"||Array.isArray(r))return{ok:!1,reason:"data must be an object"};for(const l of Object.keys(r))if(!Object.prototype.hasOwnProperty.call(i,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(i)){const u=String(c||""),p=u.endsWith("?"),d=p?u.slice(0,-1):u,f=r[l];if(f==null){if(p)continue;return{ok:!1,reason:`required field ${JSON.stringify(l)} is missing`}}if(d==="json"){if(typeof f!="object")return{ok:!1,reason:`field ${JSON.stringify(l)} must be a JSON object or array`};o[l]=f;continue}if(typeof f!==d)return{ok:!1,reason:`field ${JSON.stringify(l)} must be a ${d}`};if(d==="string"&&f.length>Tr)return{ok:!1,reason:`field ${JSON.stringify(l)} exceeds ${Tr} characters`};if(d==="number"&&!Number.isFinite(f))return{ok:!1,reason:`field ${JSON.stringify(l)} must be a finite number`};o[l]=f}return Su(o)>Nr?{ok:!1,reason:`action payload exceeds ${Nr} bytes`}:{ok:!0,action:n,data:o}}function wu(t,e){return`${ki}${JSON.stringify({action:t,data:e})}`}function Fa(t){return typeof t=="string"&&t.startsWith(ki)}function vu(t){if(!Fa(t))return null;try{const e=JSON.parse(t.slice(ki.length));return!e||typeof e!="object"||typeof e.action!="string"?null:{action:e.action,data:e.data&&typeof e.data=="object"?e.data:{}}}catch{return null}}function Eu({burst:t=3,windowMs:e=3e3}={}){const s=[];return function(i=Date.now()){for(;s.length&&i-s[0]>e;)s.shift();return s.length>=t?!1:(s.push(i),!0)}}function Jt(t,e="PilotSwarm"){const s=e||"PilotSwarm",n=String(t?.agentId||"");if(n==="pilotswarm")return s;if(n==="sweeper")return"Sweeper Agent";if(n==="resourcemgr")return"Resource Manager Agent";if(n==="facts-manager")return"Facts Manager";const i=String(t?.title||"").trim();return/^pilotswarm(?: agent)?$/i.test(i)?s:/^sweeper agent$/i.test(i)||/^sweeper$/i.test(i)?"Sweeper Agent":/^resource manager agent$/i.test(i)||/^resourcemgr$/i.test(i)?"Resource Manager Agent":/^facts manager$/i.test(i)||/^facts-manager$/i.test(i)?"Facts Manager":i||"System Agent"}function Da(t){const e=Jt(t,"PilotSwarm");return e==="PilotSwarm"?0:e==="Sweeper Agent"?1:e==="Resource Manager Agent"?2:e==="Facts Manager"?3:10}const me=300,xu=[me,1e3,3e3,1e4],Iu=["user.message","assistant.message","system.message","session.epoch_committed","session.regenerate_refused","session.regenerate_failed","session.canvas_updated"];function Ba(t){const e=t?.data&&typeof t.data=="object"?t.data:{},s=Number.isFinite(e.toEpoch)?e.toEpoch:Number(e.epoch)||0,n=Number.isFinite(e.turnsArchived)?e.turnsArchived:null;return{id:`${t.sessionId}:${t.seq}:epoch`,kind:"epoch-divider",role:"epoch-divider",epoch:s,turnsArchived:n,time:Le(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Ha(t){const e=t?.data&&typeof t.data=="object"?t.data:{};return{id:`${t.sessionId}:${t.seq}:regen-refused`,kind:"regen-refused",role:"regen-refused",reason:typeof e.reason=="string"?e.reason:"unknown",time:Le(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function ja(t){const e=t?.data&&typeof t.data=="object"?t.data:{},s=typeof e.error=="string"?e.error:"";return{id:`${t.sessionId}:${t.seq}:regen-failed`,kind:"regen-failed",role:"regen-failed",stage:typeof e.stage=="string"?e.stage:"unknown",error:s,time:Le(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Fe(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(me,Number(e)||me);return s.length>n?s.slice(-n):s}function lt(t){return String(t||"").replace(/\r\n/g,`
7
+ `).trim()}function Mr(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"";try{return e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short"}).replace(/,\s*/g," ").replace(/\s+/g," ").trim()}catch{return e.toISOString().replace(/\.000Z$/,"Z")}}const Ga=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\./i,ku=/^The session was dehydrated and has been rehydrated on a new worker(?: \([^)]+\))?\.\s*The LLM conversation history is preserved\.?/i;function Ai(t){return Ga.test(lt(t))}function ft(t){const e=String(t||"").replace(/\r\n/g,`
8
+ `).trim();if(!e)return"";const s=e.replace(ku,"").trimStart();return s!==e?s.trim():Ai(e)?e.replace(Ga,"").trim():e}function Ua(t){const e=String(t||"").replace(/\r\n/g,`
9
+ `).split(`
10
+ `),s=[];let n=[];function i(){n.length!==0&&(s.push({kind:"text",text:n.join(`
11
+ `)}),n=[])}for(let r=0;r<e.length;){const o=e[r];if(!/^\s*\[SYSTEM:/i.test(o)){n.push(o),r+=1;continue}const l=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(o);if(l){i(),s.push({kind:"system",text:l[1].trim()}),r+=1;continue}const c=[o.replace(/^\s*\[SYSTEM:\s*/i,"")];let u=-1;for(let p=r+1;p<e.length;p+=1){const d=e[p];if(d.trim()==="]"){u=p;break}if(/\]\s*$/.test(d.trim())){const f=d.replace(/\]\s*$/,"");f.trim()&&c.push(f),u=p;break}c.push(d)}if(u===-1){n.push(o),r+=1;continue}i(),s.push({kind:"system",text:c.join(`
12
+ `).trim()}),r=u+1}return i(),s}function za(t,e){const s=String(t||"").replace(/\r\n/g,`
13
+ `);return e==="user"||e==="assistant"?Ua(s).filter(n=>n.kind==="text").map(n=>n.text).join(`
14
+ `).trim():s.trim()}function Au(t,e){return e!=="user"&&e!=="assistant"?[]:Ua(t).filter(s=>s.kind==="system").map(s=>s.text).filter(Boolean)}function Pr(t){const e=lt(t?.text||"");if(!e)return"";if(t?.role==="user"||t?.role==="assistant"){const s=za(e,t.role);if(s)return s}return ft(e)}function Ci(t){const e=String(t||"").replace(/\r\n/g,`
15
+ `).trim(),s='The user was asked: "',n=`"
16
+ The user responded: "`;if(!e.startsWith(s)||!e.endsWith('"'))return null;const i=e.indexOf(n,s.length);if(i===-1)return null;const r=e.slice(s.length,i),o=e.slice(i+n.length,-1);return!r.trim()||!o.trim()?null:{question:r,answer:o}}function Cu(t){return lt(xi(t)).length>0}function Tu(t){const e=lt(t);return e?/^\[SYSTEM:/i.test(e)||/^\[CHILD_UPDATE\b/i.test(e)||/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(e)||/^Buffered child updates arrived /i.test(e)||/^There is an active recurring schedule every /i.test(e)||/^It remains active automatically after this turn completes/i.test(e)||/^Sub-agent spawned successfully\./i.test(e)||/^Message sent to sub-agent /i.test(e)||/^No sub-agents have been spawned yet\./i.test(e)||/^Sub-agent status report \(/i.test(e)||/^Active sessions \(/i.test(e)||/^Sub-agents completed:/i.test(e)||/^Sub-agent .* has been (completed gracefully|cancelled|deleted)\./i.test(e)||/^The runtime recovered this session after the worker lost the live Copilot session\./i.test(e)||/^The runtime recovered this session after the live Copilot session was lost on a worker\./i.test(e)||/^The runtime is replaying this turn after a worker restart/i.test(e)||/^The runtime detected missing Copilot session state for /i.test(e)||/^(spawn_agent|message_agent|check_agents|wait_for_agents|complete_agent|cancel_agent|delete_agent) failed/i.test(e):!1}function Nu(t){return/^\[SESSION_MESSAGE(?:_RESPONSE)?\b/i.test(lt(t))}function Pt(t,e){const s=String(t||""),n=`${e}=`,i=s.indexOf(n);if(i<0)return"";const r=s.slice(i+n.length),o=[" request_id="," from="," subject="," reason="," expects_response="," expires_at="," verdict="];let l=r.length;for(const c of o){const u=r.indexOf(c);u>=0&&(l=Math.min(l,u))}return r.slice(0,l).trim()}function Mu(t,e){const s=lt(e);if(!s)return null;const n=/^\[SESSION_MESSAGE\s+([^\]]+)\]\n?/i.exec(s);if(n){const r=n[1],o=`
17
+ Request body:
18
+ `,l=s.indexOf(o),c=l>=0?s.slice(l+o.length).trim():s.slice(n[0].length).trim(),u=Pt(r,"request_id"),p=Pt(r,"from"),d=Pt(r,"subject"),f=/\bexpects_response=true\b/i.test(r),h=[p?`From: session-${ge(p)}`:"",u?`Request ID: ${u}`:"",d?`Subject: ${d}`:"",f?"Response: required":"Response: not required","",c].filter((m,g)=>g===4||String(m||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:h.join(`
19
+ `),time:Le(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:f?"Session Request":"Session Message",cardTitleColor:"cyan",cardBorderColor:"cyan"}}const i=/^\[SESSION_MESSAGE_RESPONSE\s+([^\]]+)\]\n?/i.exec(s);if(i){const r=i[1],o=/^This is the requested cross-session response\.[^\n]*\n\n?/i,l=s.slice(i[0].length).trim().replace(o,"").trim(),c=Pt(r,"request_id"),u=Pt(r,"from"),p=Pt(r,"verdict")||"answered",d=[u?`From: session-${ge(u)}`:"",c?`Request ID: ${c}`:"",`Verdict: ${p}`,"",l].filter((f,h)=>h===3||String(f||"").trim());return{id:`${t.sessionId}:${t.seq}`,role:"system",text:d.join(`
20
+ `),time:Le(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),cardTitle:"Session Reply",cardTitleColor:"green",cardBorderColor:"green"}}return null}function Pu(t,e,s){return t?.eventType==="system.message"||(e==="user"||e==="assistant")&&Tu(s)?"system":e}function Ru(t,e){const s=Array.isArray(t?.clientMessageIds)?t.clientMessageIds:[],n=Array.isArray(e?.clientMessageIds)?e.clientMessageIds:[];return s.length===0||n.length===0?null:s.some(i=>n.includes(i))}function _u(t,e){if(!t||!e||t.role!==e.role)return!1;if(t.kind==="canvas-update"||e.kind==="canvas-update")return t.kind===e.kind&&t.id===e.id;const s=Pr(t),n=Pr(e);if(!s||!n||s!==n)return!1;const i=Ru(t,e);if(i!=null)return i;const r=Number(t.createdAt||0),o=Number(e.createdAt||0);return t.optimistic||e.optimistic?!0:!r||!o?!1:Math.abs(r-o)<=1e4}function Gt(t=[]){const e=[];for(const s of t){if(!s)continue;const n=e[e.length-1];if(!_u(n,s)){e.push(s);continue}if(n?.optimistic&&!s?.optimistic){e[e.length-1]=s;continue}if(!n?.optimistic&&s?.optimistic)continue;const i=Number(n?.createdAt||0),r=Number(s?.createdAt||0),o=r>=i?s:n;if(o.role==="user"&&!n?.optimistic&&!s?.optimistic){const l=Math.min(Number(n?.firstDeliveredAt||i||1/0),Number(s?.firstDeliveredAt||r||1/0));e[e.length-1]={...o,redelivered:!0,...Number.isFinite(l)?{firstDeliveredAt:l}:{}};continue}e[e.length-1]=o}return e}function Lu(t){return typeof t=="string"?t.replace(/^\[FROM:[^\]\n]*\]\n?/,""):t}function Ut(t,e){const s=es(t),n=Mu(t,s);if(n)return n;if(e==="user"&&Fa(s)){const c=vu(s);if(c)return{id:`${t.sessionId}:${t.seq}`,kind:"canvas-action",role:"user",action:c.action,data:c.data,text:s,time:Le(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...Array.isArray(t?.data?.clientMessageIds)&&t.data.clientMessageIds.length>0?{clientMessageIds:t.data.clientMessageIds}:{}}}const i=Lu(za(s,e));if(!Cu(i))return null;const r=Array.isArray(t?.data?.clientMessageIds)?t.data.clientMessageIds.filter(c=>typeof c=="string"&&c):[],o=t?.data?.sender&&typeof t.data.sender=="object"?t.data.sender:null,l=Array.isArray(t?.data?.attachments)?t.data.attachments.filter(c=>c&&typeof c.filename=="string"&&c.filename):[];return{id:`${t.sessionId}:${t.seq}`,role:Pu(t,e,i),text:i,time:Le(t.createdAt),createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),...r.length>0?{clientMessageIds:r}:{},...o?{sender:o}:{},...l.length>0?{attachments:l}:{}}}function Wa(t){return t?.eventType!=="system.message"?!1:!Nu(es(t))}function Hs(t,e){return Au(es(t),e).map((s,n)=>kt({...t,seq:`${t?.seq??"?"}:system:${n+1}`,eventType:"system.message",data:{content:s}})).filter(Boolean)}function Ou(t,e){if(!Array.isArray(t)||e?.role!=="user")return[...t||[]];const s=lt(e.text),n=Ci(e.text),i=n?lt(n.answer):"";let r=!1;return t.filter(o=>{if(r||!o?.optimistic||o.role!==e.role)return!0;const l=lt(o.text);return l!==s&&l!==i?!0:(r=!0,!1)})}function es(t){const e=t?.data;if(typeof e=="string")return e;if(e&&typeof e=="object"){if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;if(typeof e.message=="string")return e.message;if(typeof e.question=="string")return e.question}return Ma(e)}function qa(t){return(t||[]).map(e=>e?.text||"").join("")}function $u(t,e=120){const s=String(t||"").replace(/\s+/g," ").trim();return s?s.length>e?`${s.slice(0,e-3)}...`:s:""}function Ti(t=[]){const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();if(!i)continue;const r=i.toLowerCase();e.has(r)||(e.add(r),s.push(i))}return s.join(" | ")}function Fu(t,e=""){return Ti([t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function Du(t,e=""){return Ti([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function Bu(t,e=""){const s=es(t),n=ft(e);return Ti([ft(s),n,t?.data?.detail,t?.data?.message])}function Hu(t){return t==null?"null":typeof t=="string"?JSON.stringify(t.length>32?`${t.slice(0,29)}...`:t):typeof t=="number"||typeof t=="boolean"?String(t):Array.isArray(t)?`[${t.length}]`:typeof t=="object"?"{...}":String(t)}function ju(t,e){if(!e||typeof e!="object")return"";if(t==="wait"){const i=e.seconds!=null?`${e.seconds}s`:"?",r=e.preserveWorkerAffinity===!0?" preserve=true":"",o=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${i}${r}${o}`}if(t==="cron"){if(e.action==="cancel")return" cancel";const i=e.seconds!=null?`${e.seconds}s`:"?",r=typeof e.reason=="string"&&e.reason?` reason=${JSON.stringify(e.reason)}`:"";return` ${i}${r}`}const s=Object.entries(e).slice(0,4).map(([i,r])=>`${i}=${Hu(r)}`);if(s.length===0)return"";const n=Object.keys(e).length>s.length?", ...":"";return` ${s.join(", ")}${n}`}function Ni(t){return t?[{text:`[${t}] `,color:"white"}]:[]}function de(t,e,s,n="",i="white"){return[...Ni(t),{text:e,color:s},...n?[{text:` ${n}`,color:i}]:[]]}function Gu(t,e=96){return $u(xi(es(t)),e)||""}function xn(t,e,s="start"){const n=typeof e?.data?.toolCallId=="string"?e.data.toolCallId:"",i=typeof e?.data?.requestId=="string"?e.data.requestId:"",r=e?.data?.toolName||e?.data?.name||(n?`tool call ${n.slice(0,8)}`:i?`tool request ${i.slice(0,8)}`:"tool"),o=e?.data?.arguments||e?.data?.args,l=e?.data?.durableSessionId,c=ju(r,o),u=s==="start"?"▶":s==="partial"?"…":"✓",p=s==="start"?"yellow":s==="partial"?"cyan":"green";return[...Ni(t),{text:`${u} ${r}${c}`,color:p},...l?[{text:` [sess ${ge(l)}]`,color:"gray"}]:[]]}function kt(t){const e=Le(t.createdAt),s=Gu(t);let n=null;switch(t.eventType){case"assistant.usage":case"session.info":case"session.idle":case"session.usage_info":case"pending_messages.modified":case"pending_messages.cancelled":case"abort":case"assistant.turn_end":case"assistant.streaming_progress":return null;case"session.artifact_presented":{const i=(t?.data??{})||{},r=String(i.filename||"artifact"),o=typeof i.note=="string"&&i.note.trim()?` — ${i.note.trim()}`:"";n=de(e,"[show]","cyan",`${r}${o}`,"white");break}case"session.canvas_updated":{const i=(t?.data??{})||{},r=Number(i.rev)||0,o=typeof i.note=="string"&&i.note.trim()?` — ${i.note.trim()}`:"",l=typeof i.source?.filename=="string"&&i.source.filename.trim()?` from ${i.source.filename.trim()}`:"";n=de(e,"[canvas]","cyan",`rev ${r}${l}${o}`,"white");break}case"session.canvas_data":{const i=(t?.data??{})||{},r=Number(i.dataRev)||0,o=Number.isFinite(Number(i.sizeBytes))?` (${(Number(i.sizeBytes)/1024).toFixed(1)} KB)`:"",l=typeof i.note=="string"&&i.note.trim()?` — ${i.note.trim()}`:"";n=de(e,"[canvas]","cyan",`data tick ${r}${o}${l}`,"white");break}case"tool.execution_start":n=xn(e,t,"start");break;case"tool.execution_complete":n=xn(e,t,"complete");break;case"tool.execution_partial_result":n=xn(e,t,"partial");break;case"tool.execution_progress":{const i=(t?.data??{})||{},r=i.toolName||i.name||"tool",o=typeof i.message=="string"&&i.message?i.message:typeof i.detail=="string"&&i.detail?i.detail:i.percent!=null?`${Math.round(Number(i.percent))}%`:"running…";n=de(e,"[tool]","cyan",`${r} ${o}`,"white");break}case"assistant.reasoning":n=de(e,"[reasoning]","gray",s||"…","white");break;case"assistant.intent":{const i=(t?.data??{})||{},r=typeof i.summary=="string"&&i.summary?i.summary:typeof i.intent=="string"&&i.intent?i.intent:s||"";n=de(e,"[intent]","gray",r||"…","white");break}case"assistant.turn_start":n=de(e,"[turn start]","gray",s);break;case"session.turn_completed":n=de(e,"[turn completed]","gray",t?.data?.iteration!=null?`iter ${t.data.iteration}`:s);break;case"session.lossy_handoff":n=de(e,"[lossy handoff]","yellow",Du(t,s)||"handoff to a new worker");break;case"session.dehydrated":n=de(e,"[dehydrated]","cyan",Fu(t,s));break;case"session.hydrated":case"session.rehydrated":n=de(e,"[rehydrated]","green",s);break;case"session.wait_started":{const i=t?.data?.seconds!=null?`${t.data.seconds}s`:"?",r=typeof t?.data?.reason=="string"&&t.data.reason?` reason=${JSON.stringify(t.data.reason)}`:"",o=t?.data?.preserveAffinity?" preserve=true":"";n=de(e,"[wait]","yellow",`${i}${o}${r}`.trim());break}case"session.input_required_started":n=de(e,"[input]","yellow",s);break;case"session.agent_spawned":n=de(e,"[spawn]","cyan",t?.data?.agentId||ge(t?.data?.childSessionId),"white");break;case"session.cron_started":n=de(e,"[cron]","magenta",`started${t?.data?.seconds!=null?` ${t.data.seconds}s`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_scheduled":case"session.cron_at_started":n=de(e,"[cron]","magenta",`scheduled${t?.data?.nextFireAt?` ${Mr(t.data.nextFireAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_fired":n=de(e,"[cron]","magenta",`fired${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_fired":n=de(e,"[cron]","magenta",`fired${t?.data?.scheduledAt?` ${Mr(t.data.scheduledAt)}`:""}${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_cancelled":case"session.cron_at_cancelled":n=de(e,"[cron]","magenta",`cancelled${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.cron_at_completed":n=de(e,"[cron]","magenta",`completed${t?.data?.reason?` reason=${JSON.stringify(t.data.reason)}`:""}`);break;case"session.command_received":n=de(e,"[command]","magenta",`/${t?.data?.cmd||"?"}${s?` ${s}`:""}`);break;case"session.command_completed":n=de(e,"[command]","magenta",`/${t?.data?.cmd||"?"} ok${s?` ${s}`:""}`);break;case"session.compaction_start":case"session.compaction_complete":n=Jc(e,t.eventType,t.data||{});break;case"session.error":n=de(e,"[error]","red",s||"session error","white");break;case"system.message":Ai(es(t))?n=de(e,"[rehydrated]","green",Bu(t,s)||"conversation preserved"):n=de(e,"[system]","gray",s||"system message");break;default:n=[...Ni(e),{text:`[${t.eventType}]`,color:"gray"},...s?[{text:` ${s}`,color:"white"}]:[]];break}return{id:`${t.sessionId}:${t.seq}`,eventType:t.eventType,time:e,seq:Number.isFinite(Number(t?.seq))?Number(t.seq):0,createdAt:t?.createdAt instanceof Date?t.createdAt.getTime():t?.createdAt?new Date(t.createdAt).getTime():0,text:qa(n),line:n}}function Uu(t=me){const e=Math.max(me,Number(t)||me);return xu.find(n=>n>e)||Math.min(1e5,e*2)}function Ka(t){const e=t.sessionId||null;return{id:`${t.sessionId||""}:${t.seq}:canvas`,kind:"canvas-update",role:"canvas-update",sessionId:e,rev:Number(t?.data?.rev)||0,note:typeof t?.data?.note=="string"?t.data.note:"",text:e?`artifact://${e}/canvas.html`:"",createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime()}}function Va(t,e){const s=Le(t.createdAt),n=`action ${e.action}${Object.keys(e.data||{}).length?" "+Ma(e.data):""}`,i=de(s,"[canvas]","cyan",n,"white");return{id:`${t.sessionId}:${t.seq}:canvas-action`,eventType:t.eventType,time:s,seq:Number.isFinite(Number(t?.seq))?Number(t.seq):0,createdAt:t.createdAt instanceof Date?t.createdAt.getTime():new Date(t.createdAt).getTime(),text:qa(i),line:i}}function Es(t=[],e={}){const s=Math.max(me,Number(e.requestedLimit??e.eventLimit??me)||me),n=[],i=[],r=[];for(const o of t){if(r.push(o),o.eventType==="user.message"){i.push(...Hs(o,"user"));const c=Ut(o,"user");if(c&&n.push(c),c?.kind==="canvas-action"){const u=Va(o,c);u&&i.push(u)}continue}if(o.eventType==="session.canvas_updated"){n.push(Ka(o));const c=kt(o);c&&i.push(c);continue}if(o.eventType==="assistant.message"){i.push(...Hs(o,"assistant"));const c=Ut(o,"assistant");c&&n.push(c);continue}if(o.eventType==="system.message"){if(Wa(o)){const c=kt(o);c&&i.push(c)}else{const c=Ut(o,"system");c&&n.push(c)}continue}if(o.eventType==="session.epoch_committed"){n.push(Ba(o));continue}if(o.eventType==="session.regenerate_refused"){n.push(Ha(o));continue}if(o.eventType==="session.regenerate_failed"){n.push(ja(o));continue}const l=kt(o);l&&i.push(l)}return{chat:Gt(n),activity:i,events:r.slice(-s),loadedEventLimit:s,loadedEventCount:r.length,hasOlderEvents:r.length>=s}}function Rr(t,e){const s=Array.isArray(t?.events)?t.events:[],n=Math.max(me,Number(t?.loadedEventLimit??me)||me),i=s.length>0&&s[s.length-1]?.seq===e?.seq?s:[...s,e].slice(-n),r={chat:Fe(t?.chat||[],n),activity:Fe(t?.activity||[],n),events:i,lastSeq:Number.isFinite(Number(e.seq))?e.seq:t?.lastSeq||0,loadedEventLimit:n,loadedEventCount:Math.max(Number(t?.loadedEventCount||0),i.length),hasOlderEvents:!!t?.hasOlderEvents,stoppedMessageIds:Array.isArray(t?.stoppedMessageIds)?t.stoppedMessageIds:[]};if(e.eventType==="session.turn_stopped"){const l=Array.isArray(e?.data?.clientMessageIds)?e.data.clientMessageIds.filter(c=>typeof c=="string"&&c):[];if(l.length>0){const c=new Set([...r.stoppedMessageIds,...l]);r.stoppedMessageIds=Array.from(c),r.chat=r.chat.map(u=>Array.isArray(u.clientMessageIds)&&u.clientMessageIds.some(p=>c.has(p))?{...u,stopped:!0}:u)}return r}if(e.eventType==="user.message"){r.activity.push(...Hs(e,"user"));const l=Ut(e,"user");if(l?.kind==="canvas-action"){const c=Va(e,l);c&&r.activity.push(c)}return r.activity=Fe(r.activity,n),l&&(Array.isArray(l.clientMessageIds)&&l.clientMessageIds.some(c=>r.stoppedMessageIds.includes(c))&&(l.stopped=!0),r.chat=Ou(r.chat,l),r.chat.push(l),r.chat=Fe(Gt(r.chat),n)),r}if(e.eventType==="session.canvas_updated"){r.chat.push(Ka(e)),r.chat=Fe(r.chat,n);const l=kt(e);return l&&(r.activity.push(l),r.activity=Fe(r.activity,n)),r}if(e.eventType==="assistant.message"){r.activity.push(...Hs(e,"assistant")),r.activity=Fe(r.activity,n);const l=Ut(e,"assistant");return l&&(r.chat.push(l),r.chat=Fe(Gt(r.chat),n)),r}if(e.eventType==="system.message"){if(Wa(e)){const l=kt(e);l&&(r.activity.push(l),r.activity=Fe(r.activity,n))}else{const l=Ut(e,"system");if(!l)return r;r.chat.push(l),r.chat=Fe(Gt(r.chat),n)}return r}if(e.eventType==="session.epoch_committed")return r.chat.push(Ba(e)),r.chat=Fe(r.chat,n),r;if(e.eventType==="session.regenerate_refused")return r.chat.push(Ha(e)),r.chat=Fe(r.chat,n),r;if(e.eventType==="session.regenerate_failed")return r.chat.push(ja(e)),r.chat=Fe(r.chat,n),r;const o=kt(e);return o&&(r.activity.push(o),r.activity=Fe(r.activity,n)),r}function In(t,e=null){const s=typeof e?.splash=="string"&&e.splash.trim()?e.splash:null,n=s||t?.splash;if(!n)return[];const i=s?e?.splashMobile:t?.splashMobile,r=typeof i=="string"&&i.trim()?i:null,o=e?.isSystem?Jt(e,t?.title||"PilotSwarm"):e?.title||t?.title||"PilotSwarm",l="{gray-fg}Start interacting with this session to replace the splash screen.{/gray-fg}";return[{id:`splash:${o}`,role:"system",text:`${n}
21
+
22
+ ${l}`,...r?{mobileText:`${r}
23
+
24
+ ${l}`}:{},time:"",splash:!0}]}const Ya=.7,zu=30,_r=36,kn=18,_s=18,An=0,Xa=3,Yt=6,ln=10,Wu=.25,qu=.5,zt=6,js=10,Qa=.336,Cn=zt,Tn=js,Nn=Yt,Mn=ln;function Ot(t,e,s){return Math.max(e,Math.min(s,t))}function Ku(t){return[N.SESSIONS,N.CHAT,N.INSPECTOR,N.ACTIVITY].includes(t)?t:null}function Vu(t={}){return{width:Math.max(40,Number(t.width)||120),height:Math.max(18,Number(t.height)||40)}}function Wt(t=""){const e=String(t||"").split(`
25
+ `).length;return Ot(e,1,Xa)}function Za(t){return Math.max(Yt,Math.floor(t*Wu))}function Ja(t,e){const s=Math.floor(Math.max(0,Number(t)||0)*qu),n=Math.max(Yt,e-ln);return Math.max(Yt,Math.min(n,s))}function Lr(t,e){const s=Math.max(0,Number(t)||0),n=Ot(Math.max(0,Number(e)||0),0,s),i=-(s/2);return{minAdjust:i,maxAdjust:Math.max(i,s/2-n)}}function gs(t,e=0,s=1,n=0,i=0,r=null){const o=Vu(t),l=o.width,c=o.height,u=Ot(Number(s)||1,1,Xa),p=Ku(r),d=5+u,f=Math.max(18,c-d),m=Math.floor(l*Ya)+(Number(e)||0),g=l-m-An;let S=!1,y=!1;m<=kn&&g>_s?S=!0:g<=_s&&m>kn?y=!0:m<=kn&&g<=_s&&(y=e>=0,S=!y);let v,x;S?(v=0,x=l):y?(v=l,x=0):(v=Ot(m,zu,l-_r-An),x=Math.max(_r,l-v-An));const w=Za(f)+(Number(n)||0),I=f-w;let b=!1,M=!1;I<=Mn&&w>Nn?M=!0:w<=Nn&&I>Mn?b=!0:I<=Mn&&w<=Nn&&(M=(Number(n)||0)>=0,b=!M);let A,O;if(b)A=0,O=f;else if(M)A=f,O=0;else{const he=Ja(c,f);A=Ot(w,Yt,he),O=Math.max(ln,f-A)}const L=Math.max(zt,Math.floor(f*Qa))+(Number(i)||0),G=f-L;let P=!1,H=!1;G<=Tn&&L>Cn?P=!0:L<=Cn&&G>Tn?H=!0:G<=Tn&&L<=Cn&&(P=(Number(i)||0)>=0,H=!P);let U,re;return P?(U=f,re=0):H?(re=f,U=0):(U=Ot(L,zt,Math.max(zt,f-js)),re=Math.max(js,f-U)),{viewport:o,totalWidth:l,totalHeight:c,reservedRows:d,bodyHeight:f,promptRows:u,fullscreenPane:p,paneAdjust:Number(e)||0,sessionPaneAdjust:Number(n)||0,activityPaneAdjust:Number(i)||0,leftHidden:S,rightHidden:y,inspectorHidden:P,activityHidden:H,sessionHidden:b,chatHidden:M,leftWidth:v,rightWidth:x,sessionPaneHeight:A,chatPaneHeight:O,activityPaneHeight:U,inspectorPaneHeight:re}}function ei(t){if(t?.fullscreenPane)return[t.fullscreenPane,N.PROMPT];if(t?.leftHidden)return[N.INSPECTOR,N.ACTIVITY,N.PROMPT];if(t?.rightHidden)return[...t?.sessionHidden?[N.CHAT]:t?.chatHidden?[N.SESSIONS]:[N.SESSIONS,N.CHAT],N.PROMPT];if(t?.sessionHidden){const e=t?.inspectorHidden?[N.ACTIVITY]:t?.activityHidden?[N.INSPECTOR]:[N.INSPECTOR,N.ACTIVITY];return[N.CHAT,...e,N.PROMPT]}if(t?.chatHidden){const e=t?.inspectorHidden?[N.ACTIVITY]:t?.activityHidden?[N.INSPECTOR]:[N.INSPECTOR,N.ACTIVITY];return[N.SESSIONS,...e,N.PROMPT]}return t?.inspectorHidden?[N.SESSIONS,N.CHAT,N.ACTIVITY,N.PROMPT]:t?.activityHidden?[N.SESSIONS,N.CHAT,N.INSPECTOR,N.PROMPT]:[N.SESSIONS,N.CHAT,N.INSPECTOR,N.ACTIVITY,N.PROMPT]}function Qe(t,e){const s=ei(e);return s.includes(t)?t:s[0]||N.PROMPT}function Yu(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[N.PROMPT]:N.PROMPT,[N.ACTIVITY]:N.INSPECTOR,[N.INSPECTOR]:N.INSPECTOR}[t]||N.INSPECTOR:e?.rightHidden?{[N.PROMPT]:N.PROMPT,[N.CHAT]:e?.sessionHidden?N.CHAT:N.SESSIONS,[N.SESSIONS]:N.SESSIONS}[t]||(e?.sessionHidden?N.CHAT:N.SESSIONS):{[N.PROMPT]:e?.sessionHidden?N.CHAT:N.SESSIONS,[N.ACTIVITY]:e?.chatHidden?N.SESSIONS:N.CHAT,[N.INSPECTOR]:e?.chatHidden?N.SESSIONS:N.CHAT,[N.CHAT]:e?.sessionHidden?N.CHAT:N.SESSIONS,[N.SESSIONS]:N.SESSIONS}[t]||(e?.sessionHidden?N.CHAT:N.SESSIONS)}function Xu(t,e){return e?.fullscreenPane?e.fullscreenPane:e?.leftHidden?{[N.PROMPT]:N.PROMPT,[N.INSPECTOR]:N.ACTIVITY,[N.ACTIVITY]:N.ACTIVITY}[t]||N.INSPECTOR:e?.rightHidden?{[N.PROMPT]:N.PROMPT,[N.SESSIONS]:e?.chatHidden?N.SESSIONS:N.CHAT,[N.CHAT]:N.CHAT}[t]||(e?.chatHidden?N.SESSIONS:N.CHAT):e?.inspectorHidden?{[N.PROMPT]:N.PROMPT,[N.SESSIONS]:N.CHAT,[N.CHAT]:N.ACTIVITY,[N.ACTIVITY]:N.ACTIVITY}[t]||N.CHAT:e?.activityHidden?{[N.PROMPT]:N.PROMPT,[N.SESSIONS]:N.CHAT,[N.CHAT]:N.INSPECTOR,[N.INSPECTOR]:N.INSPECTOR}[t]||N.CHAT:{[N.PROMPT]:N.PROMPT,[N.SESSIONS]:N.CHAT,[N.CHAT]:N.INSPECTOR,[N.INSPECTOR]:N.ACTIVITY,[N.ACTIVITY]:N.ACTIVITY}[t]||N.CHAT}function el(t){const e=String(t||"").trim();if(!e)return{error:"Paste a link to plugin.json or the folder that contains it."};let s;try{s=new URL(e)}catch{return{error:"That does not look like a URL — paste the browser link to plugin.json or its folder."}}const n=s.hostname.toLowerCase();if(n==="github.com"||n==="www.github.com"){const r=s.pathname.split("/").filter(Boolean);if(r.length<2)return{error:"GitHub links need at least github.com/org/repo."};const[o,l,c,u,...p]=r,d=l.replace(/\.git$/u,""),f=`https://github.com/${o}/${d}`;return c?c!=="blob"&&c!=="tree"?{error:`Unrecognized GitHub link shape (…/${c}/…) — use a /blob/ or /tree/ link, or the bare repo URL.`}:u?{kind:"github",repoUrl:f,ref:u,path:p.length?`/${p.join("/")}`:null}:{error:"That GitHub link is missing the branch segment."}:{kind:"github",repoUrl:f,ref:null,path:null}}if(n==="dev.azure.com"||n.endsWith(".visualstudio.com")){if(!s.pathname.includes("/_git/"))return{error:"Azure DevOps links must point at a repo (…/_git/<repo>…)."};const r=`${s.origin}${s.pathname.split("?")[0]}`.replace(/\/$/u,""),o=s.searchParams.get("path"),l=s.searchParams.get("version"),c=l&&/^G[BT]/u.test(l)?l.slice(2):l||null;return{kind:"ado",repoUrl:r,ref:c,path:o||null}}return{error:"Only GitHub and Azure DevOps links are recognized here — for a tarball use the URL tab."}}const Gs=2*1024*1024,Qu=new Set(["node_modules",".git"]);function ti(t){const e=t instanceof Uint8Array?t:new Uint8Array(t);if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let s="";const n=32768;for(let i=0;i<e.length;i+=n)s+=String.fromCharCode.apply(null,e.subarray(i,i+n));return btoa(s)}function tl(t){const e=String(t||"").replace(/\s+/gu,"");if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const s=atob(e),n=new Uint8Array(s.length);for(let i=0;i<s.length;i+=1)n[i]=s.charCodeAt(i);return n}function sl(t){return t.split("/").some(e=>Qu.has(e))}function nl(t){const e=String(t||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.endsWith("/plugin.json")?e.slice(0,-12):e==="plugin.json"?"":e:""}function Zu(t,e){return t?`${t}/${e}`:e}function il(t,e){const s=String(e?.message||e||"");return new Error(`could not reach ${t} from the browser (${s||"network error"}) — the host may block cross-origin reads from this portal; use Upload folder instead`)}async function Us(t,e,s,n){let i;try{i=await t(e,{headers:{accept:"application/json",...s}})}catch(r){throw il(n,r)}if(!i.ok){const r=await i.text().catch(()=>"");throw new Error(`${n} returned HTTP ${i.status}${r?`: ${r.slice(0,200)}`:""}`)}return i.json()}async function rl(t,e,s,n){let i;try{i=await t(e,{headers:s})}catch(o){throw il(n,o)}if(!i.ok)throw new Error(`${n} returned HTTP ${i.status} for ${e}`);const r=await i.arrayBuffer();return new Uint8Array(r)}function Ju(t){const e=new URL(t).pathname.split("/").filter(Boolean);if(e.length<2)throw new Error(`not a GitHub repository URL: ${t}`);return{owner:e[0],repo:e[1].replace(/\.git$/u,"")}}async function ed({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:i,onProgress:r}){const{owner:o,repo:l}=Ju(t),c="https://api.github.com",u={"x-github-api-version":"2022-11-28",...i?{authorization:`Bearer ${i}`}:{}};let p=e;p||(r("resolving the default branch…"),p=(await Us(n,`${c}/repos/${o}/${l}`,u,"api.github.com"))?.default_branch||"main"),r(`reading the file tree of ${o}/${l}@${p}…`);const d=await Us(n,`${c}/repos/${o}/${l}/git/trees/${encodeURIComponent(p)}?recursive=1`,u,"api.github.com");if(d?.truncated)throw new Error("this repository's file tree is too large for the API listing — point the link at the package folder");const f=Array.isArray(d?.tree)?d.tree:[],h=nl(s),m=Zu(h,"plugin.json");if(!f.some(E=>E.type==="blob"&&E.path===m))throw new Error(`no plugin.json at ${m||"the repository root"} on ${p} — link to the folder that contains the manifest`);const g=h?`${h}/`:"",S=f.filter(E=>E.type==="blob"&&(!g||E.path.startsWith(g))&&!sl(E.path.slice(g.length))),y=[];let v=0,x=0;for(const E of S){x+=1;const w=E.path.slice(g.length);r(`fetching ${x}/${S.length}: ${w}`);const I=i?await td(n,c,o,l,E.sha,u):await rl(n,`https://raw.githubusercontent.com/${o}/${l}/${encodeURIComponent(p)}/${E.path.split("/").map(encodeURIComponent).join("/")}`,{},"raw.githubusercontent.com");if(v+=I.length,v>Gs)throw new Error(`package exceeds the ${Math.round(Gs/1024)} KB upload limit at ${w}`);y.push({path:w,contentBase64:ti(I)})}return y}async function td(t,e,s,n,i,r){const o=await Us(t,`${e}/repos/${s}/${n}/git/blobs/${i}`,r,"api.github.com"),l=String(o?.content||"").replace(/\s+/gu,"");if(o?.encoding&&o.encoding!=="base64")throw new Error(`unexpected blob encoding "${o.encoding}" from api.github.com`);return tl(l)}function sd(t){const e=new URL(t),s=e.pathname.split("/").filter(Boolean),n=s.indexOf("_git");if(n<0||n===s.length-1)throw new Error(`not an Azure DevOps repository URL: ${t}`);const i=decodeURIComponent(s[n+1]),r=s.slice(0,n).map(decodeURIComponent),o=e.hostname.toLowerCase(),l=o.endsWith(".visualstudio.com")?o.split(".")[0]:r[0],c=o.endsWith(".visualstudio.com")?r[0]:r[1];if(!l||!c)throw new Error(`could not read org/project from ${t}`);return{org:l,project:c,repo:i}}async function nd({repoUrl:t,ref:e,path:s},{fetchImpl:n,token:i,tokenKind:r,onProgress:o}){if(!i)throw new Error("Azure DevOps needs a credential — sign-in did not yield a token; paste a PAT with Code (read)");const{org:l,project:c,repo:u}=sd(t),p=`https://dev.azure.com/${encodeURIComponent(l)}/${encodeURIComponent(c)}/_apis/git/repositories/${encodeURIComponent(u)}`,f={authorization:r==="pat"?`Basic ${ti(new TextEncoder().encode(`:${i}`))}`:`Bearer ${i}`},h=nl(s),m=`/${h}`,g=e?`&versionDescriptor.version=${encodeURIComponent(e)}&versionDescriptor.versionType=branch`:"";o(`reading ${u}${h?`/${h}`:""}…`);const S=await Us(n,`${p}/items?scopePath=${encodeURIComponent(m)}&recursionLevel=Full${g}&api-version=7.1`,f,"dev.azure.com"),v=(Array.isArray(S?.value)?S.value:[]).filter(M=>M?.gitObjectType==="blob"&&!M?.isFolder),x=h?`/${h}/`:"/";if(!v.find(M=>M.path===`${x}plugin.json`.replace("//","/")))throw new Error(`no plugin.json under ${m} — link to the folder that contains the manifest`);const w=[];let I=0,b=0;for(const M of v){const A=String(M.path||"").slice(x.length);if(!A||sl(A))continue;b+=1,o(`fetching ${b}/${v.length}: ${A}`);const O=await rl(n,`${p}/blobs/${encodeURIComponent(M.objectId)}?api-version=7.1&$format=octetStream`,{...f,accept:"application/octet-stream"},"dev.azure.com");if(I+=O.length,I>Gs)throw new Error(`package exceeds the ${Math.round(Gs/1024)} KB upload limit at ${A}`);w.push({path:A,contentBase64:ti(O)})}return w}async function id(t,{fetchImpl:e=typeof fetch=="function"?fetch:null,token:s=null,tokenKind:n="bearer",onProgress:i=()=>{}}={}){if(typeof e!="function")throw new Error("no fetch implementation available");const r=el(t);if(r.error)throw new Error(r.error);const o={fetchImpl:e,token:s,tokenKind:n,onProgress:i},l=r.kind==="github"?await ed(r,o):await nd(r,o);if(l.length===0)throw new Error("the package folder is empty");return{kind:r.kind,files:l}}function rd(t=[]){const e=(Array.isArray(t)?t:[]).find(s=>s?.path==="plugin.json");if(!e?.contentBase64)return null;try{const s=tl(e.contentBase64),n=JSON.parse(new TextDecoder().decode(s));return String(n?.name||"").trim()||null}catch{return null}}function Or(t){return t?.isSystem?Da(t):Number.MAX_SAFE_INTEGER}function od(t=[]){const e=new Map;for(let s=0;s<t.length;s+=1){const n=t[s]?.sessionId;!n||e.has(n)||e.set(n,s)}return e}function ad(t=[]){if(t instanceof Map)return new Map(t);if(Array.isArray(t))return od(t);const e=new Map;for(const[s,n]of Object.entries(t||{}))!s||typeof n!="number"||Number.isNaN(n)||e.set(s,n);return e}function ld(t){if(t instanceof Map)return t;const e=new Map;if(!Array.isArray(t))return e;for(let s=0;s<t.length;s+=1){const n=t[s];typeof n!="string"||!n||e.has(n)||e.set(n,s)}return e}function Xt(t){return!!(t&&!t.isSystem&&!t.parentSessionId)}function cd(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function $r(t,e){return!!(cd(t)&&e&&e.has(t.sessionId))}function Fr(t,e){return t.isSystem?0:t.isGroup&&$r(t,e)?1:$r(t,e)?2:t.isGroup?3:4}function Dr(t){const e=t?.updatedAt??t?.summaryUpdatedAt??t?.latestSummaryUpdatedAt,s=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(s)?s:0}function Br(t,e,s,n,i){const r=Fr(t,n),o=Fr(e,n);if(r!==o)return r-o;const l=Or(t),c=Or(e);if(l!==c)return l-c;if(i&&i.size>0&&Xt(t)&&Xt(e)){const y=i.has(t.sessionId)?i.get(t.sessionId):1/0,v=i.has(e.sessionId)?i.get(e.sessionId):1/0;if(y!==v)return y-v}const u=s.get(t.sessionId),p=s.get(e.sessionId);if(typeof u=="number"&&typeof p=="number"&&u!==p)return u-p;const d=Dr(t),f=Dr(e);if(d>0&&f>0&&d!==f)return d-f;const h=(t.createdAt||0)-(e.createdAt||0);if(h!==0)return h;const m=String(t.title||""),g=String(e.title||""),S=m.localeCompare(g);return S!==0?S:String(t.sessionId||"").localeCompare(String(e.sessionId||""))}function Ze(t=[],e=new Set,s=[],n=null,i=null){const r=new Map,o=new Map,l=ad(s),c=ld(i),u=n instanceof Set?n:new Set(Array.isArray(n)?n:[]);for(const g of t)r.set(g.sessionId,g);const p=[];for(const g of t){if(g.isGroup||!g.groupId||g.parentSessionId)continue;const S=`group:${g.groupId}`;if(r.has(S))continue;const y={sessionId:S,groupId:g.groupId,isGroup:!0,title:"Group",status:"group",shortSummary:"reconnecting…",createdAt:0,updatedAt:0};r.set(S,y),p.push(y)}const d=new Set(p.map(g=>g.sessionId));p.length>0&&(t=[...t,...p]);for(const g of t){const S=!g.isGroup&&g.groupId&&!g.parentSessionId&&r.has(`group:${g.groupId}`)?`group:${g.groupId}`:null,y=g.parentSessionId||S;!y||!r.has(y)||(o.has(y)||o.set(y,[]),o.get(y).push(g))}for(const g of o.values())g.sort((S,y)=>Br(S,y,l,u,c));const f=t.filter(g=>!(g.parentSessionId||!g.isGroup&&g.groupId)).sort((g,S)=>Br(g,S,l,u,c)),h=[];function m(g,S){const y=o.get(g.sessionId)||[];if(h.push({sessionId:g.sessionId,depth:S,hasChildren:y.length>0,collapsed:e.has(g.sessionId),...d.has(g.sessionId)?{standIn:g}:{}}),!e.has(g.sessionId))for(const v of y)m(v,S+1)}for(const g of f)m(g,0);return h}const tt="VS Code",ts="Retro",Tt="Others",Hr=Object.freeze([tt,ts,Tt]);function ud(t){return Object.freeze({...t,page:Object.freeze({...t.page||{}}),terminal:Object.freeze({...t.terminal||{}}),tui:Object.freeze({...t.tui||{}})})}function Pn(t){return Number.parseInt(t,16)/255}function dd(t){const e=String(t||"").trim();return/^#[0-9a-f]{3}$/iu.test(e)?`#${e.slice(1).split("").map(s=>s+s).join("")}`:/^#[0-9a-f]{6}$/iu.test(e)?e:null}function Rn(t){return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function pd(t){const e=dd(t);if(!e)return 0;const s=Rn(Pn(e.slice(1,3))),n=Rn(Pn(e.slice(3,5))),i=Rn(Pn(e.slice(5,7)));return .2126*s+.7152*n+.0722*i}function fd(t){const e=t?.page?.background||t?.tui?.background||t?.terminal?.background;return pd(e)>=.5}function xe({id:t,label:e,description:s,group:n=Tt,page:i,terminal:r,tui:o={},icon:l=null}){const c={background:i?.background||r?.background||"#000000",surface:r?.background||i?.background||"#000000",foreground:r?.foreground||i?.foreground||"#ffffff",white:r?.foreground||i?.foreground||"#ffffff",gray:i?.hintColor||r?.brightBlack||r?.white||"#999999",black:r?.black||"#000000",red:r?.red||"#ff5555",green:r?.green||"#55ff55",yellow:r?.yellow||"#ffff55",blue:r?.blue||"#5555ff",magenta:r?.magenta||"#ff55ff",cyan:r?.cyan||"#55ffff",userChat:"#ffd866",userChatLabel:"#ffec99",otherUserChatLabel:r?.brightMagenta||r?.magenta||"#c9a3ff",activeHighlightBackground:r?.blue||"#5555ff",activeHighlightForeground:r?.background||"#000000",selectionBackground:r?.cursor||r?.blue||"#5555ff",selectionForeground:r?.cursorAccent||r?.background||"#000000",promptCursorBackground:r?.cursor||r?.green||"#55ff55",promptCursorForeground:r?.cursorAccent||r?.background||"#000000"};return ud({id:t,label:e,description:s,group:n,icon:l||null,page:i,terminal:r,tui:{...c,...o}})}const hd=xe({id:"github-dark",label:"GitHub Dark",description:"GitHub dark palette with soft blue accents and cool neutrals.",group:tt,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"}}),md=xe({id:"github-light",label:"GitHub Light",description:"GitHub light palette with crisp neutrals, blue actions, and high-contrast status colors.",group:tt,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"}}),ol=xe({id:"workspace-dark",label:"Workspace Dark",description:"Flat workspace chrome: tone surfaces and hairlines instead of panel borders.",group:Tt,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"}}),gd=xe({id:"cobalt2",label:"Cobalt2",description:"Electric blue shell with bright yellow accents and saturated syntax colors.",group:tt,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"}}),yd=xe({id:"dracula",label:"Dracula",description:"Classic Dracula contrast with neon green, pink, and violet accents.",group:tt,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"}}),Sd=xe({id:"catppuccin-mocha",label:"Catppuccin Mocha",description:"Creamy dark palette with soft pastels and high legibility.",group:tt,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"}}),bd=xe({id:"hacker-x-matrix",label:"Hacker X - Matrix",description:"Black-and-phosphor terminal palette with vivid green glow and CRT-style contrast.",group:tt,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"}}),wd=xe({id:"hacker-x-orion-prime",label:"Hacker X - Orion Prime",description:"Deep-space navy palette with electric cyan, violet, and amber accents.",group:tt,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"}}),vd=xe({id:"gruvbox-dark",label:"Gruvbox Dark",description:"Retro warm palette with earthy browns, oranges, and high readability.",group:tt,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"}}),Ed=xe({id:"noctis",label:"Noctis",description:"Dark cyan-tinted palette with warm and cold medium contrast accents.",group:tt,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"}}),xd=xe({id:"noctis-obscuro",label:"Noctis Obscuro",description:"Deep obsidian palette with cool blue accents and restrained contrast for long sessions.",group:tt,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"}}),Id=xe({id:"terminal-green",label:"Terminal Green",description:"Classic black terminal with phosphor green text, amber warnings, and crisp operator contrast.",group:ts,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"}}),kd=xe({id:"high-contrast-mono",label:"High Contrast Mono",description:"Accessibility-first monochrome theme with cobalt selection and severity colors only where they matter.",group:Tt,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"}}),Ad=xe({id:"win95",label:"Windows 95",description:"Authentic 3D-bevelled grey, navy title bars, teal desktop, and the 16-colour VGA terminal set.",group:ts,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"}}),Cd=xe({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:ts,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"}}),Td=xe({id:"doom",label:"DOOM",description:"STBAR brown metal, bone type, and the three keycards as the status palette.",group:ts,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"}}),Nd=xe({id:"winamp",label:"WinAMP",description:"Bevelled grey chrome, black glass panes, phosphor green, and the spectrum ramp as the status palette.",group:ts,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"}}),Md=xe({id:"rust",label:"Rust",description:"Graphite and iron oxide, Ferris in the corner, and rustc's diagnostic levels as the status palette.",group:Tt,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"}}),Pd="#a35838",Rd="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",_d=xe({id:"duroxide",label:"Duroxide",description:"Iron oxide pressed into black felt - the durable-execution runtime's own mark, traced from the banner.",group:Tt,icon:{viewBox:"0 0 64 64",paths:[{d:Rd,fill:Pd}]},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"}}),Ld=xe({id:"spongebob",label:"SpongeBob",description:"Bikini Bottom at depth, sponge-yellow accents, and the cast as the status palette.",group:Tt,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 Od(t,e){const s=Hr.indexOf(t.group),n=Hr.indexOf(e.group),i=s===-1?Number.MAX_SAFE_INTEGER:s,r=n===-1?Number.MAX_SAFE_INTEGER:n;return i!==r?i-r:t.label.localeCompare(e.label,void 0,{sensitivity:"base"})}const al=Object.freeze([ol,yd,hd,md,gd,wd,bd,Sd,vd,Ed,xd,Id,kd,Ad,Cd,Td,Nd,Md,_d,Ld].sort(Od)),$d=new Map(al.map(t=>[t.id,t])),Fd=ol.id;function Dd(){return al}function rt(t){return t?$d.get(t)??null:null}const Bd=new Set(["agent","user","system"]);function zs(t){const e=Array.isArray(t?.ownerKeys)?[...new Set(t.ownerKeys.map(n=>String(n||"").trim()).filter(Boolean))]:[];return{all:t&&typeof t=="object"?t?.all===!0:!0,includeSystem:t?.includeSystem===!0,includeUnowned:t?.includeUnowned===!0,includeMe:t?.includeMe===!0,includeShared:t?.includeShared===!0,ownerKeys:e}}function Hd(t){if(typeof t=="string"){const i=t.trim();return i?{filename:i,sizeBytes:null,contentType:"",isBinary:!1,uploadedAt:"",source:"agent"}:null}if(!t||typeof t!="object")return null;const e=String(t.filename||"").trim();if(!e)return null;const s=Number(t.sizeBytes),n=typeof t.contentType=="string"?t.contentType:"";return{filename:e,sizeBytes:Number.isFinite(s)&&s>=0?s:null,contentType:n,isBinary:t.isBinary===!0,uploadedAt:typeof t.uploadedAt=="string"?t.uploadedAt:"",source:Bd.has(t.source)?t.source:"agent"}}function Ws(t){const e=Array.isArray(t)?t:[],s=[],n=new Set;for(const i of e){const r=Hd(i);!r||n.has(r.filename)||(n.add(r.filename),s.push(r))}return s}function jd(t,e){const s=String(e||"").trim();return s&&Ws(t).find(n=>n.filename===s)||null}function Mi(t){const e=t&&typeof t=="object"?t:{},s=Number(e.paneAdjust),n=Number(e.sessionPaneAdjust),i=Number(e.portalSessionColumnAdjust),r=Number(e.activityPaneAdjust),o=Number(e.canvasPaneAdjust),l=Number(e.diagnosticsPaneAdjust),c=Number(e.diagnosticsSplitAdjust);return{paneAdjust:Number.isFinite(s)?Math.trunc(s):0,sessionPaneAdjust:Number.isFinite(n)?Math.trunc(n):0,portalSessionColumnAdjust:Number.isFinite(i)?Math.trunc(i):0,activityPaneAdjust:Number.isFinite(r)?Math.trunc(r):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 qs(t){if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();!i||e.has(i)||(e.add(i),s.push(i))}return s}function Pi(t){if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();!i||e.has(i)||(e.add(i),s.push(i))}return s}function si(t){if(!Array.isArray(t))return new Set;const e=new Set;for(const s of t){const n=String(s||"").trim();n&&e.add(n)}return e}function Gd(t){return t==="canvas"?"canvas":"panes"}function ll(t,e){const s=t&&typeof t=="object"?t:null;return s&&(typeof s.canvasOpen=="boolean"||typeof s.diagnosticsOpen=="boolean")?{canvasOpen:s.canvasOpen===!0,diagnosticsOpen:s.diagnosticsOpen===!0,zen:s.zen===!0&&s.canvasOpen===!0}:{canvasOpen:e==="canvas",diagnosticsOpen:!1,zen:!1}}function qe(t,e){const s=String(t||""),n=Number(e);return Number.isInteger(n)&&n>=2&&n<=5?`${s}#${n}`:s}function Ud(t){const e=/^(.*)#([2-5])$/.exec(String(t||""));return e?{sessionId:e[1],slot:Number(e[2])}:{sessionId:String(t||""),slot:1}}function Ri(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[s,n]of Object.entries(t)){const i=String(s||"").trim();if(!i||!n||typeof n!="object")continue;const r=Number(n.lastViewedRev),o=Number(n.lastViewedDataRev),l=Number(n.zenRailPx);e[i]={optedOut:n.optedOut===!0,lastViewedRev:Number.isFinite(r)&&r>0?Math.floor(r):0,lastViewedDataRev:Number.isFinite(o)&&o>0?Math.floor(o):0,...Number.isFinite(l)&&l>0?{zenRailPx:Math.floor(l)}:{}}}return e}function cl(t){if(t==null)return null;const e=String(t).trim();return e||null}function ni({mode:t="local",branding:e=null,docs:s=null,themeId:n=null,sessionOwnerFilter:i=null,layoutAdjustments:r=null,pinnedSessionIds:o=null,collapsedSessionIds:l=null,activeSessionId:c=null,sessionOrder:u=null,rightPaneMode:p=null,desktopPanes:d=null,canvasPrefs:f=null}={}){const h=ll(d,Gd(p)),m=i!=null,g=l!=null,S=Mi(r);return{branding:e||{title:"PilotSwarm",splash:"{bold}{cyan-fg}PilotSwarm{/cyan-fg}{/bold}"},docs:{agentPackageGuideUrl:s?.agentPackageGuideUrl||"https://github.com/affandar/PilotSwarm/blob/main/docs/building-agent-packages.md"},auth:{principal:null,authorization:null},ui:{focusRegion:N.SESSIONS,inspectorTab:et[0],nodeMapSelectedNode:null,sequenceExpandedTurns:[],sequenceSelectedTurn:null,rightPaneMode:h.canvasOpen?"canvas":"panes",canvasOpen:h.canvasOpen,diagnosticsOpen:h.diagnosticsOpen,canvasZen:h.zen,canvasMaximized:!1,statsViewMode:"session",prompt:"",promptCursor:0,promptRows:1,promptAttachments:[],promptEdit:null,statusText:"Starting PilotSwarm...",themeId:rt(n)?.id||Fd,touchScale:!1,modal:null,fullscreenPane:null,layout:{...S,viewportWidth:120,viewportHeight:40},scroll:{chat:0,inspector:0,activity:0,filePreview:0},chatScrollBySession:{},followBottom:{inspector:!0,activity:!0}},connection:{mode:t,connected:!1,workersOnline:null,error:null},sessions:{byId:{},groupRows:[],flat:[],activeSessionId:cl(c),collapsedIds:si(l),collapsedIdsExplicit:g,pinnedIds:qs(o),manualOrder:Pi(u),listingSeen:!1,groupsListingSeen:!1,selectedIds:[],selectMode:!1,listDeselected:!1,orderById:{},nextOrderOrdinal:0,filterQuery:"",ownerFilterExplicit:m,ownerFilter:zs(i),navigationIntent:null,filterExceptionId:null},history:{bySessionId:new Map},outbox:{bySessionId:{}},orchestration:{bySessionId:{}},executionHistory:{bySessionId:{},format:"pretty"},files:{bySessionId:{},fullscreen:!1,selectedArtifactId:null,markedIds:[],previewOrigin:null,restoreArtifactId:null,paneOpen:!1,paneRestoresToHidden:!1,htmlViewMode:"rendered",htmlZoom:1,htmlFitWidth:!1,filter:{scope:"selectedSession",query:""}},canvas:{bySessionId:{},prefs:Ri(f),flipSeq:0},logs:{available:!1,availabilityReason:"Log tailing disabled: no K8S_CONTEXT configured in the env file.",tailing:!1,entries:[],filter:{source:"allNodes",level:"all",format:"pretty"}},sessionStats:{bySessionId:{}},fleetStats:{loading:!1,data:null,userStats:null,fetchedAt:0},admin:{visible:!1,loading:!1,loadError:null,profile:null,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:0,storeAsSystem:!1},systemGhcpKey:{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null},section:"ghcp",packages:{loading:!1,error:null,list:[],workerState:[],fetchedAt:0,selectedName:null,detail:null,detailLoading:!1,detailError:null,changelog:null,workspace:{tree:null,treeLoading:!1,treeError:null,expandedDirs:[],selectedPath:null,file:null,fileLoading:!1,fileError:null},action:{pending:null,error:null},addDialog:{open:!1,kind:"repo",scope:"user",updateName:null,repoUrl:"",ref:"",path:"",url:"",authToken:"",submitting:!1,progress:null,error:null}},workers:{loading:!1,error:null,list:[],fetchedAt:0,attempts:0,lastAttemptAt:0,lastSkip:null}}}}function ul(t){const e=String(t||"");return/\bConnection is closed\b/i.test(e)||/\bLive Copilot connection lost\b/i.test(e)}function zd(t,e){return!(!ul(t?.error)||e?.error!==void 0||String(e?.status||"")!=="running"||["Completed","Failed","Terminated"].includes(String(e?.orchestrationStatus||"")))}const dl="activeHighlightBackground",_i="activeHighlightForeground",_n="userChat",Wd="userChatLabel",qd="otherUserChatLabel",jr=new WeakMap,Gr=new WeakMap;function Kd(t){return t||_i}function pl(t,{preserveColors:e=!1}={}){return(t||[]).map(s=>({...s,color:e?Kd(s?.color):_i,backgroundColor:dl,bold:s?.bold??!0}))}function st(t,{color:e=_i,bold:s=!0}={}){return{text:t,color:e,backgroundColor:dl,bold:s}}function Je(t,e){return[{text:String(t||""),color:e,bold:!0}]}const Vd=72;function fl(t){const e=Number(t)||0;return e>0&&e<=Vd}function hl(t){if(!t)return"unknown";const e=t.status||"unknown",s=e==="waiting"||e==="idle"||e==="unknown";return t.cronActive===!0&&s?"cron_waiting":s&&(Number(t.activeChildCount)||0)>0?"awaiting_children":e}function Yd(t,e){if(e==="cron_waiting")return"waiting";if(e==="awaiting_children"){const s=Number(t?.activeChildCount)||0;return s>0?`waiting on ${s}`:"waiting on children"}return e}function Xd(t){if(!t)return null;const e=t.updatedAt||t.summaryUpdatedAt||t.latestSummaryUpdatedAt||t.createdAt||0;return{status:ml(t)||"unknown",timestampMs:e||null,relative:e?Zi(e):"—"}}function ml(t){const e=gl(t);return!e||e==="unknown"?"":Yd(t,e)}function gl(t){return t?.rowVisualStatus||hl(t)}function yl(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function Li(t){const e=hl(t);return t?.orchestrationStatus==="Failed"||e==="failed"?"failed":e==="error"||e==="running"&&ul(t?.error)&&!yl(t?.orchestrationStatus)?"warning":null}function Sl(t,e="local"){const s=Li(t);if(s)return s;const n=gl(t);if(e==="remote"&&yl(t?.orchestrationStatus)&&n!=="cron_waiting"&&n!=="awaiting_children"&&n!=="waiting"&&n!=="input_required"){if(t?.orchestrationStatus==="Completed")return"completed";if(t?.orchestrationStatus==="Terminated")return"terminated"}return n==="terminated"?"terminated":n}function qt(t,e="local"){switch(Sl(t,e)){case"running":return"green";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 bl(t,e="local"){switch(Sl(t,e)){case"running":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 we(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function cn(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const Oi=we({provider:"system",subject:"system"});function Ur(t){const e=String(t||"").trim();if(!e)return"";const s=e.replace(/@.*/u,"").split(/[^A-Za-z0-9]+/u).map(i=>i.trim()).filter(Boolean);return s.length>=2?`${s[0][0]}${s[1][0]}`.toUpperCase():(s[0]||e).replace(/[^A-Za-z0-9]/gu,"").slice(0,2).toUpperCase()}function ii(t){return Ur(t?.displayName)||Ur(t?.email)||"?"}function Qd(t,e=!1){return Xt(t)?e?t.isGroup?"pinned:folders":"pinned:sessions":t.isGroup?"folders":t.groupId?`g:${t.groupId}`:"":null}function wl(t,{isMine:e=!1}={}){if(!t)return null;const s=cn(t,t?.email||"");return{initials:ii(t),hue:tp(sp(t,t?.email)),name:s||"unknown user",isMine:!!e}}function Zd(t){const e=new Map;for(const s of Object.values(t||{})){const n=s?.owner;if(!n?.subject||!n.displayName&&!n.email)continue;const i=we(n);i&&!e.has(i)&&e.set(i,n)}return e}function Jd(t,e){if(t?.owner?.displayName||t?.owner?.email)return t.owner;const s=e?.get?.(we(t?.owner))||null;return s||(t?.createdBy?{email:t.createdBy}:null)}const ep=8;function tp(t){const e=String(t||"").trim().toLowerCase();if(!e)return 0;let s=2166136261;for(let n=0;n<e.length;n+=1)s^=e.charCodeAt(n),s=Math.imul(s,16777619)>>>0;return s%ep}function sp(t,e){return String(e||t?.email||t?.displayName||(t?.provider&&t?.subject?`${t.provider}:${t.subject}`:"")||"").trim().toLowerCase()}function np(t,e=1/0){const s=t?.sessions?.byId,n=t?.sessions?.ownerFilter||{all:!0},i=t?.auth||{},r=new Set;for(const o of Object.values(s||{})){if(!o||o.isSystem||o.isGroup)continue;const l=we(o.owner);if(!(!l||l===Oi)&&oi(o,n,i)&&(r.add(l),r.size>=e))break}return r.size}function ri(t){return np(t,2)>1}function vl(t,e={}){return!t?.isGroup||!t?.groupId?[]:Object.values(e||{}).filter(s=>s&&!s.isGroup&&!s.parentSessionId&&s.groupId===t.groupId)}function $t(t,e={}){if(!t?.isGroup)return t?.owner??null;if(t.owner)return t.owner;const s=new Map;for(const n of vl(t,e)){const i=we(n?.owner);i&&!s.has(i)&&s.set(i,n.owner)}return s.size===1?s.values().next().value:null}function zr(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Wr(t,e){const s=zr(t),n=zr(e?.agentId);return!!(s&&n&&s===n)}function ip(t){if(!t?.agentId||t?.isSystem)return null;const e=String(t?.title||"").trim();if(!e)return null;const s=" · ",n=e.lastIndexOf(s);if(n>0){const o=e.slice(0,n).trim(),l=e.slice(n+s.length).trim();if(o&&Wr(l,t))return{displayTitle:o,agentTitle:l}}const i=/^(.+?)\s+[–—-]\s+(.+)$/u.exec(e);if(i){const o=i[1].trim(),l=i[2].trim();if(o&&l)return{displayTitle:l,agentTitle:o}}const r=e.indexOf(": ");if(r>0){const o=e.slice(0,r).trim(),l=e.slice(r+2).trim();if(l&&Wr(o,t))return{displayTitle:l,agentTitle:o}}return null}function rp(t){const e=String(t||""),s=e.indexOf(": ");if(s<=0)return null;const n=e.slice(0,s).trim(),i=e.slice(s+2).trim();return!n||!i?null:{userTitle:i,typeTitle:n}}const op=[[/&lt;/g,"<"],[/&gt;/g,">"],[/&quot;/g,'"'],[/&#0?39;/g,"'"],[/&apos;/g,"'"],[/&nbsp;/g," "],[/&amp;/g,"&"]];function ap(t){let e=String(t??"");if(!e.includes("&"))return e;for(const[s,n]of op)e=e.replace(s,n);return e}function $i(t){return ap(lp(t))}function lp(t){const e=String(t?.title||"").trim(),s=ip(t);if(!s)return e;const n=rp(s.displayTitle);return n?`${n.userTitle} · ${n.typeTitle} · ${s.agentTitle}`:`${s.displayTitle} · ${s.agentTitle}`}function El(t,e){const s=ge(t?.sessionId);if(t?.isSystem)return`${Jt(t,e)} (${s})`;const n=$i(t);return n?n.includes(s)?n:`${n} (${s})`:`(${s})`}function oi(t,e={},s={},n=void 0){if(!e||e.all===!0||t?.isGroup)return!0;if(t?.isSystem)return e.includeSystem===!0;const i=we(n!==void 0?n:t?.owner);if(!i)return e.includeUnowned===!0;if(i===Oi)return e.includeSystem===!0;const r=we(s?.principal);return e.includeMe&&r&&i===r||e.includeShared===!0&&i!==r?!0:Array.isArray(e.ownerKeys)&&e.ownerKeys.includes(i)}function xl(t,e={},s={},n=null){const i=$t(t,n||{});if(oi(t,e,s,i))return!0;if(!n)return!1;if(t?.isGroup)return vl(t,n).some(l=>xl(l,e,s,n));let r=t,o=0;for(;r?.parentSessionId&&o<16;){const l=n[r.parentSessionId];if(!l)return!1;if(oi(l,e,s))return!0;r=l,o+=1}return!1}function cp(t){return(t||[]).map(e=>e?.text||"").join("")}function Fi(t){const e=new Map,s=new Map;for(const n of Object.values(t||{})){const i=n?.parentSessionId;i&&(s.set(n.sessionId,i),e.has(i)||e.set(i,[]),e.get(i).push(n.sessionId))}return{childMap:e,parentMap:s}}function qr(t){const{childMap:e}=Fi(t),s=new Map,n=new Set;function i(r){if(s.has(r))return s.get(r);if(n.has(r))return 0;n.add(r);const l=(e.get(r)||[]).reduce((c,u)=>c+1+i(u),0);return n.delete(r),s.set(r,l),l}for(const r of Object.keys(t||{}))i(r);return s}function Kr(t=[],e={}){const{parentMap:s}=Fi(e),n=new Map;for(const i of t){let r=s.get(i.sessionId);for(;r;)n.set(r,(n.get(r)||0)+1),r=s.get(r)}return n}function Di(t={}){if(!t||typeof t!="object")return qr(t);const e=jr.get(t);if(e)return e;const s=qr(t);return jr.set(t,s),s}function Bi(t=[],e={}){if(!Array.isArray(t))return Kr(t,e);const s=Gr.get(t);if(s)return s;const n=Kr(t,e);return Gr.set(t,n),n}function Il(t,e,s,n){const i=s.get(t)||0,r=n.get(t)||0,o=Math.max(0,i-r),l=e?.collapsed?i:o;return l?{text:`[+${l}]`,color:"cyan"}:null}function Ks(t){if(!t)return"scheduled";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"scheduled";try{return e.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1,timeZoneName:"short"}).replace(/,\s*/g," ").replace(/\s+/g," ").trim()}catch{return e.toISOString().replace(/\.000Z$/,"Z")}}function up(t){return t?.cronActive===!0&&t?.cronKind==="wall-clock"?{text:`[cron ${Ks(t.cronNextFireAt)}]`,color:"magenta"}:t?.cronActive===!0&&typeof t?.cronInterval=="number"?{text:`[cron ${Dt(t.cronInterval)}]`,color:"magenta"}:null}function kl(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function dp(t,e){const s=[];typeof t?.regenStage=="string"&&t.regenStage&&s.push({text:`↻ regen:${t.regenStage}`,color:"magenta"});const n=ml(t);n&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:n,color:qt(t,e)}));const i=qi(t?.model,t?.reasoningEffort);i&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:i,color:"cyan"}));const r=Xc(t?.contextUsage);r&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:r.text,color:r.color}));const o=Qc(t?.contextUsage);return o&&(s.length>0&&s.push({text:" · ",color:"gray"}),s.push({text:o.text,color:o.color})),s}function pp(t,e,s,n,i){const r=[],o=s.connection?.mode||"local",l=t.depth>0?`${" ".repeat(Math.max(0,t.depth-1))}└ `:"";l&&r.push({text:l,color:"gray",role:"depth"});const c=new Set(Array.isArray(s.sessions?.pinnedIds)?s.sessions.pinnedIds:[]),u=new Set(Array.isArray(s.sessions?.selectedIds)?s.sessions.selectedIds:[]),p=!!s.sessions?.selectMode,d=u.has(t.sessionId),f=c.has(t.sessionId);if(d&&r.push({text:"▌",color:"cyan",bold:!0,role:"selection"}),t.depth===0&&kl(e)&&c.size>0&&(f&&!e?.isSystem?r.push({text:"📌 ",color:"yellow"}):r.push({text:" ",color:"gray"})),e?.isGroup)r.push({text:"🗂 ",color:"cyan",bold:!0});else if(e?.isSystem)r.push({text:"⚙ ",color:"yellow",bold:!0});else if(e?.serviceKind)r.push({text:"⚗ ",color:"magenta",bold:!0});else{const H=bl(e,o);r.push({text:H?`${H} `:" ",color:qt(e,o),role:"status"})}const h=e?.isGroup?"cyan":e?.isSystem?"yellow":qt(e,o),m=$t(e,s.sessions?.byId||{}),g=ge(e?.sessionId),S=e?.updatedAt||e?.summaryUpdatedAt||e?.latestSummaryUpdatedAt||e?.createdAt||0,y=S?ih(S):"",v=qi(e?.model,e?.reasoningEffort),x=e?.isSystem?Jt(e,s.branding?.title||"PilotSwarm"):$i(e),E=!!(e?.isSystem||e?.isGroup||x&&x.trim()),w=[...r];if(ri(s)&&!e?.isSystem&&!e?.isGroup){const H=we(s?.auth?.principal),U=!!(H&&we(m)===H),re=m?ii(m):"?";w.push({text:`[${re}] `,color:U?"green":"cyan",bold:!0,ownerChip:!0})}E?w.push({text:x,color:h,bold:!!(e?.isSystem||e?.isGroup)}):(w.push({text:g,color:h}),y&&(w.push({text:" · ",color:"gray"}),w.push({text:y,color:"gray"})),v&&(w.push({text:" · ",color:"gray"}),w.push({text:v,color:"green"})));const I=Il(e?.sessionId,t,n,i);I&&w.push({text:` ${I.text}`,color:I.color,bold:I.bold});const b=up(e);b&&w.push({text:" ⏱",color:"magenta"});const M=[],A=e?.contextUsage?.compaction?.state,O=Ei(e?.contextUsage);e?.isGroup?e?.memberCount!=null&&M.push({text:`${e.memberCount}`,color:"gray"}):A==="running"?M.push({text:"⇊",color:"magenta"}):A==="failed"?M.push({text:"!",color:"red"}):O!=null?M.push({text:`${O}%`,color:O>=85?"red":O>=70?"yellow":"green"}):M.push({text:"—",color:"gray"});const F=[];e?.isGroup&&e?.memberCount!=null&&(F.push({text:`${e.memberCount} member${e.memberCount===1?"":"s"}`,color:"gray"}),y&&(F.push({text:" · ",color:"gray"}),F.push({text:y,color:"gray"})));const L=[],G=()=>{L.length&&L.push({text:" · ",color:"gray"})};if(e?.isGroup)L.push(...F);else{E&&(L.push({text:g,color:"cyan"}),y&&(G(),L.push({text:y,color:"gray"})),v&&(G(),L.push({text:v,color:"green"})));const H=e?.contextUsage;H&&Number.isFinite(H.currentTokens)&&Number.isFinite(H.tokenLimit)&&H.tokenLimit>0&&(G(),L.push({text:`ctx ${ee(H.currentTokens)}/${ee(H.tokenLimit)}`,color:"gray"}));const U=n?.[e?.sessionId];U&&(G(),L.push({text:`${U} child${U===1?"":"ren"}`,color:"gray"})),b&&(G(),L.push({text:b.text,color:b.color})),(e?.visibility==="shared_read"||e?.visibility==="shared_write")&&(G(),L.push({text:e.visibility==="shared_write"?"shared·write":"shared·read",color:"magenta"}))}return{runs:[...w,...E&&y&&!e?.isGroup?[{text:" ",color:"gray"},{text:y,color:"gray"}]:[],...M.length&&!e?.isGroup?[{text:" · ",color:"gray"},...M]:[],...e?.isGroup&&F.length?[{text:" ",color:"gray"},...F]:[]],titleRuns:w,ctxRuns:M,metaRuns:F,badgeRuns:[],selectedMetaRuns:L,detailRuns:L,childCount:n?.get?.(e?.sessionId)||0,chrome:{kind:e?.isGroup?"group":e?.isSystem?"system":e?.serviceKind?"service":"session",title:E?x:g,untitled:!E,statusColor:qt(e,o),accentColor:h,pinned:f,selectMode:p,checked:d,owner:ri(s)&&!e?.isSystem&&!e?.isGroup?{initials:m?ii(m):"?",isMine:!!(we(s?.auth?.principal)&&we(m)===we(s?.auth?.principal))}:null,childBadge:I?{text:I.text,color:I.color}:null,cron:!!b,age:y||null,model:v||null,shortId:g,ctx:M.length>0?{text:M[0].text,color:M[0].color}:null}}}function Al(t){return String(t||"").trim().toLowerCase()}function xt(t,e){const s=Al(e);return s?String(t||"").toLowerCase().includes(s):!0}function fp(t){const e=t?.filterExceptionId||null,s=t?.byId||{};if(!e||!s[e])return null;const n=new Set([e]);let i=s[e],r=0;for(;i&&r<16;){let o=null;if(i.parentSessionId&&s[i.parentSessionId]?o=i.parentSessionId:!i.isGroup&&i.groupId&&s[`group:${i.groupId}`]&&(o=`group:${i.groupId}`),!o||n.has(o))break;n.add(o),i=s[o],r+=1}return n}const Vr=new WeakMap;function hp(t,e){if(!t||t.length!==e.length)return!1;for(let s=0;s<t.length;s+=1)if(t[s]!==e[s])return!1;return!0}function Qt(t){const e=Di(t.sessions.byId),s=Bi(t.sessions.flat,t.sessions.byId),n=Al(t.sessions?.filterQuery||""),i=t.sessions?.ownerFilter||{all:!0},r=t.auth||{},o=new Set(Array.isArray(t.sessions?.pinnedIds)?t.sessions.pinnedIds:[]),l=new Set(Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds:[]),c=fp(t.sessions);let u=Vr.get(t.sessions.flat);return u||(u=new Map,Vr.set(t.sessions.flat,u)),t.sessions.flat.filter(p=>!!(t.sessions.byId[p.sessionId]||p.standIn)).map(p=>{const d=t.sessions.byId[p.sessionId]||p.standIn,f=p.sessionId===t.sessions.activeSessionId&&!t.sessions.listDeselected,h=o.has(p.sessionId),m=l.has(p.sessionId),g=[p,d,f,h,m,n,i,r,t.connection?.mode,t.sessions.selectMode,e,s,t.branding?.title,t.canvas?.bySessionId?.[p.sessionId],t.canvas?.prefs?.[p.sessionId]],S=u.get(p.sessionId);if(S&&hp(S.deps,g))return S.row;const y=pp(p,d,t,e,s),v={sessionId:p.sessionId,text:cp(y.runs),...y,depth:p.depth,status:d?.status,statusColor:qt(d,t.connection?.mode||"local"),active:f,groupId:d?.groupId||p?.groupId||null,isSystem:!!d?.isSystem,isGroup:!!d?.isGroup,hasChildren:p.hasChildren,collapsed:p.collapsed,pinned:h,selected:m,canPin:kl(d),ownerBadge:ri(t)&&!d?.isSystem&&!d?.isGroup&&$t(d,t.sessions.byId)?wl($t(d,t.sessions.byId),{isMine:!!(we(t?.auth?.principal)&&we($t(d,t.sessions.byId))===we(t?.auth?.principal))}):null,orderable:Xt(d),orderContainer:Qd(d,h),canvasMark:Wp(t,p.sessionId)};return u.set(p.sessionId,{deps:g,row:v}),v}).filter(p=>{if(c?.has(p.sessionId))return!0;const d=t.sessions.byId[p.sessionId];if(!xl(d,i,r,t.sessions.byId))return!1;const f=$t(d,t.sessions.byId),h=f?`${cn(f,"")} ${f.email||""}`:"";return xt(p.text,n)||xt(p.sessionId,n)||xt(h,n)||xt("",n)})}function ai(t,e=8){const s=Qt(t);if(s.length===0)return[];const n=new Set(s.map(d=>d.sessionId)),i=(Array.isArray(t.sessions?.flat)?t.sessions.flat:[]).filter(d=>n.has(d.sessionId)),r=i.findIndex(d=>d.sessionId===t.sessions.activeSessionId),o=Math.max(0,r);if(i.length<=e)return s;const l=Math.floor(e/2);let c=Math.max(0,o-l),u=Math.min(i.length,c+e);u>i.length&&(u=i.length,c=Math.max(0,u-e));const p=i.slice(c,u);return Di(t.sessions.byId),Bi(i,t.sessions.byId),s.filter(d=>p.some(f=>f.sessionId===d.sessionId))}function Ve(t){const e=t.sessions.activeSessionId;return e&&t.sessions.byId[e]||null}function mp(t){const e=t.sessions?.navigationIntent;if(!e||e.status!=="failed")return null;const s=e.errorKind==="not_found"?"not_found":"network";return{sessionId:e.sessionId,errorKind:s,retryable:s==="network",message:s==="not_found"?"This session was not found or has not been shared with you.":"Could not load the linked session. Check your connection and try again."}}function jS(t){const e=t.sessions?.filterExceptionId||null;return!e||!t.sessions?.byId?.[e]?null:"Showing linked session outside your current filters."}function Cl(t){return!t||t.isGroup?!1:(t.status||"")==="running"}function gp(t){const e=t?.pendingQuestion;if(!e?.question)return null;const s=[String(e.question).trim()],n=Array.isArray(e.choices)?e.choices.filter(i=>typeof i=="string"&&i.trim()):[];if(n.length>0){s.push("","Choices:");for(const i of n)s.push(`- ${i}`)}return n.length>0&&e.allowFreeform===!1?s.push("","Reply with one of the choices above in the prompt below."):n.length>0?s.push("","Reply with one of the choices above, or type a free-form answer below."):s.push("","Type your answer in the prompt below and press Enter."),{id:`pending-question:${t.sessionId}:${e.question}`,role:"system",text:s.join(`
26
+ `),time:"",createdAt:t.updatedAt||Date.now(),cardTitle:"Question",cardTitleColor:"cyan",cardBorderColor:"cyan"}}function yp(t,e=[]){const s=t?.answeredPendingQuestion,n=String(s?.question||"").trim(),i=String(s?.answer||"").trim();if(!n||!i||Tl(e,n))return null;const r=s.pendingPhase==="queued"?"queued":"pending",o=Number(s.answeredAt||0)||t.updatedAt||Date.now();return{id:`answered-question:${t.sessionId}:${n}:${o}`,role:"user",text:`The user was asked: "${n}"
27
+ The user responded: "${i}"`,time:"",createdAt:o,optimistic:!0,pendingPhase:r}}function Sp(t,e){if(!t||!e?.id)return null;const s=String(e.text||"").trim();return s?{id:`pending-outbox:${t}:${e.id}`,role:"user",text:s,time:"",createdAt:Number(e.createdAt)||Date.now(),pendingPhase:e.phase==="cancelling"?"cancelling":e.phase==="rejected"?"rejected":e.phase==="queued"?"queued":"pending"}:null}function Tl(t,e){const s=String(e||"").trim();return s?(t||[]).some(n=>Ci(n?.text||"")?.question?.trim()===s):!1}function bp(t){const e=String(t?.error||"").trim();if(!e)return null;const s=Li(t);if(!s)return null;const n=s==="failed",i=n?e:`${e}
28
+
29
+ The orchestration is still running, so this may be transient.`;return{id:`session-error:${t.sessionId}:${s}:${e}`,role:"system",text:i,time:"",createdAt:t.updatedAt||Date.now(),cardTitle:n?"Error":"Warning",cardTitleColor:n?"red":"yellow",cardBorderColor:n?"red":"yellow"}}function Yr(t=[],e){for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n?.eventType===e)return Number(n?.seq||0)}return 0}function wp(t){const e=String(t||"").replace(/\s+/g," ").trim();return e?e.replace(/^\[[^\]]+\]\s*/,"").replace(/^\[[^\]]+\]\s*/,"").trim():""}function vp(t,e=0){const s=Array.isArray(t?.activity)?t.activity:[],n=new Set(["assistant.reasoning","assistant.turn_start","session.turn_started","session.turn_completed"]);for(let i=s.length-1;i>=0;i-=1){const r=s[i];if(!r||n.has(r.eventType)||Number(r?.seq||0)<=e)continue;const o=wp(r.text);if(o)return{...r,summaryText:o}}return null}function Ep(t,e,s=[],n=[]){if(!t||t?.pendingQuestion?.question)return null;const i=String(t?.status||"").toLowerCase();if(i==="completed"||i==="failed"||i==="cancelled")return null;const r=(s||[]).filter(w=>w?.role==="user"||w?.role==="assistant"),o=r[r.length-1]||null,l=o?.role==="user",c=l&&o?.optimistic===!0,u=(n||[]).filter(w=>w?.phase==="pending").length,p=(n||[]).filter(w=>w?.phase==="queued").length,d=(n||[]).filter(w=>w?.phase==="cancelling").length,f=Array.isArray(e?.events)?e.events:[],h=Yr(f,"user.message"),m=Yr(f,"assistant.message"),g=h>m;if(i==="waiting"||i==="input_required"||!l&&!g&&i!=="running"&&!c)return null;const S=Math.max(h,m),y=f.filter(w=>w?.eventType==="assistant.reasoning"&&Number(w?.seq||0)>S),v=y[y.length-1]||null,x=String(v?.data?.content||v?.data?.text||v?.data?.message||"").trim();if(x)return{kind:"thinking",label:"Thinking",text:x,createdAt:v?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:v?.seq||0};const E=vp(e,S);return E?.summaryText?{kind:i==="running"?"working":"sending",label:i==="running"?"Working":"Sending",text:E.summaryText,createdAt:E.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:E.seq||0}:u>0?{kind:"pending",label:u===1?"Pending":`Pending ${u}`,text:u===1?"One prompt is waiting to be sent.":`${u} prompts are waiting to be sent.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:p>0?{kind:"queued",label:p===1?"Queued":`Queued ${p}`,text:p===1?"One prompt is durably queued, waiting for the LLM to receive it.":`${p} prompts are durably queued, waiting for the LLM to receive them.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:d>0?{kind:"cancelling",label:d===1?"Cancelling":`Cancelling ${d}`,text:d===1?"One queued prompt is waiting for cancellation confirmation.":`${d} queued prompts are waiting for cancellation confirmation.`,createdAt:n[n.length-1]?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:c?{kind:"sending",label:"Sending",text:"Working on it...",createdAt:o?.createdAt||t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:i==="running"?{kind:"working",label:"Working",text:"Working on it...",createdAt:t.updatedAt||Date.now(),lastUserSeq:h,lastAssistantSeq:m,tokenSeq:0}:null}function Hi(t){const e=t.sessions.activeSessionId,s=e&&t.sessions.byId[e]||null;if(!e)return In(t.branding);if(s?.isGroup){const u=Object.values(t.sessions.byId||{}).filter(h=>h&&!h.isGroup&&h.groupId===s.groupId&&!h.parentSessionId),p=h=>String(h??"").replace(/\|/g,"\\|").replace(/[\r\n]+/g," ").trim()||" ",d=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",...d.length>0?["| Session | Status |","|---|---|",...d]:["_No top-level members._"]];return[{id:`group-details:${s.sessionId}`,role:"system",noChrome:!0,text:f.filter((h,m)=>m===1||String(h||"").length>0).join(`
30
+ `),createdAt:s.updatedAt||Date.now()}]}const n=t.history.bySessionId.get(e),i=n?.chat||[],r=s?.pendingQuestion?.question&&!Tl(i,s.pendingQuestion.question)?gp(s):null,o=yp(s,i),l=bp(s);if((!n||i.length===0)&&!r&&!o&&!l)return In(t.branding,s);const c=i.length>0?[...i]:In(t.branding,s);return r&&c.push(r),o&&c.push(o),l&&c.push(l),c}function Ln(t,e="gray",s={}){return[{text:t,color:e,bold:!!s.bold,underline:!!s.underline}]}function xp(t,e={}){const s=Le(t?.createdAt||t?.time),n=t?.sender,i=n?.kind==="user"?we(n):null,r=e?.viewerKey||null,o=e?.ownerKey||null,l=e?.sharedContext===!0,c=t?.role==="user",p=l&&c&&i&&!(c&&i&&r&&i===r),f=l&&c&&o&&(i&&i===o||!i&&r&&r===o)?" (owner)":"",h=c?(p?n.display||n.subject||"User":"You")+f:t?.role==="assistant"?"Agent":t?.role==="system"?"System":"PilotSwarm";let m=null,g=null;t?.pendingPhase==="pending"?(m="○",g="yellow"):t?.pendingPhase==="queued"?(m="✓",g="cyan"):t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?(m="x",g="red"):t?.role==="user"&&!t?.optimistic&&!t?.pendingPhase&&(t?.stopped?(m="⊘",g="yellow"):t?.redelivered?(m="✓✓↻",g="yellow"):(m="✓✓",g="green"));const S=t?.pendingPhase==="pending"?"yellow":t?.pendingPhase==="queued"?"cyan":t?.pendingPhase==="cancelling"||t?.pendingPhase==="rejected"?"red":p?qd:t?.role==="user"?Wd:t?.role==="assistant"?"green":t?.role==="system"?"yellow":"white";return{time:s,glyph:m,glyphColor:g,roleLabel:h,roleColor:S,fromOtherPerson:p}}function Ip(t,e={}){const{time:s,glyph:n,glyphColor:i,roleLabel:r,roleColor:o}=xp(t,e),l=s?`[${s}] `:"",c=[...Ln(l,"gray")];return n&&c.push(...Ln(`${n} `,i)),c.push(...Ln(`${r}: `,o,{bold:!0})),c}function ht(t){return Array.isArray(t)?(t||[]).map(e=>e?.text||"").join(""):t?.kind==="markdownTable"?"[table]":String(t?.text||"")}function Nl(){return[{text:"",color:null}]}function kp(t){const e=(t||[]).find(n=>ht(n).trim().length>0);if(e?.kind==="markdownTable")return!0;const s=ht(e).trimStart();return/^[┌│└]/.test(s)}function Vs(t){const e=Array.isArray(t)?[...t]:[];for(;e.length>0;){const s=e[0];if(ht(s).trim().length>0)break;e.shift()}return e}function Ap(t){const e=String(t||"").replace(/\r\n/g,`
31
+ `),s=e.trim();if(!s)return null;if(s.startsWith("[SYSTEM:")&&s.endsWith("]"))return{leadingText:"",systemText:s.slice(8,-1).trim()};const n=e.lastIndexOf(`
32
+
33
+ [SYSTEM:`);if(n>=0&&e.trimEnd().endsWith("]")){const i=e.slice(0,n).trimEnd(),r=e.slice(n+2).trim();if(r.startsWith("[SYSTEM:"))return{leadingText:i,systemText:r.slice(8,-1).trim()}}return Cp.test(s)?{leadingText:"",systemText:s}:null}const Cp=/^(?: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 Ml(t){const e=Ap(t);if(e){const o=[];e.leadingText&&o.push({kind:"text",text:e.leadingText});const l=ft(e.systemText);return l&&o.push({kind:"system",text:l}),o}const s=String(t||"").replace(/\r\n/g,`
34
+ `).split(`
35
+ `),n=[];let i=[];function r(){i.length!==0&&(n.push({kind:"text",text:i.join(`
36
+ `)}),i=[])}for(let o=0;o<s.length;){const l=s[o];if(!/^\s*\[SYSTEM:/i.test(l)){i.push(l),o+=1;continue}const c=/^\s*\[SYSTEM:\s*(.*?)\]\s*$/i.exec(l);if(c){r();const f=ft(c[1].trim());if(!f){o+=1;continue}n.push({kind:"system",text:f}),o+=1;continue}const u=[l.replace(/^\s*\[SYSTEM:\s*/i,"")];let p=-1;for(let f=o+1;f<s.length;f+=1){const h=s[f];if(h.trim()==="]"){p=f;break}if(/\]\s*$/.test(h.trim())){const m=h.replace(/\]\s*$/,"");m.trim()&&u.push(m),p=f;break}u.push(h)}if(p===-1){i.push(l),o+=1;continue}r();const d=ft(u.join(`
37
+ `).trim());if(!d){o=p+1;continue}n.push({kind:"system",text:d}),o=p+1}return r(),n}function Tp(t){return t?t?.role==="system"?!Ai(t?.text||"")||!!ft(t?.text||""):t?.role!=="user"&&t?.role!=="assistant"?!1:Ml(t?.text||"").some(e=>e.kind==="system"):!1}function Xr(t){return Tp(t)?"system":t?.role||"other"}function Pl(t,e){return!t||!e?!1:Xr(t)!==Xr(e)}function Np(t){const e=String(t||"").replace(/\s+/g," ").trim();if(!e)return"System notice.";const s=/^The session was dehydrated and has been rehydrated on a new worker(?: \(([^)]+)\))?\./.exec(e);if(s)return s[1]?`Session rehydrated on a new worker (${s[1]}).`:"Session rehydrated on a new worker.";const i=/^(.{1,160}?[.!?])(?:\s|$)/.exec(e)?.[1]?.trim()||e;return i.length>=e.length?i.length>160?`${i.slice(0,159).trimEnd()}…`:i:`${i}…`}function Mp(t,e=""){const s=Np(t);return{kind:"systemNotice",text:`${e?`[${e}] `:""}System: ${s}`,summary:s,body:Bt(t),color:"gray"}}function Qr({title:t,summary:e,body:s,timestamp:n="",color:i="gray"}){const r=String(t||"System").trim()||"System",o=String(e||"").replace(/\s+/g," ").trim();return{kind:"systemNotice",text:`${n?`[${n}] `:""}${r}${o?`: ${o}`:""}`,summary:o,body:Bt(s||o),color:i}}function Pp(t){return t?.label?[{text:t.label,color:t.kind==="working"?"yellow":"cyan",bold:!0}]:null}function Rp(t,e){return e?(t||[]).map(s=>Array.isArray(s)?s.map(n=>({...n,color:n?.color||e})):s):t}function _p(t){const e=(t||[]).find(s=>ht(s).trim().length>0);return e?ht(e).trimStart().startsWith("┌"):!1}function Ys(t,e){!Array.isArray(e)||e.length===0||(t.length>0&&_p(e)&&ht(t[t.length-1]).trim().length>0&&t.push([{text:"",color:null}]),t.push(...e))}function Lp(t){const e=String(t||""),s=/^\s*Sub-agent\s+completed\b/i.test(e),n=/^\s*Sub-agents\s+completed/i.test(e);if(!s&&!n)return null;const i=[],r=/(?:^|\n)\s*-\s*Agent\s+(\S+)\s*\n\s*Task:\s*"([^"]*)"\s*\n\s*Status:\s*(\S+)\s*\n\s*Result:\s*([\s\S]*?)(?=(?:\n\s*-\s*Agent\s+\S+)|$)/g;let o;for(;(o=r.exec(e))!==null;)i.push({agentId:o[1],task:o[2],status:o[3],result:o[4].trim()});return i.length===0?null:s||i.length===1?{kind:"subAgentSingle",...i[0]}:{kind:"subAgentMulti",agents:i}}function Op(t,e,s){const n=Math.max(20,Number(s)||20),i=Le(e?.createdAt||e?.time),r=Lp(t),o=l=>{const c=String(l||"").replace(/^session-/i,"");return ge(c)||c||String(l||"")};if(r?.kind==="subAgentSingle"){const l=o(r.agentId),c=[r.task?`**Task:** ${r.task}`:"",r.status?`**Status:** ${r.status}`:"","",r.result||"_(no result)_"].filter((u,p)=>p===2||u).join(`
38
+ `);return[Qr({title:`Sub-agent Response — ${l}`,summary:r.status||"completed",timestamp:i,body:c,color:"cyan"})]}if(r?.kind==="subAgentMulti"){const l=r.agents.map(u=>{const p=o(u.agentId),d=u.task?`**Task:** ${u.task}`:"",f=u.status?`**Status:** ${u.status}`:"";return`${[`### ${p}`,d,f].filter(Boolean).join(`
39
+ `)}
40
+
41
+ ${u.result||"_(no result)_"}`}),c=r.agents.map(u=>`${o(u.agentId)} ${u.status||"completed"}`).join(" · ");return[Qr({title:`Sub-agent Responses (${r.agents.length})`,summary:c,timestamp:i,body:l.join(`
42
+
43
+ ---
44
+
45
+ `),color:"cyan"})]}return Ee({title:"System",timestamp:i,body:t,width:n,titleColor:"yellow",borderColor:"gray",bodyColor:"gray",fitToContent:!0})}function $p(t,e){const s=Math.max(12,Math.min(72,Number(e)||12)),n=Math.max(1,s-4),i=Le(t?.createdAt||t?.time),r=String(t?.thinkingLabel||"Thinking…").trim()||"Thinking…",o=t?.progressKind==="working"?"yellow":(t?.progressKind==="sending","cyan"),l=fe([{text:` ⠋ ${r} `,color:o,bold:!0},...i?[{text:` ${i} `,color:"gray"}]:[]],Math.max(1,s-3)),c=l.reduce((f,h)=>f+String(h?.text||"").length,0),u=Math.max(0,s-c-3),p=String(t?.text||"").trim()?Vs(Vt(Bt(t.text),{width:n})).flatMap(f=>_a(f,n)):[],d=[[{text:"┌─",color:"gray"},...l,{text:`${"─".repeat(u)}┐`,color:"gray"}]];for(const f of p)d.push([{text:"│ ",color:"gray"},...Ra(f.map(h=>({...h,color:h?.color&&h.color!=="white"?h.color:"gray"})),n),{text:" │",color:"gray"}]);return d.push([{text:`└${"─".repeat(Math.max(1,s-2))}┘`,color:"gray"}]),d.push([{text:"",color:null}]),d}function Fp(t){return String(t||"").split(`
46
+ `).reduce((e,s)=>Math.max(e,xi(s).length),0)}function Xs(t,e,s={}){if(t?.splash){const u=t.mobileText&&Fp(t.text)>e;return[{kind:"markup",value:u?t.mobileText:t.text,splashAlt:!u&&t.mobileText?t.mobileText:null}]}if(t?.thinking)return $p(t,e);if(t?.noChrome)return Vs(Vt(Bt(t?.text||""),{width:Math.max(20,e),tableMode:s.tableMode}));if(t?.role==="user"){const u=Ci(t?.text||"");if(u)return[...Ee({title:"Question",timestamp:Le(t?.createdAt||t?.time),body:u.question,width:Math.max(20,e),titleColor:_n,borderColor:_n,tableMode:s.tableMode}),...Xs({...t,text:u.answer},e,s)]}if(s.allowLeadingSystemNotices!==!1&&(t?.role==="user"||t?.role==="assistant")){const u=Ml(t?.text||"");if(u.some(p=>p.kind==="system")){const p=[];let d=!1;for(const h of u)h.kind!=="system"&&h.text.trim()&&(Ys(p,Xs({...t,text:h.text},e,{...s,allowLeadingSystemNotices:!1,skipPrefix:d})),d=!0);if(p.length>0)return p;const f=[];for(const h of u)h.kind!=="system"||!h.text.trim()||Ys(f,Op(h.text,t,e));if(f.length>0)return f}}if(t?.role!=="user"&&t?.role!=="assistant"){const u=ft(t?.text||"");if(t?.role==="system"&&!u)return[];const p=!!t?.cardTitle&&String(t.cardTitle).toLowerCase()!=="system";if(t?.role==="system"&&!p)return[Mp(u||t?.text||"",Le(t?.createdAt||t?.time))];const d=t?.role==="system"&&(!t?.cardTitle||String(t.cardTitle).toLowerCase()==="system");return Ee({title:t?.cardTitle||(t?.role==="system"?"System":"PilotSwarm"),timestamp:Le(t?.createdAt||t?.time),body:Bt(t?.text||""),width:Math.max(20,e),titleColor:t?.cardTitleColor||(t?.role==="system"?"yellow":"cyan"),borderColor:t?.cardBorderColor||"gray",tableMode:s.tableMode,...d?{bodyColor:"gray",fitToContent:!0}:{}})}const n=Vs(Vt(Bt(t?.text||""),{width:e,tableMode:s.tableMode})),i=Rp(n,t?.pendingPhase==="cancelling"?"red":t?.role==="user"?_n:null),r=s.skipPrefix?[]:Ip(t,s),o=Dp(t,s);if(i.length===0){const u=r.length>0?[r]:[];return o.length>0?[...u,...o]:u}if(kp(i)){const u=r.length>0?[r,...i]:i;return o.length>0?[...u,...o]:u}const l=[];let c=r.length===0;for(const u of i){if(!Array.isArray(u)){c||(l.push(r),c=!0),l.push(u);continue}c?l.push(u):(l.push([...r,...u]),c=!0)}return l.push(...o),l}function Dp(t,e={}){const s=Array.isArray(t?.attachments)?t.attachments:[];return s.length===0?[]:e.tableMode==="sentinel"?[{kind:"imageAttachments",sessionId:String(t?.id||"").split(":")[0]||null,attachments:s}]:s.map(n=>{const i=Number(n?.sizeBytes)||0,r=i>=1024*1024?`${(i/(1024*1024)).toFixed(1)} MB`:i>=1024?`${Math.round(i/1024)} KB`:`${i} B`;return[{text:" ",color:null},{text:`[image: ${n.filename}${i>0?` · ${r}`:""}]`,color:"cyan"}]})}const Bp=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 Hp(t){const e=Math.max(0,Math.floor((Number(t)||0)/1e3));if(e<60)return`${e}s`;const s=Math.floor(e/60),n=e%60;if(s<60)return`${s}m ${String(n).padStart(2,"0")}s`;const i=Math.floor(s/60),r=s%60;return`${i}h ${String(r).padStart(2,"0")}m`}const jp=new Set(["read_facts","facts_search","facts_similar","facts_read_uncrawled","facts_tombstone_stats"]),Gp=new Set(["store_fact","delete_fact","facts_set_crawled","facts_purge_tombstones","facts_force_purge"]);function Up(t,e){const s=String(t||"").toLowerCase();return s==="search_skills"||s.includes("skill")?e?"loading skills…":"loaded skills":jp.has(s)?e?"reading facts…":"read facts":Gp.has(s)?e?"writing facts…":"wrote facts":s.startsWith("graph_")?/upsert|delete|archive|merge|remove|set_/.test(s)?e?"writing to the graph…":"wrote to the graph":e?"reading the graph…":"read the graph":s.startsWith("facts_")||s.endsWith("_fact")||s.endsWith("_facts")?/store|write|set|delete|purge|update/.test(s)?e?"writing facts…":"wrote facts":e?"reading facts…":"read facts":""}function zp(t){const e=String(t?.eventType||"");if(e==="tool.execution_start"||e==="tool.execution_complete"){const n=(String(t?.text||"").replace(/^\s*\d{1,2}:\d{2}(?::\d{2})?\s*/,"").replace(/^\[[^\]]+\]\s*/,"").replace(/^[^A-Za-z0-9_]+/,"").trim().match(/^[A-Za-z0-9_.:-]+/)||[""])[0];if(!n)return"running tools…";const i=Up(n,e==="tool.execution_start");if(i)return i;const r=n.length>28?`${n.slice(0,27)}…`:n;return e==="tool.execution_start"?`running tool: ${r}…`:`finished tool: ${r}`}switch(e){case"skill.invoked":return"loading skills…";case"learned_skill.read":return"loading skills…";case"skills.searched":return"loading skills…";case"facts.searched":case"facts.similar":return"reading facts…";case"graph.searched":case"graph.node_searched":case"graph.node_loaded":return"reading the graph…";case"graph.namespace_mutated":return"writing to the graph…";case"assistant.reasoning":return"thinking…";case"assistant.intent":return"planning…";case"assistant.message_start":case"assistant.message":return"writing reply…";case"session.compaction_start":return"compacting context…";case"session.compaction_complete":return"context compacted";case"session.dehydrated":return"dehydrating…";case"session.hydrated":case"session.rehydrated":return"rehydrating…";case"session.agent_spawned":return"coordinating agents…";case"session.wait_started":return"waiting…";case"session.input_required_started":return"awaiting input…";case"session.lossy_handoff":return"moving to a new worker…";case"session.error":return"recovering from an error…";default:return""}}function ji(t,e={}){const s=Ve(t);if(!s||s.isGroup)return[];if(String(s?.status||"").toLowerCase()!=="running")return[];const i=t.history?.bySessionId?.get(s.sessionId)||null,r=Array.isArray(i?.chat)?i.chat:[];let o=0;for(let v=r.length-1;v>=0;v-=1)if(r[v]?.role==="user"){o=Number(r[v]?.createdAt||0);break}const l=Array.isArray(i?.activity)?i.activity:[];let c=0,u=0;for(let v=l.length-1;v>=0;v-=1){const x=l[v],E=x?.eventType,w=Number(x?.createdAt||0);if(!c&&E==="assistant.turn_start"&&(c=w),!u&&(E==="assistant.turn_end"||E==="session.turn_completed")&&(u=w),c&&u)break}let p=0;o>u?p=o:c>u&&(p=c);let d=null;for(let v=l.length-1;v>=0;v-=1){const x=l[v];if(!(!x||Bp.has(x.eventType))){if(Number(x.createdAt||0)<=u)break;d=x;break}}const f=Number.isFinite(e.now)?e.now:Date.now(),h=p>0?Hp(f-p):"",m=String(e.spinnerFrame||"").trim()||"●",g=d?zp(d):"",S=[{text:`${m} `,color:"cyan"},{text:"Working",color:"cyan"},...h?[{text:` · ${h}`,color:"gray"}]:[],...g?[{text:` — ${g}`,color:"gray"}]:[]],y=Math.max(24,Math.min(120,Math.floor(Number(e.maxWidth)||80)));return[fe(S,y)]}const Zr=4;let xs=[];function Gi(t,e=80,s={}){const n=t?.sessions?.activeSessionId??null,i={sessionId:n,session:n?t?.sessions?.byId?.[n]??null:null,byId:t?.sessions?.byId??null,chat:t?.history?.bySessionId?.get?.(n)?.chat??null,branding:t?.branding??null,principal:t?.auth?.principal??null,maxWidth:e,tableMode:s?.tableMode??null};for(const m of xs)if(m.sessionId===i.sessionId&&m.session===i.session&&m.byId===i.byId&&m.chat===i.chat&&m.viewMode===i.viewMode&&m.branding===i.branding&&m.principal===i.principal&&Object.is(m.maxWidth,i.maxWidth)&&m.tableMode===i.tableMode)return m.lines;const r=m=>(xs.unshift({...i,lines:m}),xs.length>Zr&&(xs.length=Zr),m),o=Hi(t);if(!o||o.length===0)return r([{text:"No messages yet.",color:"gray"}]);const l=we(t?.auth?.principal),c=t?.sessions?.activeSessionId,u=c?t?.sessions?.byId?.[c]:null,p=we(u?.owner),d=!!(u&&(u.visibility&&u.visibility!=="private"||p&&l&&p!==l)),f={...s?.tableMode?{tableMode:s.tableMode}:{},...l?{viewerKey:l}:{},...p?{ownerKey:p}:{},...d?{sharedContext:!0}:{}},h=[];for(const[m,g]of o.entries()){if(g?.kind==="epoch-divider")h.push(Vp(g,e));else if(g?.kind==="regen-refused")h.push(Xp(g,e));else if(g?.kind==="regen-failed")h.push(Qp(g,e));else if(g?.kind==="canvas-update")h.push(Kp(g,g.sessionId||n));else if(g?.kind==="canvas-action")h.push(qp(g));else{const y=Xs(g,e,f);Ys(h,y)}const S=o[m+1];S&&Pl(g,S)&&ht(h[h.length-1]).trim().length>0&&h.push(Nl())}return r(h.length>0?h:[{text:"No messages yet.",color:"gray"}])}function Wp(t,e){if(!e)return null;let s=null;for(let n=1;n<=5;n+=1){const i=qe(e,n),r=t?.canvas?.bySessionId?.[i],o=t?.canvas?.prefs?.[i];if(!r){(o?.lastViewedRev||0)>0&&(s=s||"canvas");continue}const l=r.latestRev||0;if(l<=0||r.sizeBytes===0)continue;if(l>(o?.lastViewedRev||0)||(r.latestDataRev||0)>(o?.lastViewedDataRev||0))return"unseen";s="canvas"}return s}function Ui(t){const e=t?.sessions?.activeSessionId||null,s=Number(t?.ui?.canvasSlot)||1,n=t?.canvas?.bySessionId||{},i=[];if(e)for(let g=1;g<=5;g+=1){const S=n[qe(e,g)];if(!S||(S.latestRev||0)<=0||S.sizeBytes===0)continue;const y=t?.canvas?.prefs?.[qe(e,g)];i.push({slot:g,name:typeof S.name=="string"?S.name:"",latestRev:S.latestRev||0,unseen:(S.latestRev||0)>(y?.lastViewedRev||0)||(S.latestDataRev||0)>(y?.lastViewedDataRev||0)})}const r=i.some(g=>g.slot===s)?s:1,o=e?qe(e,r):null,l=o?n[o]:null,c=o?t?.canvas?.prefs?.[o]:null,u=l?.latestRev||0,p=c?.lastViewedRev||0,d=l?.latestDataRev||0,f=c?.lastViewedDataRev||0,h=t?.ui?.canvasOpen?"canvas":"panes",m=u>0&&l?.sizeBytes!==0;return{sessionId:e,slot:r,slots:i,name:typeof l?.name=="string"?l.name:"",mode:h,exists:m,latestRev:u,note:l?.note||"",sizeBytes:l?.sizeBytes??null,snapshotLoaded:!!l?.snapshotLoaded,optedOut:!!c?.optedOut,lastViewedRev:p,flipSeq:t?.canvas?.flipSeq||0,responseContract:l?.responseContract||null,latestDataRev:d,lastViewedDataRev:f,dataPayload:l?.dataPayload||null,dataPatch:l?.dataPatch||null,planeSeq:l?.planeSeq||0,unseen:m&&(u>p||d>f)&&h!=="canvas"}}function qp(t){const e=t?.data&&typeof t.data=="object"?Object.keys(t.data):[],s=e.length===1&&typeof t.data[e[0]]=="string"?t.data[e[0]].slice(0,120):e.length?JSON.stringify(t.data).slice(0,120):"";return{runs:[{text:"[canvas] ",color:"cyan",bold:!0},{text:`${t.action||"action"}`,color:"white"},...s?[{text:` — ${s}`,color:"gray"}]:[]],canvasAction:!0}}function Kp(t,e){const s=Number(t?.rev)||0,n=typeof t?.note=="string"&&t.note.trim()?` — ${t.note.trim()}`:"",i=[{text:"[canvas] ",color:"cyan",bold:!0},{text:`rev ${s}${n} `,color:"white"}];return e&&(i.push({text:"[artifact: canvas.html]",color:"cyan",underline:!0,href:`artifact://${e}/canvas.html`}),i.push({text:" (press a to download)",color:"gray"})),{runs:i,canvasUpdate:!0}}function zi(t,e,s){const i=Math.max(24,Number(s)||80)-t.length;if(i<2)return[{text:t.trim(),color:e,bold:!0}];const r=Math.min(6,Math.floor(i/2));return r<1?[{text:t.trim(),color:e,bold:!0}]:[{text:"─".repeat(r),color:e},{text:t,color:e,bold:!0},{text:"─".repeat(r),color:e}]}function Vp(t,e){const s=Number.isFinite(t?.turnsArchived)?t.turnsArchived:null,n=` ↻ context regenerated · epoch ${t?.epoch??"?"}${s!=null?` · ${s} turn${s===1?"":"s"} archived`:""} `;return zi(n,"magenta",e)}const Yp={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 Xp(t,e){const s=String(t?.reason||"unknown"),i=` ↻ regeneration refused · ${Yp[s]||s.replace(/_/g," ")} `;return zi(i,"yellow",e)}function Qp(t,e){const s=String(t?.stage||"unknown"),n=String(t?.error||"").split(`
47
+ `)[0],i=n.length>120?`${n.slice(0,117)}…`:n,r=` ✕ regeneration failed at ${s}${i?` · ${i}`:""} `;return zi(r,"red",e)}function Zp(t){const e=t.sessions.activeSessionId;return e?Array.isArray(t.outbox?.bySessionId?.[e])?t.outbox.bySessionId[e].map(s=>Sp(e,s)).filter(Boolean):[]:[]}function Wi(t,e=80,s={}){const n=Zp(t);if(!n||n.length===0)return[];const i=Math.max(20,Number(e)||80),r=n.filter(m=>m.pendingPhase==="queued").length,o=n.filter(m=>m.pendingPhase==="pending").length,l=n.filter(m=>m.pendingPhase==="cancelling").length,c=n.filter(m=>m.pendingPhase==="rejected").length,u=[];o>0&&u.push(`${o} pending`),r>0&&u.push(`${r} queued`),l>0&&u.push(`${l} cancelling`),c>0&&u.push(`${c} rejected`);const f=[[{text:` queued prompts: ${u.length>0?u.join(" · "):"queued prompts"} `,color:"gray",trailingRule:!0}]],h=s?.tableMode?{tableMode:s.tableMode}:{};for(const[m,g]of n.entries()){Ys(f,Xs(g,i,h));const S=n[m+1];S&&Pl(g,S)&&ht(f[f.length-1]).trim().length>0&&f.push(Nl())}return f}function Jp(t){const e=Hi(t),s=[],n=new Set;for(const i of e||[])for(const r of du(i?.text||"")){const o=`${r.sessionId}/${r.filename}`;n.has(o)||(n.add(o),s.push(r))}return s}function ef(t){const e=Hi(t),s=[],n=new Set;for(const i of e||[])for(const r of pu(i?.text||"")){const o=String(r.href||"").trim();!o||n.has(o)||(n.add(o),s.push({href:o,text:String(r.text||o).trim()||o}))}return s}function qi(t,e){const s=Ca(t);if(!s)return"";const n=String(e||"").trim();return n?`${s}:${n}`:s}function tf(t){return Ca(t)||"(unknown)"}function Rl(t,e={}){const s=Ve(t),n=t.sessions?.byId||{},i=Array.isArray(t.sessions?.flat)?t.sessions.flat:[],r=Di(n),o=Bi(i,n),l=fl(e?.width);if(!s)return{color:"cyan",title:Je("Chat","cyan"),titleRight:null,animateTitleRight:!1};const c=ge(s.sessionId),u=s.isSystem?"yellow":"cyan",p=Je(s.isSystem?`⚙ ${Jt(s,t.branding?.title||"PilotSwarm")}`:$i(s)||"Chat",u),d=i.find(E=>E.sessionId===s.sessionId),f=Il(s.sessionId,d,r,o);f&&p.push({text:` ${f.text}`,color:f.color}),l||p.push({text:` [${c}]`,color:"gray"});const h=t.history?.bySessionId?.get(s.sessionId)||null,m=Array.isArray(t.outbox?.bySessionId?.[s.sessionId])?t.outbox.bySessionId[s.sessionId]:[],g=Ep(s,h,h?.chat||[],m),S=t.connection?.mode||"local",y=dp(s,S),v=Pp(g),x=v?[...y,...y.length?[{text:" · ",color:"gray"}]:[],...v]:y;return{color:s.isSystem?"yellow":"cyan",title:p,titleRight:x.length?x:null,animateTitleRight:!!g}}function sf(t){const e=t.sessions.activeSessionId;return e?t.history.bySessionId.get(e)?.activity||[]:[]}function _l(t){const e=jl(t),s=e.selected?e.nodes.find(o=>o.label===e.selected):null,n=Je("Worker","gray");if(!s)return n.push({text:" none",color:"gray"}),{title:n,lines:[{text:e.degraded&&e.registryError?`No worker selected — ${e.registryError}`:"No workers to show yet.",color:"gray"}]};n.push({text:` ${s.label}`,color:"cyan"});const i=[],r=(o,l,c="white")=>{l==null||l===""||i.push([{text:`${o.padEnd(10)} `,color:"gray"},{text:String(l),color:c}])};if(s.registered){if(r("Node",s.workerNodeId),r("Phase",s.phase,s.phase==="draining"?"red":s.phase==="starting"?"yellow":"green"),r("Pool",s.pool),s.owner&&r("Owner",s.owner),r("Heartbeat",s.live?`${s.agoText??"now"} · live`:`${s.agoText??"unknown"} · stale`,s.live?"green":"red"),r("Uptime",s.uptimeText),r("Memory",[s.rssText?`rss ${s.rssText}`:null,s.heapText?`heap ${s.heapText}`:null].filter(Boolean).join(" · ")||null),r("Loop p99",s.eventLoopText),r("SDK",s.sdkVersion),r("Runtime",s.substrate),s.capabilities.length&&r("Caps",s.capabilities.join(", ")),s.consumes.length&&r("Consumes",s.consumes.join(", ")),s.pkgEpoch!==null){const o=s.pkgInstalled.filter(c=>c.status==="ok").length,l=s.pkgInstalled.length-o;r("Packages",`epoch ${s.pkgEpoch} · ${o} ok${l?` · ${l} error`:""}`,l?"red":"white");for(const c of s.pkgInstalled)i.push([{text:" ",color:"gray"},{text:`${c.status==="error"?"✗":"✓"} `,color:c.status==="error"?"red":"green"},{text:`${c.name}${c.semver?`@${c.semver}`:""}`,color:c.status==="error"?"red":"white"}]),c.error&&i.push([{text:` ${c.error}`,color:"red"}]);s.pkgLastError&&i.push([{text:` last refresh error: ${s.pkgLastError}`,color:"red"}])}}else i.push({text:"Not in the worker registry — derived from recent activity only.",color:"gray"});i.push({text:"",color:"gray"}),i.push([{text:`EXECUTING (${s.executing.length})`,color:"cyan",bold:!0}]);for(const o of s.executing)i.push(o.active?st(o.text):{text:o.text,color:o.color,bold:o.bold});return s.executing.length===0&&i.push({text:`Nothing executing in the ${e.windowLabel} window.`,color:"gray"}),{title:n,lines:i}}function Ki(t,e=12){const s=sf(t),n=Ve(t),i=Je("Activity","gray");return n?.isGroup?{title:i,disabled:!0,lines:[{text:zl,color:"gray"}]}:(n?.statusVersion!=null&&i.push({text:` [current session v${n.statusVersion}]`,color:"gray"}),{title:i,lines:s.length>0?s.map(r=>r.line||[{text:r.text,color:"white"}]):[{text:"No activity yet",color:"gray"}]})}function Ll(t){switch(String(t||"").toLowerCase()){case"error":return"red";case"warn":return"yellow";case"debug":return"blue";case"trace":return"magenta";default:return"green"}}function Ol(t,e){return t==="orchestration"?"magenta":t==="activity"?"cyan":Ll(e)}function nf(t){return t==="raw"?"raw summary":"pretty text"}function rf(t){return t?.sessionId?`session-${t.sessionId}`:null}function of(t,e){const s=Array.isArray(t.logs?.entries)?t.logs.entries:[],n=t.logs?.filter||{},i=rf(e);return s.filter(r=>!(!r||n.source==="currentOrchestration"&&i&&r.orchId!==i||n.level&&n.level!=="all"&&String(r.level||"").toLowerCase()!==n.level))}function af(t){const e=bs(t?.podName)||t?.podName||"node",s=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):""),n=String(t?.level||"info").toUpperCase(),i=t?.category==="orchestration"?"◆":t?.category==="activity"?"●":"•";return[{text:`[${t?.time||"--:--:--"}] `,color:"gray"},{text:`${i} `,color:Ol(t?.category,t?.level)},{text:`${e} `,color:"white",bold:!0},...s?[{text:`[${ge(s)}] `,color:"gray"}]:[],{text:`${n} `,color:Ll(t?.level),bold:!0},{text:t?.rawLine||t?.message||"",color:"white"}]}function lf(t){const e=t?.sessionId||(String(t?.orchId||"").startsWith("session-")?String(t.orchId).slice(8):"");return[{text:`${e?`[${ge(e)}] `:""}${t?.prettyMessage||t?.message||t?.rawLine||""}`,color:Ol(t?.category,t?.level),bold:String(t?.level||"").toLowerCase()==="warn"||String(t?.level||"").toLowerCase()==="error"}]}function cf(t,e){const s=t.logs||{},n=s.filter||{},i=[{text:"Scope: ",color:"gray"},{text:n.source==="currentOrchestration"?"current orchestration":"all nodes",color:"white"},{text:" Level: ",color:"gray"},{text:n.level||"all",color:"white"},{text:" Format: ",color:"gray"},{text:nf(n.format),color:"white"}];if(!s.available)return[{text:s.availabilityReason||"Log tailing disabled: no K8S_CONTEXT configured in the env file.",color:"yellow"},{text:"",color:"gray"},i];if(!s.tailing)return[{text:"Press t to start log tailing.",color:"cyan",bold:!0},{text:"Press f to open log filters.",color:"gray"},{text:"",color:"gray"},i];const r=of(t,e);return r.length===0?[{text:"Tailing logs…",color:"cyan"},{text:"No logs match the current filter yet.",color:"gray"},{text:"",color:"gray"},i]:[i,{text:"",color:"gray"},...r.map(o=>n.format==="raw"?af(o):lf(o))]}function Jr(t){return/\.(md|markdown|mdown|mkd|mdx)$/i.test(String(t||""))}function uf(t){return/\.(json|jsonl)$/i.test(String(t||""))}function df(t){return et.map(e=>({text:e===t?`[${e}] `:`${e} `,color:e===t?"magenta":"gray",bold:e===t}))}function pf(t=""){const e=String(t||"").split(`
48
+ `);return e.length>0?e.map(s=>({text:s,color:"white"})):[{text:"",color:"white"}]}function eo(t,{selected:e=!1,width:s=24,label:n=null}={}){const i=Math.max(8,s),r=Jr(t)?"# ":uf(t)?"{ ":"• ",o=$l(`${r}${n||t}`,i).padEnd(i," ");return e?st(o):{text:o,color:Jr(t)?"cyan":"white",bold:!1}}function We(t){return t.files?.filter?.scope==="allSessions"?"allSessions":"selectedSession"}function ff(t,e={}){if(!t)return new Set;const{childMap:s}=Fi(e),n=new Set([t]),i=[t];for(;i.length>0;){const r=i.shift(),o=s.get(r)||[];for(const l of o)!l||n.has(l)||(n.add(l),i.push(l))}return n}function Qs(t,e=We(t)){const s=Ve(t)?.sessionId||null,n=Array.isArray(t.sessions?.flat)?t.sessions.flat.map(c=>c?.sessionId||c).filter(Boolean):[],i=Object.keys(t.files?.bySessionId||{}).filter(Boolean);if(e==="allSessions")return[...new Set([...n,...i])];const r=ff(s,t.sessions?.byId||{});if(r.size===0)return[];const o=[],l=new Set;for(const c of[s,...n,...Object.keys(t.sessions?.byId||{}),...i])!c||l.has(c)||!r.has(c)||(o.push(c),l.add(c));for(const c of r)l.has(c)||o.push(c);return o}function to(t){const s=Ve(t)?.sessionId;if(!s)return[];const i=t.history?.bySessionId?.get?.(s)?.events||[],r=new Set,o=[],l=/artifact:\/\/([a-f0-9-]+)\/([^\s"'{})\]]+)/g;for(const c of i){const u=typeof c?.data?.content=="string"?c.data.content:"";if(!u)continue;l.lastIndex=0;let p;for(;(p=l.exec(u))!==null;){const d=`${p[1]}/${p[2]}`;r.has(d)||(r.add(d),o.push(d))}}return o}function It(t){const e=We(t);Ve(t)?.sessionId;const s=t.files?.filter?.query||"",n=Qs(t,e),i=e==="allSessions"||n.length>1,r=[];for(const o of n){const l=Ws(t.files?.bySessionId?.[o]?.entries);for(const c of l){const u=c.filename;r.push({id:`${o}/${u}`,sessionId:o,filename:u,entry:c,label:i?`[${ge(o)}] ${u}`:u})}}return r.filter(o=>xt(o.filename,s)||xt(o.sessionId,s)||xt(o.label,s))}function ut(t){const e=It(t);if(e.length===0)return null;const s=t.files?.selectedArtifactId||null;if(s){const o=e.find(l=>l.id===s);if(o)return o}if(We(t)==="allSessions"){const o=Ve(t)?.sessionId||null,l=o&&t.files?.bySessionId?.[o]?.selectedFilename||null;if(o&&l){const c=e.find(u=>u.sessionId===o&&u.filename===l);if(c)return c}return e[0]}const i=Ve(t)?.sessionId||null,r=i&&t.files?.bySessionId?.[i]?.selectedFilename||null;return e.find(o=>o.sessionId===i&&o.filename===r)||e[0]}function Vi(t,e={}){const s=Ve(t),n=Math.max(12,Number(e?.listWidth)||Number(e?.width)||24),i=Math.max(18,Number(e?.previewWidth)||Number(e?.width)||36),r=e?.showHints!==!1,o=s?.sessionId||null,l=We(t),c=t.files?.filter?.query||"",u=It(t),p=ut(t),d=p?.filename||null,f=Math.max(0,u.findIndex(L=>L.id===p?.id)),h=p?.sessionId&&d&&t.files?.bySessionId?.[p.sessionId]?.previews?.[d]||null,m=h||p?.entry||null,g=s?ge(s.sessionId):"",S=Qs(t,l),y=l!=="allSessions"&&S.some(L=>L&&L!==o),v=[...new Set([...Array.isArray(t.sessions?.flat)?t.sessions.flat.map(L=>L?.sessionId||L):[],...Object.keys(t.files?.bySessionId||{})])].filter(Boolean),x=l==="allSessions"&&v.some(L=>!t.files?.bySessionId?.[L]?.loaded||t.files?.bySessionId?.[L]?.loading),E=l==="allSessions"&&v.map(L=>t.files?.bySessionId?.[L]?.error).find(Boolean)||null,w=[df("files"),...s||l==="allSessions"?[]:[{text:"No session selected.",color:"gray"}]];if(l==="allSessions")x&&u.length===0?w.push({text:"Loading exported files across all sessions…",color:"gray"}):E&&u.length===0?w.push({text:E,color:"red"}):u.length===0?(w.push({text:c?`No artifacts matched "${c}" across any session.`:"No exported files across any session yet.",color:"gray"}),w.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"})):w.push(...u.map((L,G)=>eo(L.filename,{selected:G===f,width:n,label:L.label})));else if(s){const L=o?t.files?.bySessionId?.[o]:null;Array.isArray(L?.entries)&&L.entries;const G=u.filter(P=>S.includes(P.sessionId));L?.loading?w.push({text:"Loading exported files…",color:"gray"}):L?.error?w.push({text:L.error,color:"red"}):G.length===0&&S.every(P=>{const H=t.files?.bySessionId?.[P]?.entries;return!Array.isArray(H)||H.length===0})?(w.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"}),w.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"})):w.push(...G.map((P,H)=>eo(P.filename,{selected:H===f,width:n,label:P.label})))}let I,b;!s&&l!=="allSessions"?(b=[{text:"Preview",color:"cyan",bold:!0}],I=[{text:"No session selected.",color:"gray"}]):d?h?.loading?(b=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(l==="allSessions"||p?.sessionId&&p.sessionId!==o)&&p?.sessionId?[{text:` · ${ge(p.sessionId)}`,color:"gray"}]:[]],I=[{text:"Loading file preview…",color:"gray"}]):h?.error?(b=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(l==="allSessions"||p?.sessionId&&p.sessionId!==o)&&p?.sessionId?[{text:` · ${ge(p.sessionId)}`,color:"gray"}]:[]],I=[{text:h.error,color:"red"}]):(b=[{text:`Preview: ${d}`,color:"cyan",bold:!0},...(l==="allSessions"||p?.sessionId&&p.sessionId!==o)&&p?.sessionId?[{text:` · ${ge(p.sessionId)}`,color:"gray"}]:[],...h?.renderMode==="markdown"?[{text:" [md]",color:"gray"}]:h?.isBinary===!0?[{text:" [file]",color:"gray"}]:h?.renderMode==="note"?[{text:" [note]",color:"gray"}]:[]],I=h?.renderMode==="markdown"?Vs(Vt(h?.content||"",{width:i})):pf(h?.content||"")):(b=[{text:"Preview",color:"cyan",bold:!0}],I=[{text:"Select a file to preview it here.",color:"gray"}]);const M=l==="allSessions"?"Files: all sessions":s?`Files: ${g}${y?" tree":""}`:"Files",A=l==="allSessions"?"all sessions":s?`${g}${y?" tree":""}`:"Files",O=l==="allSessions"?`Artifacts${u.length>0?` [${u.length}]`:""}`:`Artifacts${y?" tree":""}${u.length>0?` [${u.length}]`:""}`,F=c?` · @${c}`:"";return{panelTitle:[{text:`${M}${F}`,color:"magenta",bold:!0}],panelTitleMobile:[{text:`${A}${F}`,color:"magenta",bold:!0}],listTitle:[{text:`${O}${F}`,color:"cyan",bold:!0}],listLines:w,listBodyLines:w.slice(1),selectedIndex:f,selectedFilename:d,selectedSessionId:p?.sessionId||null,scope:l,previewTitle:b,previewLines:I,previewContent:h?.content||"",previewContentType:h?.contentType||"",previewRenderMode:h?.renderMode||null,previewIsBinary:m?.isBinary===!0,previewSizeBytes:m?.sizeBytes??null,previewUploadedAt:m?.uploadedAt||"",previewSource:m?.source||null,previewError:h?.error||null,previewLoading:!!h?.loading,previewScrollOffset:t.ui.scroll.filePreview||0,fullscreen:!!t.files?.fullscreen,fullscreenTitle:[{text:M,color:"magenta",bold:!0},...d?[{text:" · ",color:"gray"},{text:d,color:"cyan",bold:!0}]:[],...r?[{text:" [f filter] [u upload] [a download] [x delete] [o open] [v/esc close fullscreen]",color:"gray"}]:[]]}}function so(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);return Number.isNaN(e.getTime())?"—":e.toISOString().slice(0,10)}function Ft(t){const e=Number(t)||0;return e<=0?"0 B":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function hf(t){const e=String(t||"").toLowerCase();return e.endsWith(".md")?"markdown":e.endsWith(".json")?"json":/\.(mjs|cjs|js)$/.test(e)?"javascript":"text"}function mf(t){const e=t.admin||{},s=e.profile||null,n=e.ghcpKey||{editing:!1,draft:"",saving:!1,error:null},i=s?{provider:s.provider||"",subject:s.subject||"",email:s.email||null,displayName:s.displayName||null}:t.auth?.principal||null,r=e.systemGhcpKey||{supported:!1,loading:!1,configured:!1,changedBy:null,changedAt:null,error:null},o=!!s?.isAdmin,l=o&&!!n.storeAsSystem,c=l?!!r.configured:!!s?.githubCopilotKeySet,u=l?"System key":"key",p=r.configured&&r.changedBy?` (set by ${r.changedBy})`:"",d=n.saving?"Saving...":n.editing?"Editing — Enter to save, Esc to cancel":l?r.configured?`System key configured — ownerless system sessions use it for GitHub Copilot models${p}`:"System key not configured — ownerless system sessions fall back to env GITHUB_TOKEN":s?.githubCopilotKeySet?"Configured (overrides env GITHUB_TOKEN for this user)":"Not configured (using env GITHUB_TOKEN fallback)",f=e.packages||{},h=Array.isArray(f.list)?f.list:[],m=T=>!!(o||T?.owner&&i&&T.owner.provider===i.provider&&T.owner.subject===i.subject),g=Zd(t?.sessions?.byId),S=new Set;for(const T of h){if(T?.scope==="shared")continue;const Y=we(T?.owner)||String(T?.createdBy||"").trim().toLowerCase();!Y||Y===Oi||S.add(Y)}const y=S.size>1,v=(T,Y,le)=>`${T}${Y==="shared"?"shared":"user"}${Y==="shared"?"":le?.subject??""}`,x=f.selectedName?v(f.selectedName,f.selectedSelector?.scope??null,f.selectedSelector?.owner??i??null):null,E=T=>e.section!=="packages"||f.selectedName!==T.name?!1:f.selectedSelector?.scope?v(T.name,T.scope,T.owner)===x:!0,w=T=>({name:T.name,scope:T.scope==="shared"?"shared":"user",owner:T.owner??null,enabled:!!T.enabled,semver:T.active?.semver||null,sha7:T.active?.sha256?String(T.active.sha256).slice(0,7):null,agentCount:Array.isArray(T.active?.manifest?.agents)?T.active.manifest.agents.length:0,canManage:m(T),ownerBadge:T.scope==="shared"||!y?null:wl(Jd(T,g)),selected:E(T)}),I=T=>!!(T?.owner&&i&&T.owner.provider===i.provider&&T.owner.subject===i.subject),b=t.sessions?.ownerFilter,M=T=>{if(!b||b.all===!0)return!0;const Y=we(T?.owner);return Y?Array.isArray(b.ownerKeys)&&b.ownerKeys.includes(Y):b.includeUnowned===!0},A=h.filter(T=>T.scope==="shared").map(w),O=h.filter(T=>T.scope!=="shared"&&I(T)).map(w),F=h.filter(T=>T.scope!=="shared"&&!I(T)&&M(T)).map(T=>({...w(T),ownerLabel:T?.createdBy||T?.owner?.subject||"another user"})),L=["packages","workers"].includes(e.section)?e.section:"ghcp",G=[{id:"ghcp",kind:"section",depth:0,label:"GitHub Keys",selected:L==="ghcp"},{id:"agents",kind:"section",depth:0,label:"Agents",selected:L==="packages"&&!f.selectedName},{id:"group:shared",kind:"group",depth:1,label:"Shared",count:A.length},...A.map(T=>({id:`pkg:shared:${T.name}`,kind:"package",depth:2,label:T.name,...T})),{id:"group:user",kind:"group",depth:1,label:"User",count:O.length},...O.map(T=>({id:`pkg:user:${T.name}`,kind:"package",depth:2,label:T.name,...T})),...F.length>0?[{id:"group:others",kind:"group",depth:1,label:"Other users",count:F.length},...F.map(T=>({id:`pkg:user:${T.owner?.subject??"?"}:${T.name}`,kind:"package",depth:2,label:T.name,...T}))]:[],...o?[{id:"workers",kind:"section",depth:0,label:"Workers",selected:L==="workers"}]:[]],P=f.detail||null;let H=null;if(f.selectedName){const T=h.filter(_=>_.name===f.selectedName),Y=(f.selectedSelector?.scope?T.find(_=>v(_.name,_.scope,_.owner)===x):T[0])??T[0]??null,le=P?.versions?.find(_=>_.versionId===P.activeVersionId)||null,ae=le?.manifest||Y?.active?.manifest||{},Ie=Date.now()-9e4,Re=(Array.isArray(f.workerState)?f.workerState:[]).filter(_=>{const se=_?.updatedAt instanceof Date?_.updatedAt:new Date(_?.updatedAt??0);return!Number.isNaN(se.getTime())&&se.getTime()>=Ie}),ke=Re.length,Te=_=>{const se=_.installed||{},ye=P?.scope||Y?.scope||f.selectedSelector?.scope||null,D=P?.owner?.subject||Y?.owner?.subject||f.selectedSelector?.owner?.subject||"",R=ye==="user"?`${f.selectedName}#user${D?`:${D.slice(0,8)}`:""}`:`${f.selectedName}#shared`;return se[R]??se[f.selectedName]},oe=le?Re.filter(_=>Te(_)?.semver===le.semver&&Te(_)?.status==="ok").length:0,Ne=P?m(P):Y?m(Y):!1;H={name:f.selectedName,loading:!!f.detailLoading,error:f.detailError||null,scope:(P?.scope||Y?.scope)==="shared"?"shared":"user",enabled:P?!!P.enabled:!!Y?.enabled,canManage:Ne,createdBy:P?.createdBy||Y?.createdBy||null,createdAtText:so(P?.createdAt||Y?.createdAt),description:typeof ae.description=="string"?ae.description:"",activeSemver:le?.semver||Y?.active?.semver||null,activeSha12:le?.sha256?String(le.sha256).slice(0,12):null,sizeText:Ft(le?.sizeBytes??Y?.active?.sizeBytes),agents:Array.isArray(ae.agents)?ae.agents.map(_=>({name:_.name,description:_.description||"",toolCount:Array.isArray(_.tools)?_.tools.length:0,skillCount:Array.isArray(_.skills)?_.skills.length:0})):[],versions:(P?.versions||[]).map(_=>({semver:_.semver,sha12:String(_.sha256||"").slice(0,12),dateText:so(_.createdAt),active:_.versionId===P?.activeVersionId})),fleet:ke>0&&le?{current:oe,total:ke,text:`${oe}/${ke} workers current`}:null,actionPending:f.action?.pending||null,actionError:f.action?.error||null,hasSharedCounterpart:T.some(_=>_.scope==="shared"),hasOwnUserCounterpart:T.some(_=>_.scope!=="shared"&&I(_)),copyCount:T.length}}const U=f.workspace||{};let re=null;if(f.selectedName){const T=U.tree,Y=new Set(U.expandedDirs||[]),le=[];if(T){const Ce=oe=>{const Ne=oe.split("/");for(let _=1;_<Ne.length;_++)if(!Y.has(Ne.slice(0,_).join("/")))return!1;return!0},Ie=Array.isArray(T.dirs)?T.dirs:[],Re=Array.isArray(T.files)?T.files:[],ke=oe=>String(oe).split("/").join("\0"),Te=[...Ie.map(oe=>({type:"dir",path:oe})),...Re.map(oe=>({type:"file",path:oe.path,size:oe.size}))].sort((oe,Ne)=>ke(oe.path)<ke(Ne.path)?-1:1);for(const oe of Te){if(!Ce(oe.path))continue;const Ne=oe.path.split("/").length-1;le.push({type:oe.type,path:oe.path,label:oe.path.split("/").pop()+(oe.type==="dir"?"/":""),depth:Ne,expanded:oe.type==="dir"?Y.has(oe.path):void 0,sizeText:oe.type==="file"?Ft(oe.size):null,selected:U.selectedPath===oe.path})}}const ae=U.file;re={loading:!!U.treeLoading,error:U.treeError||null,semver:U.tree?.semver||null,treeRows:le,file:ae?{path:ae.path,sizeText:Ft(ae.size),truncated:!!ae.truncated,isBinary:ae.encoding==="base64",text:ae.encoding==="base64"?null:String(ae.content||""),language:hf(ae.path)}:null,fileLoading:!!U.fileLoading,fileError:U.fileError||null,selectedPath:U.selectedPath||null}}const he=e.workers||{},ce=Array.isArray(he.list)?he.list:[],Ge=9e4,k=Date.now(),$=T=>!Number.isFinite(T)||T<0?"—":T<6e4?`${Math.round(T/1e3)}s ago`:T<36e5?`${Math.round(T/6e4)}m ago`:`${Math.round(T/36e5)}h ago`,K=T=>{if(!Number.isFinite(T)||T<0)return null;if(T<60)return`${Math.round(T)}s`;if(T<3600)return`${Math.floor(T/60)}m`;const Y=Math.floor(T/3600);return Y<48?`${Y}h ${Math.floor(T%3600/60)}m`:`${Math.floor(Y/24)}d ${Y%24}h`},z=ce.map(T=>{const Y=T?.updatedAt instanceof Date?T.updatedAt:new Date(T?.updatedAt??0),le=Number.isNaN(Y.getTime())?Number.NaN:k-Y.getTime(),ae=T?.health||{},Ce=T?.info||{},Ie=T?.state?.["agent-packages"]||null,Re=Ie?.installed&&typeof Ie.installed=="object"?Object.values(Ie.installed):[],ke=Re.filter(Te=>Te?.status==="error").length;return{id:String(T?.workerNodeId??""),pool:String(T?.pool??"default"),phase:["starting","ready","draining"].includes(T?.phase)?T.phase:"ready",live:Number.isFinite(le)&&le<=Ge,agoText:$(le),uptimeText:K(ae.uptimeS),rssText:Ft(ae.rssBytes),sessions:Number.isFinite(ae.activeSessions)?ae.activeSessions:null,eventLoopText:Number.isFinite(ae.eventLoopDelayP99Ms)?`${ae.eventLoopDelayP99Ms}ms`:null,sdkVersion:typeof Ce.sdkVersion=="string"?Ce.sdkVersion:null,substrate:typeof Ce.runtime?.substrate=="string"?Ce.runtime.substrate:null,consumes:Array.isArray(Ce.consumes)?Ce.consumes:[],owner:T?.owner?.subject?String(T.owner.subject):null,pkgEpoch:Number.isFinite(Ie?.epoch)?Ie.epoch:null,pkgText:Ie?`${Re.length-ke} ok${ke?` · ${ke} error`:""}`:null}}).sort((T,Y)=>T.pool===Y.pool?T.id<Y.id?-1:1:T.pool<Y.pool?-1:1),B=z.filter(T=>T.live),Q={loading:!!he.loading,error:he.error||null,empty:z.length===0&&!he.loading,rows:z,counts:{registered:z.length,live:B.length,ready:B.filter(T=>T.phase==="ready").length,starting:B.filter(T=>T.phase==="starting").length,draining:B.filter(T=>T.phase==="draining").length,pools:[...new Set(B.map(T=>T.pool))].length},summaryText:z.length?`${B.length} live / ${z.length} registered`:null},V={loading:!!f.loading,error:f.error||null,empty:h.length===0&&!f.loading,sharedCount:A.length,userCount:O.length,selectedName:f.selectedName||null,detail:H,workspace:re,changelog:f.changelog||null,addDialog:{open:!!f.addDialog?.open,kind:f.addDialog?.kind||"repo",scope:f.addDialog?.scope||"user",repoUrl:f.addDialog?.repoUrl||"",ref:f.addDialog?.ref||"",path:f.addDialog?.path||"",url:f.addDialog?.url||"",authToken:f.addDialog?.authToken||"",submitting:!!f.addDialog?.submitting,progress:f.addDialog?.progress||null,error:f.addDialog?.error||null}},j=[];return L==="workers"?(j.push({id:"workersRefresh",label:"Refresh workers",key:"r"}),j.push({id:"showPackages",label:"Agents",key:"a"}),j.push({id:"showGhcp",label:"GitHub Keys",key:"g"}),j.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:o,section:L,settingsTree:G,packages:V,workers:Q,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:c,storeAsSystem:l,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:d},systemGhcpKey:{supported:!!r.supported,loading:!!r.loading,configured:!!r.configured,changedBy:r.changedBy||null,changedAt:r.changedAt||null,error:r.error||null},actions:j}):L==="packages"?(j.push({id:"packagesRefresh",label:"Refresh packages",key:"r"}),j.push({id:"packagesNext",label:"Next package",key:"j"}),j.push({id:"packagesPrev",label:"Previous package",key:"k"}),j.push({id:"showGhcp",label:"GitHub Keys",key:"g"}),j.push({id:"close",label:"Close console",key:"Esc"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:o,section:L,settingsTree:G,packages:V,workers:Q,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:c,storeAsSystem:l,editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,statusText:d},systemGhcpKey:{supported:!!r.supported,loading:!!r.loading,configured:!!r.configured,changedBy:r.changedBy||null,changedAt:r.changedAt||null,error:r.error||null},actions:j}):(n.editing?(j.push({id:"save",label:"Save",key:"Enter"}),j.push({id:"cancel",label:"Cancel",key:"Esc"})):(j.push({id:"edit",label:c?`Replace ${u}`:`Set ${u}`,key:"e"}),c&&j.push({id:"clear",label:`Clear ${u}`,key:"c"}),j.push({id:"refresh",label:"Refresh",key:"r"})),j.push({id:"close",label:"Close console",key:n.editing?"Ctrl+Esc":"Esc"}),L==="ghcp"&&j.splice(j.length-1,0,{id:"showPackages",label:"Agents",key:"a"}),{visible:!!e.visible,loading:!!e.loading,loadError:e.loadError||null,principal:i,isAdmin:o,section:L,settingsTree:G,packages:V,workers:Q,ghcpKey:{configured:!!s?.githubCopilotKeySet,targetConfigured:c,storeAsSystem:l,editing:!!n.editing,draft:n.draft||"",cursorIndex:Math.max(0,Math.min(Number(n.cursorIndex)||0,String(n.draft||"").length)),saving:!!n.saving,error:n.error||null,statusText:d},systemGhcpKey:{supported:!!r.supported,loading:!!r.loading,configured:!!r.configured,changedBy:r.changedBy||null,changedAt:r.changedAt||null,error:r.error||null},actions:j})}function gf(t){const e=t.ui.focusRegion,s=t.ui.fullscreenPane||null,n=Ve(t),i=!!n?.pendingQuestion?.question,r=n?.sessionId&&Array.isArray(t.outbox?.bySessionId?.[n.sessionId])?t.outbox.bySessionId[n.sessionId]:[],o=r.length>0,l=r.some(S=>S?.phase==="pending"),c=t.ui.promptEdit?.sessionId===n?.sessionId,u=c&&t.ui.promptEdit?.phase==="queued",p=c&&t.ui.promptEdit?.phase==="cancelling",d=s===e?"v/esc close fullscreen":"v fullscreen";if(t.ui.modal?.type==="artifactUpload")return{left:"Upload a local file into this session's artifact store",right:"type path · left/right move · enter upload · esc cancel"};if(t.ui.modal?.type==="renameSession")return{left:"Rename the selected session title",right:"type title · left/right move · enter save · esc cancel"};if(t.ui.modal?.type==="shareSession")return{left:"Share the selected session",right:"name [r|w] grants · -name revokes · enter apply · esc close"};if(t.ui.modal?.type==="artifactPicker")return{left:"Select a linked artifact or URL",right:"up/down move · enter open/download · a/esc close"};if(t.ui.modal?.type==="modelPicker")return{left:"Select a model for the new session",right:"up/down move · enter next · esc cancel"};if(t.ui.modal?.type==="reasoningEffortPicker")return{left:"Select reasoning effort for the new session",right:"up/down move · enter create · esc cancel"};if(t.ui.modal?.type==="themePicker")return{left:"Select a shared portal/TUI theme",right:"up/down move · enter apply · esc close"};if(t.ui.modal?.type==="sessionAgentPicker")return{left:"Select an agent for the new session",right:"up/down move · ←/→ open/close · enter start · esc cancel"};if(t.ui.modal?.type==="sessionGroupPicker")return{left:"Move selected session(s) to a group",right:"up/down move · enter choose · esc cancel"};if(t.ui.modal?.type==="sessionGroupName")return{left:"Name the new group",right:"type name · left/right move · enter create · esc cancel"};if(t.ui.modal?.type==="logFilter")return{left:"Adjust log filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="filesFilter")return{left:"Adjust files browser filters",right:"tab/shift-tab filter · up/down change · enter close · esc close"};if(t.ui.modal?.type==="sessionOwnerFilter")return{left:"Adjust session filters",right:"up/down choose · space toggle · esc close"};const f=!!t.sessions?.selectMode,h=Array.isArray(t.sessions?.selectedIds)?t.sessions.selectedIds.length:0;if(f&&e===N.SESSIONS)return{left:`Select mode · ${h} selected`,right:"up/down move · space toggle · ctrl-g group · c cancel · d complete · D hard delete · V/esc exit"};const m={[N.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",[N.CHAT]:`j/k scroll · ctrl-u/ctrl-d page · e older history · g/G top/bottom · d done · ${d} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane · p prompt`,[N.INSPECTOR]:t.ui.inspectorTab==="logs"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · t tail · f filter · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · tab next pane`:t.ui.inspectorTab==="stats"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f cycle session/fleet/users · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:t.ui.inspectorTab==="files"?t.files?.fullscreen?"a download · x delete · u/ctrl-a upload · o open · f filter · j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · v/esc close fullscreen · left/right tab · [/] resize pane · {/} columns · T themes · ? help · tab next pane":"j/k files · a download · x delete · u/ctrl-a upload · o open · f filter · ctrl-u/ctrl-d page preview · g/G preview top/bottom · d done · v fullscreen · left/right tab · [/] resize pane · {/} columns · T themes · ? help · tab next pane":t.ui.inspectorTab==="history"?`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · f format · r refresh · a save artifact · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:t.ui.inspectorTab==="sequence"?`j/k turn · enter expand · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · m next tab · tab next pane`:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · left/right tab · [/] resize pane · {/} columns · T themes · ? help · h/l focus · a linked items · drag copy · m next tab · tab next pane`,[N.ACTIVITY]:`j/k scroll · ctrl-u/ctrl-d page · g/G top/bottom · d done · ${d} · [/] resize pane · {/} columns · T themes · ? help · a linked items · drag copy · h left · tab next pane`,[N.PROMPT]:i?`type answer · enter reply · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:c?u?`queued prompt selected · d delete · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:p?`cancelling prompt selected · up/down cycle queued · enter/esc new prompt · ${s?"esc pane":"esc sessions"}`:`edit pending prompt · enter send batch · up/down cycle pending · esc cancel · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:l?`type message · enter queues · enter on empty sends batch · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:o?`type message · enter queues behind durable items · up/down recall pending · alt-enter newline · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`:`type message · enter send · alt-enter newline · T themes · ? help · arrows move · alt-left/right word · alt-delete word · @ artifacts · @@ sessions · ${s?"esc pane":"esc sessions"}`};let g=m[e]||m[N.SESSIONS];return Cl(Ve(t))&&(g=`ctrl-x stop · ${g}`),{left:t.ui.statusText,right:g}}function Nt(t){return(t||[]).reduce((e,s)=>e+String(s?.text||"").length,0)}function fe(t,e){if(e<=0)return[];const s=[];let n=e;for(const i of t||[]){if(n<=0)break;const r=String(i?.text||"");if(!r)continue;const o=r.length>n&&n>1?`${r.slice(0,n-1)}…`:r.slice(0,n);o&&(s.push({...i,text:o}),n-=o.length)}return s}function je(t){return Array.from(String(t||"")).length}function $l(t,e){const s=String(t||"");return e<=0?"":je(s)<=e?s:e===1?Array.from(s)[0]||"":`${Array.from(s).slice(0,e-1).join("")}…`}function Kt(t,e){const s=$l(t,e),n=Math.max(0,e-je(s));return s+" ".repeat(n)}function te(t,e="white",s={}){return{text:String(t||""),color:e,...s}}function Ae(t){const e=Number(t);if(!Number.isFinite(e)||e<0)return"?";if(e<1024)return`${Math.round(e)} B`;if(e<1024*1024){const n=e/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=e/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function no(t,e){const s=Number(t),n=Number(e);if(!Number.isFinite(s)||!Number.isFinite(n)||s<=0||n<=0)return null;const i=s/n;return`${i>=10?i.toFixed(0):i.toFixed(1)}×`}function Fl(t,e=18){const s=String(t||"").replace(/\s+/g," ").trim();return s?je(s)>e?`${Array.from(s).slice(0,Math.max(1,e-1)).join("")}…`:s:""}function yf(t){const e=t?.data;if(typeof e=="string")return e;if(e&&typeof e=="object"){if(typeof e.content=="string")return e.content;if(typeof e.text=="string")return e.text;if(typeof e.message=="string")return e.message;if(typeof e.question=="string")return e.question}return""}function Dl(t=[]){const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();if(!i)continue;const r=i.toLowerCase();e.has(r)||(e.add(r),s.push(i))}return s.join(" | ")}function Sf(t,e=""){return Dl([t?.data?.reason==="cron_at"?"cron":t?.data?.reason,t?.data?.detail,t?.data?.message,t?.data?.error,e])}function bf(t,e=""){return Dl([t?.data?.message,t?.data?.detail,t?.data?.error,e])}function bs(t){const e=String(t||"").trim();if(!e||e==="(unknown)")return null;const s=e.split(/[/:]/).pop()||e,n=s.length<=5?s:s.slice(-5);return n.replace(/^[^a-zA-Z0-9]+/,"")||n}const wf=300*1e3,vf="last 5m";function Yi(t){let e=0;for(const s of t.history.bySessionId.values())for(const n of s?.events||[]){const i=n?.createdAt instanceof Date?n.createdAt.getTime():new Date(n?.createdAt||0).getTime();Number.isFinite(i)&&(e=Math.max(e,i))}return(!Number.isFinite(e)||e<=0)&&(e=Date.now()),{startMs:e-wf,endMs:e,label:vf}}function Ef(t,e){if(!t||!e)return!1;const s=Number(t.createdAtMs||0);return Number.isFinite(s)?s>=e.startMs&&s<=e.endMs:!1}function Bl(t,e){if(!t||!e)return!1;const s=t?.createdAt instanceof Date?t.createdAt.getTime():new Date(t?.createdAt||0).getTime();return Number.isFinite(s)?s>=e.startMs&&s<=e.endMs:!1}const xf=new Set(["wait","timer","cron_start","cron_fire","cron_cancel","spawn","cmd_recv","cmd_done"]);function If(t){return xf.has(t)}function kf(t){const e=Na(t?.createdAt),s=bs(t?.workerNodeId),n=yf(t),i=Fl(n,20),r=t?.createdAt instanceof Date?t.createdAt.getTime():new Date(t?.createdAt||0).getTime(),o={time:e,createdAtMs:Number.isFinite(r)?r:0,nodeLabel:s,color:"white",detail:"",type:"other"};switch(t?.eventType){case"session.turn_started":return{...o,type:"turn_start",color:"gray",detail:`turn ${t?.data?.iteration??"?"}`};case"session.turn_completed":{const l=Number(t?.data?.turnIndex??t?.data?.iteration);return{...o,type:"turn_end",color:"gray",detail:`turn ${t?.data?.iteration??"?"} done`,...Number.isFinite(l)?{completedTurn:l}:{}}}case"user.message":return{...o,type:"user_msg",color:"white",detail:i?`>> ${i}`:">> user"};case"assistant.message":return{...o,type:"response",color:"green",detail:i?`< ${i}`:"< response"};case"system.message":return{...o,type:"system",color:"yellow",detail:i||"system"};case"session.wait_started":return{...o,type:"wait",color:"yellow",detail:`wait ${Dt(t?.data?.seconds??0)}`};case"session.wait_completed":return{...o,type:"timer",color:"yellow",detail:`${Dt(t?.data?.seconds??0)} up`};case"session.lossy_handoff":{const l=bf(t,i);return{...o,type:"dehydrate",color:"yellow",detail:l?`lossy ${l}`:"lossy handoff"}}case"session.dehydrated":return{...o,type:"dehydrate",color:"cyan",detail:`ZZ ${Sf(t,i)}`.trim()};case"session.rehydrated":case"session.hydrated":return{...o,type:"hydrate",color:"green",detail:"rehydrated"};case"session.agent_spawned":return{...o,type:"spawn",color:"cyan",detail:`spawn ${t?.data?.agentId||ge(t?.data?.childSessionId)||"agent"}`};case"session.cron_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${Dt(t?.data?.intervalSeconds??0)}`};case"session.cron_at_scheduled":case"session.cron_at_started":return{...o,type:"cron_start",color:"magenta",detail:`cron ${Ks(t?.data?.nextFireAtMs??t?.data?.nextFireAt)}`};case"session.cron_fired":return{...o,type:"cron_fire",color:"magenta",detail:"cron fired"};case"session.cron_at_fired":return{...o,type:"cron_fire",color:"magenta",detail:`cron fired ${Ks(t?.data?.scheduledAt)}`};case"session.cron_cancelled":case"session.cron_at_cancelled":return{...o,type:"cron_cancel",color:"magenta",detail:"cron off"};case"session.cron_at_completed":return{...o,type:"cron_cancel",color:"magenta",detail:"cron done"};case"session.command_received":return{...o,type:"cmd_recv",color:"magenta",detail:`/${t?.data?.cmd||"?"}`};case"session.command_completed":return{...o,type:"cmd_done",color:"magenta",detail:`/${t?.data?.cmd||"?"} ok`};case"session.compaction_start":return{...o,type:"compaction",color:"gray",detail:"compaction…"};case"session.compaction_complete":return{...o,type:"compaction",color:"gray",detail:"compacted"};case"session.error":return{...o,type:"error",color:"red",detail:i||"error"};default:return null}}function Hl(t=[]){const e=[];for(const s of t||[]){const n=kf(s);n&&e.push({...n,nodeLabel:If(n.type)?"orch":n.nodeLabel||"orch"})}return e}function Af(t=[]){const e=[];for(let s=0;s<t.length;s+=1){const n=t[s];if(n?.type!=="spawn"||n?.nodeLabel!=="orch"){e.push(n);continue}let i=1;for(;s+i<t.length;){const r=t[s+i];if(r?.type!=="spawn"||r?.nodeLabel!=="orch"||r?.time!==n.time)break;i+=1}if(i===1){e.push(n);continue}e.push({...n,detail:`spawn x${i}`}),s+=i-1}return e}function Cf(t){const e=String(t?.error||"").trim();if(!e)return null;const s=Li(t);if(!s)return null;const n=t?.updatedAt?Number(t.updatedAt):Date.now(),i=Number.isFinite(n)?n:Date.now();return{time:Na(i),createdAtMs:i,nodeLabel:"orch",color:s==="failed"?"red":"yellow",detail:`${s==="failed"?"ERR":"WARN"} ${Fl(e,20)||(s==="failed"?"error":"warning")}`,type:s==="failed"?"error":"warning"}}function Tf(t,e){const s=Cf(e);return!s||(t||[]).some(i=>!i||i.nodeLabel!=="orch"||i.detail!==s.detail?!1:Math.abs(Number(i.createdAtMs||0)-s.createdAtMs)<=6e4)?t:[...t||[],s]}function Nf(t,e,s){if(!Number.isFinite(e)||!Number.isFinite(s)||s<e)return[];const n=new Set;for(const i of t.history.bySessionId.values()){const r=Hl(i?.events||[]);for(const o of r){if(!o?.nodeLabel||o.nodeLabel==="orch")continue;const l=Number(o.createdAtMs||0);Number.isFinite(l)&&(l<e||l>s||n.add(o.nodeLabel))}}return Array.from(n).sort((i,r)=>i.localeCompare(r))}function Mf(t,e){const s=new Set;for(const n of t.history.bySessionId.values())for(const i of n?.events||[]){if(!Bl(i,e))continue;const r=bs(i?.workerNodeId);r&&s.add(r)}return Array.from(s).sort((n,i)=>n.localeCompare(i))}function Xi(t){const e=t.slice();for(;e.length>0;){const s=e[e.length-1],n=String(s.text??"").replace(/\s+$/,"");if(n===""){e.pop();continue}e[e.length-1]={...s,text:n};break}return e}function io(t){return Array.isArray(t?.runs)?t.runs.reduce((e,s)=>e+je(String(s.text??"")),0):Array.isArray(t)?t.reduce((e,s)=>e+je(String(s.text??"")),0):je(String(t?.text??""))}function Pf(t,e,s){const n=[{text:Kt("TIME",e),color:"white",bold:!0},{text:" ",color:null}];return t.forEach((i,r)=>{r>0&&n.push({text:" ",color:null}),n.push({text:Kt(i,s),color:"white",bold:!0})}),Xi(n)}function Rf(t,e,s,n=1/0){const i=`${"-".repeat(e)} ${t.map(()=>"─".repeat(s)).join(" ")}`;return te(Number.isFinite(n)?i.slice(0,Math.max(e,n)):i,"gray")}function _f(t,e,s){const n=t?.orchestration?.bySessionId?.[e?.sessionId]||null;let i="loading orchestration stats...";if(n)if(n.loading&&!n.stats)i="loading orchestration stats...";else if(!n.stats)i="orchestration stats unavailable";else{const r=n.stats,o=[],l=[];if(typeof r.orchestrationVersion=="string"&&r.orchestrationVersion&&(o.push(`v ${r.orchestrationVersion}`),l.push(`v${r.orchestrationVersion}`)),r.historyEventCount!=null&&(o.push(`hist ${Number(r.historyEventCount)||0} ev`),l.push(`h${Number(r.historyEventCount)||0}`)),r.historySizeBytes!=null){const c=Ae(r.historySizeBytes);o.push(c),l.push(c)}r.queuePendingCount!=null&&(o.push(`q ${Number(r.queuePendingCount)||0}`),l.push(`q${Number(r.queuePendingCount)||0}`)),r.kvUserKeyCount!=null&&(o.push(`kv ${Number(r.kvUserKeyCount)||0} keys`),l.push(`kv${Number(r.kvUserKeyCount)||0}`)),r.kvTotalValueBytes!=null&&o.push(Ae(r.kvTotalValueBytes)),i=s<=40?l.join(" · "):o.join(" | "),i||(i="orchestration stats unavailable")}return Ee({title:"Stats",body:i,width:Math.max(24,s),titleColor:"cyan",borderColor:"gray",fitToContent:!0}).slice(0,-1)}function Lf(t,e,s,n){const i=e.includes(t.nodeLabel)?t.nodeLabel:e.includes("…")?"…":e[e.length-1],r=[{text:Kt(t.time||"",s),color:"white"},{text:" ",color:null}];return e.forEach((o,l)=>{l>0&&r.push({text:" ",color:null}),o===i?r.push({text:Kt(t.detail||"",n),color:t.color||"white",bold:!!t.bold,underline:!!t.underline,...t.completedTurn!=null?{completedTurn:t.completedTurn}:{}}):r.push({text:Kt("│",n),color:"gray"})}),Xi(r)}const Of=new Set(["none","minimal","low","medium","high","xhigh","max"]);function $f(t){const e=String(t||"").trim();if(!e)return"unknown";const s=e.split(":").filter(Boolean);if(s.length===0)return"unknown";const n=String(s[s.length-1]).toLowerCase(),i=s.length>1&&Of.has(n)?s.length-2:s.length-1;return s[Math.max(0,i)]||s[0]||"unknown"}function ro(t){const e=Number(t||0);if(!Number.isFinite(e))return"?K";const s=e/1e3;return`${s.toFixed(Math.abs(s)>=10?1:2)}K`}function bt(t){return Number(t||0).toLocaleString("en-US")}function Ff(t){const e=new Map;for(const s of t||[]){if(s?.eventType!=="session.turn_completed")continue;const n=Number(s?.data?.turnIndex??s?.data?.iteration);Number.isFinite(n)&&e.set(n,s.data||{})}return e}function Df(t,{expanded:e,selected:s,maxWidth:n}){const i=e?"v":">",r=$f(t?.model),o=t?.durationMs!=null?`${(Number(t.durationMs)/1e3).toFixed(1)}s`:"n/a",l=`${i} Mod: ${r} tok ${ro(t?.tokensInput)}/${ro(t?.tokensOutput)} dur ${o}`,c=[];if(s?c.push(st(Kt(l,Math.max(18,n)))):c.push([{text:l,color:"magenta"}]),e){const u=[["model",t?.reasoningEffort?`${t?.model||"(unknown)"}:${t.reasoningEffort}`:t?.model||"(unknown)"],["duration",t?.durationMs!=null?`${bt(t.durationMs)} ms`:null],["tokens",`${bt(t?.tokensInput)} in / ${bt(t?.tokensOutput)} out`],["cache",`${bt(t?.tokensCacheRead)} read / ${bt(t?.tokensCacheWrite)} write`],["tools",`${bt(t?.toolCalls)} calls / ${bt(t?.toolErrors)} errors`],["names",Array.isArray(t?.toolNames)&&t.toolNames.length?t.toolNames.join(", "):null],["worker",t?.workerNodeId||null],["result",t?.resultType||null],["error",t?.errorMessage||null]].filter(([,p])=>p!=null&&p!=="");for(const[p,d]of u)c.push([{text:` ${p}: `,color:"gray"},{text:String(d),color:"white"}])}return c}function Bf(t,e,s,n={}){const i=!!n?.allowWideColumns,r=_f(t,e,s),o=t.history.bySessionId.get(e.sessionId),l=Tf(Af(Hl(o?.events||[])),e);if(l.length===0)return{stickyLines:r,lines:[te("No events yet - interact with this session to populate the sequence diagram.")]};const c=Yi(t),u=l.filter(F=>Ef(F,c)),p=(u.length>0?u:l).slice(-48),d=Nf(t,c.startMs,c.endMs),f=Array.from(new Set(p.map(F=>F.nodeLabel).filter(F=>F&&F!=="orch"))).sort((F,L)=>F.localeCompare(L)),h=d.length>0?d:f,m=Math.min(13,Math.max(8,...p.map(F=>je(String(F.time||""))))),g=Math.max(18,s),S=Math.max(1,Math.floor((g-m-1)/6));let y=["orch",...h];if(!i&&y.length>S){const F=Math.max(1,S-1);y=[...y.slice(0,F),"…"]}const v=Math.max(0,y.length-1),x=Math.max(4,Math.floor((g-m-1-v)/Math.max(1,y.length))),E=n?.sequenceExpansion||null,w=E?Ff(o?.events||[]):null,I=E?new Set((E.expandedTurns||[]).map(Number)):null,b=E&&E.selectedTurn!=null?Number(E.selectedTurn):null,M=[];for(const F of p)if(M.push(Lf(F,y,m,x)),E&&F.completedTurn!=null){const L=Number(F.completedTurn),G=w.get(L);if(G)for(const P of Df(G,{expanded:I.has(L),selected:b===L,maxWidth:g}))M.push(P)}const A=Pf(y,m,x),O=M.reduce((F,L)=>Math.max(F,io(L)),io(A));return{stickyLines:[...r,te(`Window: ${c.label}`,"gray"),A,Rf(y,m,x,O)],lines:M}}function Hf(t){const e=[],s=new Set;for(const n of t.sessions.flat||[])!n?.sessionId||s.has(n.sessionId)||(s.add(n.sessionId),e.push(n.sessionId));for(const n of Object.keys(t.sessions.byId||{}))s.has(n)||(s.add(n),e.push(n));return e}function jf(t,e=null){const s=t?.events||[];for(let n=s.length-1;n>=0;n-=1){if(e&&!Bl(s[n],e))continue;const i=bs(s[n]?.workerNodeId);if(i)return i}return null}function Gf(t){return!Number.isFinite(t)||t<0?null:t<6e4?`${Math.round(t/1e3)}s ago`:t<36e5?`${Math.round(t/6e4)}m ago`:`${Math.round(t/36e5)}h ago`}function Uf(t){if(!Number.isFinite(t)||t<0)return null;if(t<60)return`${Math.round(t)}s`;if(t<3600)return`${Math.floor(t/60)}m`;const e=Math.floor(t/3600);return e<48?`${e}h ${Math.floor(t%3600/60)}m`:`${Math.floor(e/24)}d ${e%24}h`}function zf(t,e,s){const n=t?.isSystem?Jt(t,e):t?.title||ge(t?.sessionId),i=t?.isSystem?"⚙ ":t?.serviceKind?"⚗ ":`${bl(t)||"."} `;return{sessionId:t?.sessionId||null,text:`${i}${n}`,color:t?.isSystem?"yellow":qt(t),bold:!!t?.isSystem,active:!!s}}function jl(t){const e=Yi(t),s=t.branding?.title||"PilotSwarm",n=t.sessions.activeSessionId,i=Array.isArray(t.admin?.workers?.list)?t.admin.workers.list:[],r=Date.now(),o=9e4,l=new Map;for(const h of i){const m=bs(h?.workerNodeId);if(!m)continue;const g=h?.updatedAt instanceof Date?h.updatedAt.getTime():new Date(h?.updatedAt??0).getTime(),S=Number.isFinite(g)?r-g:Number.NaN,y=h?.health||{};l.set(m,{label:m,workerNodeId:String(h?.workerNodeId??""),registered:!0,live:Number.isFinite(S)&&S<=o,phase:["starting","ready","draining"].includes(h?.phase)?h.phase:"ready",pool:String(h?.pool??"default"),agoText:Gf(S),uptimeText:Uf(y.uptimeS),rssText:Number.isFinite(y.rssBytes)?Ft(y.rssBytes):null,heapText:Number.isFinite(y.heapUsedBytes)?Ft(y.heapUsedBytes):null,eventLoopText:Number.isFinite(y.eventLoopDelayP99Ms)?`${y.eventLoopDelayP99Ms}ms`:null,sessions:Number.isFinite(y.activeSessions)?y.activeSessions:null,sdkVersion:typeof h?.info?.sdkVersion=="string"?h.info.sdkVersion:null,substrate:typeof h?.info?.runtime?.substrate=="string"?h.info.runtime.substrate:null,capabilities:h?.info?.capabilities&&typeof h.info.capabilities=="object"?Object.entries(h.info.capabilities).filter(([,v])=>!!v).map(([v])=>v).sort():[],consumes:Array.isArray(h?.info?.consumes)?h.info.consumes:[],owner:h?.owner?.subject?String(h.owner.subject):null,pkgEpoch:Number.isFinite(h?.state?.["agent-packages"]?.epoch)?h.state["agent-packages"].epoch:null,pkgInstalled:h?.state?.["agent-packages"]?.installed&&typeof h.state["agent-packages"].installed=="object"?Object.entries(h.state["agent-packages"].installed).map(([v,x])=>({name:v,semver:x?.semver??null,status:x?.status==="error"?"error":"ok",error:x?.error?String(x.error):null})):[],pkgLastError:h?.state?.["agent-packages"]?.lastError?String(h.state["agent-packages"].lastError):null,executing:[]})}for(const h of Mf(t,e))l.has(h)||l.set(h,{label:h,workerNodeId:null,registered:!1,live:!0,phase:null,pool:null,agoText:null,uptimeText:null,rssText:null,heapText:null,eventLoopText:null,sessions:null,sdkVersion:null,substrate:null,capabilities:[],consumes:[],owner:null,pkgEpoch:null,pkgInstalled:[],pkgLastError:null,executing:[]});let c=0;for(const h of Hf(t)){const m=t.sessions.byId[h];if(!m)continue;const g=t.history.bySessionId.get(h);g?.events||(c+=1);const S=jf(g,e),y=S?l.get(S):null;y&&y.executing.push(zf(m,s,h===n))}const u=Array.from(l.values()).sort((h,m)=>{if(h.registered!==m.registered)return h.registered?-1:1;if(h.live!==m.live)return h.live?-1:1;const g=String(h.pool??"~").localeCompare(String(m.pool??"~"));return g!==0?g:h.label.localeCompare(m.label)});u.forEach((h,m)=>{h.ordinal=m+1});const p=u.filter(h=>h.registered),d=t.ui?.nodeMapSelectedNode,f=d&&u.some(h=>h.label===d)?d:u[0]?.label??null;return{windowLabel:e.label,degraded:p.length===0,registryError:t.admin?.workers?.error||null,registryFetchedAt:t.admin?.workers?.fetchedAt||0,registryLoading:!!t.admin?.workers?.loading,registryAttempts:t.admin?.workers?.attempts||0,registryLastAttemptAt:t.admin?.workers?.lastAttemptAt||0,registryLastSkip:t.admin?.workers?.lastSkip||null,registered:p.length,liveCount:p.filter(h=>h.live).length,executingTotal:u.reduce((h,m)=>h+m.executing.length,0),missingHistoryCount:c,selected:f,nodes:u}}function Wf(t,e,s={}){const n=jl(t);if(n.nodes.length===0)return[te(n.degraded?`No workers registered and no worker activity in the ${n.windowLabel} window.`:`No worker activity in the ${n.windowLabel} window.`,"gray")];const i=[];if(i.push([{text:n.degraded?`Nodes (activity-derived) · window ${n.windowLabel}`:`Nodes · ${n.liveCount} live / ${n.registered} registered · window ${n.windowLabel}`,color:"gray"}]),n.degraded)if(n.registryError)i.push([{text:`! worker registry unavailable: ${n.registryError}`,color:"red"}]);else if(n.registryFetchedAt)i.push([{text:"registry reachable but EMPTY — no worker has heartbeated in the last hour",color:"yellow"}]);else if(n.registryLoading)i.push([{text:"registry request in flight… (times out red after 10s)",color:"yellow"}]);else if(n.registryAttempts===0)i.push([{text:"registry refresh has NEVER been attempted in this tab — reload; if it persists the refresh call is not reaching the controller",color:"red"}]);else{const r=n.registryLastAttemptAt?Math.round((Date.now()-n.registryLastAttemptAt)/1e3):null;i.push([{text:`registry attempted ${n.registryAttempts}× (last ${r===null?"?":`${r}s`} ago${n.registryLastSkip?`, skipped: ${n.registryLastSkip}`:""}) but no rows and no error — reload if this persists`,color:"yellow"}])}i.push(te("","gray"));for(const r of n.nodes){const o=r.label===n.selected,l=r.live?"●":"○",c=r.live?r.phase==="draining"?"red":r.phase==="starting"?"yellow":"green":"gray",u=[{text:o?"› ":" ",color:"green",bold:o,nodeSelect:r.label,nodeSelected:o},{text:r.ordinal<=9?`${r.ordinal} `:" ",color:"gray",nodeSelect:r.label},{text:`${l} `,color:c,nodeSelect:r.label},{text:r.label.padEnd(7),color:o||r.live?"white":"gray",bold:o,nodeSelect:r.label}];if(r.registered){u.push({text:` ${(r.phase||"").padEnd(8)}`,color:c,nodeSelect:r.label}),u.push({text:` ${r.pool}`,color:"gray",nodeSelect:r.label});const p=[r.executing.length?`${r.executing.length} sess`:null,r.rssText,r.uptimeText?`up ${r.uptimeText}`:null,r.agoText].filter(Boolean).join(" · ");p&&u.push({text:` ${p}`,color:"gray",nodeSelect:r.label})}else u.push({text:" activity only",color:"gray",nodeSelect:r.label}),r.executing.length&&u.push({text:` · ${r.executing.length} sess`,color:"gray",nodeSelect:r.label});i.push(Xi(u))}return i.push(te("","gray")),i.push(te("Click a node (or press 1-9) — its details fill the pane below.","gray")),n.missingHistoryCount>0&&i.push(te(`Loading worker history for ${n.missingHistoryCount} session(s)…`,"gray")),i}function qf(t,e=72){const s=t.ui.modal;if(!s||s.type!=="modelPicker")return null;const n=Array.isArray(s.groups)?s.groups:[],i=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(24,e-4),o=[],l=[];let c=0;for(const h of n){const m=fe([{text:`${h.providerId}`,color:"cyan",bold:!0},{text:` (${h.providerType||"provider"})`,color:"gray"}],r);o.push(m),l.push(null);for(const g of h.models||[]){const S=Array.isArray(s.items)?s.items.findIndex(w=>w.id===g.id):-1,y=S===i,v=!!g.disabled,x=fe([{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"}]:[]],r),E=y?st(x.map(w=>w.text).join("").padEnd(r," ")):x;y&&(c=o.length),o.push(E),l.push(S>=0?S:null)}}const u=Array.isArray(s.items)&&s.items[i]||null,p=Array.isArray(u?.supportedReasoningEfforts)?u.supportedReasoningEfforts.filter(Boolean):[],d=typeof u?.defaultReasoningEffort=="string"?u.defaultReasoningEffort:null,f=u?[[{text:u.modelName||u.qualifiedName||u.id,color:"white",bold:!0}],[{text:`${u.providerId} (${u.providerType||"provider"})`,color:"gray"}],...u.cost?[[{text:`Cost: ${u.cost}`,color:"gray"}]]:[],...p.length>0?[[{text:`Reasoning: ${p.join(", ")}`,color:"gray"}]]:[],...d?[[{text:`Default reasoning: ${d}`,color:"gray"}]]:[],...u.disabled?[[{text:"Unavailable: requires a GitHub Copilot key. Add yours in the Admin console, then reopen this picker.",color:"yellow"}]]:[],[{text:"",color:"gray"}],[{text:u.description||"No description available for this model.",color:u.description?"white":"gray"}]]:[[{text:"No model selected.",color:"gray"}]];return{title:s.title||"Select model for new session",rows:o,rowItemIndexes:l,selectedRowIndex:c,detailsTitle:"Model Details",detailsLines:f,idealWidth:Math.min(Math.max(46,o.reduce((h,m)=>Array.isArray(m)?Math.max(h,Nt(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function Kf(t,e=76){const s=t.ui.modal;if(!s||s.type!=="sessionAgentPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(24,e-4),o=[],l=[];n.forEach((h,m)=>{const g=m===i,S=" ".repeat(Math.max(0,Number(h?.depth)||0)*2);let y;if(h?.kind==="section"){const v=h.collapsed?"▸":"▾",x=h.sectionKind==="package"&&h.packageScope==="user"&&!h.mine?" [private]":"";y=fe([{text:`${S}${v} `,color:"cyan"},{text:h.title||"Section",color:"white",bold:!0},...x?[{text:x,color:"cyan"}]:[],...h.meta?[{text:` · ${h.meta}`,color:"gray"}]:[]],r)}else{const v=h?.kind==="generic"||h?.supportsDirectStart!==!1,x=h?.kind==="generic"?"○ ":(h?.depth||0)>0&&h?.parentAgentName?"└ ":"★ ";y=fe([{text:`${S}${x}`,color:v?"yellow":"gray"},{text:h?.title||h?.agentName||h?.id||"Agent",color:v?"white":"gray",bold:v}],r)}o.push(g?st(y.map(v=>v.text).join("").padEnd(r," ")):y),l.push(m)});const c=n[i]||null,u=s.sessionOptions?.model||null,p=s.sessionOptions?.reasoningEffort||null,d=c?.kind==="section"?[[{text:c.title||"Section",color:"white",bold:!0}],...c.sectionKind==="package"?[[{text:`${c.packageName||"package"}@${c.packageSemver||"?"}`,color:"gray"}],...c.ownerLabel?[[{text:`Published by ${c.ownerLabel}`,color:"gray"}]]:[]]:[[{text:c.sectionKind==="builtin"?"Agents baked into this deployment.":"Agent packages installed on this deployment.",color:"gray"}]],[{text:"",color:"gray"}],[{text:c.meta||"",color:"gray"}],[{text:"",color:"gray"}],[{text:c.collapsed?"Enter or → to open.":"Enter or ← to close.",color:"gray"}]]:c?[[{text:c.title||c.agentName||c.id||"Agent",color:"white",bold:!0}],...c.kind==="generic"?[[{text:"Open-ended session",color:"gray"}]]:[[{text:c.agentName||c.id||"agent",color:"gray"}]],...c.packageName?[[{text:`Package: ${c.packageName}@${c.packageSemver||"?"} · ${c.packageScope||"shared"}`,color:"gray"}]]:c.kind==="agent"?[[{text:"Built-in agent",color:"gray"}]]:[],...c.startedBy?.length?[[{text:`Started by: ${c.startedBy.join(", ")}`,color:"gray"}]]:[],...c.kind!=="generic"&&c.supportsDirectStart===!1?[[{text:"Cannot be started on its own",color:"yellow"}]]:[],...u?[[{text:`Model: ${u}`,color:"gray"}]]:[],...p?[[{text:`Reasoning: ${p}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:c.description||(c.kind==="generic"?"Create a general-purpose session without a specialized named agent.":"No description available for this agent."),color:c.description?"white":"gray"}],[{text:"",color:"gray"}],[{text:c.tools?.length?`Tools: ${c.tools.join(", ")}`:"Tools: system defaults only",color:"gray"}]]:[[{text:"No agent selected.",color:"gray"}]],f=l.indexOf(i);return{title:s.title||"Select agent for new session",rows:o,rowItemIndexes:l,selectedRowIndex:f>=0?f:0,detailsTitle:"Agent Details",detailsLines:d,idealWidth:Math.min(Math.max(52,o.reduce((h,m)=>Array.isArray(m)?Math.max(h,Nt(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function Vf(t,e=64){const s=t.ui.modal;if(!s||s.type!=="reasoningEffortPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(24,e-4),o=n.map((p,d)=>{const f=d===i,h=fe([{text:"· ",color:"gray"},{text:String(p?.label||p?.id||"effort"),color:"white",bold:!0},...p?.isDefault?[{text:" ← model default",color:"gray"}]:[]],r);return f?st(h.map(m=>m.text).join("").padEnd(r," ")):h}),l=n[i]||null,c=s.modelItem||null,u=[[{text:c?.modelName||c?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${c?.providerId||"provider"} (${c?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:l?.id?`Using reasoning effort: ${l.id}`:"Choose an effort.",color:"white"}]];return{title:s.title||"Select reasoning effort",rows:o,selectedRowIndex:i,detailsTitle:"Reasoning Details",detailsLines:u,idealWidth:Math.min(Math.max(46,o.reduce((p,d)=>Array.isArray(d)?Math.max(p,Nt(d)):Math.max(p,String(d?.text||"").length),0)+4),e)}}function Yf(t,e=64){const s=t.ui.modal;if(!s||s.type!=="contextTierPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(24,e-4),o=n.map((d,f)=>{const h=f===i,m=fe([{text:"· ",color:"gray"},{text:String(d?.label||d?.id||"tier"),color:"white",bold:!0},...d?.isDefault?[{text:" ← model default",color:"gray"}]:[]],r);return h?st(m.map(g=>g.text).join("").padEnd(r," ")):m}),l=n[i]||null,c=s.modelItem||null,u=l?.label||l?.id,p=[[{text:c?.modelName||c?.qualifiedName||"Selected model",color:"white",bold:!0}],[{text:`${c?.providerId||"provider"} (${c?.providerType||"provider"})`,color:"gray"}],[{text:"",color:"gray"}],[{text:u?`Using context window: ${u}`:"Choose a context window.",color:"white"}],[{text:"Long context costs more per token.",color:"gray"}]];return{title:s.title||"Select context window",rows:o,selectedRowIndex:i,detailsTitle:"Context Window",detailsLines:p,idealWidth:Math.min(Math.max(46,o.reduce((d,f)=>Array.isArray(f)?Math.max(d,Nt(f)):Math.max(d,String(f?.text||"").length),0)+4),e)}}function Xf(t,e=72){const s=t.ui.modal;if(!s||s.type!=="sessionGroupPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(24,e-4),o=Array.isArray(s.sessionIds)?s.sessionIds.length:0,l=n.map((p,d)=>{const f=d===i,h=p?.kind==="noGroup"?"○ ":p?.kind==="newGroup"?"+ ":"🗂 ",m=fe([{text:h,color:p?.kind==="group"?"cyan":"gray",bold:p?.kind!=="noGroup"},{text:p?.label||p?.groupId||"Group",color:"white",bold:!0},...p?.kind==="group"?[{text:` (${p.memberCount??0})`,color:"gray"}]:[]],r);return f?st(m.map(g=>g.text).join("").padEnd(r," ")):m}),c=n[i]||null,u=c?[[{text:c.label||c.groupId||"Group",color:"white",bold:!0}],[{text:`${o} session${o===1?"":"s"} selected`,color:"gray"}],...c.kind==="group"?[[{text:`${c.memberCount??0} current member${c.memberCount===1?"":"s"}`,color:"gray"}]]:[],[{text:"",color:"gray"}],[{text:c.description||"Move selected session(s) to this group.",color:"white"}]]:[[{text:"No group selected.",color:"gray"}]];return{title:s.title||"Move to Group",rows:l,selectedRowIndex:i,detailsTitle:"Move Details",detailsLines:u,idealWidth:Math.min(Math.max(50,l.reduce((p,d)=>Array.isArray(d)?Math.max(p,Nt(d)):Math.max(p,String(d?.text||"").length),0)+4),e)}}function Qf(t,e=76){const s=t.ui.modal;if(!s||s.type!=="renameSession")return null;const n=String(s.value||""),i=typeof s.agentTitlePrefix=="string"&&s.agentTitlePrefix.trim()?s.agentTitlePrefix.trim():null,r=String(s.currentTitle||"").trim(),o=n.trim()?i?`${i}: ${n.trim()}`:n.trim():i?`${i}: …`:"…",l=[[{text:"Current: ",color:"gray"},{text:r||"(untitled session)",color:r?"white":"gray"}],[{text:"Saved as: ",color:"gray"},{text:o,color:"white",bold:!0}],...i?[[{text:"Named-agent prefix stays fixed.",color:"gray"}]]:[]];return{title:s.title||"Rename Session",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:i?"Type the title after the fixed agent name":"Type a session title",helpTitle:"Rename Rules",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" save ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],...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,je(r||"(untitled session)")+18,je(o)+18),e)}}function Zf(t,e=76){const s=t.ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=String(s.value||""),i=Array.isArray(s.sessionIds)?s.sessionIds.length:0,r=n.trim()||"…",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 ${i} selected session${i===1?"":"s"}.`,color:"gray"}]],detailsLines:[[{text:o?"Rename to: ":"New group: ",color:"gray"},{text:r,color:"white",bold:!0}],[{text:"Groups are containers only; session actions remain per-session.",color:"gray"}]],idealWidth:Math.min(Math.max(56,je(r)+18),e)}}function Jf(t,e=82){const s=t.ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=String(s.value||""),i=s.sessionId||t.ui.promptAttachments?.[0]?.sessionId||t.sessions?.activeSessionId||null,r=i&&t.sessions?.byId?.[i]||null,o=i?r?El(r,t.branding?.title):ge(i):"A new session will be created on upload",l=[[{text:"Target: ",color:"gray"},{text:o,color:i?"white":"gray",bold:!!i}]];return{title:s.title||"Upload Artifact",value:n,cursorIndex:Math.max(0,Math.min(Number(s.cursorIndex)||0,n.length)),placeholder:"~/path/to/file.md",helpTitle:"Upload Rules",helpLines:[[{text:"Enter",color:"cyan",bold:!0},{text:" upload ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],[{text:"",color:"gray"}],[{text:"The file is uploaded into this session's artifact store immediately.",color:"gray"}],[{text:"Use the files browser or @-driven browsing in the prompt to reference it after upload.",color:"gray"}]],detailsLines:l,idealWidth:Math.min(Math.max(60,je(n||"~/path/to/file.md")+20,je(o)+20),e)}}function Qi(t,e={},s=96,n="Filters",i="Choose how this pane is filtered and rendered."){const r=Array.isArray(t.items)?t.items:[],o=Math.max(0,Number(t.selectedIndex)||0),l=r[o]||null,c=r.map((u,p)=>{const d=e?.[u.id]||u.options?.[0]?.id,f=(u.options||[]).map(h=>h.id===d?st(h.label):{text:h.label,color:"white"});return{id:u.id,title:u.label,focused:p===o,description:u.description||"",lines:f.length>0?f:[{text:"No options available.",color:"gray"}],idealWidth:Math.max(20,String(u.label||"").length+4,...(u.options||[]).map(h=>String(h?.label||"").length+4))}});return{title:t.title||n,panes:c,helpTitle:l?.label||n,helpLines:[[{text:l?.description||i,color:"white"}],[{text:"",color:"gray"}],[{text:"Tab/Shift-Tab",color:"cyan",bold:!0},{text:" switch filter ",color:"gray"},{text:"Up/Down",color:"cyan",bold:!0},{text:" change value ",color:"gray"},{text:"Enter",color:"cyan",bold:!0},{text:" close ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}]],footerRuns:[{text:"Tab/Shift-Tab",color:"cyan",bold:!0},{text:" switch filter · ",color:"gray"},{text:"Up/Down",color:"cyan",bold:!0},{text:" change value · ",color:"gray"},{text:"Enter",color:"cyan",bold:!0},{text:" close · ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" cancel",color:"gray"}],idealWidth:Math.min(Math.max(72,c.reduce((u,p)=>u+p.idealWidth,0)+Math.max(0,c.length-1)*2+4),s)}}function Gl(t,e={},s={}){return t?t.kind==="all"?e?.all===!0:e?.all===!0?!1:t.kind==="system"?e?.includeSystem===!0:t.kind==="unowned"?e?.includeUnowned===!0:t.kind==="me"?e?.includeMe===!0&&!!we(s?.principal):t.kind==="shared"?e?.includeShared===!0:t.kind==="owner"?Array.isArray(e?.ownerKeys)&&e.ownerKeys.includes(t.ownerKey):!1:!1}function oo(t=[],e={},s={}){if(e?.all===!0)return"All sessions";const n=t.filter(i=>i?.kind!=="all"&&Gl(i,e,s)).map(i=>i.kind==="me"?"Me":i.label);return n.length>0?n.join(" + "):"All sessions"}function eh(t,e=88){const s=t.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return null;const n=Array.isArray(s.items)?s.items:[],i=t.sessions?.ownerFilter||{all:!0},r=t.auth||{},o=Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1))),l=n[o]||null,c=n.map((p,d)=>{const f=Gl(p,i,r),h=p.kind==="system"?"yellow":p.kind==="unowned"?"gray":p.kind==="all"?"cyan":"white",m=[{text:f?"[x] ":"[ ] ",color:f?"cyan":"gray",bold:f},{text:p.label||p.id,color:h,bold:f}];return d===o?pl(m,{preserveColors:!0}):m}),u=[[{text:"Active: ",color:"gray"},{text:oo(n,i,r),color:"white",bold:!0}],[{text:"",color:"gray"}],[{text:l?.description||"Toggle which session owners appear in the session list.",color:"white"}],[{text:"",color:"gray"}],[{text:"Space",color:"cyan",bold:!0},{text:" toggle ",color:"gray"},{text:"Esc",color:"cyan",bold:!0},{text:" close",color:"gray"}]];return{title:s.title||"Session Filter",rows:c.length>0?c:[{text:"No filter entries available.",color:"gray"}],selectedRowIndex:o,detailsTitle:l?.label||"Session Filter",detailsLines:u,idealWidth:Math.min(Math.max(48,c.reduce((p,d)=>Math.max(p,Array.isArray(d)?Nt(d):je(d?.text||"")),0)+8,je(oo(n,i,r))+16),e)}}function th(t,e=96){const s=t.ui.modal;return!s||s.type!=="logFilter"?null:Qi(s,t.logs?.filter||{},e,"Log Filters","Choose how the log pane is filtered and rendered.")}function sh(t,e=88){const s=t.ui.modal;return!s||s.type!=="filesFilter"?null:Qi(s,t.files?.filter||{},e,"Files Filter","Choose whether the files browser shows the selected session tree or aggregates artifacts across all sessions.")}function nh(t,e=88){const s=t.ui.modal;if(!s||s.type!=="artifactPicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),r=Math.max(28,e-4),o=n.filter(h=>h.kind==="artifact"),l=n.filter(h=>h.kind==="url"),c=o.reduce((h,m)=>{const g=t.files?.bySessionId?.[m.sessionId]?.downloads?.[m.filename];return h+(g?.localPath?1:0)},0),u=Math.max(0,o.length-c),p=n.map((h,m)=>{let g;if(h.kind==="downloadAll")g=fe([{text:"dl ",color:"cyan",bold:!0},{text:"Download All",color:"white",bold:!0},{text:` [${u} pending]`,color:"gray"}],r);else if(h.kind==="url")g=fe([{text:"go ",color:"cyan",bold:!0},{text:h.text&&h.text!==h.href?h.text:h.href,color:"white",bold:!0},...h.text&&h.text!==h.href?[{text:` ${h.href}`,color:"gray"}]:[]],r);else{const S=t.files?.bySessionId?.[h.sessionId]?.downloads?.[h.filename];g=fe([{text:S?.localPath?"ok ":"dl ",color:S?.localPath?"green":"cyan",bold:!0},{text:`${ge(h.sessionId)}/`,color:"gray"},{text:h.filename,color:"white"}],r)}return m!==i?g:st(g.map(S=>S.text).join("").padEnd(r," "))}),d=n[i]||null;let f=[[{text:"No linked item selected.",color:"gray"}]];if(d?.kind==="downloadAll")f=[[{text:`${o.length} artifacts available`,color:"white",bold:!0}],...l.length>0?[[{text:`${l.length} links available`,color:"gray"}]]:[],[{text:`${c} already downloaded`,color:"gray"}],[{text:`${u} pending download`,color:"gray"}],...s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:"Press Enter to download all pending artifacts.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(d?.kind==="url")f=[[{text:d.text||d.href,color:"white",bold:!0}],[{text:d.href,color:"gray"}],[{text:"",color:"gray"}],[{text:"Press Enter to open this link in the browser.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]];else if(d?.kind==="artifact"){const h=t.sessions?.byId?.[d.sessionId]||null,m=t.files?.bySessionId?.[d.sessionId]?.downloads?.[d.filename]||null;f=[[{text:d.filename,color:"white",bold:!0}],[{text:h?El(h,t.branding?.title):ge(d.sessionId),color:"gray"}],...m?.localPath?[[{text:`Saved to: ${m.localPath}`,color:"white"}]]:s.exportDirectory?[[{text:`Save location: ${s.exportDirectory}`,color:"white"}]]:[],[{text:"",color:"gray"}],[{text:m?.localPath?"Press Enter to download this artifact again.":"Press Enter to download this artifact.",color:"white"}],[{text:"Press a or Esc to close the picker.",color:"gray"}]]}return{title:s.title||"Linked Items",rows:p.length>0?p:[{text:"No linked items available.",color:"gray"}],selectedRowIndex:i,detailsTitle:"Linked Item Details",detailsLines:f,confirmLabel:l.length>0?o.length>0?"Open / Download":"Open":"Download",idealWidth:Math.min(Math.max(54,p.reduce((h,m)=>Array.isArray(m)?Math.max(h,Nt(m)):Math.max(h,String(m?.text||"").length),0)+4),e)}}function ee(t){return t==null||!Number.isFinite(t)?"0":t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e4?`${(t/1e3).toFixed(1)}K`:t>=1e3?t.toLocaleString("en-US"):String(t)}function Zi(t){if(!t)return"—";const e=Date.now()-t;return e<6e4?`${Math.max(1,Math.floor(e/1e3))}s ago`:e<36e5?`${Math.floor(e/6e4)}m ago`:e<864e5?`${Math.floor(e/36e5)}h ago`:`${Math.floor(e/864e5)}d ago`}function ih(t){if(!t)return"—";const e=Date.now()-t;if(e<6e4)return"<1min";const s=Math.floor(e/6e4);if(s<60)return`${s}min`;const n=Math.floor(s/60);if(n<24)return`${n}h${String(s%60).padStart(2,"0")}m`;const i=Math.floor(n/24);return i<14?`${i}d${String(n%24).padStart(2,"0")}h`:`${Math.floor(i/7)}w`}function ao(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"—";const s=e.toLocaleDateString(void 0,{month:"short",day:"numeric"}),n=e.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",second:"2-digit"});return`${s}, ${n}`}function lo(t){if(!t)return"—";const e=t instanceof Date?t:new Date(t);return Number.isNaN(e.getTime())?"—":e.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",second:"2-digit",timeZoneName:"short"})}function fs(t){return["session","fleet","users"].includes(t)?t:"session"}function un(t,e){const s=fs(t),n=[{text:"View ",color:"cyan",bold:!0}];for(const i of["session","fleet","users"])n.push({text:i===s?`[${i}]`:i,color:i===s?"magenta":"gray",bold:i===s}),n.push({text:" ",color:"gray"});return n.push({text:" [f cycle]",color:"gray"}),fe(n,e)}function rh(t,e,s){if(!e)return[te("No session selected.")];const n=t.sessionStats?.bySessionId?.[e.sessionId]||null;if(!n||n.loading&&!n.summary)return[te("Loading session stats...")];const i=n.summary;if(!i)return[te("Session stats unavailable.")];const r=[],o=Math.max(24,s);r.push(un("session",o)),r.push(te("")),r.push(fe([{text:"Session ",color:"cyan",bold:!0},{text:ge(e.sessionId),color:"white"}],o));const l=e.isSystem?"system":e.owner?"user":"unowned",c=e.isSystem?"system":e.owner?cn(e.owner):"(?) unowned",u=e.owner?.email||"—";r.push(fe([{text:"Owner ",color:"cyan",bold:!0},{text:c,color:e.owner?"white":"gray"}],o)),r.push(fe([{text:"Email ",color:"cyan",bold:!0},{text:u,color:e.owner?.email?"white":"gray"}],o)),r.push(fe([{text:"Type ",color:"cyan",bold:!0},{text:l,color:l==="user"?"white":"gray"}],o)),i.agentId&&r.push(fe([{text:"Agent ",color:"cyan",bold:!0},{text:i.agentId,color:"white"}],o));const p=qi(i.model||e.model,i.reasoningEffort||e.reasoningEffort);p&&r.push(fe([{text:"Model ",color:"cyan",bold:!0},{text:p,color:"white"}],o)),e.createdAt&&r.push(fe([{text:"Created ",color:"cyan",bold:!0},{text:lo(e.createdAt),color:"white"}],o)),e.updatedAt&&r.push(fe([{text:"Updated ",color:"cyan",bold:!0},{text:lo(e.updatedAt),color:"white"}],o)),r.push(te(""));const d=Array.isArray(n.tokensByModel)?n.tokensByModel:[];d.length>1&&(r.push(...Ee({title:"Models",body:d.map(F=>`${tf(F.model)} · ${F.turnCount||0} turns · ${ee(F.totalTokensInput)} in / ${ee(F.totalTokensOutput)} out`).join(`
49
+ `),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),r.push(te("")));const f=(i.tokensInput||0)+(i.tokensOutput||0),h=i.cacheHitRatio,m=h==null?"—":`${(h*100).toFixed(1)}%`;r.push(...Ee({title:"Tokens",body:At([["Input",ee(i.tokensInput)],["Output",ee(i.tokensOutput)],["Total",ee(f)],["Cache Read",ee(i.tokensCacheRead)],["Cache Write",ee(i.tokensCacheWrite)],["Hit Ratio",m]],{maxWidth:Math.max(12,o-4)}),width:o,titleColor:"green",borderColor:"gray",fitToContent:!0})),r.push(te(""));const g=Number(i.regenCount)||0,S=i.lastRegenStats&&typeof i.lastRegenStats=="object"?i.lastRegenStats:null,y=Number.isFinite(S?.toEpoch)?S.toEpoch:g,v=S?S.distillMode==="deterministic"||!S.distillMode&&!S.distillerModel?"fast":String(S.distillerModel||"llm").replace(/^[^:]*:/,""):null,x=S?`${S.turnsArchived??0} turn${S.turnsArchived===1?"":"s"} · ${(Number(S.totalMs)/1e3).toFixed(1)}s${v?` · ${v}`:""}`:null;r.push(...Ee({title:"Persistence",body:At([["Epoch",String(y)],["Regens",g>0?String(g):null],["Last Regen",x],["Snapshot",Ae(i.snapshotSizeBytes)],["Uncompressed",i.rawSizeBytes?Ae(i.rawSizeBytes):null],["Compression",no(i.rawSizeBytes,i.snapshotSizeBytes)],["Dehydrations",String(i.dehydrationCount)],["Hydrations",String(i.hydrationCount)],["Lossy Handoffs",String(i.lossyHandoffCount)],["Last Dehydrated",i.lastDehydratedAt?ao(i.lastDehydratedAt):null],["Last Hydrated",i.lastHydratedAt?ao(i.lastHydratedAt):null]],{maxWidth:Math.max(12,o-4)}),width:o,titleColor:"yellow",borderColor:"gray",fitToContent:!0}));const E=n.treeStats?.tree;if(E&&E.sessionCount>1){const F=E.cacheHitRatio,L=F==null?"—":`${(F*100).toFixed(1)}%`,G=(E.totalTokensInput||0)+(E.totalTokensOutput||0);r.push(te("")),r.push(...Ee({title:`Tree (${E.sessionCount} sessions)`,body:At([["Input",ee(E.totalTokensInput)],["Output",ee(E.totalTokensOutput)],["Total",ee(G)],["Cache Read",ee(E.totalTokensCacheRead)],["Cache Write",ee(E.totalTokensCacheWrite)],["Hit Ratio",L],["Snapshot",Ae(E.totalSnapshotSizeBytes)],["Uncompressed",E.totalRawSizeBytes?Ae(E.totalRawSizeBytes):null],["Compression",no(E.totalRawSizeBytes,E.totalSnapshotSizeBytes)],["Dehydrations",String(E.totalDehydrationCount)],["Hydrations",String(E.totalHydrationCount)]]),width:o,titleColor:"magenta",borderColor:"gray",fitToContent:!0}));const P=Array.isArray(n.treeStats?.byModel)?n.treeStats.byModel:[];P.length>1&&(r.push(te("")),r.push(...Ee({title:"Tree By Model",body:dh(P),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})))}const w=Array.isArray(n.skillUsage)?n.skillUsage:[];w.length>0&&(r.push(te("")),r.push(...Ee({title:`Skills (${w.length})`,body:co(w,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const I=n.treeSkillUsage,b=Array.isArray(I?.rolledUp)?I.rolledUp:[],M=Array.isArray(I?.perSession)?I.perSession.length:0;b.length>0&&M>1&&(r.push(te("")),r.push(...Ee({title:`Tree Skills (${b.length})`,body:co(b,o),width:o,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const A=n.factsStats,O=n.treeFactsStats;if(A&&Array.isArray(A.rows)&&A.rows.length>0){r.push(te(""));const F=Ul(A.rows),L=F?F.split(`
50
+ `).length:0,G=`${A.totalCount} · ${Ae(A.totalBytes)}`;let P=F;O&&O.totalCount>A.totalCount&&(P+=`
51
+ Tree (${O.sessionIds.length} sessions): ${O.totalCount} · ${Ae(O.totalBytes)}`),L>0&&r.push(...Ee({title:`Facts (${G})`,body:P,width:o,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}return r}function At(t,e={}){const s=e.gap??2,n=(t||[]).filter(u=>Array.isArray(u)&&u[1]!=null&&u[1]!=="");if(n.length===0)return"";const i=n.reduce((u,[p])=>Math.max(u,String(p).length),0),r=n.reduce((u,[,p])=>Math.max(u,String(p).length),0),o=" ".repeat(s),l=Number(e.maxWidth),c=!Number.isFinite(l)||i+s+r<=l;return n.map(([u,p])=>c?`${String(u).padEnd(i)}${o}${String(p).padStart(r)}`:`${String(u).padEnd(i)}${o}${String(p)}`).join(`
52
+ `)}function dn(t,e){const s=String(t??"");if(!Number.isFinite(e)||e<=0)return s;const n=Math.floor(e);return s.length<=n?s:n<=1?s.slice(0,n):`${s.slice(0,n-1)}…`}function ws(t,e={}){const s=e.gap??2,n=(t||[]).filter(l=>Array.isArray(l)&&l.length>0);if(n.length===0)return"";const i=n.reduce((l,c)=>Math.max(l,c.length),0),r=new Array(i).fill(0);for(const l of n)for(let c=0;c<i;c+=1){const u=l[c]==null?"":String(l[c]);u.length>r[c]&&(r[c]=u.length)}const o=" ".repeat(s);return n.map(l=>l.map((c,u)=>{const p=c==null?"":String(c);return u===0?p.padEnd(r[u]):p.padStart(r[u])}).join(o)).join(`
53
+ `)}function co(t,e){const s=t.slice().sort((d,f)=>(f.invocations||0)-(d.invocations||0)).slice(0,12),n=s.map(d=>`${d.invocations||0} inv`),i=n.reduce((d,f)=>Math.max(d,f.length),0),l=4+2+i,c=Number.isFinite(e)&&e>0?Math.max(8,Math.floor(e)-l):1/0,u=s.map((d,f)=>{const h=d.kind==="learned"?"L":"S",m=String(d.name||"(unknown)");return[dn(`${h} ${m}`,c),n[f]]}),p=ws(u);return t.length>s.length?`${p}
54
+ … ${t.length-s.length} more`:p}function Ul(t){const s=t.slice().sort((n,i)=>(i.factCount||0)-(n.factCount||0)).map(n=>[String(n.namespace||"(other)"),String(n.factCount||0),Ae(n.totalValueBytes||0)]);return ws(s)}function oh(t){const e=t.oldestUnreconciledAgeSeconds==null?"-":Dt(Math.max(0,Number(t.oldestUnreconciledAgeSeconds)||0));return ws([["pending",String(Number(t.pendingTotal)||0)],["unreconciled",String(Number(t.unreconciled)||0)],["ttl-blocked",String(Number(t.ttlBlocked)||0)],["oldest",e],["reconciled",String(Number(t.reconciledUnswept)||0)]])}function ah(t){switch(t){case"facts_search":return"facts search";case"facts_similar":return"facts similar";case"search_skills":return"skill search";case"graph_search_nodes":return"graph nodes";case"graph_search_edges":return"graph edges";case"graph_neighbourhood":return"graph hood";default:return String(t||"retrieval")}}function lh(t,e){const s=t.slice().sort((d,f)=>(Number(f.calls)||0)-(Number(d.calls)||0)).slice(0,12),n=s.map(d=>`${Number(d.calls)||0} calls`),i=s.map(d=>`${Number(d.totalResults)||0} res`),r=n.reduce((d,f)=>Math.max(d,f.length),0),o=i.reduce((d,f)=>Math.max(d,f.length),0),l=6+r+2+o,c=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-l):1/0,u=s.map((d,f)=>{const h=d.namespace?` ${d.namespace}`:"";return[dn(`${ah(d.operation)}${h}`,c),n[f],i[f]]}),p=ws(u);return t.length>s.length?`${p}
55
+ … ${t.length-s.length} more`:p}function ch(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.data)return[te("Loading fleet stats...")];const n=s.data;if(!n)return[te("Fleet stats unavailable.")];const i=[],r=Math.max(24,e);i.push(un("fleet",r)),i.push(te(""));const o=n.windowStart?`Since: ${Zi(n.windowStart).replace(" ago","")}`:"All time",l=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";i.push(fe([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],r)),i.push(fe([{text:`Sessions: ${n.totals.sessionCount}`,color:"white"},{text:` Tokens: ${ee(n.totals.totalTokensInput)} in / ${ee(n.totals.totalTokensOutput)} out`,color:"white"}],r)),i.push(te(""));const c=new Map;for(const g of n.byAgent||[]){const S=g.model||"(default)",y=c.get(S)||{totalTokensInput:0,totalTokensOutput:0,totalTokensCacheRead:0,totalTokensCacheWrite:0,totalSnapshotSizeBytes:0,turnCount:0};y.totalTokensInput+=Number(g.totalTokensInput)||0,y.totalTokensOutput+=Number(g.totalTokensOutput)||0,y.totalTokensCacheRead+=Number(g.totalTokensCacheRead)||0,y.totalTokensCacheWrite+=Number(g.totalTokensCacheWrite)||0,y.totalSnapshotSizeBytes+=Number(g.totalSnapshotSizeBytes)||0,y.turnCount+=Number(g.turnCount)||0,c.set(S,y)}if(c.size>0){const g=[];for(const[S,y]of c.entries()){const v=y.totalTokensInput>0?y.totalTokensCacheRead/y.totalTokensInput:null;g.push(S),g.push(Ji(y,v)),g.push("")}i.push(...Ee({title:"Tokens By Model",body:g.join(`
56
+ `).trimEnd(),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})),i.push(te(""))}const u=n.totals.cacheHitRatio,p=u==null?"—":`${(u*100).toFixed(1)}%`;i.push(...Ee({title:"Fleet Totals",body:At([["Sessions",String(n.totals.sessionCount)],["Tokens In",ee(n.totals.totalTokensInput)],["Tokens Out",ee(n.totals.totalTokensOutput)],["Total Tokens",ee(n.totals.totalTokensInput+n.totals.totalTokensOutput)],["Cache Read",ee(n.totals.totalTokensCacheRead)],["Cache Write",ee(n.totals.totalTokensCacheWrite)],["Hit Ratio",p],["Snapshots",Ae(n.totals.totalSnapshotSizeBytes)]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0}));const d=(Array.isArray(s.skillUsage?.rows)?s.skillUsage.rows:[]).filter(g=>!(g&&g.agentId==="facts-manager"&&String(g.name||"").startsWith("skills/")));d.length>0&&(i.push(te("")),i.push(...Ee({title:`Fleet Skills (${d.length})`,body:uh(d,e),width:r,titleColor:"cyan",borderColor:"gray",fitToContent:!0})));const f=Array.isArray(s.retrievalUsage?.rows)?s.retrievalUsage.rows:[];if(f.length>0){const g=f.reduce((S,y)=>S+(Number(y.calls)||0),0);i.push(te("")),i.push(...Ee({title:`Fleet Retrieval (${ee(g)})`,body:lh(f,e),width:r,titleColor:"magenta",borderColor:"gray",fitToContent:!0}))}const h=s.sharedFactsStats;if(h&&Array.isArray(h.rows)&&h.rows.length>0){i.push(te(""));const g=`${h.totalCount} · ${Ae(h.totalBytes)}`;i.push(...Ee({title:`Shared Facts (${g})`,body:Ul(h.rows),width:r,titleColor:"blue",borderColor:"gray",fitToContent:!0}))}const m=s.factsTombstoneStats;return m&&Number(m.pendingTotal)>0&&(i.push(te("")),i.push(...Ee({title:`Fact Tombstones (${Number(m.pendingTotal)||0})`,body:oh(m),width:r,titleColor:"yellow",borderColor:"gray",fitToContent:!0}))),i}function uh(t,e){const n=t.slice().sort((m,g)=>{const S=w=>w==="learned"?1:0,y=S(m.kind)-S(g.kind);if(y!==0)return y;const v=m.agentId?0:1,x=g.agentId?0:1;if(v!==x)return v-x;const E=String(m.agentId||"").localeCompare(String(g.agentId||""));return E!==0?E:String(m.name||"").localeCompare(String(g.name||""))}).slice(0,15),i=n.map(m=>`${m.invocations||0} inv`),r=n.map(m=>`${m.sessionCount||0} sess`),o=i.reduce((m,g)=>Math.max(m,g.length),0),l=r.reduce((m,g)=>Math.max(m,g.length),0),c=4,u=2,p=c+u+o+u+l,d=Number.isFinite(e)&&e>0?Math.max(10,Math.floor(e)-p):1/0,f=n.map((m,g)=>{const S=m.kind==="learned"?"L":"S",y=m.agentId||".",v=String(m.name||"(unknown)");return[dn(`${S} ${y}/${v}`,d),i[g],r[g]]}),h=ws(f);return t.length>n.length?`${h}
57
+ … ${t.length-n.length} more`:h}function dh(t){const e=t.slice().sort((n,i)=>(i.totalTokensInput||0)-(n.totalTokensInput||0)),s=[];for(const n of e){const i=n.cacheHitRatio;s.push(`${String(n.model||"(unknown)")} · ${n.sessionCount||0} sess · ${n.turnCount||0} turns`),s.push(Ji(n,i)),s.push("")}return s.join(`
58
+ `).trimEnd()}function Ji(t,e){const s=e==null?"—":`${(e*100).toFixed(1)}%`,n=(Number(t.totalTokensInput)||0)+(Number(t.totalTokensOutput)||0),i=[["Input",ee(t.totalTokensInput||0)],["Output",ee(t.totalTokensOutput||0)],["Total",ee(n)],["Turns",ee(t.turnCount||0)],["Cache Read",ee(t.totalTokensCacheRead||0)],["Cache Write",ee(t.totalTokensCacheWrite||0)],["Hit Ratio",s],["Snapshot",Ae(t.totalSnapshotSizeBytes||0)]];return Number.isFinite(Number(t.totalOrchestrationHistorySizeBytes))&&i.push(["Orch",Ae(t.totalOrchestrationHistorySizeBytes||0)]),At(i).split(`
59
+ `).map(o=>` ${o}`).join(`
60
+ `)}function li(t){return t?.ownerKind==="system"?"System":t?.ownerKind==="unowned"?"Unowned":cn(t?.owner,"Unknown User")}function ph(t){if(t?.ownerKind!=="user")return"";const e=String(t?.owner?.email||"").trim(),s=li(t);return e&&e!==s?e:""}function fh(t,e){const s=Array.isArray(t?.byModel)?t.byModel:[];if(s.length===0)return"";const n=s.slice().sort((r,o)=>(o.totalTokensInput||0)-(r.totalTokensInput||0)).slice(0,6),i=[];for(const r of n){const o=dn(String(r.model||"(default)"),Math.max(12,e-10));i.push(`${o} · ${r.sessionCount||0} sess · ${r.turnCount||0} turns`),i.push(Ji(r,r.cacheHitRatio)),i.push("")}return s.length>n.length&&i.push(`… ${s.length-n.length} more models`),i.join(`
61
+ `).trimEnd()}function hh(t,e){const s=t.fleetStats;if(!s||s.loading&&!s.userStats)return[te("Loading user stats...")];const n=s.userStats;if(!n)return[te("User stats unavailable.")];const i=[],r=Math.max(24,e);i.push(un("users",r)),i.push(te(""));const o=n.windowStart?`Since: ${Zi(n.windowStart).replace(" ago","")}`:"All time",l=n.earliestSessionCreatedAt?`Earliest: ${new Date(n.earliestSessionCreatedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"";i.push(fe([{text:o,color:"cyan"},{text:l?` ${l}`:"",color:"gray"}],r)),i.push(fe([{text:`Users: ${Array.isArray(n.users)?n.users.length:0}`,color:"white"},{text:` Sessions: ${n.totals.sessionCount||0}`,color:"white"}],r)),i.push(te(""));const c=n.totals.cacheHitRatio,u=c==null?"—":`${(c*100).toFixed(1)}%`;i.push(...Ee({title:"User Totals",body:At([["Sessions",String(n.totals.sessionCount||0)],["Tokens In",ee(n.totals.totalTokensInput||0)],["Tokens Out",ee(n.totals.totalTokensOutput||0)],["Total Tokens",ee((n.totals.totalTokensInput||0)+(n.totals.totalTokensOutput||0))],["Cache Read",ee(n.totals.totalTokensCacheRead||0)],["Cache Write",ee(n.totals.totalTokensCacheWrite||0)],["Hit Ratio",u],["Snapshots",Ae(n.totals.totalSnapshotSizeBytes||0)],["Orch Size",Ae(n.totals.totalOrchestrationHistorySizeBytes||0)]]),width:r,titleColor:"green",borderColor:"gray",fitToContent:!0}));const p=Array.isArray(n.users)?n.users:[],d=p.slice().sort((f,h)=>(h.totalTokensInput||0)-(f.totalTokensInput||0)||(h.totalSnapshotSizeBytes||0)-(f.totalSnapshotSizeBytes||0)).slice(0,8);for(const f of d){const h=ph(f),m=f.cacheHitRatio,g=m==null?"—":`${(m*100).toFixed(1)}%`,S=h?`${li(f)} <${h}>`:li(f),y=At([["Sessions",String(f.sessionCount||0)],["Tokens In",ee(f.totalTokensInput||0)],["Tokens Out",ee(f.totalTokensOutput||0)],["Total Tokens",ee((f.totalTokensInput||0)+(f.totalTokensOutput||0))],["Cache Read",ee(f.totalTokensCacheRead||0)],["Cache Write",ee(f.totalTokensCacheWrite||0)],["Hit Ratio",g],["Snapshots",Ae(f.totalSnapshotSizeBytes||0)],["Orch Size",Ae(f.totalOrchestrationHistorySizeBytes||0)]]),v=fh(f,r);i.push(te("")),i.push(...Ee({title:`${S} (${f.sessionCount||0})`,body:v?`${y}
62
+
63
+ ${v}`:y,width:r,titleColor:f.ownerKind==="user"?"cyan":"yellow",borderColor:"gray",fitToContent:!0}))}return p.length>d.length&&(i.push(te("")),i.push(te(`… ${p.length-d.length} more users`))),i}function mt(t,e={}){const s=Ve(t),n=t.ui.inspectorTab,i=Math.max(18,Number(e?.width)||36),r=!!e?.allowWideColumns,o=fl(i);if(s?.isGroup)return{title:Je("Inspector","magenta"),activeTab:n,tabs:et,disabled:!0,stickyLines:[],lines:[te(zl,"gray")]};const l=s?ge(s.sessionId):"",c=n==="sequence"||n==="nodes"?Yi(t):null,u=n==="nodes"?[...Je("Node Map","magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:s?n==="sequence"?[...Je(o?"Sequence":`Sequence: ${l}`,"magenta"),...o?[]:[{text:` [${c.label}]`,color:"gray"}]]:n==="logs"?[...Je(o?"Logs":`Logs: ${l}`,"magenta")]:n==="history"?[...Je(o?"Duroxide Events":`Duroxide Event History: ${l}`,"magenta")]:n==="stats"?[...Je(o?"Stats":`Stats: ${l}`,"magenta"),{text:` [${fs(t.ui?.statsViewMode)}]`,color:"gray"}]:[...Je(o?"Files":`Files: ${l}`,"magenta")]:n==="stats"?`Stats: ${fs(t.ui?.statsViewMode).replace(/^./u,f=>f.toUpperCase())}`:"No session selected";let p,d=[];switch(n){case"sequence":{const f=s?Bf(t,s,i,{allowWideColumns:r,sequenceExpansion:e?.sequenceExpansion||null}):{stickyLines:[],lines:["No session selected."]};d=f.stickyLines||[],p=f.lines;break}case"logs":p=s?cf(t,s):["No session selected."];break;case"nodes":p=Wf(t,i,{});break;case"files":p=s?["Files view is rendered in the shared host layout."]:["No session selected."];break;case"history":p=s?Sh(t,s):["No session selected."];break;case"stats":p=fs(t.ui?.statsViewMode)==="users"?hh(t,i):fs(t.ui?.statsViewMode)==="fleet"?ch(t,i):s?rh(t,s,i):[un("session",Math.max(24,i)),te(""),te("No session selected. Press f to cycle to fleet or users view.")];break;default:p=["Inspector view is scaffolded in the new architecture."];break}return{title:u,activeTab:n,tabs:et,stickyLines:d,lines:p}}const mh={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"},zl="Select a session to see details.";function gh(t){const e=t.timestampMs?new Date(t.timestampMs).toISOString().slice(11,23):"???",s=mh[t.kind]||"gray",n=[],i=[{text:`#${t.eventId}`,color:"white",bold:!0},{text:` ${e}`,color:"gray"},{text:` ${t.kind}`,color:s,bold:t.kind.includes("Failed")}];if(t.sourceEventId!=null&&i.push({text:` ←#${t.sourceEventId}`,color:"cyan"}),n.push(i),t.data)try{const r=JSON.parse(t.data);if(typeof r=="object"&&r!==null)for(const[o,l]of Object.entries(r)){const c=typeof l=="string"?l:JSON.stringify(l),u=c.length>100?c.slice(0,97)+"...":c;n.push([{text:` ${o}: `,color:"yellow"},{text:u,color:"white"}])}else n.push({text:` ${String(r).slice(0,120)}`,color:"white"})}catch{const r=t.data.length>120?t.data.slice(0,117)+"...":t.data;n.push({text:` ${r}`,color:"white"})}return n}function yh(t){const e={...t};if(e.data)try{e.data=JSON.parse(e.data)}catch{}return JSON.stringify(e,null,2)}function Sh(t,e){const s=t.executionHistory?.bySessionId?.[e.sessionId];if(!s)return["No execution history loaded. Press r to refresh."];if(s.loading)return["Loading execution history..."];if(s.error)return[`Error: ${s.error}`];const n=s.events;if(!Array.isArray(n)||n.length===0)return["No history events found."];const i=t.executionHistory?.format||"pretty",r=[];if(r.push({text:`${n.length} event(s) · format: ${i}`,color:"gray"}),r.push(""),i==="raw")for(let o=0;o<n.length;o++){const l=yh(n[o]).split(`
64
+ `);for(const c of l)r.push({text:c,color:"gray"});o<n.length-1&&r.push({text:"────────────────────────────────",color:"gray"})}else for(let o=0;o<n.length;o++){const l=gh(n[o]);for(const c of l)r.push(c);o<n.length-1&&r.push({text:"────────────────────────────────",color:"gray"})}return r}function bh(t,e=88){const s=t.ui.modal;return!s||s.type!=="historyFormat"?null:Qi(s,{format:t.executionHistory?.format||"pretty"},e,"Execution History Format","Choose the display format for duroxide execution history events.")}function uo(t=[]){const e=[];for(const s of t)e.length>0&&e.push({text:" ",color:"gray"}),e.push({text:`${s.label} `,color:"gray"}),e.push({text:"██",color:s.color,backgroundColor:s.color});return e}function wh(t,e=80){const s=t.ui.modal;if(!s||s.type!=="themePicker")return null;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Number(s.selectedIndex)||0),r=n[i]||null,o=s.currentThemeId||t.ui.themeId||null,l=n.find(f=>f.id===o)||null,c=r&&r.id!==o,u=Math.max(24,e-4),p=n.map((f,h)=>{const m=f.id===o?" [current]":"",g=`${f.label}${m}`.slice(0,u);return h===i?st(g.padEnd(u," ")):[{text:g,color:f.id===o?"cyan":"white",bold:f.id===o}]}),d=r?[[{text:`theme: ${r.description||"Shared theme for the portal and native TUI."}`,color:"white"}],...r.group?[[{text:`group: ${r.group}`,color:"gray"}]]:[],{text:"",color:"gray"},[{text:c?`Previewing now. Cancel reverts to ${l?.label||"the previous theme"}.`:"Currently active in this TUI session.",color:c?"yellow":"green"}],uo([{label:"bg",color:r.tui?.background||r.terminal?.background||"#000000"},{label:"surface",color:r.tui?.surface||r.terminal?.background||"#000000"},{label:"fg",color:r.tui?.white||r.terminal?.foreground||"#ffffff"}]),uo([{label:"blue",color:r.tui?.blue||r.terminal?.blue||"#5555ff"},{label:"green",color:r.tui?.green||r.terminal?.green||"#55ff55"},{label:"magenta",color:r.tui?.magenta||r.terminal?.magenta||"#ff55ff"},{label:"yellow",color:r.tui?.yellow||r.terminal?.yellow||"#ffff55"}]),{text:"",color:"gray"},[{text:"Selecting previews immediately. Apply Theme keeps it; Cancel restores the previous theme.",color:"gray"}]]:[{text:"No themes available.",color:"gray"}];return{title:s.title||"Theme Picker",idealWidth:Math.max(60,Math.min(e,80)),rows:p,selectedRowIndex:i,detailsTitle:"Theme Details",detailsLines:d}}function vh(t){const e=t.ui.modal;return!e||e.type!=="confirm"?null:{title:e.title||"Confirm",message:e.message||"Are you sure?",confirmLabel:e.confirmLabel||"Confirm"}}function as(t,e){return t.selectedName!==e.name?!0:typeof e.seq=="number"?(t.selectionSeq??0)!==e.seq:!1}function po(t){return new Map(t)}function hs(t){return new Set(t)}function Eh(t){return Array.isArray(t)?[...t]:[]}function xh(t){return Array.isArray(t)?[...t]:[]}const Ih=5e3;function fo(t,e){const s=[],n=new Set;for(const i of t||[])!i||n.has(i)||e[i]&&(n.add(i),s.push(i));return s}function Wl(t){return!!(t&&!t.isSystem&&(t.isGroup||!t.parentSessionId&&!t.groupId))}function Is(t,e){const s=[],n=new Set;for(const i of t||[]){if(!i||n.has(i))continue;n.add(i);const r=e?.[i];(!r||Wl(r))&&s.push(i)}return s}function kh(t,e,s){const n={},i=new Set([...Object.keys(e||{}),...Object.keys(t||{})]);for(const r of i){const o=(e||{})[r],l=(t||{})[r],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 u=s?.[Ud(r).sessionId];u&&u.isGroup||(n[r]=c)}return n}function ql(t){return hs(t)}function Ah(t,e){const s=[],n=new Set([t]);let i=e?.[t]||null;for(;i;){let r=null;if(i.parentSessionId&&e?.[i.parentSessionId]?r=i.parentSessionId:!i.isGroup&&i.groupId&&e?.[`group:${i.groupId}`]&&(r=`group:${i.groupId}`),!r||n.has(r))break;s.push(r),n.add(r),i=e[r]||null}return s}function ho(t,e,s){const n=ql(t);if(!s||!e?.[s])return n;for(const i of Ah(s,e))n.delete(i);return n}function mo(t,e){if(t===e)return!0;if(!(t instanceof Set)||!(e instanceof Set)||t.size!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}function Ch(t){return{...t||{}}}function nt(t){return{...t||{}}}function go(t){return{...t||{}}}function ks(t){return{...t||{}}}function On(t){return{scope:t?.scope==="allSessions"?"allSessions":"selectedSession",query:typeof t?.query=="string"?t.query:""}}function Th(t){return(Array.isArray(t)?t.filter(Boolean):[]).slice(-1e3)}function Nh(t){return[N.SESSIONS,N.CHAT,N.INSPECTOR,N.ACTIVITY].includes(t)?t:null}function $n(t,e){const s=Array.isArray(t)?t.filter(Boolean):[],n=Math.max(me,Number(e)||me);return s.length>n?s.slice(-n):s}function ci(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i+=1)if(!ci(t[i],e[i]))return!1;return!0}if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!ci(t[i],e[i]))return!1;return!0}function yo(t){const e=t?.updatedAt;if(typeof e=="number"&&Number.isFinite(e))return e;if(e instanceof Date)return e.getTime();const s=Date.parse(e||"");return Number.isFinite(s)?s:0}function Mh(t,e){const s=yo(t),n=yo(e);return s>0&&n>0&&n<=s}const Ph=new Set(["completed","failed","cancelled","error"]);function Rh(t,e){const s=String(e?.status??"").toLowerCase();if(t?.status!=="running"||s==="running"||Ph.has(s))return!1;const n=Number(t?.statusVersion),i=Number(e?.statusVersion);return Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?i<=n:Mh(t,e)}function So(t={},e={}){let s=t||{};const n=Rh(t,e);for(const[i,r]of Object.entries(e||{}))if(r!==void 0&&!(i==="status"&&n)){if(i==="pendingQuestion"&&Oh(t,r)){s===t&&(s={...t||{}}),s.pendingQuestion=null;continue}ci(t?.[i],r)||(s===t&&(s={...t||{}}),s[i]=r)}return s}function bo(t){if(!t)return"unknown";const e=t.status||"unknown",s=e==="waiting"||e==="idle"||e==="unknown";return t.cronActive===!0&&s?"cron_waiting":s&&(Number(t.activeChildCount)||0)>0?"awaiting_children":e}function _h(t,e,s){if(!e?.sessionId||e.isGroup)return e;const n=bo(e),i=t?.rowVisualStatus||bo(t||e);if(!t)return e.rowVisualStatus===n&&e.rowVisualStatusCandidate==null&&e.rowVisualStatusCandidateSince==null?e:{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0};if(n===i)return e.rowVisualStatus===n&&e.rowVisualStatusCandidate==null&&e.rowVisualStatusCandidateSince==null?e:{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0};const o=t.rowVisualStatusCandidate===n&&Number(t.rowVisualStatusCandidateSince)||s;return s-o>=Ih?{...e,rowVisualStatus:n,rowVisualStatusCandidate:void 0,rowVisualStatusCandidateSince:void 0}:e.rowVisualStatus===i&&e.rowVisualStatusCandidate===n&&Number(e.rowVisualStatusCandidateSince)===o?e:{...e,rowVisualStatus:i,rowVisualStatusCandidate:n,rowVisualStatusCandidateSince:o}}const Lh=new Set(["running","input_required"]);function Fn(t){const e=new Map;for(const i of Object.values(t||{})){if(!i?.sessionId||i.isGroup||!Lh.has(i.status))continue;const r=new Set([i.sessionId]);let o=i.parentSessionId;for(;o&&t[o]&&!r.has(o);)r.add(o),e.set(o,(e.get(o)||0)+1),o=t[o].parentSessionId}let s=!1;const n={};for(const[i,r]of Object.entries(t||{})){const o=e.get(i)||0,l=Number(r?.activeChildCount)||0;if(o===l){n[i]=r;continue}s=!0,n[i]=o>0?{...r,activeChildCount:o}:{...r,activeChildCount:void 0}}return s?n:t}function wo(t={},e={},s){let n=!1;const i={};for(const[r,o]of Object.entries(e)){const l=_h(t[r],o,s);i[r]=l,l!==o&&(n=!0)}return n?i:e}function vo(t){return String(t?.question||"").trim()}function Oh(t,e){const s=vo(t?.answeredPendingQuestion),n=vo(e);return!!(s&&n&&s===n)}function $h(t=[]){const e=(t||[]).find(n=>n?.sessionId&&n.isSystem&&Da(n)===0);return e?.sessionId?e.sessionId:(t||[]).find(n=>n?.sessionId)?.sessionId||null}function Eo(t=[]){const e=new Set((t||[]).map(n=>n?.sessionId).filter(Boolean)),s=new Set;for(const n of t||[]){if(!n?.sessionId)continue;n.isGroup&&s.add(n.sessionId);const i=n.parentSessionId;i&&e.has(i)&&s.add(i)}return s}function xo(t={}){const e=String(t?.filterQuery||"").trim(),s=zs(t?.ownerFilter);return!!e||s.all!==!0}function Fh(t,e=[]){const s=Qt(t),n=t.sessions?.activeSessionId||null;if(n&&s.some(r=>r.sessionId===n)||t.sessions?.navigationIntent||n&&t.sessions?.byId?.[n]&&!xo(t.sessions)||n&&!t.sessions?.listingSeen)return n;if(xo(t.sessions))return s[0]?.sessionId||null;const i=s.length>0?s.map(r=>t.sessions?.byId?.[r.sessionId]||null).filter(Boolean):e;return $h(i)}function Dh(t,e){return e===t.sessions.activeSessionId?t.ui:{...t.ui,scroll:{...t.ui.scroll,chat:0,inspector:0,activity:0},followBottom:{...t.ui.followBottom||{},inspector:!0,activity:!0}}}function wt(t,e){let s=e;const n=s.navigationIntent||null,i=n&&n.status!=="failed"&&s.byId?.[n.sessionId]?n.sessionId:null;i&&(s={...s,activeSessionId:i,listDeselected:!1,navigationIntent:n.status==="resolved"?n:{sessionId:n.sessionId,status:"resolved"}});const r=s.activeSessionId||null;if(r&&s.byId?.[r]){const d=ho(s.collapsedIds,s.byId,r);mo(d,s.collapsedIds)||(s={...s,collapsedIds:d,flat:Ze(Object.values(s.byId||{}),d,s.orderById,s.pinnedIds,s.manualOrder)})}i&&s.filterExceptionId!==i&&(Qt({...t,sessions:s}).some(f=>f.sessionId===i)||(s={...s,filterExceptionId:i}));const o={...t,sessions:s},l=Fh(o,Object.values(s.byId||{})),c=ho(s.collapsedIds,s.byId,l);return{sessions:{...!mo(c,s.collapsedIds)?{...s,collapsedIds:c,flat:Ze(Object.values(s.byId||{}),c,s.orderById,s.pinnedIds,s.manualOrder)}:s,activeSessionId:l},ui:Dh(t,l)}}function Dn(t={},e=0,s=[]){const n=Ch(t);let i=Number.isFinite(e)?e:0;for(const r of s||[]){const o=r?.sessionId;o&&typeof n[o]!="number"&&(n[o]=i,i+=1)}return{orderById:n,nextOrderOrdinal:i}}function Bh(t=[],e=[]){const s=Ze(t,new Set,{},e),n={};let i=0;for(const r of s){const o=r?.sessionId;!o||typeof n[o]=="number"||(n[o]=i,i+=1)}for(const r of t||[]){const o=r?.sessionId;!o||typeof n[o]=="number"||(n[o]=i,i+=1)}return{orderById:n,nextOrderOrdinal:i}}function Hh(t,e,s=null){const n=String(t||""),i=Number.isFinite(e)?e:Number.isFinite(s)?s:n.length;return Math.max(0,Math.min(i,n.length))}function Io(t,e){const s=String(t||"");return(Array.isArray(e)?e.filter(Boolean):[]).filter(i=>{if(i?.kind==="image")return!0;const r=String(i?.token||"").trim();return r&&s.includes(r)})}function jh(t,e){switch(e.type){case"connection/ready":return{...t,connection:{...t.connection,connected:!0,workersOnline:e.workersOnline??t.connection.workersOnline,error:null},ui:{...t.ui,statusText:e.statusText??t.ui.statusText??"Ready"}};case"connection/error":return{...t,connection:{...t.connection,connected:!1,error:e.error},ui:{...t.ui,statusText:e.statusText||e.error||"Connection error"}};case"auth/context":return{...t,auth:{principal:e.principal??null,authorization:e.authorization??null}};case"ui/status":return{...t,ui:{...t.ui,statusText:e.text}};case"ui/theme":return{...t,ui:{...t.ui,themeId:e.themeId||t.ui.themeId}};case"ui/touchScale":return!!e.enabled==!!t.ui.touchScale?t:{...t,ui:{...t.ui,touchScale:!!e.enabled}};case"profileSettings/apply":{const s=e.settings&&typeof e.settings=="object"&&!Array.isArray(e.settings)?e.settings:{},n=Object.prototype.hasOwnProperty.call(s,"themeId")&&typeof s.themeId=="string"&&s.themeId.trim(),i=Object.prototype.hasOwnProperty.call(s,"sessionOwnerFilter"),r=Object.prototype.hasOwnProperty.call(s,"layoutAdjustments"),o=Object.prototype.hasOwnProperty.call(s,"touchScale")&&typeof s.touchScale=="boolean",l=Object.prototype.hasOwnProperty.call(s,"rightPaneMode")&&(s.rightPaneMode==="canvas"||s.rightPaneMode==="panes"),c=Object.prototype.hasOwnProperty.call(s,"desktopPanes")&&s.desktopPanes&&typeof s.desktopPanes=="object",u=c||l?ll(c?s.desktopPanes:null,l?s.rightPaneMode:null):null,p=Object.prototype.hasOwnProperty.call(s,"canvasPrefs"),d=Object.prototype.hasOwnProperty.call(s,"pinnedSessionIds"),f=Object.prototype.hasOwnProperty.call(s,"collapsedSessionIds"),h=Object.prototype.hasOwnProperty.call(s,"sessionOrder"),m=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.status!=="failed"),g=Object.prototype.hasOwnProperty.call(s,"activeSessionId")&&!m,S=Object.keys(t.sessions.byId||{}).length>0,y=r?{...t.ui.layout||{},...Mi(s.layoutAdjustments)}:t.ui.layout,v=d?S?Is(qs(s.pinnedSessionIds),t.sessions.byId):qs(s.pinnedSessionIds):t.sessions.pinnedIds,x=f?S?ql(si(s.collapsedSessionIds),t.sessions.byId):si(s.collapsedSessionIds):t.sessions.collapsedIds,E=h?Pi(s.sessionOrder):t.sessions.manualOrder,w=g?cl(s.activeSessionId):t.sessions.activeSessionId,I={...t.sessions,...i?{ownerFilter:zs(s.sessionOwnerFilter),ownerFilterExplicit:!0}:{},pinnedIds:v,manualOrder:E,collapsedIds:x,collapsedIdsExplicit:f?!0:t.sessions.collapsedIdsExplicit,activeSessionId:w,flat:d||f||h?Ze(Object.values(t.sessions.byId),x,t.sessions.orderById,v,E):t.sessions.flat},b=S&&(i||d||f||g)?wt(t,I):{sessions:I,ui:t.ui};return{...t,sessions:b.sessions,ui:{...b.ui,themeId:n?s.themeId.trim():b.ui.themeId,touchScale:o?s.touchScale:b.ui.touchScale,rightPaneMode:l?s.rightPaneMode:b.ui.rightPaneMode,...u?{canvasOpen:u.canvasOpen,diagnosticsOpen:u.diagnosticsOpen,canvasZen:u.zen===!0}:{},layout:y},canvas:p?{...t.canvas,prefs:kh(t.canvas.prefs,Ri(s.canvasPrefs),S?t.sessions.byId:null)}:t.canvas}}case"ui/modal":return{...t,ui:{...t.ui,modal:e.modal??null}};case"ui/viewport":{const s=t.ui.layout?.viewportWidth??120,n=t.ui.layout?.viewportHeight??40,i=Math.max(40,e.width??s),r=Math.max(18,e.height??n);return i===s&&r===n?t:{...t,ui:{...t.ui,layout:{...t.ui.layout||{},viewportWidth:i,viewportHeight:r}}}}case"ui/paneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},paneAdjust:Number(e.paneAdjust)||0}}};case"ui/sessionPaneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},sessionPaneAdjust:Number(e.sessionPaneAdjust)||0}}};case"ui/portalSessionColumnAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},portalSessionColumnAdjust:Number(e.portalSessionColumnAdjust)||0}}};case"ui/canvasPaneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},canvasPaneAdjust:Number(e.canvasPaneAdjust)||0}}};case"ui/diagnosticsSplitAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},diagnosticsSplitAdjust:Number(e.diagnosticsSplitAdjust)||0}}};case"ui/diagnosticsPaneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},diagnosticsPaneAdjust:Number(e.diagnosticsPaneAdjust)||0}}};case"ui/activityPaneAdjust":return{...t,ui:{...t.ui,layout:{...t.ui.layout||{},activityPaneAdjust:Number(e.activityPaneAdjust)||0}}};case"ui/focus":return{...t,ui:{...t.ui,focusRegion:e.focusRegion,requestedFocusRegion:e.requestedFocusRegion??e.focusRegion}};case"ui/sequenceExpandedTurns":return{...t,ui:{...t.ui,sequenceExpandedTurns:Array.isArray(e.turns)?e.turns:[]}};case"ui/sequenceSelectedTurn":return{...t,ui:{...t.ui,sequenceSelectedTurn:e.turn==null?null:Number(e.turn)}};case"sessions/filterQuery":{const s={...t.sessions,filterQuery:typeof e.query=="string"?e.query:"",navigationIntent:null,filterExceptionId:null},n=wt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/ownerFilter":{const s={...t.sessions,ownerFilterExplicit:!0,ownerFilter:zs(e.filter),navigationIntent:null,filterExceptionId:null},n=wt(t,s);return{...t,sessions:n.sessions,ui:n.ui}}case"sessions/navigationIntent":{const s=String(e.sessionId||"").trim();if(!s)return t;const n={...t.sessions,listDeselected:!1,navigationIntent:{sessionId:s,status:"pending"},filterExceptionId:null},i=wt(t,n);return{...t,sessions:i.sessions,ui:i.ui}}case"sessions/navigationIntentFailed":{const s=t.sessions.navigationIntent,n=String(e.sessionId||"").trim();return!s||n&&s.sessionId!==n?t:{...t,sessions:{...t.sessions,navigationIntent:{sessionId:s.sessionId,status:"failed",errorKind:e.errorKind==="not_found"?"not_found":"network"}}}}case"ui/modalSelection":{const s=t.ui.modal;if(!s)return t;if(s.type==="help")return{...t,ui:{...t.ui,modal:{...s,selectedIndex:Math.max(0,Number(e.index)||0)}}};if(!Array.isArray(s.items)||s.items.length===0)return t;const n=Math.max(0,Math.min(e.index??0,s.items.length-1)),i=s.type==="themePicker"?s.items[n]?.id:null;return{...t,ui:{...t.ui,...i?{themeId:i}:{},modal:{...s,selectedIndex:n}}}}case"ui/scroll":return{...t,ui:{...t.ui,scroll:{...t.ui.scroll,[e.pane]:Math.max(0,e.offset??0)}}};case"ui/followBottom":{if(e.pane!=="inspector"&&e.pane!=="activity")return t;const s=!!e.followBottom;return t.ui.followBottom?.[e.pane]===s?t:{...t,ui:{...t.ui,followBottom:{...t.ui.followBottom||{},[e.pane]:s}}}}case"ui/nodeMapSelect":return e.label?{...t,ui:{...t.ui,nodeMapSelectedNode:String(e.label)}}:t;case"ui/inspectorTab":return{...t,ui:{...t.ui,inspectorTab:e.inspectorTab,fullscreenPane:e.inspectorTab==="files"&&t.ui.fullscreenPane===N.INSPECTOR?null:t.ui.fullscreenPane,scroll:{...t.ui.scroll,inspector:0},followBottom:{...t.ui.followBottom||{},inspector:!0}},files:e.inspectorTab==="files"?t.files:{...t.files,fullscreen:!1}};case"ui/statsViewMode":return{...t,ui:{...t.ui,statsViewMode:["session","fleet","users"].includes(e.statsViewMode)?e.statsViewMode:"session",scroll:{...t.ui.scroll,inspector:0}}};case"ui/prompt":return{...t,ui:{...t.ui,prompt:e.prompt,promptCursor:Hh(e.prompt,e.promptCursor,t.ui.promptCursor),promptRows:Wt(e.prompt),promptAttachments:Io(e.prompt,t.ui.promptAttachments)}};case"ui/promptEdit":return{...t,ui:{...t.ui,promptEdit:e.promptEdit??null}};case"ui/promptAttachments":return{...t,ui:{...t.ui,promptAttachments:Io(t.ui.prompt,e.attachments)}};case"sessions/gone":{const s=e.sessionId;if(!s)return t;const n=!!t.sessions.byId[s],i=t.sessions.activeSessionId===s;if(!n&&!i)return t;const r={...t.sessions.byId};delete r[s];const o=Fn(r),l=Array.isArray(t.sessions.selectedIds)?t.sessions.selectedIds.filter(c=>c!==s):t.sessions.selectedIds;return{...t,sessions:{...t.sessions,byId:o,selectedIds:l,activeSessionId:i?null:t.sessions.activeSessionId}}}case"sessions/loaded":{const s={};let n=!1;const i=Date.now();for(const I of t.sessions.groupRows||[])s[I.sessionId]=t.sessions.byId[I.sessionId]||I;for(const I of e.sessions){const b=t.sessions.byId[I.sessionId];s[I.sessionId]=So(b,I)}t.sessions.activeSessionId&&t.sessions.byId[t.sessions.activeSessionId]&&!t.sessions.byId[t.sessions.activeSessionId]?.isGroup&&!s[t.sessions.activeSessionId]&&(s[t.sessions.activeSessionId]={...t.sessions.byId[t.sessions.activeSessionId]},n=!0);const r=Fn(s),o=wo(t.sessions.byId,r,i);for(const[I,b]of Object.entries(o))if(b!==t.sessions.byId[I]){n=!0;break}const l=Object.keys(t.sessions.byId),c=Object.keys(o);if(l.length!==c.length&&(n=!0),!n){for(const I of c)if(!t.sessions.byId[I]){n=!0;break}}if(!n)return t;const u=Object.values(o),p=Object.keys(t.sessions.orderById||{}).length>0,d=Eo(u),f=!!t.sessions.collapsedIdsExplicit,{orderById:h,nextOrderOrdinal:m}=p?Dn(t.sessions.orderById,t.sessions.nextOrderOrdinal,u):Bh(u,t.sessions.pinnedIds),g=f?hs(t.sessions.collapsedIds):d,S=t.sessions.listingSeen===!0;if(f&&S){const I=Eo(Object.values(t.sessions.byId));for(const b of d)I.has(b)||g.add(b)}const y=Is(t.sessions.pinnedIds,o),v=fo(t.sessions.selectedIds,o),x=Ze(u,g,h,y,t.sessions.manualOrder),E={...t.sessions,byId:o,collapsedIds:g,collapsedIdsExplicit:f,listingSeen:!0,pinnedIds:y,selectedIds:v,selectMode:t.sessions.selectMode&&v.length>0,flat:x,activeSessionId:t.sessions.activeSessionId,orderById:h,nextOrderOrdinal:m},w=wt(t,E);return{...t,sessions:w.sessions,ui:w.ui}}case"sessions/groupsLoaded":{const s=Array.isArray(e.groups)?e.groups:[],n={...t.sessions.byId},i=Array.isArray(e.sessions)?e.sessions:Object.values(t.sessions.byId),r=new Set(i.filter(m=>m&&!m.isGroup&&m.groupId&&!m.parentSessionId).map(m=>`group:${m.groupId}`)),o=[];for(const m of Object.keys(n))if(n[m]?.isGroup&&!s.some(g=>g.sessionId===m)){if(r.has(m)){o.push(n[m]);continue}delete n[m]}for(const m of s)n[m.sessionId]={...n[m.sessionId]||{},...m};const l=Is(t.sessions.pinnedIds,n),{orderById:c,nextOrderOrdinal:u}=Dn(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(n)),p=t.sessions.groupsListingSeen===!0,d=hs(t.sessions.collapsedIds);for(const m of s)p&&(t.sessions.byId[m.sessionId]||d.add(m.sessionId));const f={...t.sessions,groupRows:[...s,...o],byId:n,pinnedIds:l,orderById:c,nextOrderOrdinal:u,collapsedIds:d,groupsListingSeen:!0,flat:Ze(Object.values(n),d,c,l,t.sessions.manualOrder)},h=wt(t,f);return{...t,sessions:h.sessions,ui:h.ui}}case"sessions/merged":{if(!e.session?.sessionId)return t;const s=t.sessions.byId[e.session.sessionId],n=So(s,e.session),i=wo(t.sessions.byId,Fn({...t.sessions.byId,[e.session.sessionId]:n}),Date.now());let r=!1;for(const[d,f]of Object.entries(i))if(f!==t.sessions.byId[d]){r=!0;break}if(!r)return t;const o=Is(t.sessions.pinnedIds,i),{orderById:l,nextOrderOrdinal:c}=Dn(t.sessions.orderById,t.sessions.nextOrderOrdinal,Object.values(i)),u={...t.sessions,byId:i,pinnedIds:o,flat:Ze(Object.values(i),t.sessions.collapsedIds,l,o,t.sessions.manualOrder),activeSessionId:t.sessions.activeSessionId,orderById:l,nextOrderOrdinal:c},p=wt(t,u);return{...t,sessions:p.sessions,ui:p.ui}}case"sessions/selected":{t={...t,sessions:{...t.sessions,listDeselected:!1}};const s=t.sessions.activeSessionId,n={...t.ui.chatScrollBySession||{}};s&&s!==e.sessionId&&(n[s]=Number(t.ui.scroll?.chat)||0);const i=s!==e.sessionId,r={...t.ui.promptDraftBySession||{}};let o=t.ui.prompt,l=t.ui.promptCursor,c=t.ui.promptAttachments,u=t.ui.promptEdit??null;if(i){if(!!!t.ui.promptEdit&&s){const h={prompt:String(t.ui.prompt||""),attachments:Array.isArray(t.ui.promptAttachments)?t.ui.promptAttachments:[]};h.prompt||h.attachments.length>0?r[s]=h:delete r[s]}const f=e.sessionId?r[e.sessionId]:null;delete r[e.sessionId],o=f?.prompt||"",l=o.length,c=Array.isArray(f?.attachments)?f.attachments:[],u=null}const p=!!(t.sessions.navigationIntent&&t.sessions.navigationIntent.sessionId!==e.sessionId);return{...t,sessions:{...t.sessions,activeSessionId:e.sessionId,...p?{navigationIntent:null,filterExceptionId:null}:{}},ui:{...t.ui,chatScrollBySession:n,promptDraftBySession:r,prompt:o,promptCursor:l,promptRows:Wt(o),promptAttachments:c,promptEdit:u,statusText:s!==e.sessionId?"":t.ui.statusText,scroll:{...t.ui.scroll,chat:Number(n[e.sessionId])||0,inspector:0,activity:0},followBottom:{...t.ui.followBottom||{},inspector:!0,activity:!0}}}}case"ui/fullscreenPane":{const s=Nh(e.fullscreenPane);return{...t,files:s?{...t.files,fullscreen:!1}:t.files,ui:{...t.ui,fullscreenPane:s,focusRegion:s||t.ui.focusRegion}}}case"sessions/collapse":{const s=hs(t.sessions.collapsedIds);return s.add(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:Ze(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds,t.sessions.manualOrder)}}}case"sessions/expand":{const s=hs(t.sessions.collapsedIds);return s.delete(e.sessionId),{...t,sessions:{...t.sessions,collapsedIds:s,collapsedIdsExplicit:!0,flat:Ze(Object.values(t.sessions.byId),s,t.sessions.orderById,t.sessions.pinnedIds,t.sessions.manualOrder)}}}case"sessions/pinToggle":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=t.sessions.byId[s];if(!Wl(n))return t;const i=Eh(t.sessions.pinnedIds),o=i.indexOf(s)>=0?i.filter(l=>l!==s):[...i,s];return{...t,sessions:{...t.sessions,pinnedIds:o,flat:Ze(Object.values(t.sessions.byId),t.sessions.collapsedIds,t.sessions.orderById,o,t.sessions.manualOrder)}}}case"sessions/reorder":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=t.sessions.byId[s];if(!Xt(n))return t;const i=e.beforeSessionId==null?null:String(e.beforeSessionId).trim()||null;if(i===s)return t;const o=(Array.isArray(t.sessions.manualOrder)&&t.sessions.manualOrder.length>0?t.sessions.manualOrder:(t.sessions.flat||[]).map(p=>p.sessionId).filter(p=>Xt(t.sessions.byId[p]))).filter(p=>p!==s),l=i?o.indexOf(i):-1,c=l>=0?[...o.slice(0,l),s,...o.slice(l)]:[...o,s];return c.length===(t.sessions.manualOrder||[]).length&&c.every((p,d)=>p===t.sessions.manualOrder[d])?t:{...t,sessions:{...t.sessions,manualOrder:c,flat:Ze(Object.values(t.sessions.byId),t.sessions.collapsedIds,t.sessions.orderById,t.sessions.pinnedIds,c)}}}case"sessions/selectMode":{const s=!!e.enabled;return s===!!t.sessions.selectMode&&(s||t.sessions.selectedIds.length===0)?t:{...t,sessions:{...t.sessions,selectMode:s,selectedIds:s?t.sessions.selectedIds:[]}}}case"sessions/selectToggle":{const s=String(e.sessionId||"").trim(),n=s?t.sessions.byId[s]:null;if(!n||n.isSystem||n.isGroup)return t;const i=xh(t.sessions.selectedIds),o=i.indexOf(s)>=0?i.filter(l=>l!==s):[...i,s];return{...t,sessions:{...t.sessions,selectedIds:o,selectMode:o.length>0?!0:t.sessions.selectMode}}}case"sessions/selectSet":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[],n=fo(s,t.sessions.byId).filter(i=>!t.sessions.byId[i]?.isSystem&&!t.sessions.byId[i]?.isGroup);return{...t,sessions:{...t.sessions,selectedIds:n,selectMode:n.length>0?!0:t.sessions.selectMode}}}case"sessions/listReselect":return t.sessions.listDeselected?{...t,sessions:{...t.sessions,listDeselected:!1}}:t;case"sessions/listDeselect":return{...t,sessions:{...t.sessions,listDeselected:!0,selectedIds:[],selectMode:!1}};case"sessions/selectClear":return t.sessions.selectedIds.length===0&&!t.sessions.selectMode?t:{...t,sessions:{...t.sessions,selectedIds:[],selectMode:!1}};case"history/set":{const s=t.history.bySessionId.get(e.sessionId)||null,n=s?.chat||[],i=Math.max(me,Number(e.history?.loadedEventLimit??s?.loadedEventLimit??me)||me),r=$n(Gt(e.history?.chat||[]),i),o=n[n.length-1]?.id||null,l=r[r.length-1]?.id||null,c=e.sessionId===t.sessions.activeSessionId&&l!==o,u=po(t.history.bySessionId);return u.set(e.sessionId,{...e.history||{},chat:r,activity:$n(e.history?.activity||[],i),events:$n(e.history?.events||[],i),loadedEventLimit:i}),{...t,history:{...t.history,bySessionId:u},ui:c?{...t.ui,scroll:{...t.ui.scroll,chat:0}}:t.ui}}case"history/evict":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=po(t.history.bySessionId);for(const l of s)n.delete(l);const i=go(t.outbox?.bySessionId);for(const l of s)delete i[l];const r={...t.ui.chatScrollBySession||{}};for(const l of s)delete r[l];const o={...t.ui.promptDraftBySession||{}};for(const l of s)delete o[l];return{...t,history:{...t.history,bySessionId:n},outbox:{...t.outbox,bySessionId:i},ui:{...t.ui,chatScrollBySession:r,promptDraftBySession:o}}}case"outbox/setSessionItems":{const s=e.sessionId;if(!s)return t;const n=Array.isArray(e.items)?e.items.filter(Boolean):[],i=go(t.outbox?.bySessionId);return n.length===0?delete i[s]:i[s]=n,{...t,outbox:{...t.outbox,bySessionId:i}}}case"orchestration/statsLoading":{const s=ks(t.orchestration.bySessionId);return s[e.sessionId]={...s[e.sessionId]||{},loading:!0,error:null},{...t,orchestration:{...t.orchestration,bySessionId:s}}}case"orchestration/statsLoaded":{const s=ks(t.orchestration.bySessionId);return s[e.sessionId]={loading:!1,error:null,fetchedAt:e.fetchedAt||Date.now(),stats:e.stats||null},{...t,orchestration:{...t.orchestration,bySessionId:s}}}case"orchestration/statsError":{const s=ks(t.orchestration.bySessionId);return s[e.sessionId]={...s[e.sessionId]||{},loading:!1,error:e.error||"Failed to load orchestration stats",fetchedAt:e.fetchedAt||Date.now()},{...t,orchestration:{...t.orchestration,bySessionId:s}}}case"orchestration/evict":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=ks(t.orchestration.bySessionId);for(const i of s)delete n[i];return{...t,orchestration:{...t.orchestration,bySessionId:n}}}case"executionHistory/loading":{const s={...t.executionHistory?.bySessionId||{}};return s[e.sessionId]={...s[e.sessionId]||{},loading:!0,error:null},{...t,executionHistory:{...t.executionHistory,bySessionId:s}}}case"executionHistory/loaded":{const s={...t.executionHistory?.bySessionId||{}},n=e.events||[],i=1e3,r=n.length>i?n.slice(-i):n;return s[e.sessionId]={loading:!1,error:null,fetchedAt:e.fetchedAt||Date.now(),events:r},{...t,executionHistory:{...t.executionHistory,bySessionId:s}}}case"executionHistory/evict":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n={...t.executionHistory?.bySessionId||{}};for(const i of s)delete n[i];return{...t,executionHistory:{...t.executionHistory,bySessionId:n}}}case"executionHistory/error":{const s={...t.executionHistory?.bySessionId||{}};return s[e.sessionId]={...s[e.sessionId]||{},loading:!1,error:e.error||"Failed to load execution history",fetchedAt:e.fetchedAt||Date.now()},{...t,executionHistory:{...t.executionHistory,bySessionId:s}}}case"executionHistory/format":return{...t,executionHistory:{...t.executionHistory,format:e.format||"pretty"}};case"sessionStats/loading":{const s={...t.sessionStats?.bySessionId||{}};return s[e.sessionId]={...s[e.sessionId]||{},loading:!0},{...t,sessionStats:{...t.sessionStats,bySessionId:s}}}case"sessionStats/loaded":{const s={...t.sessionStats?.bySessionId||{}};return s[e.sessionId]={loading:!1,fetchedAt:Date.now(),summary:e.summary||null,tokensByModel:Array.isArray(e.tokensByModel)?e.tokensByModel:[],treeStats:e.treeStats||null,skillUsage:e.skillUsage||null,treeSkillUsage:e.treeSkillUsage||null,factsStats:e.factsStats||null,treeFactsStats:e.treeFactsStats||null},{...t,sessionStats:{...t.sessionStats,bySessionId:s}}}case"fleetStats/loading":return{...t,fleetStats:{...t.fleetStats,loading:!0}};case"fleetStats/loaded":return{...t,fleetStats:{loading:!1,data:e.data||null,userStats:e.userStats||null,skillUsage:e.skillUsage||null,retrievalUsage:e.retrievalUsage||null,sharedFactsStats:e.sharedFactsStats||null,factsTombstoneStats:e.factsTombstoneStats||null,fetchedAt:Date.now()}};case"admin/visibility":{const s=!!e.visible;return t.admin.visible===s?t:{...t,admin:{...t.admin,visible:s,ghcpKey:s?t.admin.ghcpKey:{editing:!1,draft:"",saving:!1,error:null,lastSavedAt:t.admin.ghcpKey.lastSavedAt}}}}case"admin/profile/loading":return{...t,admin:{...t.admin,loading:!0,loadError:null}};case"admin/profile/loaded":return{...t,admin:{...t.admin,loading:!1,loadError:null,profile:e.profile||null,ghcpKey:{...t.admin.ghcpKey,error:t.admin.ghcpKey.editing?t.admin.ghcpKey.error:null}}};case"admin/profile/loadFailed":return{...t,admin:{...t.admin,loading:!1,loadError:e.error?String(e.error):"Failed to load profile"}};case"admin/ghcpKey/beginEdit":{const s=typeof e.draft=="string"?e.draft:"";return{...t,admin:{...t.admin,ghcpKey:{editing:!0,draft:s,cursorIndex:s.length,saving:!1,error:null,lastSavedAt:t.admin.ghcpKey.lastSavedAt,storeAsSystem:!!t.admin.ghcpKey.storeAsSystem}}}}case"admin/ghcpKey/setDraft":{if(!t.admin.ghcpKey.editing)return t;const s=typeof e.draft=="string"?e.draft:"",n=Number.isFinite(e.cursorIndex)?Number(e.cursorIndex):s.length,i=Math.max(0,Math.min(n,s.length));return s===t.admin.ghcpKey.draft&&i===t.admin.ghcpKey.cursorIndex?t:{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,draft:s,cursorIndex:i,error:null}}}}case"admin/ghcpKey/cancelEdit":return!t.admin.ghcpKey.editing&&!t.admin.ghcpKey.draft?t:{...t,admin:{...t.admin,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:t.admin.ghcpKey.lastSavedAt,storeAsSystem:!!t.admin.ghcpKey.storeAsSystem}}};case"admin/ghcpKey/saving":return{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,saving:!0,error:null}}};case"admin/ghcpKey/saveFailed":return{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,saving:!1,error:e.error?String(e.error):"Failed to save key"}}};case"admin/ghcpKey/saved":return{...t,admin:{...t.admin,profile:e.profile||t.admin.profile,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:Date.now(),storeAsSystem:!!t.admin.ghcpKey.storeAsSystem}}};case"admin/ghcpKey/setSystemTarget":{const s=!!e.value;return!!t.admin.ghcpKey.storeAsSystem===s?t:{...t,admin:{...t.admin,ghcpKey:{...t.admin.ghcpKey,storeAsSystem:s,error:null}}}}case"admin/systemGhcpKey/loading":return{...t,admin:{...t.admin,systemGhcpKey:{...t.admin.systemGhcpKey,loading:!0,error:null}}};case"admin/systemGhcpKey/loaded":{const s=e.status||{};return{...t,admin:{...t.admin,systemGhcpKey:{supported:!0,loading:!1,configured:!!s.configured,changedBy:s.changedBy||null,changedAt:s.changedAt||null,error:null}}}}case"admin/systemGhcpKey/loadFailed":return{...t,admin:{...t.admin,systemGhcpKey:{...t.admin.systemGhcpKey,loading:!1,error:e.error?String(e.error):"Failed to load System key status"}}};case"admin/section":{const s=["packages","workers","ghcp"].includes(e.section)?e.section:"ghcp";return{...t,admin:{...t.admin,section:s}}}case"admin/workers/attempt":{const s=t.admin.workers||{};return{...t,admin:{...t.admin,workers:{...s,attempts:(s.attempts||0)+1,lastAttemptAt:Date.now(),lastSkip:e.skip||null}}}}case"admin/workers/loading":return{...t,admin:{...t.admin,workers:{...t.admin.workers,loading:!0,error:null}}};case"admin/workers/loaded":return{...t,admin:{...t.admin,workers:{loading:!1,error:null,list:Array.isArray(e.list)?e.list:[],fetchedAt:Date.now()}}};case"admin/workers/loadFailed":return{...t,admin:{...t.admin,workers:{...t.admin.workers,loading:!1,error:e.error||"Failed to load workers"}}};case"admin/packages/loading":return{...t,admin:{...t.admin,packages:{...t.admin.packages,loading:!0,error:null}}};case"admin/packages/loaded":{const s=t.admin.packages,n=Array.isArray(e.list)?e.list:[],i=s.selectedName&&n.some(r=>r.name===s.selectedName);return{...t,admin:{...t.admin,packages:{...s,loading:!1,error:null,list:n,workerState:Array.isArray(e.workerState)?e.workerState:[],fetchedAt:Date.now(),selectedName:i?s.selectedName:null,selectedSelector:i?s.selectedSelector??null:null,...i?{}:{detail:null,workspace:{...s.workspace,tree:null,selectedPath:null,file:null}}}}}}case"admin/packages/loadFailed":return{...t,admin:{...t.admin,packages:{...t.admin.packages,loading:!1,error:e.error||"Failed to load agent packages"}}};case"admin/packages/select":return{...t,admin:{...t.admin,section:"packages",packages:{...t.admin.packages,selectedName:e.name||null,selectedSelector:e.selector||null,selectionSeq:(t.admin.packages.selectionSeq??0)+1,detail:null,detailLoading:!!e.name,detailError:null,changelog:null,action:{pending:null,error:null},workspace:{tree:null,treeLoading:!!e.name,treeError:null,expandedDirs:[],selectedPath:null,file:null,fileLoading:!1,fileError:null}}}};case"admin/packages/detail/loaded":return as(t.admin.packages,e)?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,detail:e.detail,detailLoading:!1,detailError:null}}};case"admin/packages/detail/loadFailed":return as(t.admin.packages,e)?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,detail:null,detailLoading:!1,detailError:e.error||"Failed to load package"}}};case"admin/packages/changelog/loaded":return as(t.admin.packages,e)?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,changelog:e.content||null}}};case"admin/packages/tree/loaded":{if(as(t.admin.packages,e))return t;const s=Array.isArray(e.tree?.dirs)?e.tree.dirs.filter(n=>!n.includes("/")):[];return{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,tree:e.tree,treeLoading:!1,treeError:null,expandedDirs:s}}}}}case"admin/packages/tree/loadFailed":return as(t.admin.packages,e)?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,treeLoading:!1,treeError:e.error||"Failed to load package files"}}}};case"admin/packages/toggleDir":{const s=t.admin.packages.workspace,n=new Set(s.expandedDirs);return n.has(e.dir)?n.delete(e.dir):n.add(e.dir),{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...s,expandedDirs:[...n]}}}}}case"admin/packages/file/loading":return{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,selectedPath:e.path,file:null,fileLoading:!0,fileError:null}}}};case"admin/packages/file/loaded":return t.admin.packages.workspace.selectedPath!==e.file?.path||typeof e.seq=="number"&&(t.admin.packages.selectionSeq??0)!==e.seq?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,file:e.file,fileLoading:!1,fileError:null}}}};case"admin/packages/file/loadFailed":return t.admin.packages.workspace.selectedPath!==e.path||typeof e.seq=="number"&&(t.admin.packages.selectionSeq??0)!==e.seq?t:{...t,admin:{...t.admin,packages:{...t.admin.packages,workspace:{...t.admin.packages.workspace,fileLoading:!1,fileError:e.error||"Failed to load file"}}}};case"admin/packages/action/pending":return{...t,admin:{...t.admin,packages:{...t.admin.packages,action:{pending:e.action,error:null}}}};case"admin/packages/action/done":return{...t,admin:{...t.admin,packages:{...t.admin.packages,action:{pending:null,error:null}}}};case"admin/packages/action/failed":return{...t,admin:{...t.admin,packages:{...t.admin.packages,action:{pending:null,error:e.error||"Action failed"}}}};case"admin/packages/addDialog/open":{const s={...ni().admin.packages.addDialog,open:!0,updateName:e.updateName||null,scope:e.scope==="shared"?"shared":"user"};return{...t,admin:{...t.admin,section:"packages",packages:{...t.admin.packages,addDialog:s}}}}case"admin/packages/addDialog/close":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...ni().admin.packages.addDialog,open:!1}}}};case"admin/packages/addDialog/setField":{const s=t.admin.packages.addDialog;return e.field in s?{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...s,[e.field]:e.value,error:null}}}}:t}case"admin/packages/addDialog/submitting":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,submitting:!0,progress:null,error:null}}}};case"admin/packages/addDialog/progress":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,progress:e.message||null}}}};case"admin/packages/addDialog/failed":return{...t,admin:{...t.admin,packages:{...t.admin.packages,addDialog:{...t.admin.packages.addDialog,submitting:!1,progress:null,error:e.error||"Failed to import package"}}}};case"admin/systemGhcpKey/saved":{const s=e.status||{};return{...t,admin:{...t.admin,ghcpKey:{editing:!1,draft:"",cursorIndex:0,saving:!1,error:null,lastSavedAt:Date.now(),storeAsSystem:!!t.admin.ghcpKey.storeAsSystem},systemGhcpKey:{supported:!0,loading:!1,configured:!!s.configured,changedBy:s.changedBy||null,changedAt:s.changedAt||null,error:null}}}}case"files/evictPreviews":{const s=Array.isArray(e.sessionIds)?e.sessionIds:[];if(s.length===0)return t;const n=nt(t.files.bySessionId);for(const i of s)n[i]&&(n[i]={...n[i],previews:{}});return{...t,files:{...t.files,bySessionId:n}}}case"files/sessionLoading":{const s=nt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null};return s[e.sessionId]={...n,loading:!0,error:null},{...t,files:{...t.files,bySessionId:s}}}case"files/sessionLoaded":{const s=nt(t.files.bySessionId),n=s[e.sessionId]||{previews:{},downloads:{}},i=Ws(e.entries),r=Number(e.fetchedAt)||0,o=c=>i.some(u=>u.filename===c),l=n.selectedFilename&&o(n.selectedFilename)?n.selectedFilename:e.selectedFilename&&o(e.selectedFilename)?e.selectedFilename:i[0]?.filename||null;return s[e.sessionId]={...n,entries:i,selectedFilename:l,loading:!1,loaded:!0,fetchedAt:r,error:null},{...t,files:{...t.files,bySessionId:s}}}case"files/sessionError":{const s=nt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null};return s[e.sessionId]={...n,loading:!1,loaded:!0,error:e.error||"Failed to load files"},{...t,files:{...t.files,bySessionId:s}}}case"files/select":{const s=nt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null};return s[e.sessionId]={...n,selectedFilename:e.filename||null},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:t.files.selectedArtifactId},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}}}case"files/toggleMark":{const s=String(e.artifactId||"");if(!s)return t;const n=new Set(t.files.markedIds||[]);return n.has(s)?n.delete(s):n.add(s),{...t,files:{...t.files,markedIds:[...n]}}}case"files/setMarks":return{...t,files:{...t.files,markedIds:Array.isArray(e.artifactIds)?[...new Set(e.artifactIds.map(String))]:[]}};case"files/previewOrigin":return{...t,files:{...t.files,previewOrigin:e.origin||null,restoreArtifactId:e.origin==="chat"?e.restoreArtifactId??t.files.restoreArtifactId??null:null}};case"files/pane":return{...t,files:{...t.files,paneOpen:!!e.open,paneRestoresToHidden:e.open?t.files.paneOpen?t.files.paneRestoresToHidden:!!e.restoresToHidden:!1}};case"ui/rightPaneMode":{const s=e.mode==="canvas"?"canvas":"panes",n=e.sessionId||t.sessions.activeSessionId||null;let i=t.canvas.prefs;if(n){const r=i[n]||{optedOut:!1,lastViewedRev:0};s==="canvas"&&r.optedOut?i={...i,[n]:{...r,optedOut:!1}}:s==="panes"&&e.manual&&!r.optedOut&&(i={...i,[n]:{...r,optedOut:!0}})}return{...t,ui:{...t.ui,rightPaneMode:s,canvasOpen:s==="canvas"},canvas:{...t.canvas,prefs:i}}}case"ui/canvasOpen":{const s=typeof e.open=="boolean"?e.open:!t.ui.canvasOpen,n=e.sessionId||t.sessions.activeSessionId||null;let i=t.canvas.prefs;if(n){const r=i[n]||{optedOut:!1,lastViewedRev:0};s&&r.optedOut?i={...i,[n]:{...r,optedOut:!1}}:!s&&e.manual&&!r.optedOut&&(i={...i,[n]:{...r,optedOut:!0}})}return{...t,ui:{...t.ui,canvasOpen:s,rightPaneMode:s?"canvas":"panes",...s?{}:{canvasMaximized:!1,canvasZen:!1}},canvas:{...t.canvas,prefs:i}}}case"ui/canvasZen":{const s=typeof e.on=="boolean"?e.on:!t.ui.canvasZen;return s===!!t.ui.canvasZen?t:{...t,ui:{...t.ui,canvasZen:s,...s?{canvasOpen:!0,rightPaneMode:"canvas"}:{}}}}case"canvas/zenRail":{const s=String(e.sessionId||"").trim(),n=Number(e.px);if(!s||!Number.isFinite(n))return t;const i=t.canvas.prefs[s]||{optedOut:!1,lastViewedRev:0},r=Math.max(260,Math.min(720,Math.round(n)));return{...t,canvas:{...t.canvas,prefs:{...t.canvas.prefs,[s]:{...i,zenRailPx:r}}}}}case"ui/canvasMaximized":{const s=typeof e.on=="boolean"?e.on:!t.ui.canvasMaximized;return s===!!t.ui.canvasMaximized?t:{...t,ui:{...t.ui,canvasMaximized:s}}}case"ui/diagnosticsOpen":{const s=typeof e.open=="boolean"?e.open:!t.ui.diagnosticsOpen;return s===t.ui.diagnosticsOpen?t:{...t,ui:{...t.ui,diagnosticsOpen:s}}}case"canvas/flip":{const s=Number.isInteger(Number(e.slot))&&Number(e.slot)>=1&&Number(e.slot)<=5?Number(e.slot):1;return{...t,ui:{...t.ui,rightPaneMode:"canvas",canvasOpen:!0,canvasSlot:s},canvas:{...t.canvas,flipSeq:(t.canvas.flipSeq||0)+1}}}case"ui/canvasSlot":{const s=Number.isInteger(Number(e.slot))&&Number(e.slot)>=1&&Number(e.slot)<=5?Number(e.slot):1;return s===(t.ui.canvasSlot||1)?t:{...t,ui:{...t.ui,canvasSlot:s}}}case"canvas/viewed":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=Number(e.rev),i=Number(e.dataRev),r=qe(s,e.slot),o=t.canvas.prefs[r]||{optedOut:!1,lastViewedRev:0,lastViewedDataRev:0},l=Number.isFinite(n)&&n>(o.lastViewedRev||0)?n:o.lastViewedRev||0,c=Number.isFinite(i)&&i>(o.lastViewedDataRev||0)?i:o.lastViewedDataRev||0;return l===(o.lastViewedRev||0)&&c===(o.lastViewedDataRev||0)?t:{...t,canvas:{...t.canvas,prefs:{...t.canvas.prefs,[r]:{...o,lastViewedRev:l,lastViewedDataRev:c}}}}}case"canvas/seed":{const s=Array.isArray(e.entries)?e.entries:[];if(!s.length)return t;let n=null;for(const i of s){const r=String(i?.sessionId||"").trim(),o=Number(i?.latestRev),l=Number(i?.slot);if(!r||!Number.isFinite(o)||o<=0||!Number.isInteger(l)||l<1||l>5)continue;const c=qe(r,l),u=(n||t.canvas.bySessionId)[c]||{};(u.latestRev||0)>=o&&u.name!==void 0||(n=n||{...t.canvas.bySessionId},n[c]={...u,slot:l,latestRev:Math.max(u.latestRev||0,o),...typeof i.name=="string"&&u.name===void 0?{name:i.name}:{},...u.sizeBytes===void 0&&i.sizeBytes!==void 0?{sizeBytes:i.sizeBytes}:{}})}return n?{...t,canvas:{...t.canvas,bySessionId:n}}:t}case"canvas/updated":{const s=String(e.sessionId||"").trim(),n=Number(e.rev);if(!s||!Number.isFinite(n)||n<=0)return t;const i=Number.isInteger(Number(e.slot))&&Number(e.slot)>=1&&Number(e.slot)<=5?Number(e.slot):1,r=qe(s,i),o=t.canvas.bySessionId[r]||{};return(o.latestRev||0)>=n?t:{...t,canvas:{...t.canvas,bySessionId:{...t.canvas.bySessionId,[r]:{...o,slot:i,...typeof e.name=="string"?{name:e.name}:{},latestRev:n,note:typeof e.note=="string"?e.note:"",sizeBytes:Number.isFinite(Number(e.sizeBytes))?Number(e.sizeBytes):null,responseContract:e.responseContract&&typeof e.responseContract=="object"?e.responseContract:null}}}}}case"canvas/data":{const s=String(e.sessionId||"").trim(),n=Number.isInteger(Number(e.slot))&&Number(e.slot)>=1&&Number(e.slot)<=5?Number(e.slot):1,i=qe(s,n),r=Number(e.dataRev);if(!s||!Number.isFinite(r)||r<=0)return t;const o=t.canvas.bySessionId[i]||{},l=Number(e.planeSeq),c=Number.isFinite(l)&&l>0;if(c){if((o.planeSeq||0)>=l)return t}else if(o.planeSeq||(o.latestDataRev||0)>=r)return t;return{...t,canvas:{...t.canvas,bySessionId:{...t.canvas.bySessionId,[i]:{...o,latestDataRev:Math.max(r,o.latestDataRev||0),...c?{planeSeq:l}:{},dataPayload:e.payload&&typeof e.payload=="object"?e.payload:null,dataPatch:c&&e.patch&&typeof e.patch=="object"?e.patch:null}}}}}case"canvas/planeReleased":{const s=String(e.sessionId||"").trim();if(!s)return t;let n=!1;const i={...t.canvas.bySessionId};for(let r=1;r<=5;r++){const o=qe(s,r),l=i[o];if(l&&l.planeSeq){const{planeSeq:c,...u}=l;i[o]=u,n=!0}}return n?{...t,canvas:{...t.canvas,bySessionId:i}}:t}case"canvas/snapshot":{const s=String(e.sessionId||"").trim();if(!s)return t;const n=Number.isInteger(Number(e.slot))&&Number(e.slot)>=1&&Number(e.slot)<=5?Number(e.slot):1,i=qe(s,n),r=t.canvas.bySessionId[i]||{},o=Number(e.rev)||0;return{...t,canvas:{...t.canvas,bySessionId:{...t.canvas.bySessionId,[i]:{...r,slot:n,...typeof e.name=="string"&&(r.latestRev||0)<=o?{name:e.name}:{},latestRev:Math.max(r.latestRev||0,o),note:(r.latestRev||0)>o?r.note:typeof e.note=="string"?e.note:r.note||"",sizeBytes:(r.latestRev||0)>o?r.sizeBytes:Number.isFinite(Number(e.sizeBytes))?Number(e.sizeBytes):r.sizeBytes??null,responseContract:(r.latestRev||0)>o?r.responseContract??null:e.responseContract&&typeof e.responseContract=="object"?e.responseContract:null,snapshotLoaded:!0}}}}}case"canvas/snapshotInvalidate":{const s=String(e.sessionId||"").trim(),n=t.canvas.bySessionId[s];return!s||!n?.snapshotLoaded?t:{...t,canvas:{...t.canvas,bySessionId:{...t.canvas.bySessionId,[s]:{...n,snapshotLoaded:!1}}}}}case"files/htmlViewMode":return{...t,files:{...t.files,htmlViewMode:e.mode==="source"?"source":"rendered"}};case"files/htmlFitWidth":return{...t,files:{...t.files,htmlFitWidth:!!e.enabled}};case"files/htmlZoom":{const s=Number(e.zoom),n=Number.isFinite(s)?Math.min(3,Math.max(.5,Math.round(s*100)/100)):1;return{...t,files:{...t.files,htmlZoom:n}}}case"files/clearMarks":return{...t,files:{...t.files,markedIds:[]}};case"files/selectGlobal":return{...t,files:{...t.files,selectedArtifactId:e.artifactId||null},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}};case"files/previewLoading":{const s=nt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.previews||{},[e.filename]:{...n.previews?.[e.filename]||{},loading:!0,error:null}};return s[e.sessionId]={...n,previews:i},{...t,files:{...t.files,bySessionId:s}}}case"files/previewLoaded":{const s=nt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.previews||{},[e.filename]:{loading:!1,error:null,content:e.content||"",contentType:e.contentType||"text/plain",renderMode:e.renderMode||"text",isBinary:e.isBinary===!0,sizeBytes:Number.isFinite(e.sizeBytes)?e.sizeBytes:null,uploadedAt:e.uploadedAt||"",source:e.source||"agent"}};return s[e.sessionId]={...n,previews:i},{...t,files:{...t.files,bySessionId:s}}}case"files/previewError":{const s=nt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.previews||{},[e.filename]:{...n.previews?.[e.filename]||{},loading:!1,error:e.error||"Failed to load file preview"}};return s[e.sessionId]={...n,previews:i},{...t,files:{...t.files,bySessionId:s}}}case"files/downloaded":{const s=nt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:e.filename||null},i={...n.downloads||{},[e.filename]:{localPath:e.localPath||null,downloadedAt:e.downloadedAt||Date.now()}};return s[e.sessionId]={...n,downloads:i},{...t,files:{...t.files,bySessionId:s}}}case"files/deleted":{t={...t,files:{...t.files,markedIds:(t.files.markedIds||[]).filter(d=>d!==`${e.sessionId}/${e.filename}`)}};const s=nt(t.files.bySessionId),n=s[e.sessionId]||{entries:[],previews:{},downloads:{},selectedFilename:null},i=Ws(n.entries).filter(d=>d.filename!==e.filename),r=n.selectedFilename===e.filename?i[0]?.filename||null:n.selectedFilename,{[e.filename]:o,...l}=n.previews||{},{[e.filename]:c,...u}=n.downloads||{},p=e.sessionId&&e.filename?`${e.sessionId}/${e.filename}`:null;return s[e.sessionId]={...n,entries:i,previews:l,downloads:u,selectedFilename:r},{...t,files:{...t.files,bySessionId:s,selectedArtifactId:t.files.selectedArtifactId===p?r?`${e.sessionId}/${r}`:null:t.files.selectedArtifactId},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}}}case"files/fullscreen":return{...t,files:{...t.files,fullscreen:!!e.fullscreen},ui:e.fullscreen?{...t.ui,focusRegion:"inspector",fullscreenPane:null}:t.ui};case"files/filter":return{...t,files:{...t.files,filter:{...On(t.files.filter),...On(e.filter)},...On(e.filter).scope==="selectedSession"?{}:{selectedArtifactId:t.files.selectedArtifactId||null}},ui:{...t.ui,scroll:{...t.ui.scroll,filePreview:0}}};case"logs/config":return{...t,logs:{...t.logs,available:!!e.available,availabilityReason:e.availabilityReason||t.logs.availabilityReason}};case"logs/tailing":return{...t,logs:{...t.logs,tailing:!!e.tailing}};case"logs/filter":return{...t,logs:{...t.logs,filter:{...t.logs.filter,...e.filter||{}}}};case"logs/set":return{...t,logs:{...t.logs,entries:Th(e.entries)}};case"logs/append":{const s=(Array.isArray(e.entries)?e.entries:[e.entry]).filter(Boolean);if(s.length===0)return t;const n=[...t.logs.entries||[],...s],i=n.length>1e3?n.slice(-1e3):n;return{...t,logs:{...t.logs,entries:i}}}default:return t}}function Zs(t,e){const s=Array.isArray(e)?e.filter(i=>i?.origin&&i?.label):[];if(s.length<2)return[{label:null,url:String(t||"")}];let n;try{const i=new URL(String(t||""));n=`${i.pathname}${i.search}${i.hash}`}catch{return[{label:null,url:String(t||"")}]}return s.map(i=>({label:String(i.label),url:`${i.origin}${n}`}))}function er(t){const e=Array.isArray(t)?t:[];return e.length<=1?String(e[0]?.url||""):e.map(s=>`${s.label}: ${s.url}`).join(`
65
+ `)}function Gh(t,e){let s=e;const n=new Set;return{getState(){return s},dispatch(i){const r=t(s,i);if(Object.is(r,s))return i;s=r;for(const o of n)o(s,i);return i},subscribe(i){return n.add(i),()=>n.delete(i)}}}function Uh(t){return t?{...t.scope==="shared"||t.scope==="user"?{scope:t.scope}:{},...t.scope==="user"&&t.owner?.provider&&t.owner?.subject?{owner:{provider:t.owner.provider,subject:t.owner.subject}}:{}}:null}const zh=2e4,Wh=2e4,qh=3e4,Kh=30,ko="Session refresh failed",Vh=3,Yh=200,Xh=5,Qh=new Set([N.SESSIONS,N.CHAT,N.INSPECTOR,N.ACTIVITY]);function Zh(t){if(!t?.groupId)return null;const e=t.latestSummaryUpdatedAt?new Date(t.latestSummaryUpdatedAt).getTime():null,s=t.memberCount??0;return{sessionId:`group:${t.groupId}`,groupId:t.groupId,isGroup:!0,title:t.title||t.groupId,status:"group",description:t.description??null,owner:t.owner??null,shortSummary:`${s} grouped session${s===1?"":"s"}`,summaryUpdatedAt:Number.isFinite(e)?e:null,latestSummaryUpdatedAt:Number.isFinite(e)?e:null,memberCount:s,runningCount:t.runningCount??0,waitingCount:t.waitingCount??0,completedCount:t.completedCount??0,failedCount:t.failedCount??0,cancelledCount:t.cancelledCount??0,createdAt:t.createdAt?new Date(t.createdAt).getTime():0,updatedAt:t.updatedAt?new Date(t.updatedAt).getTime():Date.now()}}function Bn(t){return!t?.sessionId||t.isGroup?t:{...t,groupId:t.viewerGroupId??null,parentSessionId:t.parentSessionId??null}}function Ls(t){return String(t||"").startsWith("group:")?String(t).slice(6):null}function ls(t){return Ls(t)!==null}function Jh(t){const e=new Map;for(const s of t||[]){const n=s?.reason==="system"?"system":"not found";e.set(n,(e.get(n)||0)+1)}return[...e.entries()].map(([s,n])=>`${n} ${s}`).join(", ")}function Hn(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||e===403||s==="NOT_FOUND"||s==="FORBIDDEN"?"not_found":"network"}function cs(t){const e=Number(t?.status),s=String(t?.code||"").toUpperCase();return e===404||s==="NOT_FOUND"}async function em(t){if(typeof t.listSessionsPage!="function")return t.listSessions();const e=[];let s=null;for(let n=0;n<Xh;n+=1){const i=await t.listSessionsPage({limit:Yh,cursor:s}),r=Array.isArray(i?.sessions)?i.sessions:[];if(e.push(...r),!i?.hasMore||!i?.nextCursor)break;s=i.nextCursor}return e}function tm(t=[]){const e=[],s=new Map;for(const n of t){const i=n?.providerId||"models";let r=s.get(i);r||(r={providerId:i,providerType:n?.providerType||"provider",models:[]},s.set(i,r),e.push(r)),r.models.push(n)}return e}function ui(t){if(!Array.isArray(t))return[];const e=[];for(const s of t){const n=String(s||"").trim().toLowerCase();!n||e.includes(n)||e.push(n)}return e}function Ao(t){const e=ui(t?.supportedReasoningEfforts);if(e.length===0)return null;const s=String(t?.defaultReasoningEffort||"").trim().toLowerCase();return s&&e.includes(s)?s:e.includes("medium")?"medium":e[0]||null}function di(t){if(!Array.isArray(t))return[];const e=[];for(const s of t){const n=String(s||"").trim().toLowerCase();!n||e.includes(n)||n!=="default"&&n!=="long_context"||e.push(n)}return e}function sm(t){const e=di(t?.supportedContextTiers);if(e.length===0)return null;const s=String(t?.defaultContextTier||"").trim().toLowerCase();return s&&e.includes(s)?s:e.includes("default")?"default":e[0]||null}const Kl={default:"Default (smaller window)",long_context:"Long context (larger window, higher cost)"};function nm(t){const e=Number(t);return!Number.isSafeInteger(e)||e<=0?null:e%1e6===0?`${e/1e6}M`:e%1e3===0?`${e/1e3}K`:e.toLocaleString("en-US")}function im(t,e){const s=nm(e);return s?t==="long_context"?`Long context (${s} tokens, higher cost)`:`Default (${s} tokens)`:Kl[t]||t}function pi(t=[]){for(let e=t.length-1;e>=0;e-=1){const s=t[e];if(s?.eventType!=="session.model_changed")continue;const n=s?.data;if(!n||typeof n!="object")continue;const i=typeof n.newModel=="string"&&n.newModel?n.newModel:typeof n.model=="string"&&n.model?n.model:void 0;if(i)return{model:i,...typeof n.newReasoningEffort=="string"||n.newReasoningEffort===null?{reasoningEffort:n.newReasoningEffort}:{}}}}function rm(t){return pi([t])}function Co(t,e=[]){let s=Ia(t);for(const n of e){const i=ka(s,n?.eventType,n?.data,{timestamp:n?.createdAt});i&&(s=i)}return s}function Js(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i+=1)if(!Js(t[i],e[i]))return!1;return!0}if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Js(t[i],e[i]))return!1;return!0}function To(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(t instanceof Date)return t.getTime();const e=Date.parse(t||"");return Number.isFinite(e)?e:0}function tr(t,e){const s=To(t?.updatedAt),n=To(e?.updatedAt);return s>0&&n>0&&n<=s}function om(t){return!t||t==="idle"||t==="unknown"||t==="pending"}function am(t,e){return t?.status==="waiting"&&typeof t?.waitReason=="string"&&t.waitReason.trim().length>0&&(e?.waitReason===void 0||e?.waitReason===null)&&om(e?.status)&&tr(t,e)}function lm(t,e){return t?.cronActive===!0&&e?.cronActive!==!0&&!Yl(e?.status)&&!Vl(e?.orchestrationStatus)&&tr(t,e)}function cm(t,e){if(!e?.sessionId)return null;const s={sessionId:e.sessionId};let n=!1;for(const[l,c]of Object.entries(e))l==="sessionId"||c===void 0||Js(t?.[l],c)||(s[l]=c,n=!0);if(e.pendingQuestion===void 0&&t?.pendingQuestion&&e.status!=="input_required"&&!tr(t,e)&&(s.pendingQuestion=null,n=!0),am(t,e)?(s.status!==t.status&&(s.status=t.status,n=!0),s.waitReason!==t.waitReason&&(s.waitReason=t.waitReason,n=!0)):e.waitReason===void 0&&t?.waitReason&&e.status!=="waiting"&&e.status!=="input_required"&&(s.waitReason=null,n=!0),zd(t,e)?s.error!==t.error&&(s.error=t.error,n=!0):e.error===void 0&&t?.error&&e.status!=="failed"&&e.status!=="error"&&(s.error=null,n=!0),e.result===void 0&&t?.result&&e.status!=="completed"&&(s.result=null,n=!0),lm(t,e))for(const l of["cronActive","cronKind","cronInterval","cronReason","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[l]!=null&&(Js(s[l],t[l])||(s[l]=t[l],n=!0));else if(e.cronActive!==!0){t?.cronReason&&(s.cronReason=null,n=!0);for(const l of["cronKind","cronNextFireAt","cronTimezone","cronMaxFires","cronFiresCompleted"])t?.[l]!=null&&e[l]===void 0&&(s[l]=null,n=!0);t?.cronInterval!=null&&e.cronInterval===void 0&&(s.cronInterval=null,n=!0)}if((Yl(e.status)||Vl(e.orchestrationStatus))&&t?.contextUsage?.compaction?.state==="running"&&e.contextUsage===void 0){const l={...t.contextUsage};delete l.compaction,s.contextUsage=Object.keys(l).length>0?l:null,n=!0}return n?s:null}function No(t){return String(t||"").replace(/\r\n/g,`
66
+ `).trim()}function Vl(t){return t==="Completed"||t==="Failed"||t==="Terminated"}function Yl(t){return t==="completed"||t==="failed"||t==="cancelled"}function _e(t){return String(t||"").slice(0,8)}function en(t){const e=String(t?.provider||"").trim(),s=String(t?.subject||"").trim();return e&&s?`${e}${s}`:null}function As(t,e="unknown user"){return String(t?.displayName||t?.email||"").trim()||e}const um=en({provider:"system",subject:"system"});function Mo(t){const e=t.auth?.principal||null,s=en(e),n=[{id:"all",kind:"all",label:"All",description:"Show every session, including system and unowned sessions."},{id:"system",kind:"system",label:"System",description:"Show sessions created by system agents."},{id:"unowned",kind:"unowned",label:"Unowned",description:"Show non-system sessions that do not have an owner link."}];if(s){const r=As(e,"current user");n.push({id:"me",kind:"me",label:`Me (${r})`,ownerKey:s,description:"Show sessions owned by the authenticated user currently signed in."}),n.push({id:"shared",kind:"shared",label:"Shared with me",description:"Show sessions other users have shared with you."})}const i=new Map;for(const r of Object.values(t.sessions?.byId||{})){const o=r?.owner,l=en(o);!l||l===s||l===um||i.has(l)||i.set(l,o)}for(const[r,o]of[...i.entries()].sort((l,c)=>As(l[1]).localeCompare(As(c[1])))){const l=As(o),c=String(o?.email||"").trim();n.push({id:`owner:${r}`,kind:"owner",ownerKey:r,label:c&&c!==l?`${l} <${c}>`:l,description:"Show sessions owned by this user."})}return n}function tn(t){return en(t)?{all:!1,includeSystem:!0,includeUnowned:!1,includeMe:!0,includeShared:!0,ownerKeys:[]}:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function dm(t){return!!(t?.includeSystem||t?.includeUnowned||t?.includeMe||t?.includeShared||Array.isArray(t?.ownerKeys)&&t.ownerKeys.length>0)}function pm(t,e,s){const n=t||tn(s);if(!e)return n;if(e.kind==="all")return n.all?tn(s):{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]};const i={...n,all:!1,ownerKeys:Array.isArray(n.ownerKeys)?[...n.ownerKeys]:[]};if(e.kind==="system"&&(i.includeSystem=!i.includeSystem),e.kind==="unowned"&&(i.includeUnowned=!i.includeUnowned),e.kind==="me"&&(i.includeMe=!i.includeMe),e.kind==="shared"&&(i.includeShared=!i.includeShared),e.kind==="owner"&&e.ownerKey){const r=i.ownerKeys.indexOf(e.ownerKey);r>=0?i.ownerKeys.splice(r,1):i.ownerKeys.push(e.ownerKey)}return dm(i)?i:{all:!0,includeSystem:!1,includeUnowned:!1,includeMe:!1,includeShared:!1,ownerKeys:[]}}function sr(t){if(!t?.agentId||t?.isSystem)return null;const e=String(t?.title||"").trim();if(!e)return null;const s=e.indexOf(": ");return s>0&&e.slice(0,s).trim()||null}function fm(t){const e=sr(t);return e?Math.max(1,60-`${e}: `.length):60}function hm(t){const e=String(t?.title||"").trim();if(!e)return"";const s=sr(t);if(s&&e.startsWith(`${s}: `)){const n=e.slice(`${s}: `.length).trim();return!n||n===_e(t?.sessionId)?"":n}return e===_e(t?.sessionId)?"":e}function Po(t,e){const s=String(e||"").trim();if(s)return s;const n=String(t||"").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):"Agent"}const ms="builtin",Xl="installed:shared",Ql="installed:mine";function Zl(t){const e=String(t?.packageScope||t?.scope||"shared"),s=String(t?.ownerLabel||"");return`pkg:${e}:${s}:${String(t?.packageName||"")}`}function Cs(t){return String(t||"").toLowerCase().replace(/[^a-z0-9]+/g,"")}function Ro(t){const e=new Map;for(const p of t)p?.agentName&&e.set(Cs(p.agentName),p);const s=new Map,n=new Map;for(const p of t){const d=Cs(p.agentName),f=(p.startedBy||[]).map(m=>Cs(m)).filter(m=>m&&e.has(m)&&m!==d);if(f.length===0)continue;const h=f[0];n.set(p,h),s.has(h)||s.set(h,[]),s.get(h).push(p)}const i=p=>n.has(p),r=p=>typeof p.supportsDirectStart=="boolean"?p.supportsDirectStart:!i(p),o=[],l=new Set,c=(p,d,f)=>{if(!l.has(p)){l.add(p),o.push({...p,depth:d,parentAgentName:f||null,supportsDirectStart:r(p)});for(const h of s.get(Cs(p.agentName))||[])c(h,d+1,p.agentName)}};for(const p of t)i(p)||c(p,0,null);const u=p=>{const d=new Set;let f=p;for(;f&&!d.has(f);)if(d.add(f),f=e.get(n.get(f)),f===p)return!0;return!1};for(const p of t)!l.has(p)&&u(p)&&c(p,0,null);for(const p of t)c(p,0,null);return o}function mm(t=[]){const e=t.findIndex(n=>n.kind!=="section");if(e>=0)return e;const s=t.findIndex(n=>n.kind==="section"&&n.collapsed);return s>=0?s:0}function _o(t=[],e=[],s=null){const n=new Set(e),i=[],r=t.filter(l=>l.builtin),o=t.filter(l=>!l.builtin);if(s&&i.push({...s,depth:0}),r.length>0){const l=Ro(r);i.push({id:`section:${ms}`,kind:"section",sectionKind:"builtin",sectionKey:ms,title:"Built-in",meta:`${l.length} agent${l.length===1?"":"s"}`,collapsed:n.has(ms),depth:0}),n.has(ms)||i.push(...l.map(c=>({...c,depth:c.depth+1})))}for(const[l,c,u]of[[Xl,"Installed · Shared",p=>p.group!=="mine"],[Ql,"Installed · Yours",p=>p.group==="mine"]]){const p=o.filter(u);if(p.length===0)continue;const d=new Map;for(const h of p){const m=Zl(h);d.has(m)||d.set(m,[]),d.get(m).push(h)}if(i.push({id:`section:${l}`,kind:"section",sectionKind:"installed",sectionKey:l,title:c,meta:`${d.size} package${d.size===1?"":"s"}`,collapsed:n.has(l),depth:0}),n.has(l))continue;const f=[...d.keys()].sort((h,m)=>{const g=d.get(h)[0],S=d.get(m)[0];return String(g.packageTitle||g.packageName||"").localeCompare(String(S.packageTitle||S.packageName||""))});for(const h of f){const m=Ro(d.get(h)),g=m[0]||{},S=m.filter(y=>y.depth===0).length;i.push({id:`section:${h}`,kind:"section",sectionKind:"package",sectionKey:h,title:g.packageTitle||g.packageName||"Package",packageName:g.packageName||null,packageSemver:g.packageSemver||null,packageScope:g.packageScope||null,ownerLabel:g.ownerLabel||null,mine:g.group==="mine",meta:`${S} ${S===1?"entry":"entries"} · ${m.length} agent${m.length===1?"":"s"}`,collapsed:n.has(h),depth:1}),!n.has(h)&&i.push(...m.map(y=>({...y,depth:y.depth+2})))}}return i}function Lo(t){return`📎 ${String(t||"").trim()}`}function Oo(t,e){const s=String(t||""),n=be(s,e,s.length),r=s.slice(0,n).match(/(^|\s)(@@?)([^\s]*)$/u);if(!r)return null;const o=r[2],l=String(r[3]||"");return{kind:o==="@@"?"sessions":"artifacts",query:l,signature:`${o}${l}`,tokenStart:(r.index||0)+String(r[1]||"").length,tokenEnd:n}}function gm(t,e,s,n){const i=String(t||""),r=be(i,e),o=be(i,s),l=String(n||"");return{prompt:`${i.slice(0,r)}${l}${i.slice(o)}`,cursor:r+l.length}}function ym(t,e="session"){return String(t||"").replace(/\s+/gu," ").trim()||e}function Sm(t){const e=String(t?.sessionId||"").trim(),s=_e(e)||"session";return`Referenced session: ${ym(t?.title,s)} — session://${e}`}function $o(t,e,s){if(!e)return dt(t,String(t||"").length,s);const n=String(t||""),i=n.slice(e.tokenEnd,e.tokenEnd+1),r=!i||/\s/u.test(i);return gm(n,e.tokenStart,e.tokenEnd,`${String(s||"")}${r?" ":""}`)}function bm(t,e=[]){let s=String(t||"");for(const n of e||[]){const i=String(n?.token||"").trim();i&&(s=s.split(i).join(" "))}return s.replace(/[ \t]+\n/g,`
67
+ `).replace(/\n[ \t]+/g,`
68
+ `).replace(/[ \t]{2,}/g," ").trim()}const Fo=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Do=4*1024*1024,jn=4;function wm(t,e=[]){const s=Array.isArray(e)?e.filter(r=>r?.sessionId&&r?.filename&&r?.kind!=="image"):[];if(s.length===0)return String(t||"");const n=s.map(r=>`[Attached file: ${r.filename} — artifact://${r.sessionId}/${r.filename}]`),i=bm(t,s);return n.join(`
69
+ `)+(i?`
70
+
71
+ ${i}`:"")}function Rt(t,e){return String(t||"").replace(/\r?\n/g," ").slice(0,Math.max(0,Number(e)||0))}function Jl(t){return Array.from(String(t||"")).length}function vm(t){const e=[];for(const s of t||[]){if(s?.kind==="markup"){const n=Aa(s.value||"");for(const i of n)e.push(i);continue}if(Array.isArray(s)){e.push(s);continue}e.push(s)}return e}function Em(t,e){const s=Math.max(1,Number(e)||1),n=Jl(t);return Math.max(1,Math.ceil(n/s))}function _t(t,e){const s=Math.max(1,Number(e)||1);return vm(t).reduce((n,i)=>{if(!i)return n+1;if(Array.isArray(i)){const r=i.reduce((o,l)=>o+Jl(l?.text||""),0);return n+Math.max(1,Math.ceil(r/s))}return n+Em(i.text||"",s)},0)}function be(t,e){const s=String(t||"");return Math.max(0,Math.min(Number(e)||0,s.length))}function ec(t){return String(t||"").split(`
72
+ `)}function xm(t,e){const n=String(t||"").slice(0,be(t,e)).split(`
73
+ `),i=n[n.length-1]||"";return{line:Math.max(0,n.length-1),column:i.length}}function Im(t,e,s){const n=ec(t),i=Math.max(0,Math.min(Number(e)||0,Math.max(0,n.length-1))),r=Math.max(0,Math.min(Number(s)||0,n[i]?.length||0));let o=0;for(let l=0;l<i;l+=1)o+=(n[l]?.length||0)+1;return be(t,o+r)}function dt(t,e,s){const n=String(t||""),i=be(n,e),r=String(s||"");return{prompt:`${n.slice(0,i)}${r}${n.slice(i)}`,cursor:i+r.length}}function Lt(t,e){const s=String(t||""),n=be(s,e);return n<=0?{prompt:s,cursor:n}:{prompt:`${s.slice(0,n-1)}${s.slice(n)}`,cursor:n-1}}function Ts(t){return/\s/u.test(t||"")}function tc(t,e,s){const n=String(t||"");let i=be(n,e);if(s<0){for(;i>0&&Ts(n[i-1]);)i-=1;for(;i>0&&!Ts(n[i-1]);)i-=1;return i}for(;i<n.length&&Ts(n[i]);)i+=1;for(;i<n.length&&!Ts(n[i]);)i+=1;return i}function km(t,e){const s=String(t||""),n=be(s,e),i=tc(s,n,-1);return i===n?{prompt:s,cursor:n}:{prompt:`${s.slice(0,i)}${s.slice(n)}`,cursor:i}}function Am(t,e,s){const n=ec(t);if(n.length<=1)return be(t,e);const i=xm(t,e),r=Math.max(0,Math.min(i.line+s,n.length-1));return r===i.line?be(t,e):Im(t,r,i.column)}const fi=3e3,Cm=new Set(["logs","sequence"]),Tm=2e5,Nm=new Set([".md",".markdown",".mdown",".mkd",".mdx"]),Mm=new Set([".json",".jsonl"]),Pm=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".ico",".pdf",".zip",".gz",".tgz",".tar",".wasm",".sqlite",".db"]);function sc(t){const e=String(t||""),s=e.lastIndexOf(".");return s>=0?e.slice(s).toLowerCase():""}function Rm(t,e=""){const s=sc(t),n=String(e||"").toLowerCase();return Pm.has(s)?!0:n.startsWith("image/")||n==="application/pdf"||n.startsWith("application/zip")||n==="application/wasm"}const Gn=12e4;function Bo(t,e=Tm){const s=String(t??"");return s.length<=e?s:`${s.slice(0,e)}
74
+
75
+ [Preview truncated at ${e.toLocaleString()} characters. Open the artifact directly if you need the full file.]`}function _m(t){const e=Number(t);if(!Number.isFinite(e)||e<0)return"?";if(e<1024)return`${Math.round(e)} B`;if(e<1024*1024){const n=e/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=e/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function Lm(t,e="",s=null){const n=[`Preview is not available here for ${t}.`,""];return e&&n.push(`Type: ${e}`),s!=null&&n.push(`Size: ${_m(s)}`),n.push("Download the artifact to open it in the default app."),n.join(`
76
+ `)}function Ho(t,e,s="",n=null){const i=String(s||"").toLowerCase(),r=sc(t);if(n?.isBinary===!0||Rm(t,s))return{content:Lm(t,n?.contentType||s,n?.sizeBytes??null),contentType:n?.contentType||s||"application/octet-stream",renderMode:"note",isBinary:!0,sizeBytes:n?.sizeBytes??null,uploadedAt:n?.uploadedAt||"",source:n?.source||"agent"};const o=Bo(e);if(Nm.has(r)||i.includes("markdown"))return{content:o,contentType:s||"text/markdown",renderMode:"markdown",isBinary:!1,sizeBytes:n?.sizeBytes??null,uploadedAt:n?.uploadedAt||"",source:n?.source||"agent"};if(Mm.has(r)||i.includes("json"))try{return{content:Bo(JSON.stringify(JSON.parse(String(e??"")),null,2)),contentType:s||"application/json",renderMode:"text"}}catch{return{content:o,contentType:s||"application/json",renderMode:"text"}}return{content:o,contentType:s||"text/plain",renderMode:"text"}}const Om=1e4,$m=140,Fm=1500;class Dm{constructor({store:e,transport:s}){this.store=e,this.transport=s,this.catalogTimer=null,this.activeSessionUnsub=null,this.activeSessionSubscriptionId=null,this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.sessionRefreshTimer=null,this.sessionHistoryLoads=new Map,this.sessionHistoryExpansionLoads=new Map,this.sessionOrchestrationStatsLoads=new Map,this.outboxFlushPromises=new Map,this.logUnsubscribe=null,this.promptReferenceSignature=null,this.promptReferenceSyncVersion=0,this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}getState(){return this.store.getState()}subscribe(e){return this.store.subscribe(e)}dispatch(e){return this.store.dispatch(e)}setStatus(e){this.dispatch({type:"ui/status",text:e})}getPromptAttachments(){const e=this.getState().ui.promptAttachments;return Array.isArray(e)?e.filter(Boolean):[]}setPromptAttachments(e){this.dispatch({type:"ui/promptAttachments",attachments:Array.isArray(e)?e:[]})}getSessionOutbox(e){if(!e)return[];const s=this.getState().outbox?.bySessionId?.[e];return Array.isArray(s)?s.filter(Boolean):[]}setSessionOutboxItems(e,s){e&&this.dispatch({type:"outbox/setSessionItems",sessionId:e,items:Array.isArray(s)?s:[]})}buildOutboxItem(e,s="pending"){const n=`msg:${Date.now()}:${Math.random().toString(36).slice(2,10)}`,i=s==="queued"||s==="cancelling"?s:"pending";return{id:n,text:String(e||""),createdAt:Date.now(),phase:i,attempted:!1,clientMessageIds:[n]}}getPendingOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="pending")}getQueuedOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="queued")}getNavigableOutboxItems(e){return this.getSessionOutbox(e).filter(s=>s?.phase==="pending"||s?.phase==="queued"||s?.phase==="cancelling")}getEditableOutboxItems(e){return this.getPendingOutboxItems(e).filter(s=>s?.attempted!==!0)}getPromptEditSessionMatch(e=this.getState().sessions.activeSessionId){const s=this.getState().ui.promptEdit;return s?.sessionId===e?s:null}enterPendingPromptEdit(e,s){if(!e||!s)return!1;const i=this.getNavigableOutboxItems(e).find(c=>c.id===s);if(!i)return!1;const r=this.getState().ui,o=this.getPromptEditSessionMatch(e),l=o?{...o,itemId:s,phase:i.phase}:{sessionId:e,itemId:s,phase:i.phase,draftPrompt:r.prompt,draftCursor:r.promptCursor};return this.dispatch({type:"ui/promptEdit",promptEdit:l}),this.setPrompt(i.text,i.text.length),this.setFocus(N.PROMPT),!0}exitPendingPromptEdit({restoreDraft:e=!0}={}){const s=this.getState().ui.promptEdit;return s?(this.dispatch({type:"ui/promptEdit",promptEdit:null}),e&&this.setPrompt(s.draftPrompt||"",Number.isFinite(s.draftCursor)?s.draftCursor:String(s.draftPrompt||"").length),!0):!1}selectPreviousPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e);if(s.length===0)return!1;const n=this.getPromptEditSessionMatch(e);if(!n)return this.enterPendingPromptEdit(e,s[s.length-1].id);const i=s.findIndex(r=>r.id===n.itemId);return i<=0?!1:this.enterPendingPromptEdit(e,s[i-1].id)}selectNextPendingPrompt(e=this.getState().sessions.activeSessionId){const s=this.getNavigableOutboxItems(e),n=this.getPromptEditSessionMatch(e);if(!n)return!1;const i=s.findIndex(r=>r.id===n.itemId);return i===-1||i>=s.length-1?this.exitPendingPromptEdit({restoreDraft:!0}):this.enterPendingPromptEdit(e,s[i+1].id)}async cancelSelectedOutboxPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const n=this.getSessionOutbox(e.sessionId).find(r=>r.id===e.itemId);return n?n.phase==="cancelling"?(this.exitPendingPromptEdit({restoreDraft:!0}),!1):await this.cancelOutboxItem(e.sessionId,e.itemId)?(this.exitPendingPromptEdit({restoreDraft:!0}),!0):!1:!1}cancelSelectedPendingPrompt(){const e=this.getState().ui.promptEdit;if(!e?.sessionId||!e?.itemId)return!1;const s=this.getSessionOutbox(e.sessionId);if(!s.find(r=>r.id===e.itemId&&r.phase==="pending"))return!1;const i=s.filter(r=>r.id!==e.itemId);return this.setSessionOutboxItems(e.sessionId,i),this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"ui/status",text:"Cancelled pending prompt"}),!0}async cancelOutboxItem(e,s){if(!e||!s)return!1;const n=this.getSessionOutbox(e),i=n.find(o=>o.id===s);if(!i||i.phase==="cancelling")return!1;this.getPromptEditSessionMatch(e)?.itemId===s&&this.exitPendingPromptEdit({restoreDraft:!0});const r=Array.isArray(i.clientMessageIds)&&i.clientMessageIds.length>0?i.clientMessageIds:[i.id];if(i.phase==="queued")if(this.setSessionOutboxItems(e,n.map(o=>o.id===s?{...o,phase:"cancelling"}:o)),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,r),this.dispatch({type:"ui/status",text:"Cancelling queued prompt"})}catch(o){return this.setSessionOutboxItems(e,n),this.dispatch({type:"ui/status",text:o?.message||String(o)}),!1}else this.dispatch({type:"ui/status",text:"Queued prompt marked cancelling (local only — transport has no cancel)"});else{const o=n.filter(l=>l.id!==s);if(this.setSessionOutboxItems(e,o),typeof this.transport?.cancelPendingMessage=="function")try{await this.transport.cancelPendingMessage(e,r)}catch{}this.dispatch({type:"ui/status",text:"Cancelled pending prompt"})}return!0}async cancelLatestQueuedOutbox(e=this.getState().sessions.activeSessionId){if(!e)return!1;const s=this.getQueuedOutboxItems(e);if(s.length===0)return!1;const n=s[s.length-1];return await this.cancelOutboxItem(e,n.id)}queuePromptInOutbox(e,s,n=null){const i=this.buildOutboxItem(s,"pending");return Array.isArray(n?.attachments)&&n.attachments.length>0&&(i.attachments=n.attachments),this.setSessionOutboxItems(e,[...this.getSessionOutbox(e),i]),i}addPendingImageFiles(e){const s=Array.from(e||[]).filter(Boolean),n=this.getPromptAttachments(),i=n.filter(l=>l?.kind==="image"),r=[],o=[];for(const l of s){const c=String(l.type||"").toLowerCase();if(!Fo.has(c)){o.push({name:l.name||"image",reason:"unsupported type"});continue}if((Number(l.size)||0)>Do){o.push({name:l.name||"image",reason:"over 4 MB"});continue}if(i.length+r.length>=jn){o.push({name:l.name||"image",reason:`max ${jn} images`});continue}r.push({kind:"image",file:l,filename:String(l.name||"image"),contentType:c,sizeBytes:Number(l.size)||0})}return r.length>0&&this.setPromptAttachments([...n,...r]),o.length>0&&this.dispatch({type:"ui/status",text:`Skipped ${o.map(l=>`${l.name} (${l.reason})`).join(", ")}`}),{accepted:r.length,rejected:o}}stageUploadedImageAttachment(e,s){const n=String(e?.contentType||"").toLowerCase();return!Fo.has(n)||(Number(e?.sizeBytes)||0)>Do||this.getPromptAttachments().filter(r=>r?.kind==="image").length>=jn?!1:(this.setPromptAttachments([...this.getPromptAttachments(),{kind:"image",uploaded:!0,sessionId:s,filename:e.filename,contentType:n,sizeBytes:Number(e?.sizeBytes)||0}]),!0)}async pasteImageFromClipboard(){if(typeof this.transport.captureClipboardImage!="function"||typeof this.transport.uploadArtifactFromPath!="function")return this.dispatch({type:"ui/status",text:"Clipboard image paste is not supported by this transport"}),!1;let e=null;try{e=await this.transport.captureClipboardImage()}catch(s){return this.dispatch({type:"ui/status",text:`Clipboard read failed: ${s?.message||s}`}),!1}if(!e?.path)return this.dispatch({type:"ui/status",text:"No image on the clipboard"}),!1;this.dispatch({type:"ui/status",text:"Attaching clipboard image..."});try{const s=this.getPromptDraftSessionId()||await this.ensurePromptAttachmentSessionId(),n=await this.transport.uploadArtifactFromPath(s,e.path),i=await this.finalizeArtifactUpload(n,{sessionId:s,suppressStatus:!0});return this.stageUploadedImageAttachment(i,s)?(this.dispatch({type:"ui/status",text:`Clipboard image attached to your next message (${i.filename})`}),!0):(this.dispatch({type:"ui/status",text:`Uploaded ${i.filename} (not attachable: type/size/count limit)`}),!1)}catch(s){return this.dispatch({type:"ui/status",text:`Clipboard image attach failed: ${s?.message||s}`}),!1}}removePendingImageAttachment(e){const s=this.getPromptAttachments(),i=s.filter(r=>r?.kind==="image")[e];i&&this.setPromptAttachments(s.filter(r=>r!==i))}async uploadPendingImageAttachments(e,s,n){const i=[],r=String(n||Date.now()).replace(/[^a-zA-Z0-9_-]/g,"").slice(-24)||"img";let o=0;for(const l of s){if(!l.file){l.uploaded&&l.filename&&i.push({filename:l.filename});continue}o+=1;const c={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"}[l.contentType]||"png",u=`attach-${r}-${o}.${c}`;await this.transport.uploadArtifactFromFile(e,l.file,u),i.push({filename:u})}return i}acknowledgeOutboxPrompt(e,s,n=null){if(!e)return!1;const i=this.getSessionOutbox(e);if(n){const c=i.findIndex(u=>(u?.phase==="pending"||u?.phase==="queued"||u?.phase==="cancelling")&&Array.isArray(u.clientMessageIds)&&u.clientMessageIds.includes(n));if(c!==-1){const u=i[c];return this.setSessionOutboxItems(e,i.filter((p,d)=>d!==c)),this.getPromptEditSessionMatch(e)?.itemId===u?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}}const r=No(s);if(!r)return!1;const o=i.findIndex(c=>(c?.phase==="pending"||c?.phase==="queued"||c?.phase==="cancelling")&&No(c.text)===r);if(o===-1)return!1;const l=i[o];return this.setSessionOutboxItems(e,i.filter((c,u)=>u!==o)),this.getPromptEditSessionMatch(e)?.itemId===l?.id&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}acknowledgeCancelledOutboxPrompt(e,s=[]){if(!e)return!1;const n=new Set((s||[]).filter(c=>typeof c=="string"&&c));if(n.size===0)return!1;const i=this.getSessionOutbox(e),r=i.filter(c=>c?.phase!=="cancelling"?!0:!(Array.isArray(c.clientMessageIds)?c.clientMessageIds:[c.id]).some(p=>n.has(p)));if(r.length===i.length)return!1;const o=new Set(i.filter(c=>!r.some(u=>u.id===c.id)).map(c=>c.id));this.setSessionOutboxItems(e,r);const l=this.getPromptEditSessionMatch(e);return l&&o.has(l.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0}),!0}scheduleOutboxDispatch(e){if(!e||(this._outboxDispatchTimers||(this._outboxDispatchTimers=new Map),this._outboxDispatchTimers.has(e)))return;const s=setTimeout(()=>{this._outboxDispatchTimers.delete(e),this.dispatchPendingOutbox(e).catch(()=>{})},10);this._outboxDispatchTimers.set(e,s)}async dispatchPendingOutbox(e){if(!e)return!1;await Promise.resolve();const s=this.outboxFlushPromises.get(e);if(s)return await s.catch(()=>{}),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e),!1;const n=this.getPendingOutboxItems(e),i=n.find(m=>m?.attempted===!0),r=i?[i]:n.filter(m=>m?.attempted!==!0);if(r.length===0)return!1;const o=r.flatMap(m=>Array.isArray(m.clientMessageIds)&&m.clientMessageIds.length>0?m.clientMessageIds:[m.id]),l=r.map(m=>String(m.text||"")).join(`
77
+
78
+ `),c=r.flatMap(m=>Array.isArray(m.attachments)?m.attachments:[]),u={id:r[0].id,text:l,createdAt:r[0].createdAt||Date.now(),phase:"pending",attempted:!0,clientMessageIds:o,...c.length>0?{attachments:c}:{}},p=new Set(r.map(m=>m.id)),d=this.getSessionOutbox(e).filter(m=>!p.has(m.id));this.setSessionOutboxItems(e,[...d,u]);const f=this.getPromptEditSessionMatch(e);f&&p.has(f.itemId)&&this.exitPendingPromptEdit({restoreDraft:!0});const h=(async()=>{await this.transport.sendMessage(e,u.text,{enqueueOnly:!0,clientMessageIds:u.clientMessageIds,...Array.isArray(u.attachments)&&u.attachments.length>0?{attachments:u.attachments}:{}});const g=this.getSessionOutbox(e).map(S=>S.id===u.id?{...S,phase:"queued"}:S);return this.setSessionOutboxItems(e,g),this.syncSessionEvents(e).catch(()=>{}),this.scheduleSessionsRefresh(250),!0})().catch(m=>{const g=m?.code==="FORBIDDEN"||m?.code==="UNAUTHORIZED"||m?.status===403||m?.status===401,S=this.getSessionOutbox(e);if(g){const y=S.map(v=>v.id===u.id?{...v,phase:"rejected"}:v);this.setSessionOutboxItems(e,y),setTimeout(()=>{const v=this.getSessionOutbox(e),x=v.filter(E=>!(E.id===u.id&&E.phase==="rejected"));x.length!==v.length&&this.setSessionOutboxItems(e,x)},6e3)}else{const y=S.map(v=>v.id===u.id?{...u,phase:"pending",attempted:!0}:v);this.setSessionOutboxItems(e,y)}throw this.dispatch({type:"ui/status",text:m?.message||String(m)}),m}).finally(()=>{this.outboxFlushPromises.delete(e),this.getPendingOutboxItems(e).length>0&&this.scheduleOutboxDispatch(e)});return this.outboxFlushPromises.set(e,h),await h}async flushQueuedOutbox(e){return await this.dispatchPendingOutbox(e)}maybeFlushQueuedOutbox(e){return!e||this.getPendingOutboxItems(e).length===0?!1:(this.scheduleOutboxDispatch(e),!0)}getPromptReferenceContext(){const e=this.getState();return Oo(e.ui.prompt,e.ui.promptCursor)}acceptPromptReferenceAutocomplete(){const e=this.getPromptReferenceContext();return e?e.kind==="sessions"?this.acceptSessionPromptReference(e):this.acceptArtifactPromptReference(e):!1}acceptArtifactPromptReference(e=this.getPromptReferenceContext()){if(!e||e.kind!=="artifacts")return!1;const s=this.getState(),n=ut(s),i=n?.sessionId||s.sessions.activeSessionId||null,r=n?.filename||null;if(!i||!r)return!1;const o=Lo(r),l=$o(s.ui.prompt,e,o),c=this.getPromptAttachments(),u=c.findIndex(f=>f?.sessionId===i&&f?.filename===r),p={...u>=0?c[u]:{},id:`${i}/${r}`,sessionId:i,filename:r,resolvedPath:r,token:o},d=u>=0?c.map((f,h)=>h===u?p:f):[...c,p];return this.setPrompt(l.prompt,l.cursor),this.setPromptAttachments(d),this.setFocus(N.PROMPT),this.dispatch({type:"ui/status",text:`Attached ${r}`}),!0}acceptSessionPromptReference(e=this.getPromptReferenceContext()){if(!e||e.kind!=="sessions")return!1;const s=this.getState(),i=Qt(s)[0]||null,r=i?.sessionId&&s.sessions.byId[i.sessionId]||null;if(!r?.sessionId)return!1;const o=Sm(r),l=$o(s.ui.prompt,e,o);return this.setPrompt(l.prompt,l.cursor),this.setFocus(N.PROMPT),this.dispatch({type:"ui/status",text:`Referenced session ${_e(r.sessionId)}`}),!0}setSessionFilterQuery(e=""){this.dispatch({type:"sessions/filterQuery",query:String(e||"")})}openSessionOwnerFilter(){const e=this.getState(),s=Mo(e);this.dispatch({type:"ui/modal",modal:{type:"sessionOwnerFilter",title:"Session Filter",previousFocus:e.ui.focusRegion,selectedIndex:0,items:s}}),this.dispatch({type:"ui/status",text:"Up/Down choose entry · Space toggle · Esc close"})}toggleSessionOwnerFilter(e=null){const s=this.getState(),n=s.ui.modal;if(!n||n.type!=="sessionOwnerFilter")return;const i=e==null?Math.max(0,Number(n.selectedIndex)||0):Math.max(0,Number(e)||0),r=n.items?.[i];if(!r)return;const o=pm(s.sessions.ownerFilter,r,s.auth?.principal);this.dispatch({type:"sessions/ownerFilter",filter:o}),this.dispatch({type:"ui/modalSelection",index:i}),this.dispatch({type:"ui/status",text:`Session filter updated: ${r.label||r.id||"selection"}`})}refreshOpenSessionOwnerFilterModal(){const e=this.getState(),s=e.ui.modal;if(!s||s.type!=="sessionOwnerFilter")return;const n=Mo(e),i=Array.isArray(s.items)?s.items:[];if(i.length===n.length&&i.every((u,p)=>u?.id===n[p]?.id))return;const o=i[Math.max(0,Number(s.selectedIndex)||0)]?.id,l=o!=null?n.findIndex(u=>u.id===o):-1,c=l>=0?l:Math.max(0,Math.min(Number(s.selectedIndex)||0,Math.max(0,n.length-1)));this.dispatch({type:"ui/modal",modal:{...s,items:n,selectedIndex:c}})}setFilesFilter(e={}){this.dispatch({type:"files/filter",filter:e})}clearPromptReferenceBrowser(){this.promptReferenceSignature=null,this.promptReferenceSyncVersion+=1,this.getState().sessions.filterQuery&&this.setSessionFilterQuery(""),this.getState().files.filter?.query&&this.setFilesFilter({query:""})}syncPromptReferenceBrowser(){const e=this.getState(),s=Oo(e.ui.prompt,e.ui.promptCursor);if(!s){this.clearPromptReferenceBrowser();return}if(this.promptReferenceSignature===s.signature)return;if(this.promptReferenceSignature=s.signature,s.kind==="sessions"){this.promptReferenceSyncVersion+=1,this.setFilesFilter({query:""}),this.setSessionFilterQuery(s.query);return}const n=e.sessions.activeSessionId;if(this.setSessionFilterQuery(""),this.setFilesFilter({scope:"selectedSession",query:s.query}),!n)return;this.selectInspectorTab("files").catch(()=>{});const i=++this.promptReferenceSyncVersion;this.ensureFilesForScope("selectedSession").then(async()=>{if(this.promptReferenceSyncVersion!==i)return;const r=new Set(Qs(this.getState(),"selectedSession")),l=It(this.getState()).filter(c=>r.has(c.sessionId))[0]||null;l?.filename&&(this.dispatch({type:"files/select",sessionId:l.sessionId,filename:l.filename}),await this.ensureFilePreview(l.sessionId,l.filename).catch(()=>{}))}).catch(()=>{})}async start({initialSessionId:e=null}={}){await this.transport.start();const s=typeof this.transport.getAuthContext=="function"?this.transport.getAuthContext():null;this.dispatch({type:"auth/context",principal:s?.principal??null,authorization:s?.authorization??null}),this.getState().sessions.ownerFilterExplicit||this.dispatch({type:"sessions/ownerFilter",filter:tn(s?.principal??null)});const n=typeof this.transport.getLogConfig=="function"?this.transport.getLogConfig():null;n&&this.dispatch({type:"logs/config",available:n.available,availabilityReason:n.availabilityReason}),this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,statusText:"Connected"});const i=String(e||"").trim();i&&this.dispatch({type:"sessions/navigationIntent",sessionId:i}),await this.refreshSessions(),this.catalogTimer=setInterval(()=>{this.refreshSessions().catch(r=>{this.dispatch({type:"connection/error",error:r?.message||String(r),statusText:ko})})},4e3)}async stop(){this.catalogTimer&&clearInterval(this.catalogTimer),this.catalogTimer=null,this.activeSessionDetailTimer&&clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.sessionRefreshTimer&&clearTimeout(this.sessionRefreshTimer),this.sessionRefreshTimer=null,this.sessionHistoryExpansionLoads.clear(),this.sessionOrchestrationStatsLoads.clear(),this.detachActiveSession(),this.detachLogStream(),await this.transport.stop()}detachActiveSession(){this.activeSessionUnsub&&(this.activeSessionUnsub(),this.activeSessionUnsub=null),this.activeSessionSubscriptionId=null}handleSessionGone(e){e&&(ls(e)||(this.activeSessionSubscriptionId===e&&this.detachActiveSession(),this.activeSessionDetailSessionId===e&&this.activeSessionDetailTimer&&(clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null),this.dispatch({type:"sessions/gone",sessionId:e})))}detachLogStream(){this.logUnsubscribe&&(this.logUnsubscribe(),this.logUnsubscribe=null)}async refreshSessions(){this.refreshWorkerRegistryIfStale().catch(()=>{});const e=this.sessionRefreshSeq=(this.sessionRefreshSeq||0)+1,s=this.getState(),n=!s.connection.connected||!!s.connection.error,i=s.ui.statusText===ko,r=this.getState().sessions.activeSessionId;let o=(await em(this.transport)).map(Bn),l=null;if(typeof this.transport.listSessionGroups=="function")try{const h=await this.transport.listSessionGroups();l=(Array.isArray(h)?h:[]).map(Zh).filter(Boolean)}catch(h){console.warn(`[PilotSwarmUi] session-group fetch failed, keeping the known folders: ${h?.message||h}`)}const c=s.sessions.navigationIntent;if(c?.status==="pending"&&!o.some(h=>h?.sessionId===c.sessionId)&&typeof this.transport.getSession=="function")try{const h=await this.transport.getSession(c.sessionId);h?.sessionId?o=[...o,Bn(h)]:this.dispatch({type:"sessions/navigationIntentFailed",sessionId:c.sessionId,errorKind:"not_found"})}catch(h){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:c.sessionId,errorKind:Hn(h)})}const u=r;if(u&&!ls(u)&&!o.some(h=>h?.sessionId===u)&&typeof this.transport.getSession=="function"){const h=await this.transport.getSession(u).catch(()=>null);h?.sessionId&&(o=[...o,Bn(h)])}if(e!==this.sessionRefreshSeq)return;n&&this.dispatch({type:"connection/ready",workersOnline:typeof this.transport.getWorkerCount=="function"?this.transport.getWorkerCount():null,...i?{statusText:"Connected"}:{}}),l&&this.dispatch({type:"sessions/groupsLoaded",groups:l,sessions:o});const p=[];for(const h of o)for(const m of Array.isArray(h?.canvases)?h.canvases:[])p.push({sessionId:h.sessionId,slot:m.slot,name:m.name,latestRev:m.latestRev,sizeBytes:m.sizeBytes});p.length&&this.dispatch({type:"canvas/seed",entries:p}),this.dispatch({type:"sessions/loaded",sessions:o}),this.refreshOpenSessionOwnerFilterModal();const d=this.getState().sessions.activeSessionId,f=new Set;if(d){if(d!==r){if(!this.getState().sessions.byId[d]?.isGroup){const S=this.getState().sessions.navigationIntent;if(S&&S.sessionId===d&&S.status!=="failed")try{await this.loadSession(d)}catch(y){this.dispatch({type:"sessions/navigationIntentFailed",sessionId:d,errorKind:Hn(y)})}else await this.loadSession(d)}return}if(this.getState().sessions.byId[d]?.isGroup)return;this.getState().history.bySessionId.get(d)?.events?.length||await this.ensureSessionHistory(d,{force:!0}).catch(()=>{}),this.ensureCanvasSnapshot(d).catch(()=>{}),this.activeSessionSubscriptionId!==d&&this.attachActiveSession(d),await this.syncSessionDetail(d).catch(()=>{}),await this.syncSessionEvents(d).catch(()=>{}),f.add(d);const m=this.getState(),g=m.sessions.byId[d]||null;if(g?.parentSessionId&&typeof this.transport.getSession=="function"){const S=Object.values(m.sessions.byId).filter(y=>y?.parentSessionId===g.parentSessionId).map(y=>y.sessionId).filter(y=>y&&y!==d).slice(0,6);await Promise.all(S.map(y=>this.syncSessionDetail(y).catch(()=>{})));for(const y of S)f.add(y)}}await this.syncVisibleSessionDetails(f).catch(()=>{}),this.ensureInspectorData().catch(()=>{}),this.evictStaleSessionState()}async refreshWorkerRegistryIfStale(){const e=this.getState().admin?.workers;if(e?.loading){this.dispatch({type:"admin/workers/attempt",skip:"already in flight"});return}if(e?.fetchedAt&&Date.now()-e.fetchedAt<2e4){this.dispatch({type:"admin/workers/attempt",skip:"fresh"});return}this.dispatch({type:"admin/workers/attempt",skip:null}),await this.refreshAdminWorkers()}evictStaleSessionState(){const e=this.getState(),s=e.sessions.activeSessionId,n=Date.now(),i=6e4,r=20,o=Object.entries(e.orchestration.bySessionId||{});if(o.length>r){const p=o.filter(([d,f])=>d!==s&&!f?.loading).sort((d,f)=>(d[1]?.fetchedAt||0)-(f[1]?.fetchedAt||0)).slice(0,o.length-r).filter(([,d])=>n-(d?.fetchedAt||0)>i);p.length>0&&this.dispatch({type:"orchestration/evict",sessionIds:p.map(([d])=>d)})}const l=Object.entries(e.executionHistory?.bySessionId||{});if(l.length>r){const p=l.filter(([d,f])=>d!==s&&!f?.loading).sort((d,f)=>(d[1]?.fetchedAt||0)-(f[1]?.fetchedAt||0)).slice(0,l.length-r).filter(([,d])=>n-(d?.fetchedAt||0)>i);p.length>0&&this.dispatch({type:"executionHistory/evict",sessionIds:p.map(([d])=>d)})}const c=Object.entries(e.files.bySessionId||{});if(c.length>r){const p=c.filter(([d])=>d!==s).slice(0,c.length-r);p.length>0&&this.dispatch({type:"files/evictPreviews",sessionIds:p.map(([d])=>d)})}const u=[...e.history.bySessionId.entries()];if(u.length>r*2){const p=u.filter(([d])=>d!==s).slice(0,u.length-r*2).map(([d])=>d);p.length>0&&this.dispatch({type:"history/evict",sessionIds:p})}}async syncVisibleSessionDetails(e=new Set){if(typeof this.transport.getSession!="function")return;const s=this.getState(),n=gs({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??Wt(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),r=ai(s,i),o=[...new Set(r.map(l=>l.sessionId).filter(l=>l&&!ls(l)&&!e.has(l)))];o.length!==0&&await Promise.all(o.map(l=>this.syncSessionDetail(l).catch(()=>{})))}async catchUpSessionHistory(e,s,n){let r;try{r=await this.transport.getSessionEvents(e,n,1e3)}catch(p){return cs(p)&&this.handleSessionGone(e),null}if(!Array.isArray(r)||r.length>=1e3)return null;if(r.length===0)return s;let o=s;for(const p of r)o=Rr(o,p);o={...o,loadedEventLimit:Math.max(Number(s.loadedEventLimit)||0,Array.isArray(o.events)?o.events.length:0)},this.dispatch({type:"history/set",sessionId:e,history:o});for(const p of r)this.reconcileOutboxAgainstEvent(e,p);const l=pi(r),c=this.getState().sessions.byId[e]||{},u=Co(c.contextUsage,r);return(l||u)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...l||{},...u?{contextUsage:u}:{}}}),o}async ensureSessionHistory(e,{force:s=!1}={}){if(!e)return null;const n=this.getState().history.bySessionId.get(e),i=Math.min(Fm,Math.max(me,Number(n?.loadedEventLimit??me)||me));if(!s&&n?.events)return n;if(!s&&this.sessionHistoryLoads.has(e))return this.sessionHistoryLoads.get(e);const r=Number(n?.lastSeq)||0;if(s&&r>0&&Array.isArray(n?.events)&&n.events.length>0){const l=await this.catchUpSessionHistory(e,n,r);if(l)return l}const o=(async()=>{let l;try{l=await this.transport.getSessionEvents(e,void 0,i)}catch(f){if(cs(f))return this.handleSessionGone(e),null;throw f}const c={...Es(l,{requestedLimit:i}),lastSeq:l[l.length-1]?.seq||0};this.dispatch({type:"history/set",sessionId:e,history:c});for(const f of l||[])this.reconcileOutboxAgainstEvent(e,f);const u=pi(l),p=this.getState().sessions.byId[e]||{},d=Co(p.contextUsage,l);return(u||d)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...u||{},...d?{contextUsage:d}:{}}}),c})().finally(()=>{this.sessionHistoryLoads.delete(e)});return this.sessionHistoryLoads.set(e,o),o}async ensureInspectorData(e=this.getState().ui.inspectorTab){if(e==="sequence"){const s=this.getState().sessions.activeSessionId;if(!s)return;await this.ensureSessionHistory(s).catch(()=>{}),await this.ensureOrchestrationStats(s).catch(()=>{});return}if(e==="nodes"){this.refreshWorkerRegistryIfStale().catch(()=>{});const s=this.getState(),n=gs({width:s.ui.layout.viewportWidth,height:s.ui.layout.viewportHeight},s.ui.layout.paneAdjust,s.ui.promptRows??Wt(s.ui.prompt),s.ui.layout.sessionPaneAdjust,s.ui.layout.activityPaneAdjust,s.ui.fullscreenPane),i=this.getSessionListMaxRows(n),r=ai(s,i),o=[...new Set(r.map(l=>l.sessionId).filter(Boolean))];if(o.length===0)return;await Promise.allSettled(o.map(l=>this.ensureSessionHistory(l)));return}if(e==="files"&&await this.ensureFilesForScope(We(this.getState())),e==="history"){const s=this.getState().sessions.activeSessionId,n=s&&this.getState().executionHistory?.bySessionId?.[s]||null;s&&!n&&await this.ensureExecutionHistory(s)}e==="stats"&&(await this.ensureSessionStats().catch(()=>{}),await this.ensureFleetStats().catch(()=>{}))}async ensureOrchestrationStats(e,{force:s=!1}={}){if(!e||typeof this.transport.getOrchestrationStats!="function")return null;const n=this.getState().orchestration.bySessionId?.[e]||null,i=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&i-n.fetchedAt<zh)return n;if(!s&&this.sessionOrchestrationStatsLoads.has(e))return this.sessionOrchestrationStatsLoads.get(e);this.dispatch({type:"orchestration/statsLoading",sessionId:e});const r=(async()=>{try{const o=await this.transport.getOrchestrationStats(e);return this.dispatch({type:"orchestration/statsLoaded",sessionId:e,stats:o,fetchedAt:Date.now()}),this.getState().orchestration.bySessionId?.[e]||null}catch(o){return cs(o)?(this.handleSessionGone(e),null):(this.dispatch({type:"orchestration/statsError",sessionId:e,error:o?.message||String(o),fetchedAt:Date.now()}),null)}})().finally(()=>{this.sessionOrchestrationStatsLoads.delete(e)});return this.sessionOrchestrationStatsLoads.set(e,r),r}async ensureSessionStats({force:e=!1}={}){const s=this.getState().sessions.activeSessionId;if(!s||typeof this.transport.getSessionMetricSummary!="function")return;const n=this.getState().sessionStats?.bySessionId?.[s]||null,i=Date.now();if(!(!e&&n?.loading)&&!(!e&&n&&Number.isFinite(n.fetchedAt)&&i-n.fetchedAt<Wh)){this.dispatch({type:"sessionStats/loading",sessionId:s});try{const[r,o,l,c,u,p,d]=await Promise.all([this.transport.getSessionMetricSummary(s),typeof this.transport.getSessionTokensByModel=="function"?this.transport.getSessionTokensByModel(s).catch(()=>[]):[],typeof this.transport.getSessionTreeStats=="function"?this.transport.getSessionTreeStats(s):null,typeof this.transport.getSessionSkillUsage=="function"?this.transport.getSessionSkillUsage(s).catch(()=>null):null,typeof this.transport.getSessionTreeSkillUsage=="function"?this.transport.getSessionTreeSkillUsage(s).catch(()=>null):null,typeof this.transport.getSessionFactsStats=="function"?this.transport.getSessionFactsStats(s).catch(()=>null):null,typeof this.transport.getSessionTreeFactsStats=="function"?this.transport.getSessionTreeFactsStats(s).catch(()=>null):null]);this.dispatch({type:"sessionStats/loaded",sessionId:s,summary:r,tokensByModel:o,treeStats:l,skillUsage:c,treeSkillUsage:u,factsStats:p,treeFactsStats:d})}catch{this.dispatch({type:"sessionStats/loaded",sessionId:s,summary:null,tokensByModel:[],treeStats:null,skillUsage:null,treeSkillUsage:null,factsStats:null,treeFactsStats:null})}}}async ensureFleetStats({force:e=!1}={}){if(typeof this.transport.getFleetStats!="function")return;const s=this.getState().fleetStats,n=Date.now();if(!(!e&&s?.loading)&&!(!e&&s?.data&&Number.isFinite(s.fetchedAt)&&n-s.fetchedAt<qh)){this.dispatch({type:"fleetStats/loading"});try{const r={since:new Date(Date.now()-Kh*864e5),includeDeleted:!0},[o,l,c,u,p,d]=await Promise.all([this.transport.getFleetStats(r),typeof this.transport.getUserStats=="function"?this.transport.getUserStats(r).catch(()=>null):null,typeof this.transport.getFleetSkillUsage=="function"?this.transport.getFleetSkillUsage(r).catch(()=>null):null,typeof this.transport.getFleetRetrievalUsage=="function"?this.transport.getFleetRetrievalUsage(r).catch(()=>null):null,typeof this.transport.getSharedFactsStats=="function"?this.transport.getSharedFactsStats().catch(()=>null):null,typeof this.transport.getFactsTombstoneStats=="function"?this.transport.getFactsTombstoneStats().catch(()=>null):null]);this.dispatch({type:"fleetStats/loaded",data:o,userStats:l,skillUsage:c,retrievalUsage:u,sharedFactsStats:p,factsTombstoneStats:d})}catch{this.dispatch({type:"fleetStats/loaded",data:null,userStats:null,skillUsage:null,retrievalUsage:null,sharedFactsStats:null,factsTombstoneStats:null})}}}async openAdminConsole(){this.dispatch({type:"admin/visibility",visible:!0}),await this.refreshAdminProfile().catch(()=>{}),this.refreshAdminAgentPackages().catch(()=>{})}closeAdminConsole(){this.dispatch({type:"admin/visibility",visible:!1})}revealCreatedSession(){this.getState().admin?.visible&&this.closeAdminConsole(),this.setFocus(N.PROMPT)}async refreshAdminProfile(){if(typeof this.transport.getCurrentUserProfile!="function")return this.dispatch({type:"admin/profile/loadFailed",error:"Admin Console is not available on this transport."}),null;this.dispatch({type:"admin/profile/loading"});try{const e=await this.transport.getCurrentUserProfile();return this.dispatch({type:"admin/profile/loaded",profile:e}),await this.refreshSystemGhcpKeyStatus(e),e||null}catch(e){return this.dispatch({type:"admin/profile/loadFailed",error:e?.message||String(e)}),null}}async refreshSystemGhcpKeyStatus(e=null){if(!(e||this.getState().admin?.profile||null)?.isAdmin||typeof this.transport.getSystemGitHubCopilotKeyStatus!="function")return null;this.dispatch({type:"admin/systemGhcpKey/loading"});try{const n=await this.transport.getSystemGitHubCopilotKeyStatus();return this.dispatch({type:"admin/systemGhcpKey/loaded",status:n}),n||null}catch(n){return this.dispatch({type:"admin/systemGhcpKey/loadFailed",error:n?.message||String(n)}),null}}setAdminGhcpKeyStoreAsSystem(e){e&&!this.getState().admin?.profile?.isAdmin||this.dispatch({type:"admin/ghcpKey/setSystemTarget",value:!!e})}setAdminSection(e){this.dispatch({type:"admin/section",section:e}),e==="packages"&&(this.getState().admin?.packages?.fetchedAt||this.refreshAdminAgentPackages().catch(()=>{})),e==="workers"&&this.refreshAdminWorkers().catch(()=>{})}selectNodeMapNode(e){this.dispatch({type:"ui/nodeMapSelect",label:e?String(e):null})}async refreshAdminWorkers(){if(typeof this.transport.listWorkers!="function"){this.dispatch({type:"admin/workers/loadFailed",error:"The worker registry is not available on this deployment."});return}this.dispatch({type:"admin/workers/loading"});try{const e=await Promise.race([Promise.resolve().then(()=>this.transport.listWorkers()),new Promise((s,n)=>{const i=setTimeout(()=>n(new Error("request timed out after 10s (connection or auth renewal wedged — try a hard refresh)")),1e4);typeof i?.unref=="function"&&i.unref()})]);console.info(`[PilotSwarmUi] worker registry: ${Array.isArray(e)?e.length:0} row(s)`),this.dispatch({type:"admin/workers/loaded",list:e})}catch(e){console.warn(`[PilotSwarmUi] worker-registry fetch failed: ${e?.message||e}`),this.dispatch({type:"admin/workers/loadFailed",error:e?.message||String(e)})}}async refreshAdminAgentPackages(){if(typeof this.transport.listAgentPackages!="function"){this.dispatch({type:"admin/packages/loadFailed",error:"Agent packages are not available on this deployment."});return}this.dispatch({type:"admin/packages/loading"});try{const[e,s]=await Promise.all([this.transport.listAgentPackages(),typeof this.transport.listAgentWorkerState=="function"?this.transport.listAgentWorkerState().catch(()=>[]):[]]);this.dispatch({type:"admin/packages/loaded",list:e,workerState:s})}catch(e){this.dispatch({type:"admin/packages/loadFailed",error:e?.message||String(e)})}}async selectAdminPackage(e,s=null){if(this.dispatch({type:"admin/packages/select",name:e,selector:s}),!e)return;const n=this.getState().admin?.packages?.selectionSeq??0;await Promise.all([(async()=>{try{const i=await this.transport.getAgentPackage(e,s);if(!i)throw new Error(`package "${e}" not found`);this.dispatch({type:"admin/packages/detail/loaded",name:e,seq:n,detail:i})}catch(i){this.dispatch({type:"admin/packages/detail/loadFailed",name:e,seq:n,error:i?.message||String(i)})}})(),(async()=>{try{const i=await this.transport.getAgentPackageTree(e,null,s);if((this.getState().admin?.packages?.selectionSeq??0)!==n)return;this.dispatch({type:"admin/packages/tree/loaded",name:e,seq:n,tree:i}),i?.files?.some(l=>l.path==="CHANGELOG.md")&&typeof this.transport.getAgentPackageFile=="function"?(async()=>{try{const l=await this.transport.getAgentPackageFile(e,null,"CHANGELOG.md",s);if((this.getState().admin?.packages?.selectionSeq??0)!==n)return;this.dispatch({type:"admin/packages/changelog/loaded",name:e,seq:n,content:typeof l=="string"?l:l?.content??l?.text??""})}catch{}})():this.dispatch({type:"admin/packages/changelog/loaded",name:e,seq:n,content:null});const o=i?.files?.find(l=>l.path==="plugin.json")??i?.files?.[0];o&&this.selectAdminPackageFile(o.path)}catch(i){this.dispatch({type:"admin/packages/tree/loadFailed",name:e,seq:n,error:i?.message||String(i)})}})()])}async stepAdminPackageSelection(e){const s=this.getState().admin?.packages;if(!s?.list?.length)return;const n=[...s.list.filter(c=>c.scope==="shared"),...s.list.filter(c=>c.scope!=="shared")],i=c=>`${c.name}${c.scope??""}${c.owner?.subject??""}`,r=s.selectedName?`${s.selectedName}${s.selectedSelector?.scope??""}${s.selectedSelector?.owner?.subject??""}`:null;let o=n.findIndex(c=>i(c)===r);o<0&&(o=n.findIndex(c=>c.name===s.selectedName));const l=n[Math.min(n.length-1,Math.max(0,(o<0?e>0?-1:0:o)+e))];l&&(l.name!==s.selectedName||i(l)!==r)&&await this.selectAdminPackage(l.name,Uh(l))}toggleAdminPackageDir(e){this.dispatch({type:"admin/packages/toggleDir",dir:e})}async selectAdminPackageFile(e){const s=this.getState().admin?.packages,n=s?.selectedName;if(!n||!e)return;const i=s?.selectionSeq??0,r=s?.selectedSelector??null;this.dispatch({type:"admin/packages/file/loading",path:e});try{const o=await this.transport.getAgentPackageFile(n,null,e,r);this.dispatch({type:"admin/packages/file/loaded",seq:i,file:o})}catch(o){this.dispatch({type:"admin/packages/file/loadFailed",seq:i,path:e,error:o?.message||String(o)})}}async runAdminPackageAction(e,s=null){const n=this.getState().admin?.packages,i=n?.selectedName,r=n?.selectedSelector??null;if(i){this.dispatch({type:"admin/packages/action/pending",action:e});try{switch(e){case"promote":await this.transport.setAgentPackageScope(i,"shared",r);break;case"demote":await this.transport.setAgentPackageScope(i,"user",r);break;case"republish":await this.transport.republishAgentPackageVersion(i,s,r?.scope==="shared"?"user":"shared");break;case"pin":await this.transport.pinAgentPackageVersion(i,s,r);break;case"enable":case"disable":await this.transport.setAgentPackageEnabled(i,e==="enable",r);break;case"delete":await this.transport.deleteAgentPackage(i,r);break;default:throw new Error(`unknown package action: ${e}`)}if(this.dispatch({type:"admin/packages/action/done"}),await this.refreshAdminAgentPackages(),e!=="delete"){const o=e==="promote"?{scope:"shared",...r?.owner?{owner:r.owner}:{}}:e==="demote"?{scope:"user",...r?.owner?{owner:r.owner}:{}}:r;await this.selectAdminPackage(i,o)}}catch(o){this.dispatch({type:"admin/packages/action/failed",error:o?.message||String(o)})}}}failAdminAddPackage(e){this.dispatch({type:"admin/packages/addDialog/failed",error:e})}async submitAdminUploadPackage(e,s){const n=this.getState().admin?.packages?.addDialog;if(!(!n?.open||n.submitting)){if(typeof this.transport.uploadAgentPackage!="function"){this.dispatch({type:"admin/packages/addDialog/failed",error:"Folder upload is not available on this deployment."});return}this.dispatch({type:"admin/packages/addDialog/submitting"});try{const i=await this.transport.uploadAgentPackage(e,s==="shared"?"shared":"user");this.dispatch({type:"admin/packages/addDialog/close"}),await this.refreshAdminAgentPackages(),i?.name&&await this.selectAdminPackage(i.name)}catch(i){const r=Array.isArray(i?.validation?.errors)?`
79
+ ${i.validation.errors.map(o=>`[${o.code}] ${o.message}`).join(`
80
+ `)}`:"";this.dispatch({type:"admin/packages/addDialog/failed",error:`${i?.message||i}${r}`})}}}openAdminAddPackage(){this.dispatch({type:"admin/packages/addDialog/open"})}openAdminUpdatePackage(e,s="user"){const n=String(e||"").trim();n&&this.dispatch({type:"admin/packages/addDialog/open",updateName:n,scope:s})}closeAdminAddPackage(){this.dispatch({type:"admin/packages/addDialog/close"})}setAdminAddPackageField(e,s){this.dispatch({type:"admin/packages/addDialog/setField",field:e,value:s})}async submitAdminAddPackage(){const e=this.getState().admin?.packages?.addDialog;if(!e?.open||e.submitting)return;if(typeof this.transport.uploadAgentPackage!="function"){this.dispatch({type:"admin/packages/addDialog/failed",error:"Package upload is not available on this deployment."});return}const s=String(e.repoUrl||"").trim(),n=el(s);if(n.error){this.dispatch({type:"admin/packages/addDialog/failed",error:n.error});return}this.dispatch({type:"admin/packages/addDialog/submitting"});try{let r=String(e.authToken||"").trim()||null,o="pat";!r&&n.kind==="ado"&&(this.dispatch({type:"admin/packages/addDialog/progress",message:"getting an Azure DevOps token for your account…"}),r=typeof this.transport.getRepoAccessToken=="function"?await this.transport.getRepoAccessToken("ado"):null,o="bearer");const{files:l}=await id(s,{token:r,tokenKind:o,onProgress:u=>this.dispatch({type:"admin/packages/addDialog/progress",message:u})});if(e.updateName){const u=rd(l);if(u&&u!==e.updateName){this.dispatch({type:"admin/packages/addDialog/failed",error:`That folder builds "${u}", not "${e.updateName}". Use Add package to publish it as its own package.`});return}}this.dispatch({type:"admin/packages/addDialog/progress",message:`publishing ${l.length} file(s)…`});const c=await this.transport.uploadAgentPackage(l,e.scope==="shared"?"shared":"user");this.dispatch({type:"admin/packages/addDialog/close"}),await this.refreshAdminAgentPackages(),c?.name&&await this.selectAdminPackage(c.name)}catch(i){const r=Array.isArray(i?.validation?.errors)?`
81
+ ${i.validation.errors.map(o=>`[${o.code}] ${o.message}`).join(`
82
+ `)}`:"";this.dispatch({type:"admin/packages/addDialog/failed",error:`${i?.message||i}${r}`})}}beginAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/beginEdit",draft:""})}setAdminGhcpKeyDraft(e,s=String(e||"").length){this.dispatch({type:"admin/ghcpKey/setDraft",draft:e,cursorIndex:s})}insertAdminGhcpKeyText(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=String(e||"").replace(/\r?\n/g,""),i=dt(s.draft||"",s.cursorIndex||0,n);this.setAdminGhcpKeyDraft(i.prompt,i.cursor)}deleteAdminGhcpKeyChar(){const e=this.getState().admin?.ghcpKey;if(!e?.editing)return;const s=Lt(e.draft||"",e.cursorIndex||0);this.setAdminGhcpKeyDraft(s.prompt,s.cursor)}moveAdminGhcpKeyCursor(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,be(n,(s.cursorIndex||0)+e))}moveAdminGhcpKeyCursorToBoundary(e){const s=this.getState().admin?.ghcpKey;if(!s?.editing)return;const n=s.draft||"";this.setAdminGhcpKeyDraft(n,e==="start"?0:n.length)}cancelAdminEditGhcpKey(){this.dispatch({type:"admin/ghcpKey/cancelEdit"})}async saveAdminGhcpKey(){const e=!!this.getState().admin.ghcpKey.storeAsSystem,s=e?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?"This deployment does not support System keys yet.":"Admin Console is not available on this transport."});return}const n=String(this.getState().admin.ghcpKey.draft||"").trim();if(n.length===0){this.dispatch({type:"admin/ghcpKey/saveFailed",error:"Enter a key, or use Clear to remove the override."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{if(e){const i=await this.transport.setSystemGitHubCopilotKey({key:n});this.dispatch({type:"admin/systemGhcpKey/saved",status:i})}else{const i=await this.transport.setCurrentUserGitHubCopilotKey({key:n});this.dispatch({type:"admin/ghcpKey/saved",profile:i})}}catch(i){this.dispatch({type:"admin/ghcpKey/saveFailed",error:i?.message||String(i)})}}async clearAdminGhcpKey(){const e=!!this.getState().admin.ghcpKey.storeAsSystem,s=e?"setSystemGitHubCopilotKey":"setCurrentUserGitHubCopilotKey";if(typeof this.transport[s]!="function"){this.dispatch({type:"admin/ghcpKey/saveFailed",error:e?"This deployment does not support System keys yet.":"Admin Console is not available on this transport."});return}this.dispatch({type:"admin/ghcpKey/saving"});try{if(e){const n=await this.transport.setSystemGitHubCopilotKey({key:null});this.dispatch({type:"admin/systemGhcpKey/saved",status:n})}else{const n=await this.transport.setCurrentUserGitHubCopilotKey({key:null});this.dispatch({type:"admin/ghcpKey/saved",profile:n})}}catch(n){this.dispatch({type:"admin/ghcpKey/saveFailed",error:n?.message||String(n)})}}async ensureExecutionHistory(e,{force:s=!1}={}){if(!e||typeof this.transport.getExecutionHistory!="function")return null;const n=this.getState().executionHistory?.bySessionId?.[e]||null,i=Date.now();if(!s&&n?.loading||!s&&n&&Number.isFinite(n.fetchedAt)&&i-n.fetchedAt<15e3)return n;this.dispatch({type:"executionHistory/loading",sessionId:e});try{const r=await this.transport.getExecutionHistory(e);this.dispatch({type:"executionHistory/loaded",sessionId:e,events:r||[],fetchedAt:Date.now()})}catch(r){console.error("[executionHistory] fetch error:",r?.message||r),this.dispatch({type:"executionHistory/error",sessionId:e,error:r?.message||String(r),fetchedAt:Date.now()})}return this.getState().executionHistory?.bySessionId?.[e]||null}async ensureFilesForScope(e=We(this.getState()),{force:s=!1}={}){const n=Qs(this.getState(),e);return n.length===0?e==="allSessions"?[]:null:e==="allSessions"||n.length>1?Promise.allSettled(n.map(i=>this.ensureFilesForSession(i,{force:s}))):this.ensureFilesForSession(n[0],{force:s})}async ensureSelectedFilePreview(){const e=ut(this.getState());return!e?.sessionId||!e?.filename?null:this.ensureFilePreview(e.sessionId,e.filename).catch(()=>null)}async ensureFilesForSession(e,{force:s=!1}={}){if(!e||typeof this.transport.listArtifacts!="function")return null;const n=this.getState().files.bySessionId[e];if(!s&&n?.loading)return n;const i=Date.now()-(Number(n?.fetchedAt)||0);if(!s&&n?.loaded&&i<Om)return n.selectedFilename&&await this.ensureFilePreview(e,n.selectedFilename).catch(()=>{}),n;this.dispatch({type:"files/sessionLoading",sessionId:e});try{const r=await this.transport.listArtifacts(e),o=Date.now();this.dispatch({type:"files/sessionLoaded",sessionId:e,entries:r,fetchedAt:o});const l=this.getState().files.bySessionId[e];return l?.selectedFilename&&await this.ensureFilePreview(e,l.selectedFilename).catch(()=>{}),l}catch(r){return this.dispatch({type:"files/sessionError",sessionId:e,error:r?.message||String(r)}),null}}async ensureFilePreview(e,s,{force:n=!1}={}){if(!e||!s||typeof this.transport.downloadArtifact!="function")return null;const i=this.getState().files.bySessionId[e],r=i?.previews?.[s];let o=jd(i?.entries,s);if(!n&&r?.loading||!n&&r&&(r.content!==void 0||r.error))return r;if(!o&&typeof this.transport.getArtifactMetadata=="function")try{o=await this.transport.getArtifactMetadata(e,s)}catch{o=null}this.dispatch({type:"files/previewLoading",sessionId:e,filename:s});try{const l=o?.isBinary===!0?Ho(s,"",o.contentType||"",o):Ho(s,await this.transport.downloadArtifact(e,s),o?.contentType||"",o);return this.dispatch({type:"files/previewLoaded",sessionId:e,filename:s,...l}),l}catch(l){return this.dispatch({type:"files/previewError",sessionId:e,filename:s,error:l?.message||String(l)}),null}}buildArtifactPickerItems(e=[],s=[]){const n=(e||[]).map(i=>({id:`${i.sessionId}/${i.filename}`,kind:"artifact",sessionId:i.sessionId,filename:i.filename}));for(const i of s||[]){const r=String(i?.href||"").trim();r&&n.push({id:`url:${r}`,kind:"url",href:r,text:String(i?.text||r).trim()||r})}return(e||[]).length>1&&n.push({id:"__downloadAll__",kind:"downloadAll"}),n}buildArtifactPickerModal({artifactLinks:e,httpLinks:s,previousFocus:n,selectedId:i}={}){const r=this.buildArtifactPickerItems(e,s);if(r.length===0)return null;const o=r.findIndex(l=>l.id===i);return{type:"artifactPicker",title:"Linked Items",previousFocus:n,artifactLinks:e,httpLinks:s,items:r,selectedIndex:o>=0?o:0,exportDirectory:typeof this.transport.getArtifactExportDirectory=="function"?this.transport.getArtifactExportDirectory():null}}getArtifactPickerSelectionId(){const e=this.getState().ui.modal;return!e||e.type!=="artifactPicker"?null:e.items?.[e.selectedIndex||0]?.id||null}replaceArtifactPickerModal(e=null){const s=this.getState().ui.modal;if(!s||s.type!=="artifactPicker")return;const n=this.buildArtifactPickerModal({artifactLinks:s.artifactLinks||[],httpLinks:s.httpLinks||[],previousFocus:s.previousFocus,selectedId:e||this.getArtifactPickerSelectionId()});if(!n){this.dispatch({type:"ui/modal",modal:null}),this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:n})}async saveArtifactDownload(e,s){if(typeof this.transport.saveArtifactDownload!="function")return this.dispatch({type:"ui/status",text:"Artifact download is not supported by this transport"}),null;try{const n=await this.transport.saveArtifactDownload(e,s);this.dispatch({type:"files/downloaded",sessionId:e,filename:s,localPath:n?.localPath||"",downloadedAt:Date.now()});const i=this.getState().sessions.activeSessionId;return(e===i||this.getState().ui.inspectorTab==="files")&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),e===i&&(this.dispatch({type:"files/select",sessionId:e,filename:s}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(e,s,{force:!0}).catch(()=>null))),n}catch(n){return this.dispatch({type:"ui/status",text:`Download failed: ${n?.message||String(n)}`}),null}}async openSelectedFileInDefaultApp(){const e=this.getState(),s=ut(e);if(!s?.sessionId||!s?.filename){this.dispatch({type:"ui/status",text:e.sessions.activeSessionId||We(e)==="allSessions"?"No file selected":"No session selected"});return}const{sessionId:n,filename:i}=s,r=We(e);if(typeof this.transport.openPathInDefaultApp!="function"){this.dispatch({type:"ui/status",text:"Opening files in the default app is not supported by this transport"});return}let o=e.files.bySessionId[n]?.downloads?.[i]?.localPath||null;if(o||(this.dispatch({type:"ui/status",text:`Downloading ${i} to open it...`}),o=(await this.saveArtifactDownload(n,i))?.localPath||null),!o){this.dispatch({type:"ui/status",text:`Open failed: could not save ${i} locally`});return}try{await this.transport.openPathInDefaultApp(o),this.dispatch({type:"ui/status",text:r==="allSessions"?`Opened ${_e(n)} ${i} in the default app`:`Opened ${i} in the default app`})}catch(l){this.dispatch({type:"ui/status",text:`Open failed: ${l?.message||String(l)}`})}}async downloadSelectedArtifact(){const e=ut(this.getState());if(!e?.sessionId||!e?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),null;this.dispatch({type:"ui/status",text:`Downloading ${e.filename}...`});const s=await this.saveArtifactDownload(e.sessionId,e.filename);return s?.localPath?(this.dispatch({type:"ui/status",text:`Downloaded ${e.filename}`}),s):null}toggleArtifactMark(e){e?.id&&this.dispatch({type:"files/toggleMark",artifactId:e.id})}markArtifactRange(e){if(!e?.id)return;const s=It(this.getState()),n=this.getState().files.markedIds||[],i=n.length>0?n[n.length-1]:this.getState().files.selectedArtifactId,r=s.findIndex(p=>p.id===i),o=s.findIndex(p=>p.id===e.id);if(o<0)return;if(r<0){this.dispatch({type:"files/toggleMark",artifactId:e.id});return}const[l,c]=r<=o?[r,o]:[o,r],u=s.slice(l,c+1).map(p=>p.id);this.dispatch({type:"files/setMarks",artifactIds:[...new Set([...n,...u])]})}clearArtifactMarks(){this.dispatch({type:"files/clearMarks"})}async deleteMarkedArtifacts({confirmed:e=!1}={}){const s=this.getState(),n=s.files.markedIds||[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No artifacts marked"}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifacts",message:`Delete ${n.length} artifact${n.length===1?"":"s"}? This action cannot be undone.`,confirmLabel:`Delete ${n.length}`,action:"deleteMarkedArtifacts",previousFocus:s.ui.focusRegion}}),!1;const i=new Set;let r=0;const o=[];for(const l of n){const c=String(l).indexOf("/");if(c<=0)continue;const u=l.slice(0,c),p=l.slice(c+1);try{await this.transport.deleteArtifact(u,p),this.dispatch({type:"files/deleted",sessionId:u,filename:p}),i.add(u),r+=1}catch(d){o.push(`${p}: ${d?.message||String(d)}`)}}for(const l of i)await this.ensureFilesForSession(l,{force:!0}).catch(()=>null);return this.dispatch({type:"files/clearMarks"}),this.dispatch({type:"ui/status",text:o.length>0?`Deleted ${r}, ${o.length} failed — ${o[0]}`:`Deleted ${r} artifact${r===1?"":"s"}`}),o.length===0}async deleteSelectedArtifact({confirmed:e=!1}={}){const s=this.getState(),n=ut(s);if(!n?.sessionId||!n?.filename)return this.dispatch({type:"ui/status",text:"No artifact selected"}),!1;const i=We(s),r=i==="allSessions"?`${_e(n.sessionId)} ${n.filename}`:n.filename;if(!e)return this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Artifact",message:`Delete artifact "${r}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteArtifact",sessionId:n.sessionId,filename:n.filename,previousFocus:s.ui.focusRegion}}),!1;if(typeof this.transport.deleteArtifact!="function")return this.dispatch({type:"ui/status",text:"Artifact deletion is not supported by this transport"}),!1;try{await this.transport.deleteArtifact(n.sessionId,n.filename),this.dispatch({type:"files/deleted",sessionId:n.sessionId,filename:n.filename}),await this.ensureFilesForSession(n.sessionId,{force:!0}).catch(()=>null);const o=ut(this.getState());return o?.sessionId&&o?.filename&&await this.ensureFilePreview(o.sessionId,o.filename).catch(()=>null),this.dispatch({type:"ui/status",text:i==="allSessions"?`Deleted ${_e(n.sessionId)} ${n.filename}`:`Deleted ${n.filename}`}),!0}catch(o){return this.dispatch({type:"ui/status",text:`Delete failed: ${o?.message||String(o)}`}),!1}}async openArtifactPicker(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=Jp(e),i=ef(e);if(n.length===0&&i.length===0){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}const r=this.getState().files.bySessionId[s]?.selectedFilename||null,o=r?`${s}/${r}`:null,l=this.buildArtifactPickerModal({artifactLinks:n,httpLinks:i,previousFocus:e.ui.focusRegion,selectedId:o});if(!l){this.dispatch({type:"ui/status",text:"No linked artifacts or URLs in the current chat view"});return}this.dispatch({type:"ui/modal",modal:l}),this.dispatch({type:"ui/status",text:"Select a linked item and press Enter to open or download it"})}async downloadArtifactModalSelection(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="url"){if(typeof this.transport.openUrlInDefaultBrowser!="function"){this.dispatch({type:"ui/status",text:"Opening URLs is not supported by this transport"});return}this.dispatch({type:"ui/status",text:`Opening ${s.href}...`}),await this.transport.openUrlInDefaultBrowser(s.href),this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Opened ${s.href}`});return}if(s.kind==="downloadAll"){const i=(e.items||[]).filter(o=>o.kind!=="artifact"?!1:!this.getState().files.bySessionId[o.sessionId]?.downloads?.[o.filename]?.localPath);if(i.length===0){this.dispatch({type:"ui/status",text:"All artifacts already downloaded"});return}this.dispatch({type:"ui/status",text:`Downloading ${i.length} artifacts...`});let r=0;for(const o of i)(await this.saveArtifactDownload(o.sessionId,o.filename))?.localPath&&(r+=1);this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${r}/${i.length} artifacts`});return}this.dispatch({type:"ui/status",text:`Downloading ${s.filename}...`}),(await this.saveArtifactDownload(s.sessionId,s.filename))?.localPath&&(this.replaceArtifactPickerModal(s.id),this.dispatch({type:"ui/status",text:`Downloaded ${s.filename}`}))}async moveFileSelection(e){const s=We(this.getState());await this.ensureFilesForScope(s);const n=It(this.getState());if(n.length===0)return;const i=ut(this.getState())||n[0],r=Math.max(0,n.findIndex(c=>c.id===i?.id)),o=Math.max(0,Math.min(n.length-1,r+e)),l=n[o];!l?.sessionId||!l?.filename||(s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:l.id}):this.dispatch({type:"files/select",sessionId:l.sessionId,filename:l.filename}),await this.ensureFilePreview(l.sessionId,l.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${_e(l.sessionId)} ${l.filename}`:`Previewing ${l.filename}`}))}async selectFileBrowserItem(e){if(!e?.sessionId||!e?.filename)return;this.dispatch({type:"files/previewOrigin",origin:"list"});const s=We(this.getState());s==="allSessions"?this.dispatch({type:"files/selectGlobal",artifactId:e.id}):this.dispatch({type:"files/select",sessionId:e.sessionId,filename:e.filename}),await this.ensureFilePreview(e.sessionId,e.filename).catch(()=>{}),this.dispatch({type:"ui/status",text:s==="allSessions"?`Previewing ${_e(e.sessionId)} ${e.filename}`:`Previewing ${e.filename}`})}toggleFilePreviewFullscreen(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.files.bySessionId[s],i=!!e.files.fullscreen;if(!i&&!n?.selectedFilename){this.dispatch({type:"ui/status",text:"Select a file before entering fullscreen"});return}const r=!i;this.dispatch({type:"files/fullscreen",fullscreen:r}),this.dispatch({type:"ui/status",text:r?`Fullscreen files browser: ${n?.selectedFilename||""}`:"Closed fullscreen files browser"})}toggleFocusedPaneFullscreen(){const e=this.getState(),s=e.ui.focusRegion,n=e.ui.fullscreenPane||null,i=s===N.PROMPT?n:s;if(!Qh.has(i)||i===N.INSPECTOR&&e.ui.inspectorTab==="files")return;const r=n===i?null:i;this.dispatch({type:"ui/fullscreenPane",fullscreenPane:r}),this.dispatch({type:"ui/status",text:r?`Fullscreen ${i} pane`:`Closed fullscreen ${i} pane`}),!r&&s===N.PROMPT&&this.setFocus(i)}openFilesFilter(){const e=We(this.getState());this.dispatch({type:"ui/modal",modal:{type:"filesFilter",title:"Files Filter",previousFocus:this.getState().ui.focusRegion,selectedIndex:0,items:[{id:"scope",label:"Scope",description:"Choose whether the files browser shows the selected session tree or aggregates exported files across all sessions.",options:[{id:"selectedSession",label:"Selected session tree"},{id:"allSessions",label:"All sessions"}]}]}}),this.dispatch({type:"ui/status",text:`Editing files filter: Scope = ${e==="allSessions"?"All sessions":"Selected session tree"}`})}setNavigationIntent(e){const s=String(e||"").trim();if(!s)return;this.dispatch({type:"sessions/navigationIntent",sessionId:s});const n=this.getState();if(n.sessions.byId[s]){this.loadSession(s).catch(i=>{this.dispatch({type:"sessions/navigationIntentFailed",sessionId:s,errorKind:Hn(i)})});return}Object.keys(n.sessions.byId).length>0&&this.scheduleSessionsRefresh(0)}async loadSession(e){if(!e)return;if(this.getState().sessions.activeSessionId!==e&&(this.getState().ui.promptEdit&&this.exitPendingPromptEdit({restoreDraft:!0}),this.dispatch({type:"sessions/selected",sessionId:e}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.getState().sessions.byId[e]?.isGroup){this.detachActiveSession();return}await this.ensureSessionHistory(e,{force:!0}),await this.syncSessionDetail(e).catch(()=>{}),this.attachActiveSession(e),this.ensureInspectorData().catch(()=>{}),this.dispatch({type:"canvas/snapshotInvalidate",sessionId:e}),this.ensureCanvasSnapshot(e).catch(()=>{})}reconcileOutboxAgainstEvent(e,s){if(!(!e||!s)){if(s.eventType==="user.message"){const n=s?.data?.content,i=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(r=>typeof r=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];if(i.length>0)for(const r of i)this.acknowledgeOutboxPrompt(e,n,r);else typeof n=="string"&&n.trim()&&this.acknowledgeOutboxPrompt(e,n);return}if(s.eventType==="pending_messages.cancelled"){const n=Array.isArray(s?.data?.clientMessageIds)?s.data.clientMessageIds.filter(i=>typeof i=="string"):typeof s?.data?.clientMessageId=="string"?[s.data.clientMessageId]:[];this.acknowledgeCancelledOutboxPrompt(e,n)}}}maybeRevealPresentedArtifact(e,s){const n=String(s?.data?.filename||"").trim();if(!n||e!==this.getState().sessions.activeSessionId)return!1;const i=s?.createdAt?Date.parse(s.createdAt):Number.NaN;if(Number.isFinite(i)&&Date.now()-i>Gn)return!1;const r=s?.data?.fullscreen===!0;return this.revealArtifact(e,n,r?{fullscreen:!0}:{pane:!0}).catch(()=>{}),!0}applyCanvasUpdate(e,s){const n=Number(s?.data?.rev);if(!e||!Number.isFinite(n)||n<=0)return!1;const i=Number(s?.data?.slot),r=Number.isInteger(i)&&i>=1&&i<=5?i:1;this.dispatch({type:"canvas/updated",sessionId:e,slot:r,...typeof s?.data?.name=="string"?{name:s.data.name}:{},rev:n,note:typeof s?.data?.note=="string"?s.data.note:"",sizeBytes:s?.data?.sizeBytes,responseContract:s?.data?.responseContract});const o=this.getState();if(e!==o.sessions.activeSessionId||o.canvas.prefs[qe(e,r)]?.optedOut)return!0;const l=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(l)&&Date.now()-l>Gn||this.dispatch({type:"canvas/flip",sessionId:e,slot:r}),!0}submitCanvasAction(e,s){if(!e)return Promise.resolve({ok:!1,reason:"no session"});const n=this.getState().auth?.principal||null,i=this.getState().sessions.byId[e]?.owner||null;if(n&&i&&(String(i.provider||"")!==String(n.provider||"")||String(i.subject||"")!==String(n.subject||"")))return Promise.resolve({ok:!1,reason:"only the session's creator can use canvas controls"});const r=this.getState().canvas.bySessionId[e]?.responseContract||null,o=bu(r,s);if(!o.ok)return Promise.resolve(o);this.canvasActionLimiters||(this.canvasActionLimiters=new Map);let l=this.canvasActionLimiters.get(e);if(l||(l=Eu(),this.canvasActionLimiters.set(e,l)),!l())return Promise.resolve({ok:!1,reason:"rate limited"});const c=wu(o.action,o.data);return this.transport.sendMessage(e,c,{enqueueOnly:!0}).then(()=>(this.syncSessionEvents(e).catch(()=>{}),{ok:!0,action:o.action})).catch(u=>({ok:!1,reason:u?.message||String(u)}))}async ensureCanvasSnapshot(e){if(e&&!this.getState().canvas.bySessionId[e]?.snapshotLoaded){if(typeof this.transport.getSessionEventsBefore!="function"){this.dispatch({type:"canvas/snapshot",sessionId:e,rev:0});return}try{const s=await this.transport.getSessionEventsBefore(e,Number.MAX_SAFE_INTEGER,30,["session.canvas_updated"]),n=new Map;for(const r of Array.isArray(s)?s:[]){const o=Number(r?.data?.slot)||1,l=Number(r?.data?.rev)||0;(!n.has(o)||l>(Number(n.get(o)?.data?.rev)||0))&&n.set(o,r)}n.has(1)||n.set(1,null);let i=!1;for(const[r,o]of n){const l=Number(o?.data?.rev)||0;l>0&&(i=!0),this.dispatch({type:"canvas/snapshot",sessionId:e,slot:r,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(i){const r=await this.transport.getSessionEventsBefore(e,Number.MAX_SAFE_INTEGER,30,["session.canvas_data"]).catch(()=>[]),o=new Map;for(const l of Array.isArray(r)?r:[]){const c=Number(l?.data?.slot)||1,u=Number(l?.data?.dataRev)||0;(!o.has(c)||u>(Number(o.get(c)?.data?.dataRev)||0))&&o.set(c,l)}for(const[l,c]of o)c?.data?.dataRev&&this.dispatch({type:"canvas/data",sessionId:e,slot:l,dataRev:Number(c.data.dataRev),payload:c.data.payload,note:typeof c.data.note=="string"?c.data.note:""})}}catch{}}}applyCanvasPresented(e,s){const n=Number(s?.data?.slot),i=Number.isInteger(n)&&n>=1&&n<=5?n:1;if(!e)return!1;const r=this.getState();if(e!==r.sessions.activeSessionId||r.canvas.prefs[qe(e,i)]?.optedOut)return!1;const o=s?.createdAt?Date.parse(s.createdAt):Number.NaN;return Number.isFinite(o)&&Date.now()-o>Gn?!1:(this.dispatch({type:"canvas/flip",sessionId:e,slot:i}),!0)}applyCanvasDataEvent(e,s){this.dispatch({type:"canvas/data",sessionId:e,slot:Number(s?.data?.slot)||1,dataRev:Number(s?.data?.dataRev),payload:s?.data?.payload,...Number.isFinite(Number(s?.data?.planeSeq))?{planeSeq:Number(s.data.planeSeq)}:{},...s?.data?.patch&&typeof s.data.patch=="object"?{patch:s.data.patch}:{},note:typeof s?.data?.note=="string"?s.data.note:""})}mergeSessionEvent(e,s){if(!e||!s)return!1;if(s.transient===!0)return s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(e,s),s.eventType==="session.canvas_plane_released"&&this.dispatch({type:"canvas/planeReleased",sessionId:e}),!1;const i=this.getState().history.bySessionId.get(e)||{chat:[],activity:[],lastSeq:0};if(s.seq<=(i.lastSeq||0))return!1;this.dispatch({type:"history/set",sessionId:e,history:Rr(i,s)}),s.eventType==="session.input_required_started"&&s.data?.question&&this.dispatch({type:"sessions/merged",session:{sessionId:e,status:"input_required",pendingQuestion:{question:s.data.question,choices:Array.isArray(s.data.choices)?s.data.choices:void 0,allowFreeform:s.data.allowFreeform??!0}}}),s.eventType==="session.artifact_presented"&&this.maybeRevealPresentedArtifact(e,s),s.eventType==="session.canvas_updated"&&this.applyCanvasUpdate(e,s),s.eventType==="session.canvas_presented"&&this.applyCanvasPresented(e,s),s.eventType==="session.canvas_data"&&this.applyCanvasDataEvent(e,s),this.reconcileOutboxAgainstEvent(e,s);const r=rm(s),o=this.getState().sessions.byId[e]||{sessionId:e},l=ka(o.contextUsage,s.eventType,s.data,{timestamp:s.createdAt});return(r||l)&&this.dispatch({type:"sessions/merged",session:{sessionId:e,...r||{},...l?{contextUsage:l}:{}}}),this.maybeFlushQueuedOutbox(e,this.getState().sessions.byId[e]||o),this.scheduleSessionDetailSync(e),!0}async syncSessionEvents(e){if(!e||typeof this.transport.getSessionEvents!="function")return;const s=this.getState().history.bySessionId.get(e);if(!s?.events){await this.ensureSessionHistory(e,{force:!0});return}const n=Number(s.lastSeq||0);let i=null;try{i=await this.transport.getSessionEvents(e,n,200)}catch(r){if(cs(r)){this.handleSessionGone(e);return}throw r}if(!(!Array.isArray(i)||i.length===0))for(const r of i)this.mergeSessionEvent(e,r)}attachActiveSession(e){this.activeSessionSubscriptionId===e&&this.activeSessionUnsub||(this.detachActiveSession(),this.activeSessionSubscriptionId=e,this.activeSessionUnsub=this.transport.subscribeSession(e,s=>{this.mergeSessionEvent(e,s)}),this.syncSessionEvents(e).catch(()=>{}))}scheduleSessionDetailSync(e,s=250){typeof this.transport.getSession!="function"||!e||ls(e)||(this.activeSessionDetailTimer&&clearTimeout(this.activeSessionDetailTimer),this.activeSessionDetailSessionId=e,this.activeSessionDetailTimer=setTimeout(()=>{const n=this.activeSessionDetailSessionId;this.activeSessionDetailTimer=null,this.activeSessionDetailSessionId=null,this.syncSessionDetail(n).catch(()=>{})},s))}scheduleSessionsRefresh(e=0){this.sessionRefreshTimer&&clearTimeout(this.sessionRefreshTimer),this.sessionRefreshTimer=setTimeout(()=>{this.sessionRefreshTimer=null,this.refreshSessions().catch(()=>{})},Math.max(0,e))}async syncSessionDetail(e){if(typeof this.transport.getSession!="function"||!e||ls(e))return;let s=null;try{s=await this.transport.getSession(e)}catch(r){if(cs(r)){this.handleSessionGone(e);return}throw r}if(!s)return;const n=this.getState().sessions.byId[e]||null,i=cm(n,s);(i||n?.rowVisualStatusCandidate)&&this.dispatch({type:"sessions/merged",session:i||{sessionId:e}}),this.maybeFlushQueuedOutbox(e,s)}async createSession(e={}){try{const s=this.applyActiveGroupDefault(e),n=await this.transport.createSession(s);return await this.placeCreatedSessionInGroup(n,s.groupId??null),await this.refreshSessions(),await this.loadSession(n.sessionId),this.revealCreatedSession(),this.dispatch({type:"ui/status",text:`Created session ${n.sessionId.slice(0,8)}`}),n}catch(s){return this.dispatch({type:"ui/status",text:s?.message||String(s)||"Failed to create session"}),null}}async createSessionForAgent(e,s={}){if(typeof this.transport.createSessionForAgent!="function")throw new Error("Named-agent session creation is not supported by this transport");try{const n=this.applyActiveGroupDefault(s),i=await this.transport.createSessionForAgent(e,n);return await this.placeCreatedSessionInGroup(i,n.groupId??null),await this.refreshSessions(),await this.loadSession(i.sessionId),this.revealCreatedSession(),this.dispatch({type:"ui/status",text:`Created ${Po(e,s.title)} session ${i.sessionId.slice(0,8)}`}),i}catch(n){return this.dispatch({type:"ui/status",text:n?.message||String(n)||"Failed to create session"}),null}}async placeCreatedSessionInGroup(e,s){!s||!e?.sessionId||typeof this.transport.placeSessionsInGroup=="function"&&(e.viewerGroupId??null)!==s&&await this.transport.placeSessionsInGroup([e.sessionId],s).catch(()=>{})}getMovableGroupSessionSelection(){const e=this.getState(),s=e.sessions.activeSessionId&&!e.sessions.listDeselected?[e.sessions.activeSessionId]:[];return(Array.isArray(e.sessions.selectedIds)&&e.sessions.selectedIds.length>0?e.sessions.selectedIds:s).map(i=>e.sessions.byId[i]).filter(i=>i&&!i.isSystem&&!i.isGroup&&!i.parentSessionId)}async openMoveToGroupModal(){const e=this.getState(),s=this.getMovableGroupSessionSelection();if(s.length===0){const c=e.sessions.activeSessionId?e.sessions.byId[e.sessions.activeSessionId]:null;return c?.isGroup&&c.groupId?this.openRenameGroupModal(c):this.openCreateEmptyGroupModal()}if(typeof this.transport.listSessionGroups!="function")return this.dispatch({type:"ui/status",text:"Session groups are not supported by this transport"}),null;const n=await this.transport.listSessionGroups().catch(()=>[]),i=s.map(c=>c.sessionId),r=s.length===1&&s[0].groupId||null,o=[{id:"__no_group__",kind:"noGroup",label:"[No Group]",description:"Remove the selected session(s) from any group.",groupId:null,memberCount:0},{id:"__new_group__",kind:"newGroup",label:"[New Group]",description:"Create a new group, then move the selected session(s) into it.",groupId:null,memberCount:0},...(Array.isArray(n)?n:[]).map(c=>({id:c.groupId,kind:"group",label:c.title||c.groupId,description:c.description||"Move selected session(s) into this group.",groupId:c.groupId,memberCount:c.memberCount??0}))],l=r?Math.max(0,o.findIndex(c=>c.groupId===r)):Math.min(1,o.length-1);return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupPicker",title:s.length===1?"Move Session to Group":`Move ${s.length} Sessions to Group`,previousFocus:e.ui.focusRegion,sessionIds:i,sessionLabels:s.map(c=>c.title||c.sessionId.slice(0,8)),selectedIndex:l>=0?l:0,items:o}}),this.dispatch({type:"ui/status",text:"Choose a group, [New Group], or [No Group]"}),o}async createSessionGroupFromSelection(){return this.openMoveToGroupModal()}openRenameGroupModal(e){if(typeof this.transport.updateSessionGroup!="function")return this.dispatch({type:"ui/status",text:"Group rename is not supported by this transport"}),null;const s=this.getState(),n=String(e.title||"").trim();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",mode:"rename",groupId:e.groupId,title:"Rename Group",previousFocus:s.ui.focusRegion,sessionIds:[],value:n,cursorIndex:n.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Edit the group name and press Enter"}),null}async openCreateEmptyGroupModal(){if(typeof this.transport.createSessionGroup!="function")return this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"}),null;const e=this.getState();return this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.ui.focusRegion,sessionIds:[],value:"",cursorIndex:0,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"}),null}async moveSessionsToGroup(e,s,{statusTitle:n=null}={}){const i=Array.from(new Set((Array.isArray(s)?s:[]).map(d=>String(d||"").trim()).filter(Boolean)));if(i.length===0)return this.dispatch({type:"ui/status",text:"No sessions selected to move"}),null;let r=null;if(typeof this.transport.placeSessionsInGroup=="function")r=await this.transport.placeSessionsInGroup(i,e??null);else if(typeof this.transport.moveSessionsToGroup=="function")await this.transport.moveSessionsToGroup(e??null,i);else if(e&&typeof this.transport.assignSessionsToGroup=="function")await this.transport.assignSessionsToGroup(e,i);else return this.dispatch({type:"ui/status",text:"Moving sessions between groups is not supported by this transport"}),null;const o=Array.isArray(r)?r.filter(Boolean):null,l=o?o.filter(d=>d.placed!==!0):[],c=o?o.filter(d=>d.placed===!0).length:i.length;this.dispatch({type:"sessions/selectClear"}),await this.refreshSessions(),e&&c>0&&await this.loadSession(`group:${e}`).catch(()=>{});const u=e?`group ${n||e}`:"No Group",p=l.length>0?` · skipped ${l.length} (${Jh(l)})`:"";return this.dispatch({type:"ui/status",text:c>0?`Moved ${c} session${c===1?"":"s"} to ${u}${p}`:`No sessions moved to ${u}${p}`}),c>0}async confirmSessionGroupPickerModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupPicker")return;const s=e.items?.[e.selectedIndex||0];if(!s)return;if(s.kind==="newGroup"){const i=(e.sessionLabels||[]).length===1?`${e.sessionLabels[0]} Group`:`${(e.sessionIds||[]).length} Session Group`;this.dispatch({type:"ui/modal",modal:{type:"sessionGroupName",title:"New Group",previousFocus:e.previousFocus,sessionIds:e.sessionIds||[],value:i,cursorIndex:i.length,maxLength:80}}),this.dispatch({type:"ui/status",text:"Name the new group and press Enter"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{await this.moveSessionsToGroup(s.kind==="noGroup"?null:s.groupId,e.sessionIds||[],{statusTitle:s.label})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}updateSessionGroupNameModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setSessionGroupNameValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="sessionGroupName")return;const i=Rt(e,n.maxLength||80),r=be(i,s);this.updateSessionGroupNameModal({value:i,cursorIndex:r})}insertSessionGroupNameText(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionGroupName")return;const n=dt(s.value||"",s.cursorIndex||0,Rt(e,s.maxLength||80));this.setSessionGroupNameValue(n.prompt,n.cursor)}deleteSessionGroupNameChar(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=Lt(e.value||"",e.cursorIndex||0);this.setSessionGroupNameValue(s.prompt,s.cursor)}moveSessionGroupNameCursor(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",be(s.value||"",(s.cursorIndex||0)+e))}moveSessionGroupNameCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="sessionGroupName"||this.setSessionGroupNameValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmSessionGroupNameModal(){const e=this.getState().ui.modal;if(!e||e.type!=="sessionGroupName")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"Group name cannot be empty"});return}if(e.mode==="rename"&&e.groupId){const i=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.updateSessionGroup(e.groupId,{title:s}),this.dispatch({type:"ui/status",text:`Renamed group to "${s}"`}),await this.refreshSessions().catch(()=>{})}catch(r){this.dispatch({type:"ui/status",text:`Rename failed: ${r?.message||String(r)}`})}return}if(typeof this.transport.createSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Session grouping is not supported by this transport"});return}const n=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n);try{const i=await this.transport.createSessionGroup({title:s,description:`${(e.sessionIds||[]).length} grouped session${(e.sessionIds||[]).length===1?"":"s"}`,sessionIds:e.sessionIds||[]}),r=e.sessionIds||[];r.length===0?(this.dispatch({type:"ui/status",text:`Created group "${i.title||s}"`}),await this.refreshSessions().catch(()=>{})):await this.moveSessionsToGroup(i.groupId,r,{statusTitle:i.title||s})}catch(i){this.dispatch({type:"ui/status",text:`Move failed: ${i?.message||String(i)}`})}}applyActiveGroupDefault(e={}){if(e&&Object.prototype.hasOwnProperty.call(e,"groupId"))return e;const s=this.getState(),n=s.sessions?.activeSessionId?s.sessions.byId[s.sessions.activeSessionId]:null;if(!n?.isGroup)return e;const i=n.groupId||Ls(n.sessionId);return i?{...e,groupId:i}:e}getActiveSession(e=this.getState()){const s=e.sessions?.activeSessionId;return s&&e.sessions.byId[s]||null}async openSessionAgentPicker(e={},s=null){const n=s??this.getState().ui.focusRegion,i=()=>{this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n)};let r=[];try{r=typeof this.transport.listCreatableAgents=="function"?await this.transport.listCreatableAgents():[]}catch(h){i(),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(r)||r.length===0){if(i(),!l){this.dispatch({type:"ui/status",text:"No user-creatable agents are available for this app"});return}await this.createSession(e);return}const c=[];for(const h of r){const m=String(h?.name||"").trim();m&&c.push({id:m,kind:"agent",agentName:m,title:Po(m,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 u=[...c.filter(h=>h.group==="shared"),...c.filter(h=>h.group==="mine")],p=l?{id:"__generic__",kind:"generic",group:"generic",title:"Generic Session",description:"Open-ended session with no specialized agent boundary.",tools:[],splash:null,splashMobile:null,initialPrompt:null,supportsDirectStart:!0}:null,d=[ms,Xl,Ql,...new Set(u.filter(h=>!h.builtin).map(h=>Zl(h)))],f=_o(u,d,p);this.dispatch({type:"ui/modal",modal:{type:"sessionAgentPicker",title:"Select agent for new session",catalog:u,genericItem:p,collapsed:d,items:f,selectedIndex:mm(f),previousFocus:n,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select an agent and press Enter"})}async openNewSessionFlow(e={}){if((typeof this.transport.getSessionCreationPolicy=="function"?this.transport.getSessionCreationPolicy():null)?.creation?.allowGeneric??!0){await this.createSession(e);return}if(typeof this.transport.listModels=="function"){await this.openModelPicker(e);return}await this.openSessionAgentPicker(e)}async openReasoningEffortPicker(e,s={},n=null){const i=n??this.getState().ui.focusRegion,r=ui(e?.supportedReasoningEfforts),o=s?.reasoningEffort||Ao(e);if(!r.length||!o){await this.openContextTierPicker(e,s,i);return}const l=r.map(u=>({id:u,effort:u,label:u,isDefault:o===u})),c=Math.max(0,l.findIndex(u=>u.id===o));this.dispatch({type:"ui/modal",modal:{type:"reasoningEffortPicker",title:s?.mode==="switchModel"?`Switch reasoning for ${e?.modelName||e?.qualifiedName||"model"}`:`Reasoning effort for ${e?.modelName||e?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:i,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a reasoning effort and press Enter"})}async openContextTierPicker(e,s={},n=null){const i=n??this.getState().ui.focusRegion,r=di(e?.supportedContextTiers),o=s?.contextTier||sm(e);if(!r.length||!o){if(s?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i),await this.switchSessionModel({...s,model:e?.id});return}await this.openSessionAgentPicker(s,i);return}const l=r.map(u=>({id:u,tier:u,tokenLimit:e?.contextWindowSizes?.[u]||null,label:im(u,e?.contextWindowSizes?.[u]),isDefault:o===u})),c=Math.max(0,l.findIndex(u=>u.id===o));this.dispatch({type:"ui/modal",modal:{type:"contextTierPicker",title:`Context window for ${e?.modelName||e?.qualifiedName||"model"}`,items:l,selectedIndex:c,previousFocus:i,modelItem:e,sessionOptions:s}}),this.dispatch({type:"ui/status",text:"Select a context window and press Enter"})}async openModelPicker(e={}){if(typeof this.transport.listModels!="function"){await this.openSessionAgentPicker(e);return}const s=await this.transport.listModels();if(!Array.isArray(s)||s.length===0){this.dispatch({type:"ui/status",text:"No models available"});return}const n=typeof this.transport.getDefaultModel=="function"?this.transport.getDefaultModel():void 0,i=typeof this.transport.getModelsByProvider=="function"?this.transport.getModelsByProvider():tm(s),r=await this._resolveGhcpUserKeySet(),o=[],l=i.map(p=>({providerId:p.providerId,providerType:p.type||p.providerType,models:(p.models||[]).map(d=>{const f=d.providerType||p.type||p.providerType,h=f==="github"&&d.credentialAvailable===!1&&r===!1,m={id:d.qualifiedName,qualifiedName:d.qualifiedName,modelName:d.modelName||d.qualifiedName,providerId:d.providerId||p.providerId,providerType:f,description:d.description||"",cost:d.cost||null,supportedReasoningEfforts:ui(d.supportedReasoningEfforts),defaultReasoningEffort:d.defaultReasoningEffort||null,supportedContextTiers:di(d.supportedContextTiers),defaultContextTier:d.defaultContextTier||null,contextWindowSizes:d.contextWindowSizes||null,isDefault:n===d.qualifiedName,ghcpKeyMissing:h,disabled:h};return o.push(m),m})})).filter(p=>p.models.length>0),c=e?.model||n;let u=o.findIndex(p=>p.qualifiedName===c&&!p.disabled);u<0&&(u=o.findIndex(p=>!p.disabled)),u<0&&(u=0),this.dispatch({type:"ui/modal",modal:{type:"modelPicker",title:e?.mode==="switchModel"?"Switch model for session":"Select model for new session",items:o,groups:l,selectedIndex:u,previousFocus:this.getState().ui.focusRegion,sessionOptions:e}}),this.dispatch({type:"ui/status",text:"Select a model and press Enter"})}async _resolveGhcpUserKeySet(){const e=this.getState().admin?.profile;if(typeof e?.githubCopilotKeySet=="boolean")return e.githubCopilotKeySet;if(typeof this.transport.getCurrentUserProfile!="function")return null;try{const s=await this.transport.getCurrentUserProfile();return s&&typeof s.githubCopilotKeySet=="boolean"?s.githubCopilotKeySet:!1}catch{return null}}async openSwitchModelPicker(e=null){this._onSwitchModelApplied=typeof e=="function"?e:null;const s=this.getState(),n=s.sessions.activeSessionId,i=n&&s.sessions.byId[n]||null;if(!i||i.isGroup){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Select a session before switching model"});return}if(typeof this.transport.setSessionModel!="function"){this._onSwitchModelApplied=null,this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.openModelPicker({mode:"switchModel",sessionId:n,model:i.model||void 0,reasoningEffort:i.reasoningEffort||void 0})}async switchSessionModel(e={}){const s=e.sessionId||this.getState().sessions.activeSessionId,n=String(e.model||"").trim();if(!s||!n){this.dispatch({type:"ui/status",text:"Select a model before switching"});return}if(typeof this.transport.setSessionModel!="function"){this.dispatch({type:"ui/status",text:"Model switching is not supported by this transport"});return}await this.transport.setSessionModel(s,{model:n,..."reasoningEffort"in e?{reasoningEffort:e.reasoningEffort??null}:{},..."contextTier"in e?{contextTier:e.contextTier??null}:{},source:"ui"});const i=e.reasoningEffort?`${n}:${e.reasoningEffort}`:n,r=e.contextTier?` · ${Kl[e.contextTier]||e.contextTier}`:"";this.dispatch({type:"ui/status",text:`Next turn will use ${i}${r}`}),await this.refreshSessions();const o=this._onSwitchModelApplied;this._onSwitchModelApplied=null,typeof o=="function"&&o()}openHelpModal(){this.dispatch({type:"ui/modal",modal:{type:"help",title:"Keybindings",selectedIndex:0,previousFocus:this.getState().ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Keybindings — ? or Esc to close"})}openThemePicker(){const e=Dd().map(i=>({id:i.id,label:i.label,description:i.description,group:i.group,page:i.page,terminal:i.terminal,tui:i.tui}));if(e.length===0){this.dispatch({type:"ui/status",text:"No themes available"});return}const s=this.getState().ui.themeId,n=Math.max(0,e.findIndex(i=>i.id===s));this.dispatch({type:"ui/modal",modal:{type:"themePicker",title:"Theme Picker",items:e,selectedIndex:n,previousFocus:this.getState().ui.focusRegion,currentThemeId:s}}),this.dispatch({type:"ui/status",text:"Select a theme and press Enter"})}getPromptDraftSessionId(){return this.getPromptAttachments()[0]?.sessionId||null||this.getState().sessions.activeSessionId||null}openArtifactUploadModal(){if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}const e=this.getState(),s=this.getPromptDraftSessionId();this.dispatch({type:"ui/modal",modal:{type:"artifactUpload",title:s?`Upload Artifact (${_e(s)})`:"Upload Artifact",sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0}}),this.dispatch({type:"ui/status",text:s?"Paste a local file path and press Enter to upload it into this session's artifacts":"Paste a local file path and press Enter to upload it; a new session will be created if needed"})}updateArtifactUploadModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setArtifactUploadValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="artifactUpload")return;const i=String(e||"").replace(/\r?\n/g,""),r=be(i,s);this.updateArtifactUploadModal({value:i,cursorIndex:r})}insertArtifactUploadText(e){const s=this.getState().ui.modal;if(!s||s.type!=="artifactUpload")return;const n=dt(s.value||"",s.cursorIndex||0,String(e||"").replace(/\r?\n/g,""));this.setArtifactUploadValue(n.prompt,n.cursor)}deleteArtifactUploadChar(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=Lt(e.value||"",e.cursorIndex||0);this.setArtifactUploadValue(s.prompt,s.cursor)}moveArtifactUploadCursor(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",be(s.value||"",(s.cursorIndex||0)+e))}moveArtifactUploadCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="artifactUpload"||this.setArtifactUploadValue(s.value||"",e==="start"?0:String(s.value||"").length)}async ensurePromptAttachmentSessionId(){const e=this.getPromptAttachments()[0]?.sessionId||null;if(e)return this.getState().sessions.activeSessionId!==e&&await this.loadSession(e),e;const s=this.getState().sessions.activeSessionId;if(s)return s;const n=await this.createSession({});if(!n?.sessionId)throw new Error("Create a session before attaching files");return n.sessionId}async revealArtifact(e,s,{force:n=!0,fullscreen:i=!1,pane:r=!1}={}){const o=e||this.getState().sessions.activeSessionId,l=String(s||"").trim();if(!o||!l)return!1;if(this.dispatch({type:"files/previewOrigin",origin:"chat",restoreArtifactId:this.getState().files.selectedArtifactId||null}),this.getState().sessions.activeSessionId!==o&&await this.loadSession(o).catch(()=>null),r||this.dispatch({type:"ui/inspectorTab",inspectorTab:"files"}),r){const c=!!this.getCurrentLayout()?.rightHidden;c&&this.expandRightColumn(),this.dispatch({type:"files/pane",open:!0,restoresToHidden:c})}else this.setFocus("inspector");return await this.ensureFilesForSession(o,{force:n}).catch(()=>null),this.dispatch({type:"files/select",sessionId:o,filename:l}),await this.ensureFilePreview(o,l,{force:n}).catch(()=>null),i&&this.dispatch({type:"files/fullscreen",fullscreen:!0}),!0}async closeArtifactPane(){const e=this.getState().files.paneRestoresToHidden;return this.dispatch({type:"files/pane",open:!1}),this.dispatch({type:"files/fullscreen",fullscreen:!1}),this.dispatch({type:"files/previewOrigin",origin:null}),e&&this.collapseRightColumn(),this.dispatch({type:"ui/focus",focusRegion:N.CHAT}),{collapsedRightColumn:!!e}}expandRightColumn(){this.dispatch({type:"ui/paneAdjust",paneAdjust:0});const e=this.getCurrentLayout({paneAdjust:0}),s=this.getState().ui.focusRegion,n=Qe(s,e);n!==s&&this.setFocus(n)}collapseRightColumn(){const s=(this.getState().ui.layout||{}).viewportWidth??120,n=Math.floor(s*Ya),i=s-_s-n;this.dispatch({type:"ui/paneAdjust",paneAdjust:i});const r=this.getCurrentLayout({paneAdjust:i}),o=this.getState().ui.focusRegion,l=Qe(o,r);l!==o&&this.setFocus(l)}async closeArtifactPreview(){const e=this.getState(),s=e.files.previewOrigin;if(this.dispatch({type:"files/fullscreen",fullscreen:!1}),s!=="chat"){this.dispatch({type:"files/previewOrigin",origin:null}),this.setFocus(N.INSPECTOR);return}const n=e.files.restoreArtifactId;if(n){const i=String(n).indexOf("/");i>0&&this.dispatch({type:"files/select",sessionId:n.slice(0,i),filename:n.slice(i+1)})}else this.dispatch({type:"files/select",sessionId:null,filename:null});this.dispatch({type:"files/previewOrigin",origin:null}),this.dispatch({type:"ui/focus",focusRegion:N.CHAT})}async stepArtifactPreview(e){const s=this.getState();if(s.files.previewOrigin!=="chat"){await this.moveFileSelection(e);return}const n=to(s);if(n.length===0){await this.moveFileSelection(e);return}const i=n.indexOf(s.files.selectedArtifactId),o=(i>=0?i:e>0?-1:n.length)+(e>0?1:-1);if(o<0||o>=n.length)return;const l=n[o],c=l.indexOf("/");if(c<=0)return;const u=l.slice(0,c),p=l.slice(c+1);this.dispatch({type:"files/select",sessionId:u,filename:p}),await this.ensureFilePreview(u,p).catch(()=>{})}canStepArtifactPreview(e){const s=this.getState(),n=s.files.previewOrigin==="chat"?to(s):It(s).map(r=>r.id);if(n.length===0)return!1;const i=n.indexOf(s.files.selectedArtifactId);return i<0?!0:e>0?i<n.length-1:i>0}async finalizeArtifactUpload(e,{sessionId:s=null,suppressStatus:n=!1}={}){const i=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!i||!e?.filename)throw new Error("Upload did not return a session id and filename");return this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),await this.ensureFilesForSession(i,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:i,filename:e.filename}),await this.ensureFilePreview(i,e.filename,{force:!0}).catch(()=>null),n||this.dispatch({type:"ui/status",text:`Uploaded ${e.filename}`}),{sessionId:i,filename:e.filename}}async applyUploadedPromptAttachment(e,{sessionId:s=null,suppressStatus:n=!1}={}){const i=s||e?.sessionId||await this.ensurePromptAttachmentSessionId();if(!i||!e?.filename)throw new Error("Upload did not return a session id and filename");const r=Lo(e.filename),o=this.getState().ui.prompt,l=this.getState().ui.promptCursor,c=this.getPromptAttachments(),u=c.findIndex(d=>d?.sessionId===i&&d?.filename===e.filename);if(this.getState().sessions.activeSessionId!==i&&await this.loadSession(i),u===-1||!o.includes(c[u]?.token||r)){const d=dt(o,l,`${r} `);this.setPrompt(d.prompt,d.cursor)}const p=u>=0?c.map((d,f)=>f===u?{...d,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:r}:d):[...c,{id:`${i}/${e.filename}`,sessionId:i,filename:e.filename,resolvedPath:e.resolvedPath||e.localPath||e.filename,sizeBytes:e.sizeBytes,token:r}];return this.setPromptAttachments(p),await this.ensureFilesForSession(i,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:i,filename:e.filename}),this.getState().ui.inspectorTab==="files"&&await this.ensureFilePreview(i,e.filename,{force:!0}).catch(()=>null),this.setFocus(N.PROMPT),n||this.dispatch({type:"ui/status",text:u>=0?`Re-attached ${e.filename}`:`Attached ${e.filename}`}),{sessionId:i,existingAttachmentIndex:u,token:r}}async uploadArtifactFiles(e=[],{sessionId:s=null}={}){const n=Array.isArray(e)?e.filter(c=>c&&typeof c.name=="string"):[];if(n.length===0)return this.dispatch({type:"ui/status",text:"No files selected"}),[];if(typeof this.transport.uploadArtifactFromFile!="function")return this.dispatch({type:"ui/status",text:"Browser file uploads are not supported by this transport"}),[];this.dispatch({type:"ui/status",text:n.length===1?`Uploading ${n[0].name}...`:`Uploading ${n.length} artifact files...`});const i=s||await this.ensurePromptAttachmentSessionId(),r=[];let o=0,l=null;for(const c of n)try{const u=await this.transport.uploadArtifactFromFile(i,c);r.push(u),await this.finalizeArtifactUpload(u,{sessionId:i,suppressStatus:!0})}catch(u){o+=1,l=u}return r.length>0?this.dispatch({type:"ui/status",text:o>0?`Uploaded ${r.length}/${n.length} file(s); last error: ${l?.message||String(l)}`:r.length===1?`Uploaded ${r[0].filename}`:`Uploaded ${r.length} files`}):l&&this.dispatch({type:"ui/status",text:`Upload failed: ${l?.message||String(l)}`}),r}async uploadPromptAttachmentFiles(e=[]){return this.uploadArtifactFiles(e)}async confirmArtifactUploadModal(){const e=this.getState().ui.modal;if(!e||e.type!=="artifactUpload")return;const s=String(e.value||"").trim();if(!s){this.dispatch({type:"ui/status",text:"File path cannot be empty"});return}if(typeof this.transport.uploadArtifactFromPath!="function"){this.dispatch({type:"ui/status",text:"Artifact upload is not supported by this transport"});return}this.dispatch({type:"ui/status",text:"Uploading artifact..."});try{const n=e.sessionId||await this.ensurePromptAttachmentSessionId(),i=await this.transport.uploadArtifactFromPath(n,s),r=await this.finalizeArtifactUpload(i,{sessionId:n,suppressStatus:!0});if(this.dispatch({type:"ui/modal",modal:null}),this.stageUploadedImageAttachment(r,n)){this.dispatch({type:"ui/status",text:`Uploaded ${r.filename} — attached to your next message`});return}this.dispatch({type:"ui/status",text:`Uploaded ${r.filename}`})}catch(n){this.dispatch({type:"ui/status",text:`Upload failed: ${n?.message||String(n)}`})}}openRenameSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s){this.dispatch({type:"ui/status",text:"No session selected"});return}const n=e.sessions.byId[s];if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System session titles are fixed"});return}const i=hm(n),r=sr(n),o=fm(n);this.dispatch({type:"ui/modal",modal:{type:"renameSession",title:n.isGroup?"Rename folder":`Rename (${_e(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:i,cursorIndex:i.length,agentTitlePrefix:r,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":r?`Rename title for ${r}; the agent-name prefix stays fixed`:"Type a new session title and press Enter to save"})}async openTerminatePickerModal(){const e=this.getState(),s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[];if(e.sessions.selectMode&&s.length>=1){const r=this.getBulkSelectedSessionActions(e).eligible;if(r.length===0){this.dispatch({type:"ui/status",text:"No selected sessions can be terminated"});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:"Terminate Selected Sessions",previousFocus:e.ui.focusRegion,bulkCount:r.length,skippedCount:s.length-r.length,selectedIds:r.map(o=>o.sessionId)}}),this.dispatch({type:"ui/status",text:"Choose what to do with the selected sessions"});return}const n=e.sessions.activeSessionId;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}const i=e.sessions.byId[n];if(!i){this.dispatch({type:"ui/status",text:"No session selected"});return}if(i.isSystem){const r=String(i.title||i.agentId||n.slice(0,8)).trim();this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:"Restart System Session",sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:r,state:String(i.state||"").trim(),systemRestart:!0}}),this.dispatch({type:"ui/status",text:"Choose how to restart the system session"});return}if(i.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; manage sessions individually."});return}this.dispatch({type:"ui/modal",modal:{type:"terminatePicker",title:`Terminate (${_e(n)})`,sessionId:n,previousFocus:e.ui.focusRegion,sessionTitle:String(i.title||"").trim(),state:String(i.state||"").trim(),canRegenerate:!1}})}async pickTerminateAction(e){const s=this.getState().ui.modal;if(!s||s.type!=="terminatePicker")return;const n=s.previousFocus;this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),e==="complete"?await this.completeActiveSession():e==="cancel"?await this.cancelActiveSession():e==="delete"?await this.deleteActiveSession():e==="regenerate"&&await this.regenerateActiveSession()}getBulkSelectedSessionActions(e=this.getState()){const s=Array.isArray(e.sessions.selectedIds)?e.sessions.selectedIds:[],i=[...new Set(s.map(o=>String(o||"").trim()).filter(Boolean))].map(o=>e.sessions.byId[o]).filter(Boolean),r=i.filter(o=>!o.isSystem&&!o.isGroup);return{selected:i,eligible:r,skippedCount:i.length-r.length}}updateRenameSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setRenameSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="renameSession")return;const i=Rt(e,n.maxLength),r=be(i,s);this.updateRenameSessionModal({value:i,cursorIndex:r})}insertRenameSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="renameSession")return;const n=dt(s.value||"",s.cursorIndex||0,Rt(e,s.maxLength));this.setRenameSessionValue(n.prompt,n.cursor)}deleteRenameSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=Lt(e.value||"",e.cursorIndex||0);this.setRenameSessionValue(s.prompt,s.cursor)}moveRenameSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",be(s.value||"",(s.cursorIndex||0)+e))}moveRenameSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="renameSession"||this.setRenameSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmRenameSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="renameSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim();if(!n){this.dispatch({type:"ui/status",text:"Title cannot be empty"});return}const i=this.getState().sessions.byId[s],r=i?.isGroup?i.groupId||Ls(s):null;if(r){if(typeof this.transport.updateSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group renaming is not supported by this transport"});return}const l=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),l&&this.setFocus(l),this.dispatch({type:"ui/status",text:`Renaming group ${r.slice(0,8)}...`});try{await this.transport.updateSessionGroup(r,{title:n}),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Renamed group ${n}`})}catch(c){this.dispatch({type:"ui/status",text:`Rename failed: ${c?.message||String(c)}`})}return}if(typeof this.transport.renameSession!="function"){this.dispatch({type:"ui/status",text:"Session renaming is not supported by this transport"});return}const o=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),o&&this.setFocus(o),this.dispatch({type:"ui/status",text:`Renaming ${_e(s)}...`});try{await this.transport.renameSession(s,n),await this.refreshSessions(),this.scheduleSessionDetailSync(s,100),this.dispatch({type:"ui/status",text:`Renamed ${_e(s)}`})}catch(l){this.dispatch({type:"ui/status",text:`Rename failed: ${l?.message||String(l)}`})}}async cycleSessionVisibility(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups don't have visibility"});return}if(typeof this.transport.setSessionVisibility!="function"){this.dispatch({type:"ui/status",text:"Not supported by this transport"});return}const i=Mt(["private","shared_read","shared_write"],n.visibility||"private",1);try{await this.transport.setSessionVisibility(s,i),await this.refreshSessions(),this.dispatch({type:"ui/status",text:`Visibility → ${i}`})}catch(r){this.dispatch({type:"ui/status",text:r?.message||String(r)})}}async openShareSessionModal(){const e=this.getState(),s=e.sessions.activeSessionId,n=s?e.sessions.byId[s]:null;if(!n){this.dispatch({type:"ui/status",text:"No session selected"});return}if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions are always private"});return}if(n.isGroup){this.dispatch({type:"ui/status",text:"Groups can't be shared"});return}if(typeof this.transport.listSessionShares!="function"){this.dispatch({type:"ui/status",text:"Session sharing is not supported by this transport"});return}let i;try{i=await this.transport.listSessionShares(s)}catch(r){this.dispatch({type:"ui/status",text:r?.message||String(r)});return}this.dispatch({type:"ui/modal",modal:{type:"shareSession",title:`Share (${_e(s)})`,sessionId:s,previousFocus:e.ui.focusRegion,value:"",cursorIndex:0,shares:Array.isArray(i)?i:[],visibility:n.visibility||"private"}}),this.dispatch({type:"ui/status",text:"name [r|w] grants · -name revokes · Enter apply"})}updateShareSessionModal(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return null;const n=typeof e=="function"?e(s):e;return n?(this.dispatch({type:"ui/modal",modal:{...s,...n}}),this.getState().ui.modal):null}setShareSessionValue(e,s=String(e||"").length){const n=this.getState().ui.modal;if(!n||n.type!=="shareSession")return;const i=Rt(e,120),r=be(i,s);this.updateShareSessionModal({value:i,cursorIndex:r})}insertShareSessionText(e){const s=this.getState().ui.modal;if(!s||s.type!=="shareSession")return;const n=dt(s.value||"",s.cursorIndex||0,Rt(e,120));this.setShareSessionValue(n.prompt,n.cursor)}deleteShareSessionChar(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=Lt(e.value||"",e.cursorIndex||0);this.setShareSessionValue(s.prompt,s.cursor)}moveShareSessionCursor(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",be(s.value||"",(s.cursorIndex||0)+e))}moveShareSessionCursorToBoundary(e){const s=this.getState().ui.modal;!s||s.type!=="shareSession"||this.setShareSessionValue(s.value||"",e==="start"?0:String(s.value||"").length)}async confirmShareSessionModal(){const e=this.getState().ui.modal;if(!e||e.type!=="shareSession")return;const s=e.sessionId;if(!s)return;const n=String(e.value||"").trim(),i=e.previousFocus;if(!n){this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);return}const r=n.startsWith("-")?n.slice(1).trim():n.toLowerCase().startsWith("revoke ")?n.slice(7).trim():null;if(r!==null){const h=r.toLowerCase(),m=(e.shares||[]).find(g=>g.subject&&String(g.subject).toLowerCase()===h||g.email&&String(g.email).toLowerCase()===h||g.displayName&&String(g.displayName).toLowerCase()===h);if(!m){this.dispatch({type:"ui/status",text:`No grant matching "${r}"`});return}this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.revokeSessionShare(s,{provider:m.provider,subject:m.subject}),this.dispatch({type:"ui/status",text:`Revoked ${r}`})}catch(g){this.dispatch({type:"ui/status",text:g?.message||String(g)})}return}const o=n.split(/\s+/),l={r:"read",read:"read",w:"write",write:"write"},c=o.length>1?o[o.length-1].toLowerCase():null,u=c&&l[c]?l[c]:"read",p=c&&l[c]?o.slice(0,-1).join(" "):n,d=p.toLowerCase();let f=null;if(typeof this.transport.listKnownUsers=="function"){let h=[];try{h=await this.transport.listKnownUsers({limit:500})}catch{h=[]}const m=Array.isArray(h)?h:[];if(f=m.find(g=>g.displayName&&g.displayName.toLowerCase()===d||g.email&&g.email.toLowerCase()===d||g.subject&&g.subject.toLowerCase()===d)||null,!f){const g=m.filter(S=>S.displayName&&S.displayName.toLowerCase().includes(d)||S.email&&S.email.toLowerCase().includes(d)||S.subject&&S.subject.toLowerCase().includes(d));if(g.length===1)f=g[0];else if(g.length>1){this.dispatch({type:"ui/status",text:`"${p}" is ambiguous (${g.length} matches)`});return}}}f||(f={provider:(this.getState().auth?.principal||null)?.provider||"dev",subject:p,email:null,displayName:null}),this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i);try{await this.transport.grantSessionShare(s,{provider:f.provider,subject:f.subject,email:f.email??null,displayName:f.displayName??null},u),this.dispatch({type:"ui/status",text:`Granted ${u} to ${p}`})}catch(h){this.dispatch({type:"ui/status",text:h?.message||String(h)})}}closeModal(){const e=this.getState().ui.modal;e&&(this.dispatch({type:"ui/modal",modal:null}),e.type==="themePicker"&&e.currentThemeId&&this.dispatch({type:"ui/theme",themeId:e.currentThemeId}),e.previousFocus&&this.setFocus(e.previousFocus),this.dispatch({type:"ui/status",text:"Connected"}))}toggleAgentPickerSection(e,s=null){const n=this.getState().ui.modal;if(!n||n.type!=="sessionAgentPicker"||!e)return;const i=new Set(n.collapsed||[]),r=s===null?!i.has(e):s;if(r===i.has(e))return;r?i.add(e):i.delete(e);const o=[...i],l=_o(n.catalog||[],o,n.genericItem||null),c=n.items?.[n.selectedIndex||0]?.id;let u=l.findIndex(p=>p.id===c);u<0&&(u=Math.max(0,l.findIndex(p=>p.sectionKey===e))),this.dispatch({type:"ui/modal",modal:{...n,collapsed:o,items:l,selectedIndex:u}})}moveAgentPickerSection(e){const s=this.getState().ui.modal;if(!s||s.type!=="sessionAgentPicker")return!1;const n=Array.isArray(s.items)?s.items:[],i=Math.max(0,Math.min(Number(s.selectedIndex)||0,n.length-1)),r=n[i];if(!r)return!1;if(e>0)return r.kind==="section"&&r.collapsed?(this.toggleAgentPickerSection(r.sectionKey,!1),!0):!1;if(r.kind==="section"&&!r.collapsed)return this.toggleAgentPickerSection(r.sectionKey,!0),!0;for(let o=i-1;o>=0;o-=1)if(n[o].kind==="section"&&n[o].depth<r.depth)return this.dispatch({type:"ui/modalSelection",index:o}),!0;return!1}moveModalSelection(e){const s=this.getState().ui.modal;if(!s)return;if(s.type==="help"){const r=Math.max(0,Number(s.selectedIndex)||0);this.dispatch({type:"ui/modalSelection",index:Math.max(0,r+e)});return}if(!Array.isArray(s.items)||s.items.length===0)return;if(s.type==="logFilter"||s.type==="filesFilter"||s.type==="historyFormat"){const r=Math.max(0,Math.min(Number(s.selectedIndex)||0,s.items.length-1)),o=s.items[r];if(!o||!Array.isArray(o.options)||o.options.length===0)return;const l=o.options.map(d=>d.id).filter(Boolean);if(l.length===0)return;const c=s.type==="filesFilter"?this.getState().files.filter?.[o.id]||l[0]:s.type==="historyFormat"?this.getState().executionHistory?.format||l[0]:this.getState().logs.filter?.[o.id]||l[0],u=Mt(l,c,e),p=o.options.find(d=>d.id===u)||o.options[0];this.dispatch({type:s.type==="filesFilter"?"files/filter":s.type==="historyFormat"?"executionHistory/format":"logs/filter",filter:s.type==="historyFormat"?void 0:{[o.id]:u},...s.type==="historyFormat"?{format:u}:{}}),s.type==="filesFilter"&&(this.ensureFilesForScope(u).catch(()=>{}),this.ensureSelectedFilePreview().catch(()=>{})),this.dispatch({type:"ui/status",text:`${s.type==="filesFilter"?"Files":s.type==="historyFormat"?"History":"Log"} filter updated: ${o.label} = ${p?.label||u}`});return}const n=Math.max(0,Number(s.selectedIndex)||0),i=Math.max(0,Math.min(n+e,s.items.length-1));this.dispatch({type:"ui/modalSelection",index:i})}moveModalPane(e){const s=this.getState().ui.modal;if(s?.type==="sessionAgentPicker"){this.moveAgentPickerSection(e);return}if(!s||s.type!=="logFilter"&&s.type!=="filesFilter"&&s.type!=="historyFormat"||!Array.isArray(s.items)||s.items.length===0)return;const i=(Math.max(0,Number(s.selectedIndex)||0)+e+s.items.length)%s.items.length,r=s.items[i],o=s.type==="filesFilter"?this.getState().files.filter?.[r.id]||r.options?.[0]?.id:s.type==="historyFormat"?this.getState().executionHistory?.format||r.options?.[0]?.id:this.getState().logs.filter?.[r.id]||r.options?.[0]?.id,l=r.options?.find(c=>c.id===o)||r.options?.[0];this.dispatch({type:"ui/modalSelection",index:i}),this.dispatch({type:"ui/status",text:`Editing ${r.label}: ${l?.label||o||""}`})}async confirmModal(){const e=this.getState().ui.modal;if(e){if(e.type==="help"){this.closeModal();return}if(e.type==="confirm"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s),e.action==="cancelSession"?await this.cancelActiveSession({confirmed:!0}):e.action==="completeSession"?await this.completeActiveSession("Completed by user",{confirmed:!0}):e.action==="deleteSession"?await this.deleteActiveSession({confirmed:!0}):e.action==="regenerateSession"?await this.regenerateActiveSession({confirmed:!0,...e.extras||{}}):e.action==="deleteArtifact"?await this.deleteSelectedArtifact({confirmed:!0}):e.action==="deleteMarkedArtifacts"&&await this.deleteMarkedArtifacts({confirmed:!0});return}if(e.type==="artifactUpload"){await this.confirmArtifactUploadModal();return}if(e.type==="renameSession"){await this.confirmRenameSessionModal();return}if(e.type==="shareSession"){await this.confirmShareSessionModal();return}if(e.type==="sessionGroupPicker"){await this.confirmSessionGroupPickerModal();return}if(e.type==="sessionGroupName"){await this.confirmSessionGroupNameModal();return}if(e.type==="sessionOwnerFilter"){this.toggleSessionOwnerFilter();return}if(e.type==="filesFilter"){const s=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),s&&this.setFocus(s);return}if(e.type==="themePicker"){const s=e.items?.[e.selectedIndex||0],n=rt(s?.id);if(!n){this.dispatch({type:"ui/status",text:"Unable to apply that theme"});return}const i=e.previousFocus;this.dispatch({type:"ui/modal",modal:null}),i&&this.setFocus(i),this.dispatch({type:"ui/status",text:`Applied theme: ${n.label}`});return}if(e.type==="modelPicker"){const s=e.items?.[e.selectedIndex||0];if(s?.disabled){this.dispatch({type:"ui/status",text:s.ghcpKeyMissing?"This model needs a GitHub Copilot key — add yours in the Admin console first":"This model is not available"});return}const n=e.previousFocus;if(!s){if(e.sessionOptions?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),this.dispatch({type:"ui/status",text:"No model selected"});return}await this.openSessionAgentPicker({},n);return}const i=Ao(s);if(e.sessionOptions?.mode==="switchModel"){await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,reasoningEffort:i??null},n);return}await this.openReasoningEffortPicker(s,{...e.sessionOptions||{},model:s.id,...i?{reasoningEffort:i}:{}},n);return}if(e.type==="reasoningEffortPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{};await this.openContextTierPicker(e.modelItem,{...i,...s?.id?{reasoningEffort:s.id}:{}},n);return}if(e.type==="contextTierPicker"){const s=e.items?.[e.selectedIndex||0],n=e.previousFocus,i=e.sessionOptions||{},r={...i,...s?.id?{contextTier:s.id}:{}};if(i?.mode==="switchModel"){this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),await this.switchSessionModel({...r,model:e.modelItem?.id||i.model});return}await this.openSessionAgentPicker(r,n);return}if(e.type==="sessionAgentPicker"){const s=e.items?.[e.selectedIndex||0];if(s?.kind==="section"){this.toggleAgentPickerSection(s.sectionKey);return}if(s&&s.kind!=="generic"&&s.supportsDirectStart===!1){this.dispatch({type:"ui/status",text:`${s.title||s.agentName} is created by another agent and cannot be started on its own`});return}const n=e.previousFocus,i=e.sessionOptions||{};if(this.dispatch({type:"ui/modal",modal:null}),n&&this.setFocus(n),!s||s.kind==="generic"){await this.createSession(i);return}await this.createSessionForAgent(s.agentName,{...i,...s.title?{title:s.title}:{},...s.splash?{splash:s.splash}:{},...s.splashMobile?{splashMobile:s.splashMobile}:{},...s.initialPrompt?{initialPrompt:s.initialPrompt}:{}});return}if(e.type==="logFilter"){this.closeModal();return}if(e.type==="historyFormat"){this.closeModal();return}e.type==="artifactPicker"&&await this.downloadArtifactModalSelection()}}openLogFilter(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"logFilter",title:"Log Filters",previousFocus:e,selectedIndex:0,items:[{id:"source",label:"Source nodes",description:"Choose whether the log pane shows logs from all nodes or only the current orchestration.",options:[{id:"allNodes",label:"All nodes"},{id:"currentOrchestration",label:"Current orchestration"}]},{id:"level",label:"Levels",description:"Filter logs by severity/verbosity level.",options:[{id:"all",label:"All"},{id:"info",label:"Info"},{id:"warn",label:"Warn"},{id:"error",label:"Error"},{id:"debug",label:"Debug"},{id:"trace",label:"Trace"}]},{id:"format",label:"Format",description:"Raw shows the structured time/node/level summary. Pretty shows the cleaned message text, colored by orchestration vs activity.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw summary"}]}]}}),this.dispatch({type:"ui/status",text:"Tab/Shift-Tab switch filters · Up/Down change values · Enter close · Esc cancel"})}openHistoryFormat(){const e=this.getState().ui.focusRegion;this.dispatch({type:"ui/modal",modal:{type:"historyFormat",title:"Execution History Format",previousFocus:e,selectedIndex:0,items:[{id:"format",label:"Format",description:"Pretty prints a human-readable view with colored event kinds. Raw JSON shows the full event objects.",options:[{id:"pretty",label:"Pretty text"},{id:"raw",label:"Raw JSON"}]}]}}),this.dispatch({type:"ui/status",text:"Up/Down change format · Enter close · Esc cancel"})}toggleLogTail(){const e=this.getState().logs;if(!e.available){this.dispatch({type:"ui/status",text:e.availabilityReason||"Log tailing is not available in this environment"});return}if(e.tailing){this.detachLogStream(),typeof this.transport.stopLogTail=="function"&&this.transport.stopLogTail().catch(()=>{}),this.dispatch({type:"logs/tailing",tailing:!1}),this.dispatch({type:"ui/status",text:"Log tailing stopped"});return}if(typeof this.transport.startLogTail!="function"){this.dispatch({type:"ui/status",text:"Log tailing is not supported by this transport"});return}this.logUnsubscribe=this.transport.startLogTail(s=>{const n=Array.isArray(s)?s:[s];n.length>0&&this.dispatch({type:"logs/append",entries:n})}),this.dispatch({type:"logs/tailing",tailing:!0}),this.dispatch({type:"ui/status",text:"Log tailing started"})}async sendPrompt(){const e=this.getState(),s=e.ui.prompt,n=this.getPromptAttachments(),i=n[0]?.sessionId||null,r=wm(s,n);let o=e.sessions.activeSessionId;i&&(o=i,e.sessions.activeSessionId!==i&&await this.loadSession(i));let l=o&&e.sessions.byId[o]||null;if(o&&!l&&(l=this.getState().sessions.byId[o]||null),!o){const 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(!r.trim()&&!c){o&&this.getPendingOutboxItems(o).length>0&&await this.dispatchPendingOutbox(o).catch(()=>{});return}const u=l?.pendingQuestion||null,p=!!u?.question,d=this.getPromptEditSessionMatch(o);if(d){const g=this.getSessionOutbox(o).find(S=>S.id===d.itemId);if(g?.phase==="queued"||g?.phase==="cancelling"){this.exitPendingPromptEdit({restoreDraft:!0});return}this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(o).catch(()=>{});return}if(p&&typeof this.transport.sendAnswer=="function"){const g=Date.now(),S={...u,answer:r,answeredAt:g,pendingPhase:"pending"};this.setPrompt("",0),this.setPromptAttachments([]),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:null,answeredPendingQuestion:S}}),this.dispatch({type:"ui/status",text:"Sending answer..."});try{await this.transport.sendAnswer(o,r),this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:{...S,pendingPhase:"queued"}}}),this.scheduleSessionDetailSync(o,100),this.syncSessionEvents(o).catch(()=>{}),this.scheduleSessionsRefresh(1e3),this.dispatch({type:"ui/status",text:"Answer sent"})}catch(y){this.dispatch({type:"sessions/merged",session:{sessionId:o,answeredPendingQuestion:null}}),this.dispatch({type:"sessions/merged",session:{sessionId:o,pendingQuestion:u}}),String(this.getState().ui.prompt||"").trim()||this.setPrompt(r,String(r||"").length),this.dispatch({type:"ui/status",text:y?.message||String(y)})}return}const f=n.filter(g=>g?.kind==="image");let h=null;if(f.length>0){if(f.some(y=>y.file)&&typeof this.transport.uploadArtifactFromFile!="function"){this.dispatch({type:"ui/status",text:"This transport does not support image attachments."});return}const S=this.buildOutboxItem("","pending");this.dispatch({type:"ui/status",text:`Uploading ${f.length} image${f.length>1?"s":""}...`});try{h=await this.uploadPendingImageAttachments(o,f,S.id),this.dispatch({type:"ui/status",text:""})}catch(y){this.dispatch({type:"ui/status",text:`Image upload failed: ${y?.message||y}`});return}}const m=r.trim()?r:h&&h.length>0?"See the attached image(s).":r;this.queuePromptInOutbox(o,m,h?{attachments:h}:null),this.setPrompt("",0),this.setPromptAttachments([]),await this.dispatchPendingOutbox(o).catch(()=>{})}setPrompt(e,s=String(e||"").length){const n=String(e||""),i=Math.max(0,Math.min(Number.isFinite(s)?s:n.length,n.length)),r=this.getState().ui;if(!(r.prompt===n&&r.promptCursor===i)){if(r.promptEdit?.sessionId&&r.promptEdit?.itemId){const l=this.getSessionOutbox(r.promptEdit.sessionId).map(c=>c.id===r.promptEdit.itemId&&c.phase==="pending"&&c.attempted!==!0?{...c,text:n}:c);this.setSessionOutboxItems(r.promptEdit.sessionId,l)}this.dispatch({type:"ui/prompt",prompt:n,promptCursor:i}),this.syncPromptReferenceBrowser()}}setPromptCursor(e){const s=this.getState().ui.prompt||"";this.setPrompt(s,e)}insertPromptText(e){const s=this.getState().ui,n=dt(s.prompt,s.promptCursor,e);this.setPrompt(n.prompt,n.cursor)}appendPromptChar(e){this.insertPromptText(e)}deletePromptChar(){const e=this.getState().ui,s=Lt(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}deletePromptWordBackward(){const e=this.getState().ui,s=km(e.prompt,e.promptCursor);this.setPrompt(s.prompt,s.cursor)}movePromptCursor(e){const s=this.getState().ui;this.setPrompt(s.prompt,be(s.prompt,s.promptCursor+e))}movePromptCursorWord(e){const s=this.getState().ui;this.setPrompt(s.prompt,tc(s.prompt,s.promptCursor,e))}movePromptCursorVertical(e){const s=this.getState().ui,n=Am(s.prompt,s.promptCursor,e);if(n!==s.promptCursor){this.setPrompt(s.prompt,n);return}e<0&&this.selectPreviousPendingPrompt()||e>0&&this.selectNextPendingPrompt()||this.setPrompt(s.prompt,n)}getCurrentLayout(e={}){const s=this.getState().ui.layout||{},n=this.getState().ui,i=e.prompt??n.prompt;return gs({width:e.width??s.viewportWidth??120,height:e.height??s.viewportHeight??40},e.paneAdjust??s.paneAdjust??0,e.promptRows??n.promptRows??Wt(i),e.sessionPaneAdjust??s.sessionPaneAdjust??0,e.activityPaneAdjust??s.activityPaneAdjust??0,e.fullscreenPane??n.fullscreenPane??null)}getSessionListMaxRows(e=this.getCurrentLayout()){const s=e.fullscreenPane===N.SESSIONS?e.bodyHeight:e.sessionPaneHeight;return Math.max(3,s-2)}setViewport(e={}){const s=Math.max(40,Number(e.width)||120),n=Math.max(18,Number(e.height)||40),i=this.getState().ui.layout||{};(i.viewportWidth!==s||i.viewportHeight!==n)&&this.dispatch({type:"ui/viewport",width:s,height:n});const r=this.getCurrentLayout({width:s,height:n}),o=this.getState().ui.focusRegion,l=Qe(o,r);l!==o&&this.setFocus(l)}setFocus(e){this.dispatch({type:"ui/focus",focusRegion:Qe(e,this.getCurrentLayout()),requestedFocusRegion:e})}focusNext(){const e=this.getCurrentLayout(),s=Qe(this.getState().ui.focusRegion,e),n=ei(e);this.setFocus(Mt(n,s,1))}focusPrev(){const e=this.getCurrentLayout(),s=Qe(this.getState().ui.focusRegion,e),n=ei(e);this.setFocus(Mt(n,s,-1))}focusLeft(){const e=this.getCurrentLayout(),s=Qe(this.getState().ui.focusRegion,e);this.setFocus(Yu(s,e))}focusRight(){const e=this.getCurrentLayout(),s=Qe(this.getState().ui.focusRegion,e);this.setFocus(Xu(s,e))}adjustPaneSplit(e){const s=this.getState().ui.layout||{},n=s.viewportWidth??120,i=Math.max(-n,Math.min(n,(s.paneAdjust||0)+e));this.dispatch({type:"ui/paneAdjust",paneAdjust:i});const r=this.getCurrentLayout({paneAdjust:i}),o=this.getState().ui.focusRegion,l=Qe(o,r);l!==o&&this.setFocus(l)}adjustSessionPaneSplit(e){const s=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,r=Math.max(-i,Math.min(i,(s.sessionPaneAdjust||0)+e));this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:r});const o=this.getCurrentLayout({sessionPaneAdjust:r}),l=this.getState().ui.focusRegion,c=Qe(l,o);c!==l&&this.setFocus(c)}adjustActivityPaneSplit(e){const s=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??s.viewportHeight??40,r=Math.max(-i,Math.min(i,(s.activityPaneAdjust||0)+e));this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:r});const o=this.getCurrentLayout({activityPaneAdjust:r}),l=this.getState().ui.focusRegion,c=Qe(l,o);c!==l&&this.setFocus(c)}resizeFocusedPane(e){const s=this.getState().ui.focusRegion,n=this.getState().ui.layout||{},i=this.getCurrentLayout().bodyHeight??n.viewportHeight??40,r=n.viewportHeight??40,o=(l,c,u,p)=>{const d=Math.max(u,p);return Math.max(u,Math.min(d,(l||0)+c))};if(s===N.SESSIONS||s===N.CHAT){const l=Za(i),c=Yt+1,u=Math.min(Ja(r,i),i-ln-1),p=s===N.CHAT?-e:e,d=o(n.sessionPaneAdjust,p,c-l,u-l);this.dispatch({type:"ui/sessionPaneAdjust",sessionPaneAdjust:d})}else if(s===N.INSPECTOR||s===N.ACTIVITY){const l=Math.max(zt,Math.floor(i*Qa)),c=zt+1,u=i-js-1,p=s===N.INSPECTOR?-e:e,d=o(n.activityPaneAdjust,p,c-l,u-l);this.dispatch({type:"ui/activityPaneAdjust",activityPaneAdjust:d})}}getActiveSequenceCompletedTurns(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return[];const n=e.history.bySessionId?.get?.(s),i=[],r=new Set;for(const o of n?.events||[]){if(o?.eventType!=="session.turn_completed")continue;const l=Number(o?.data?.turnIndex??o?.data?.iteration);!Number.isFinite(l)||r.has(l)||(r.add(l),i.push(l))}return i.sort((o,l)=>o-l),i}moveSequenceSelection(e){const s=this.getActiveSequenceCompletedTurns();if(s.length===0)return;const n=s.indexOf(Number(this.getState().ui.sequenceSelectedTurn)),i=n===-1?s.length-1:Math.max(0,Math.min(s.length-1,n+e));this.dispatch({type:"ui/sequenceSelectedTurn",turn:s[i]})}toggleSequenceTurnExpanded(){const e=this.getActiveSequenceCompletedTurns();if(e.length===0)return;let s=Number(this.getState().ui.sequenceSelectedTurn);e.includes(s)||(s=e[e.length-1],this.dispatch({type:"ui/sequenceSelectedTurn",turn:s}));const n=Array.isArray(this.getState().ui.sequenceExpandedTurns)?this.getState().ui.sequenceExpandedTurns.map(Number):[],i=n.includes(s)?n.filter(r=>r!==s):[...n,s];this.dispatch({type:"ui/sequenceExpandedTurns",turns:i})}nextInspectorTab(){const e=this.getState().ui.inspectorTab,s=Mt(et,e,1);this.dispatch({type:"ui/inspectorTab",inspectorTab:s}),this.ensureInspectorData(s).catch(()=>{})}prevInspectorTab(){const e=Mt(et,this.getState().ui.inspectorTab,-1);this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),this.ensureInspectorData(e).catch(()=>{})}cycleInspectorTab(){this.nextInspectorTab()}toggleStatsView(){const e=["session","fleet","users"],s=this.getState().ui.statsViewMode,n=e.includes(s)?e.indexOf(s):0,i=e[(n+1)%e.length];this.setStatsViewMode(i)}setStatsViewMode(e){this.dispatch({type:"ui/statsViewMode",statsViewMode:e}),this.getState().ui.inspectorTab==="stats"&&this.ensureInspectorData("stats").catch(()=>{})}async selectInspectorTab(e){et.includes(e)&&(this.dispatch({type:"ui/inspectorTab",inspectorTab:e}),await this.ensureInspectorData(e).catch(()=>{}))}async moveSession(e){const s=this.getState(),n=Qt(s);if(n.length===0)return;const i=s.sessions.activeSessionId||n[0].sessionId,r=Math.max(0,n.findIndex(c=>c.sessionId===i)),o=Math.max(0,Math.min(n.length-1,r+e)),l=n[o].sessionId;this.navigateToSession(l)}navigateToSession(e){e&&(this.getState().sessions.activeSessionId!==e&&(this.dispatch({type:"sessions/selected",sessionId:e}),this.dispatch({type:"ui/sequenceExpandedTurns",turns:[]}),this.dispatch({type:"ui/sequenceSelectedTurn",turn:null})),this.sessionNavSettleTimer&&clearTimeout(this.sessionNavSettleTimer),this.sessionNavSettleTimer=setTimeout(()=>{this.sessionNavSettleTimer=null,this.loadSession(e).catch(()=>{})},$m))}getSessionPageSize(){const e=this.getCurrentLayout(),s=e.fullscreenPane===N.SESSIONS?e.bodyHeight:e.sessionPaneHeight;return Math.max(1,s-3)}async moveSessionPage(e){const s=this.getSessionPageSize();await this.moveSession(s*e)}inspectorUsesBottomScroll(){return Cm.has(this.getState().ui.inspectorTab)}paneUsesStickyBottomFollow(e,s=this.getState()){return e==="activity"?!0:e==="inspector"?s.ui.inspectorTab==="logs":!1}isPaneFollowingBottom(e,s=this.getState()){return this.paneUsesStickyBottomFollow(e,s)?s.ui.followBottom?.[e]!==!1:!1}getPaneVisualScrollOffset(e,s=this.getState()){const n=this.getPaneMaxScrollOffset(e,s),i=Math.max(0,Math.min(Number(s.ui.scroll?.[e])||0,n));return this.isPaneFollowingBottom(e,s)?Math.max(0,n-i):i}applyPaneVisualScrollOffset(e,s,n={},i=this.getState()){const r=this.getPaneMaxScrollOffset(e,i),o=n.fromViewport?Math.max(0,Number(s)||0):Math.max(0,Math.min(Number(s)||0,r));if(this.paneUsesStickyBottomFollow(e,i)){const l=n.followBottom!==void 0?!!n.followBottom:n.atBottom!==void 0?!!n.atBottom:o>=r;return this.dispatch({type:"ui/followBottom",pane:e,followBottom:l}),this.dispatch({type:"ui/scroll",pane:e,offset:l?0:o}),o}return this.dispatch({type:"ui/scroll",pane:e,offset:o}),o}updatePaneScrollFromViewport(e,s,n={}){const i=this.getState();if(this.paneUsesStickyBottomFollow(e,i)){this.applyPaneVisualScrollOffset(e,s,{...n,fromViewport:!0},i);return}this.scrollPaneTo(e,s)}expandActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/expand",sessionId:e})}collapseActiveSession(){const e=this.getState().sessions.activeSessionId;e&&this.dispatch({type:"sessions/collapse",sessionId:e})}scrollPane(e,s){const n=this.getState(),i=this.getPaneMaxScrollOffset(e,n);if(this.paneUsesStickyBottomFollow(e,n)){const l=this.getPaneVisualScrollOffset(e,n),c=Math.max(0,Math.min(l-s,i));this.applyPaneVisualScrollOffset(e,c,{followBottom:c>=i},n);return}const r=Math.max(0,Math.min(Number(n.ui.scroll?.[e])||0,i)),o=Math.max(0,Math.min(r+s,i));this.dispatch({type:"ui/scroll",pane:e,offset:o}),e==="chat"&&s>0?r>=i?this.handleChatTopHistoryScrollIntent(o).catch(()=>{}):o>=i&&this.armChatTopHistoryLoad():e==="chat"&&s<0&&this.disarmChatTopHistoryLoad()}scrollPaneTo(e,s){const n=this.getState(),i=this.getPaneMaxScrollOffset(e,n),r=Math.max(0,Math.min(Number(s)||0,i));if(this.paneUsesStickyBottomFollow(e,n)){this.applyPaneVisualScrollOffset(e,r,{followBottom:r>=i},n);return}this.dispatch({type:"ui/scroll",pane:e,offset:r}),e==="chat"&&(i>0&&r>=i?this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad())}armChatTopHistoryLoad(){const e=this.getState().sessions.activeSessionId;e&&(this.chatTopHistoryLoadArmed=!0,this.chatTopHistoryLoadSessionId=e)}disarmChatTopHistoryLoad(){this.chatTopHistoryLoadArmed=!1,this.chatTopHistoryLoadSessionId=null}async handleChatTopHistoryScrollIntent(e,s={}){const i=this.getState().sessions.activeSessionId;if(i){if(!s.force&&(!this.chatTopHistoryLoadArmed||this.chatTopHistoryLoadSessionId!==i)){this.armChatTopHistoryLoad();return}await this.maybeAutoExpandActiveHistory(e,{pages:Vh,force:!0})}}artifactPreviewOwnsActivitySlot(e=this.getState()){return e.ui.inspectorTab==="files"&&!!e.files?.selectedArtifactId}focusIsArtifactList(e=this.getState()){return e.ui.focusRegion===N.INSPECTOR&&e.ui.inspectorTab==="files"}getScrollablePaneForFocus(){const e=this.getState(),s=e.ui.focusRegion;return s===N.CHAT?"chat":s===N.ACTIVITY?this.artifactPreviewOwnsActivitySlot(e)?"filePreview":"activity":s===N.INSPECTOR?this.getState().ui.inspectorTab==="files"?"filePreview":"inspector":null}scrollCurrentPane(e){const s=this.getScrollablePaneForFocus();if(!s)return;if(this.paneUsesStickyBottomFollow(s)){this.scrollPane(s,e);return}const n=s==="inspector"&&this.inspectorUsesBottomScroll(),i=s==="inspector"||s==="filePreview";this.scrollPane(s,i&&!n?-e:e)}scrollCurrentPaneToTop(){const e=this.getScrollablePaneForFocus();if(!e)return;if(this.paneUsesStickyBottomFollow(e)){this.applyPaneVisualScrollOffset(e,0,{followBottom:!1});return}const s=e==="inspector"&&this.inspectorUsesBottomScroll();if(e==="chat"||e==="activity"||s){this.scrollPaneTo(e,Number.MAX_SAFE_INTEGER);return}this.scrollPaneTo(e,0)}scrollCurrentPaneToBottom(){const e=this.getScrollablePaneForFocus();if(!e)return;if(this.paneUsesStickyBottomFollow(e)){this.applyPaneVisualScrollOffset(e,Number.MAX_SAFE_INTEGER,{followBottom:!0});return}const s=e==="inspector"&&this.inspectorUsesBottomScroll();if(e==="chat"||e==="activity"||s){this.scrollPaneTo(e,0);return}this.scrollPaneTo(e,Number.MAX_SAFE_INTEGER)}async expandActiveHistory(){const e=this.getState().sessions.activeSessionId;e&&await this.expandSessionHistory(e)}getActiveChatRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.leftHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.leftWidth-4),i=Math.max(1,s.chatPaneHeight-2),r=Gi(e,n),o=[...Wi(e,n),...ji(e)],l=Math.min(Math.max(0,Math.floor(i*.34)),_t(o,n)),c=_t(r,n);return{contentWidth:n,contentHeight:Math.max(1,i-l),totalLines:c}}getActivityRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.activityHidden)return{contentWidth:20,contentHeight:1,totalLines:0};const n=Math.max(20,s.rightWidth-4),i=Math.max(1,s.activityPaneHeight-2),r=e.sessions.activeSessionId,o={sessions:{activeSessionId:r,byId:r?{[r]:e.sessions.byId[r]||null}:{}},history:{bySessionId:r?new Map([[r,e.history.bySessionId.get(r)||null]]):new Map}},l=Ki(o);return{contentWidth:n,contentHeight:i,totalLines:_t(l.lines,n)}}getInspectorRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if(s.rightHidden||s.inspectorHidden)return{contentWidth:20,contentHeight:1,stickyLineCount:0,totalLines:0};const n=Math.max(20,s.rightWidth-4),i=e.sessions.activeSessionId,r=i&&e.orchestration.bySessionId?.[i]||null,o={branding:e.branding,sessions:{activeSessionId:i,byId:e.sessions.byId,flat:e.sessions.flat},history:{bySessionId:e.history.bySessionId},orchestration:{bySessionId:i&&r?{[i]:r}:{}},logs:e.logs,sessionStats:e.sessionStats,fleetStats:e.fleetStats,ui:{inspectorTab:e.ui.inspectorTab,statsViewMode:e.ui.statsViewMode},executionHistory:e.executionHistory},l=mt(o,{width:n}),c=l.tabs.map(f=>({text:f===l.activeTab?`[${f}] `:`${f} `,color:f===l.activeTab?"magenta":"gray",bold:f===l.activeTab})),u=(l.lines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f),p=l.activeTab==="sequence"?[c,...(l.stickyLines||[]).map(f=>typeof f=="string"?{text:f,color:"white"}:f)]:[],d=l.activeTab==="sequence"?u:[c,...u];return{contentWidth:n,contentHeight:Math.max(1,s.inspectorPaneHeight-2),stickyLineCount:_t(p,n),totalLines:_t(d,n)}}getFilePreviewRenderMetrics(e=this.getState()){const s=this.getCurrentLayout();if((s.rightHidden||s.inspectorHidden)&&!e.files?.fullscreen)return{contentWidth:20,contentHeight:1,totalLines:0};const n=e.ui.inspectorTab==="files"&&!!e.files?.fullscreen,i=n?s.totalWidth:s.rightWidth,r=n?Math.max(10,s.bodyHeight):s.inspectorPaneHeight,o=Math.max(20,i-4),l=Math.max(8,o-4),c=e.sessions.activeSessionId,u=c&&e.sessions.byId[c]||null,p={sessions:{activeSessionId:c,byId:c&&u?{[c]:u}:{},flat:e.sessions.flat},files:{bySessionId:e.files.bySessionId,fullscreen:!!e.files.fullscreen,selectedArtifactId:e.files.selectedArtifactId,filter:e.files.filter},ui:{scroll:{filePreview:e.ui.scroll.filePreview}}},d=Vi(p,{listWidth:l,previewWidth:l}),f=Math.max(9,r-4),h=Math.max(5,Math.min(10,Math.floor(f*.35)));let m=Math.max(5,Math.min(h,(d.listBodyLines||[]).length+2)),g=Math.max(5,f-m-1);const S=8;if(g<S){const y=S-g;m=Math.max(5,m-y),g=Math.max(5,f-m-1)}return{contentWidth:l,contentHeight:Math.max(1,g-2),totalLines:_t(d.previewLines,l)}}getPaneMaxScrollOffset(e,s=this.getState()){if(!e)return 0;if(e==="chat"){const n=this.getActiveChatRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="activity"){const n=this.getActivityRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}if(e==="inspector"){const n=this.getInspectorRenderMetrics(s),i=Math.min(n.contentHeight,n.stickyLineCount||0),r=Math.max(0,n.contentHeight-i);return Math.max(0,n.totalLines-r)}if(e==="filePreview"){const n=this.getFilePreviewRenderMetrics(s);return Math.max(0,n.totalLines-n.contentHeight)}return 0}async maybeAutoExpandActiveHistory(e,s={}){const n=this.getState(),i=n.sessions.activeSessionId;if(!i)return;const r=n.history.bySessionId.get(i);if(!r?.hasOlderEvents||this.sessionHistoryExpansionLoads.has(i))return;if(Number(r.loadedEventCount||0)>=fi){this.dispatch({type:"ui/status",text:"Reached automatic history limit. Press e to load more older CMS events."});return}const o=Array.isArray(r?.chat)&&r.chat.length>0;if(!s.force&&o){const{contentHeight:l,totalLines:c}=this.getActiveChatRenderMetrics(n),u=Math.max(0,c-l);if(e<u)return}await this.expandSessionHistory(i,{requestedScrollOffset:e,autoTriggered:!0,pages:s.pages,eventTypes:Iu})}async expandSessionHistory(e,s={}){if(!e)return;if(this.sessionHistoryExpansionLoads.has(e))return this.sessionHistoryExpansionLoads.get(e);const n=this.getState(),i=n.history.bySessionId.get(e),r=Math.max(me,Number(i?.loadedEventLimit??me)||me),o=me,l=Array.isArray(i?.events)&&i.events.length>0?Number(i.events[0]?.seq||0):0;if(!i?.hasOlderEvents||l<=1){this.dispatch({type:"ui/status",text:"Already showing the oldest loaded history"});return}const c=e===n.sessions.activeSessionId,u=Number(s.requestedScrollOffset??n.ui.scroll?.chat??0),p=c?this.getActiveChatRenderMetrics(n).totalLines:0,d=(async()=>{let f;const h=Math.max(1,Math.floor(Number(s.pages)||1)),m=Array.isArray(s.eventTypes)&&s.eventTypes.length>0?s.eventTypes:void 0;if(typeof this.transport.getSessionEventsBefore=="function"&&l>0){f=i||Es([],{requestedLimit:r});for(let y=0;y<h;y+=1){const v=Array.isArray(f?.events)&&f.events.length>0?Number(f.events[0]?.seq||0):0;if(!f?.hasOlderEvents||v<=1){f={...f,hasOlderEvents:!1};break}if(Number(f.loadedEventCount||0)>=fi)break;const x=await this.transport.getSessionEventsBefore(e,v,o,m);if(!Array.isArray(x)||x.length===0){f={...f,hasOlderEvents:!1};break}const E=Es(x,{requestedLimit:o}),w=[...E.events||[],...f?.events||[]];if(f={chat:Gt([...E.chat||[],...f?.chat||[]]),activity:[...E.activity||[],...f?.activity||[]],events:w,lastSeq:f?.lastSeq||f?.events?.[f?.events?.length-1]?.seq||x[x.length-1]?.seq||0,loadedEventLimit:w.length,loadedEventCount:w.length,hasOlderEvents:x.length>=o&&Number(x[0]?.seq||0)>1},!f.hasOlderEvents)break}}else{const y=Uu(r);if(y<=r){this.dispatch({type:"ui/status",text:i?.hasOlderEvents?`Already showing a large recent history window (${r} events)`:"Already showing the oldest loaded history"});return}const v=await this.transport.getSessionEvents(e,void 0,y);f={...Es(v,{requestedLimit:y}),lastSeq:v[v.length-1]?.seq||0}}this.dispatch({type:"history/set",sessionId:e,history:f});for(const y of f?.events||[])this.reconcileOutboxAgainstEvent(e,y);const g=Array.isArray(i?.chat)&&i.chat.length>0;if(c&&!g)this.dispatch({type:"ui/scroll",pane:"chat",offset:0});else if(c&&u>0&&!s.autoTriggered){const y=this.getState(),v=this.getActiveChatRenderMetrics(y).totalLines,x=Math.max(0,v-p);x>0&&this.dispatch({type:"ui/scroll",pane:"chat",offset:u+x})}const S=f.hasOlderEvents?s.autoTriggered?`Loaded older history page from CMS (${f.loadedEventCount} events loaded)`:`Loaded older history page (${f.loadedEventCount} events loaded)`:`Loaded full available history (${f.loadedEventCount} events)`;this.dispatch({type:"ui/status",text:S}),f.hasOlderEvents?s.autoTriggered&&c&&this.armChatTopHistoryLoad():this.disarmChatTopHistoryLoad()})().finally(()=>{this.sessionHistoryExpansionLoads.delete(e)});return this.sessionHistoryExpansionLoads.set(e,d),d}async cancelActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:o,skippedCount:l}=this.getBulkSelectedSessionActions(s);if(o.length===0){this.dispatch({type:"ui/status",text:"No cancellable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Sessions",message:`Cancel ${o.length} selected session${o.length===1?"":"s"}?${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Cancel Sessions",action:"cancelSession",previousFocus:s.ui.focusRegion}});return}let c=0;const u=[];for(const d of o)try{await this.transport.cancelSession(d.sessionId),c+=1}catch(f){u.push(`${d.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const p=u.length===0?`Cancelled ${c} session${c===1?"":"s"}`:`Cancelled ${c}/${o.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:p}),await this.refreshSessions();return}const i=s.sessions.activeSessionId;if(!i)return;const r=s.sessions.byId[i];if(r?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; cancel sessions individually."});return}if(r?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const o=r.title||r.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Terminate & Restart System Session",message:`Terminate system session "${o}" and start a fresh one?`,confirmLabel:"Terminate & Restart",action:"cancelSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(r.agentId||i,{disposition:"terminate",reason:"Terminated by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${r.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const l=r?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Cancel Session",message:`Cancel session "${l}"? The session will stop processing.`,confirmLabel:"Cancel Session",action:"cancelSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.cancelSession(i),this.dispatch({type:"ui/status",text:`Cancelled ${i.slice(0,8)}`}),await this.refreshSessions()}updateConfirmExtras(e){const s=this.getState().ui.modal;!s||s.type!=="confirm"||this.dispatch({type:"ui/modal",modal:{...s,extras:{...s.extras||{},...e||{}}}})}async regenerateActiveSession({confirmed:e=!1,instructions:s="",distillMode:n="llm",distillerModel:i="",distillerEffort:r="",distillerContextTier:o=""}={}){const l=this.getState(),c=l.sessions.activeSessionId;if(!c)return;if(typeof this.transport.regenerateSession!="function"){this.dispatch({type:"ui/status",text:"Session regeneration is not supported by this deployment"});return}const u=l.sessions.byId[c];if(u?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; regenerate sessions individually."});return}if(u?.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be regenerated."});return}if(u?.serviceKind){this.dispatch({type:"ui/status",text:"Service sessions are runtime machinery and cannot be regenerated."});return}if(!e){const p=u?.title||c.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Regenerate Session",message:`Regenerate context for "${p}"? The transcript is archived and distilled, then the session rebuilds fresh from it at the next turn boundary. Facts, artifacts, sub-agents, sharing, schedule, and chat history are preserved. As an operator action this overrides the rate limits (cooldown / minimum age).`,confirmLabel:"Regenerate",action:"regenerateSession",sessionId:c,previousFocus:l.ui.focusRegion,extras:{instructions:"",distillMode:"llm",distillerModel:"",distillerEffort:"",distillerContextTier:"",distillerModelOptions:await this._loadDistillerModelOptions()}}});return}try{const p=String(s||"").trim();await this.transport.regenerateSession(c,{force:!0,...p?{instructions:p.slice(0,4e3)}:{},...n==="deterministic"?{distillMode:"deterministic"}:{},...i?{distillerModel:i}:{},...r?{distillerReasoningEffort:r}:{},...o?{distillerContextTier:o}:{}}),this.dispatch({type:"ui/status",text:`Regeneration requested for ${c.slice(0,8)} — rebuilding at the next boundary`})}catch(p){this.dispatch({type:"ui/status",text:`Regenerate failed: ${p?.message||String(p)}`});return}await this.refreshSessions()}async _loadDistillerModelOptions(){if(typeof this.transport.listModels!="function")return[];try{const e=await this.transport.listModels({groupByProvider:!0});return(Array.isArray(e)?e:Array.isArray(e?.providers)?e.providers:Array.isArray(e?.models)?e.models:[]).flatMap(i=>Array.isArray(i?.models)?i.models.map(r=>({...r,providerId:r.providerId||i.providerId})):[i]).filter(i=>i&&(i.qualifiedName||i.modelName)).map(i=>({qualifiedName:i.qualifiedName||i.modelName,modelName:i.modelName||i.qualifiedName,providerId:i.providerId||"",supportedReasoningEfforts:Array.isArray(i.supportedReasoningEfforts)?i.supportedReasoningEfforts:[],supportedContextTiers:Array.isArray(i.supportedContextTiers)?i.supportedContextTiers:[]}))}catch(e){return this.dispatch({type:"ui/status",text:`Could not load distiller models: ${e?.message||String(e)}`}),[]}}async stopActiveSessionTurn(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n||n.isGroup){this.dispatch({type:"ui/status",text:"Select a session to stop its turn."});return}if(typeof this.transport.stopSessionTurn!="function"){this.dispatch({type:"ui/status",text:"Stop turn is not supported by this transport"});return}if(this._stopTurnInFlight||(this._stopTurnInFlight=new Set),!this._stopTurnInFlight.has(s)){this._stopTurnInFlight.add(s),this.dispatch({type:"ui/status",text:`Stopping turn for ${s.slice(0,8)}…`});try{const r=(await this.transport.stopSessionTurn(s,{reason:"Stopped by user"}))?.outcome||"stopped";r==="no_active_turn"?this.dispatch({type:"ui/status",text:"No active turn to stop"}):r==="timeout"?this.dispatch({type:"ui/status",text:"Stop requested — waiting for the turn to unwind"}):this.dispatch({type:"ui/status",text:`Stopped turn for ${s.slice(0,8)}`})}catch(i){this.dispatch({type:"ui/status",text:`Stop turn failed: ${i?.message||i}`})}finally{this._stopTurnInFlight.delete(s)}await this.refreshSessions(),await this.refreshActiveSessionDetail?.().catch?.(()=>{})}}togglePinActiveSession(){const e=this.getState(),s=e.sessions.activeSessionId;if(!s)return;const n=e.sessions.byId[s];if(!n)return;if(n.isSystem){this.dispatch({type:"ui/status",text:"System sessions cannot be pinned."});return}if(!n.isGroup&&(n.parentSessionId||n.groupId)){this.dispatch({type:"ui/status",text:"Sessions inside groups or parents cannot be pinned."});return}const i=Array.isArray(e.sessions.pinnedIds)&&e.sessions.pinnedIds.includes(s);this.dispatch({type:"sessions/pinToggle",sessionId:s}),this.dispatch({type:"ui/status",text:i?`Unpinned ${s.slice(0,8)}`:`Pinned ${s.slice(0,8)}`})}toggleSessionSelectMode(){const e=this.getState(),s=!e.sessions.selectMode;if(this.dispatch({type:"sessions/selectMode",enabled:s}),s){const n=e.sessions.activeSessionId;n&&e.sessions.byId[n]&&this.dispatch({type:"sessions/selectToggle",sessionId:n}),this.dispatch({type:"ui/status",text:"Select mode: space toggles, Ctrl+G moves, c cancels, V/esc exits"})}else this.dispatch({type:"ui/status",text:"Select mode off"})}toggleActiveSessionSelection(){const e=this.getState(),s=e.sessions.activeSessionId;s&&(e.sessions.selectMode||this.dispatch({type:"sessions/selectMode",enabled:!0}),this.dispatch({type:"sessions/selectToggle",sessionId:s}))}setSessionSelection(e){const s=Array.isArray(e)?e:[];this.dispatch({type:"sessions/selectSet",sessionIds:s})}clearSessionSelection(){this.dispatch({type:"sessions/selectClear"})}async completeActiveSession(e="Completed by user",{confirmed:s=!1}={}){const n=this.getState(),i=Array.isArray(n.sessions.selectedIds)?n.sessions.selectedIds:[];if(n.sessions.selectMode&&i.length>=1){const{eligible:l,skippedCount:c}=this.getBulkSelectedSessionActions(n);if(l.length===0){this.dispatch({type:"ui/status",text:"No completable sessions in selection (system sessions and groups are skipped)."});return}if(!s){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Sessions",message:`Complete ${l.length} selected session${l.length===1?"":"s"}? This will cascade to their sub-agents.${c>0?` (${c} selected row${c===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Complete Sessions",action:"completeSession",previousFocus:n.ui.focusRegion}});return}let u=0;const p=[];for(const f of l)try{await this.transport.completeSession(f.sessionId,e),u+=1}catch(h){p.push(`${f.sessionId.slice(0,8)}: ${h?.message||String(h)}`)}this.dispatch({type:"sessions/selectClear"});const d=p.length===0?`Completed ${u} session${u===1?"":"s"}`:`Completed ${u}/${l.length}; ${p.length} failed: ${p.slice(0,2).join(", ")}${p.length>2?"…":""}`;this.dispatch({type:"ui/status",text:d}),await this.refreshSessions();return}const r=this.getState().sessions.activeSessionId;if(!r)return;const o=this.getState().sessions.byId[r];if(o?.isGroup){this.dispatch({type:"ui/status",text:"Groups are containers; complete sessions individually."});return}if(o?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!s){const l=o.title||o.agentId||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete & Restart System Session",message:`Mark system session "${l}" complete and start a fresh one?`,confirmLabel:"Complete & Restart",action:"completeSession",sessionId:r,previousFocus:this.getState().ui.focusRegion}});return}await this.transport.restartSystemSession(o.agentId||r,{disposition:"complete",reason:e}),this.dispatch({type:"ui/status",text:`Restarted system session ${o.agentId||r.slice(0,8)}`}),await this.refreshSessions();return}if(typeof this.transport.completeSession!="function"){this.dispatch({type:"ui/status",text:"Session completion is not supported by this transport"});return}if(o?.status==="completed"&&!o?.cronActive&&!o?.cronInterval){this.dispatch({type:"ui/status",text:`${r.slice(0,8)} is already completed`});return}if(!s){const l=o?.title||r.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Complete Session",message:`Complete session "${l}"? This will cascade to all sub-agents.`,confirmLabel:"Complete",action:"completeSession",sessionId:r,previousFocus:this.getState().ui.focusRegion}});return}this.dispatch({type:"ui/status",text:`Completing ${r.slice(0,8)} (cascading to sub-agents)...`});try{await this.transport.completeSession(r,e),await this.refreshSessions(),this.scheduleSessionDetailSync(r,100),this.scheduleSessionsRefresh(900)}catch(l){await this.loadSession(r).catch(()=>{}),this.dispatch({type:"ui/status",text:`Failed to send /done: ${l?.message||String(l)}`})}}async deleteActiveSession({confirmed:e=!1}={}){const s=this.getState(),n=Array.isArray(s.sessions.selectedIds)?s.sessions.selectedIds:[];if(s.sessions.selectMode&&n.length>=1){const{eligible:o,skippedCount:l}=this.getBulkSelectedSessionActions(s);if(o.length===0){this.dispatch({type:"ui/status",text:"No deletable sessions in selection (system sessions and groups are skipped)."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete Sessions",message:`Hard delete ${o.length} selected session${o.length===1?"":"s"}? This action cannot be undone.${l>0?` (${l} selected row${l===1?"":"s"} will be skipped)`:""}`,confirmLabel:"Hard Delete Sessions",action:"deleteSession",previousFocus:s.ui.focusRegion}});return}let c=0;const u=[];for(const d of o)try{await this.transport.deleteSession(d.sessionId),this.handleSessionGone(d.sessionId),c+=1}catch(f){u.push(`${d.sessionId.slice(0,8)}: ${f?.message||String(f)}`)}this.dispatch({type:"sessions/selectClear"});const p=u.length===0?`Deleted ${c} session${c===1?"":"s"}`:`Deleted ${c}/${o.length}; ${u.length} failed: ${u.slice(0,2).join(", ")}${u.length>2?"…":""}`;this.dispatch({type:"ui/status",text:p}),await this.refreshSessions();return}const i=s.sessions.activeSessionId;if(!i)return;const r=s.sessions.byId[i];if(r?.isGroup){const o=r.groupId||Ls(i);if(!o||typeof this.transport.deleteSessionGroup!="function"){this.dispatch({type:"ui/status",text:"Group deletion is not supported by this transport"});return}if(Number(r.memberCount||0)>0){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Group Not Empty",message:`Group "${r.title||o}" is not empty. Move all sessions out of the group before deleting it.`,confirmLabel:"OK",action:"alert",alert:!0,previousFocus:s.ui.focusRegion}}),this.dispatch({type:"ui/status",text:"Move all sessions out of the group before deleting it."});return}if(!e){this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Group",message:`Delete empty group "${r.title||o}"? This action cannot be undone.`,confirmLabel:"Delete Group",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSessionGroup(o),this.dispatch({type:"ui/status",text:`Deleted group ${r.title||o}`}),await this.refreshSessions();return}if(r?.isSystem){if(typeof this.transport.restartSystemSession!="function"){this.dispatch({type:"ui/status",text:"System session restart is not supported by this transport"});return}if(!e){const o=r.title||r.agentId||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Hard Delete & Restart System Session",message:`Hard delete system session "${o}" and start a fresh one? This removes the current orchestration immediately.`,confirmLabel:"Hard Delete & Restart",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.restartSystemSession(r.agentId||i,{disposition:"hard_delete",reason:"Hard-deleted by user for system-session restart"}),this.dispatch({type:"ui/status",text:`Restarted system session ${r.agentId||i.slice(0,8)}`}),await this.refreshSessions();return}if(!e){const l=r?.title||i.slice(0,8);this.dispatch({type:"ui/modal",modal:{type:"confirm",title:"Delete Session",message:`Delete session "${l}"? This action cannot be undone.`,confirmLabel:"Delete",action:"deleteSession",sessionId:i,previousFocus:s.ui.focusRegion}});return}await this.transport.deleteSession(i),this.handleSessionGone(i),this.dispatch({type:"ui/status",text:`Deleted ${i.slice(0,8)}`}),await this.refreshSessions()}async handleCommand(e){switch(e){case C.REFRESH:await this.refreshSessions();return;case C.NEW_SESSION:await this.openNewSessionFlow();return;case C.OPEN_MODEL_PICKER:await this.openModelPicker();return;case C.OPEN_SWITCH_MODEL_PICKER:await this.openSwitchModelPicker();return;case C.OPEN_THEME_PICKER:this.openThemePicker();return;case C.OPEN_RENAME_SESSION:this.openRenameSessionModal();return;case C.CYCLE_SESSION_VISIBILITY:await this.cycleSessionVisibility();return;case C.OPEN_SHARE_SESSION:await this.openShareSessionModal();return;case C.OPEN_SESSION_FILTER:this.openSessionOwnerFilter();return;case C.OPEN_TERMINATE_PICKER:await this.openTerminatePickerModal();return;case C.OPEN_MOVE_TO_GROUP:await this.openMoveToGroupModal();return;case C.CREATE_SESSION_GROUP:await this.openMoveToGroupModal();return;case C.OPEN_ARTIFACT_UPLOAD:this.openArtifactUploadModal();return;case C.CLOSE_MODAL:this.closeModal();return;case C.MODAL_PREV:this.moveModalSelection(-1);return;case C.MODAL_NEXT:this.moveModalSelection(1);return;case C.MODAL_PANE_PREV:this.moveModalPane(-1);return;case C.MODAL_PANE_NEXT:this.moveModalPane(1);return;case C.MODAL_CONFIRM:await this.confirmModal();return;case C.SEND_PROMPT:await this.sendPrompt();return;case C.FOCUS_NEXT:this.focusNext();return;case C.FOCUS_PREV:this.focusPrev();return;case C.FOCUS_LEFT:this.focusLeft();return;case C.FOCUS_RIGHT:this.focusRight();return;case C.FOCUS_PROMPT:this.setFocus(N.PROMPT);return;case C.FOCUS_SESSIONS:this.setFocus(N.SESSIONS);return;case C.MOVE_SESSION_UP:await this.moveSession(-1);return;case C.MOVE_SESSION_DOWN:await this.moveSession(1);return;case C.EXPAND_SESSION:this.expandActiveSession();return;case C.COLLAPSE_SESSION:this.collapseActiveSession();return;case C.NEXT_INSPECTOR_TAB:this.nextInspectorTab();return;case C.PREV_INSPECTOR_TAB:this.prevInspectorTab();return;case C.CYCLE_INSPECTOR_TAB:this.cycleInspectorTab();return;case C.GROW_LEFT_PANE:this.adjustPaneSplit(8);return;case C.GROW_RIGHT_PANE:this.adjustPaneSplit(-8);return;case C.GROW_SESSION_PANE:this.adjustSessionPaneSplit(2);return;case C.SHRINK_SESSION_PANE:this.adjustSessionPaneSplit(-2);return;case C.GROW_FOCUSED_PANE:this.resizeFocusedPane(2);return;case C.SHRINK_FOCUSED_PANE:this.resizeFocusedPane(-2);return;case C.OPEN_ARTIFACT_PICKER:await this.openArtifactPicker();return;case C.OPEN_HELP:this.openHelpModal();return;case C.SEQUENCE_SELECT_PREV:this.moveSequenceSelection(-1);return;case C.SEQUENCE_SELECT_NEXT:this.moveSequenceSelection(1);return;case C.TOGGLE_SEQUENCE_TURN:this.toggleSequenceTurnExpanded();return;case C.TOGGLE_LOG_TAIL:this.toggleLogTail();return;case C.TOGGLE_STATS_VIEW:this.toggleStatsView();return;case C.OPEN_LOG_FILTER:this.openLogFilter();return;case C.OPEN_FILES_FILTER:this.openFilesFilter();return;case C.MOVE_FILE_UP:await this.moveFileSelection(-1);return;case C.MOVE_FILE_DOWN:await this.moveFileSelection(1);return;case C.DOWNLOAD_SELECTED_FILE:await this.downloadSelectedArtifact();return;case C.DELETE_SELECTED_FILE:await this.deleteSelectedArtifact();return;case C.OPEN_SELECTED_FILE:await this.openSelectedFileInDefaultApp();return;case C.TOGGLE_FILE_PREVIEW_FULLSCREEN:this.toggleFilePreviewFullscreen();return;case C.TOGGLE_PANE_FULLSCREEN:this.toggleFocusedPaneFullscreen();return;case C.SCROLL_UP:this.scrollCurrentPane(1);return;case C.SCROLL_DOWN:this.scrollCurrentPane(-1);return;case C.PAGE_UP:if(this.getState().ui.focusRegion===N.SESSIONS){await this.moveSessionPage(-1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(-10);return}this.scrollCurrentPane(10);return;case C.PAGE_DOWN:if(this.getState().ui.focusRegion===N.SESSIONS){await this.moveSessionPage(1);return}if(this.focusIsArtifactList()){await this.moveFileSelection(10);return}this.scrollCurrentPane(-10);return;case C.EXPAND_HISTORY:await this.expandActiveHistory();return;case C.SCROLL_TOP:this.scrollCurrentPaneToTop();return;case C.SCROLL_BOTTOM:this.scrollCurrentPaneToBottom();return;case C.CANCEL_SESSION:await this.cancelActiveSession();return;case C.STOP_TURN:await this.stopActiveSessionTurn();return;case C.DONE_SESSION:await this.completeActiveSession();return;case C.DELETE_SESSION:await this.deleteActiveSession();return;case C.REGENERATE_SESSION:await this.regenerateActiveSession();return;case C.PIN_SESSION:this.togglePinActiveSession();return;case C.TOGGLE_SELECT_MODE:this.toggleSessionSelectMode();return;case C.TOGGLE_SESSION_SELECTION:this.toggleActiveSessionSelection();return;case C.CLEAR_SESSION_SELECTION:this.clearSessionSelection();return;case C.OPEN_HISTORY_FORMAT:this.openHistoryFormat();return;case C.REFRESH_EXECUTION_HISTORY:{const s=this.getState().sessions.activeSessionId;s&&await this.ensureExecutionHistory(s,{force:!0});return}case C.EXPORT_EXECUTION_HISTORY:{await this.exportExecutionHistory();return}case C.OPEN_ADMIN_CONSOLE:await this.openAdminConsole();return;case C.CLOSE_ADMIN_CONSOLE:this.closeAdminConsole();return;case C.ADMIN_REFRESH_PROFILE:await this.refreshAdminProfile();return;case C.ADMIN_SHOW_GHCP:this.setAdminSection("ghcp");return;case C.ADMIN_SHOW_PACKAGES:this.setAdminSection("packages");return;case C.ADMIN_SHOW_WORKERS:this.setAdminSection("workers");return;case C.ADMIN_WORKERS_REFRESH:await this.refreshAdminWorkers();return;case C.ADMIN_PACKAGES_REFRESH:await this.refreshAdminAgentPackages();return;case C.ADMIN_PACKAGES_NEXT:await this.stepAdminPackageSelection(1);return;case C.ADMIN_PACKAGES_PREV:await this.stepAdminPackageSelection(-1);return;case C.ADMIN_BEGIN_EDIT_GHCP_KEY:this.beginAdminEditGhcpKey();return;case C.ADMIN_CANCEL_EDIT_GHCP_KEY:this.cancelAdminEditGhcpKey();return;case C.ADMIN_SAVE_GHCP_KEY:await this.saveAdminGhcpKey();return;case C.ADMIN_CLEAR_GHCP_KEY:await this.clearAdminGhcpKey();return;default:return}}async exportExecutionHistory(){const e=this.getState().sessions.activeSessionId;if(!e){this.dispatch({type:"ui/status",text:"No session selected."});return}if(typeof this.transport.exportExecutionHistory!="function"){this.dispatch({type:"ui/status",text:"History export is not supported by this transport."});return}this.dispatch({type:"ui/status",text:"Exporting execution history..."});try{const s=await this.transport.exportExecutionHistory(e);s?.filename&&(await this.ensureFilesForSession(e,{force:!0}).catch(()=>null),this.dispatch({type:"files/select",sessionId:e,filename:s.filename}),this.dispatch({type:"files/selectGlobal",artifactId:`${e}/${s.filename}`}),await this.ensureFilePreview(e,s.filename,{force:!0}).catch(()=>null)),this.dispatch({type:"ui/status",text:s?.filename?`History saved as artifact ${s.filename}`:`History exported → ${s?.artifactLink||"artifact created"}`})}catch(s){this.dispatch({type:"ui/status",text:`Export failed: ${s?.message||String(s)}`})}}}const pn=0;function Ue(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Object.is(t[i],e[i]))return!1;return!0}function Un(){try{const t=globalThis?.process,e=t?.memoryUsage;if(typeof e?.rss=="function"){const s=Number(e.rss());return Number.isFinite(s)&&s>0?s:null}if(typeof e=="function"){const s=Number(e.call(t)?.rss);return Number.isFinite(s)&&s>0?s:null}}catch{}return null}function Bm(t){if(!Number.isFinite(t)||t<=0)return null;const e=Math.round(t/(1024*1024));return[{text:"rss ",color:"gray"},{text:`${e}M`,color:"white",bold:!0}]}function Hm(t){const e=t?.principal;if(!e)return null;const s=e.displayName||e.email||e.subject||null;return s?t?.authorization?.role==="admin"||Array.isArray(e.roles)&&e.roles.includes("admin")?`(*) ${s}`:s:null}function jm(t,e=null,s=null){const n=[],i=typeof s=="string"?s.trim():"";i&&n.push({text:i,color:"yellow",bold:!0}),Array.isArray(t)&&t.length>0&&(n.length>0&&n.push({text:" ",color:"gray"}),n.push(...t));const r=typeof e=="string"?e.trim():"";return r?(n.length>0&&n.push({text:" ",color:"gray"}),n.push({text:r,color:"cyan",bold:!0}),n):n.length>0?n:null}function Gm(t=2e3){const[e,s]=a.useState(()=>Un());return a.useEffect(()=>{if(Un()==null)return;const n=()=>{const r=Un();r!=null&&s(o=>o===r?o:r)};n();const i=setInterval(n,t);return()=>clearInterval(i)},[t]),a.useMemo(()=>Bm(e),[e])}function ss(t,e){return t&&e?{[t]:e}:{}}function jo(t){return typeof t=="string"?{text:t,color:"white"}:t}function vs(t,e,s,n,i,r){const o=(e.tabs||et).map(d=>({text:d===e.activeTab?`[${d}] `:`${d} `,color:d===e.activeTab?"magenta":"gray",bold:d===e.activeTab})),l=(e.lines||[]).map(jo),c=(e.stickyLines||[]).map(jo),u=e.activeTab==="sequence"?[o,...c]:[],p=e.activeTab==="sequence"?l:[o,...l];return a.createElement(t.Panel,{title:e.title,color:"magenta",focused:s.focused,width:n,height:i,stickyLines:u,marginBottom:pn,lines:p,scrollOffset:s.inspectorScroll,scrollMode:e.activeTab==="sequence"||e.activeTab==="logs"&&s.inspectorFollowBottom?"bottom":"top",paneId:"inspector",paneLabel:e.activeTab==="sequence"?"Sequence":"Inspector",frame:r})}function Go(t,e){const s=String(t||"");return e<=0?"":s.length<=e?s:e===1?s.slice(0,1):`${s.slice(0,e-1)}...`}a.memo(function({controller:e,maxRows:s,width:n,height:i,frame:r,versionLabel:o=null}){const l=Xe(),c=Gm(),u=X(e,m=>({sessions:m.sessions,mode:m.connection?.mode||"local",brandingTitle:m.branding?.title||"PilotSwarm",focused:m.ui.focusRegion==="sessions",identityLabel:Hm(m.auth)}),Ue),p=a.useMemo(()=>jm(c,o,u.identityLabel),[c,o,u.identityLabel]),d=a.useMemo(()=>({sessions:u.sessions,connection:{mode:u.mode},branding:{title:u.brandingTitle}}),[u.brandingTitle,u.mode,u.sessions]),f=a.useMemo(()=>ai(d,s),[d,s]),h=a.useMemo(()=>f.length===0?[{text:"No sessions yet. Press n to create one.",color:"gray"}]:f.map(m=>m.active?pl(m.runs,{preserveColors:!0}):m.runs),[f]);return a.createElement(l.Panel,{title:[{text:"Sessions",color:"yellow",bold:!0}],titleRight:p,color:"yellow",focused:u.focused,width:n,height:i,marginBottom:pn,lines:h,paneId:"sessions",paneLabel:"Sessions",frame:r})});a.memo(function({controller:e,width:s,height:n,frame:i}){const r=Xe(),o=X(e,x=>{const E=x.sessions.activeSessionId;return{activeSessionId:E,activeSession:E&&x.sessions.byId[E]||null,activeHistory:E&&x.history.bySessionId.get(E)||null,activeOutbox:E&&x.outbox?.bySessionId?.[E]||null,authPrincipal:x.auth?.principal||null,branding:x.branding,connectionError:x.connection.error,connectionMode:x.connection.mode,chatScroll:x.ui.scroll.chat,focused:x.ui.focusRegion==="chat"}},Ue),l=Math.max(20,s-4),c=a.useMemo(()=>{const x=new Map;return o.activeSessionId&&o.activeHistory&&x.set(o.activeSessionId,o.activeHistory),{branding:o.branding,auth:{principal:o.authPrincipal},connection:{error:o.connectionError,mode:o.connectionMode},ui:{},sessions:{activeSessionId:o.activeSessionId,byId:ss(o.activeSessionId,o.activeSession)},history:{bySessionId:x},outbox:{bySessionId:o.activeSessionId&&o.activeOutbox?{[o.activeSessionId]:o.activeOutbox}:{}}}},[o.activeHistory,o.activeSessionId,o.activeSession,o.activeOutbox,o.authPrincipal,o.branding,o.connectionError,o.connectionMode]),u=a.useMemo(()=>Rl(c,{width:l}),[l,c]),p=Ea(!!u?.animateTitleRight),d=a.useMemo(()=>xa(u?.titleRight,p),[p,u?.titleRight]),f=!o.activeSessionId&&o.connectionError,h=a.useMemo(()=>f?[{kind:"markup",value:o.branding.splash},{text:"",color:"gray"},{text:"Startup failed",color:"red",bold:!0},{text:o.connectionError,color:"white"},{text:"",color:"gray"},{text:"Check env credentials and model provider config, then relaunch.",color:"yellow"}]:Gi(c,l),[o.branding.splash,o.connectionError,l,c,f]),m=String(o.activeSession?.status||"").toLowerCase()==="running",g=va(m),S=a.useMemo(()=>f?[]:ji(c,{spinnerFrame:g,maxWidth:l}),[c,f,g,l]),y=a.useMemo(()=>f?[]:Wi(c,l),[c,f,l]),v=a.useMemo(()=>y.length>0||S.length>0?[...y,...S]:[],[y,S]);return a.createElement(r.Panel,{title:u.title,titleRight:d,color:u.color,focused:o.focused,width:s,height:n,lines:h,bottomStickyLines:v,scrollOffset:o.chatScroll,scrollMode:"bottom",paneId:"chat",paneLabel:"Chat",frame:i})});const Um=a.memo(function({controller:e,width:s,height:n,shellTitle:i,focused:r=!1,frame:o,showFullscreenTitle:l=!1,embedded:c=!1}){const u=Xe(),p=X(e,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}),Ue),d=Math.max(20,s-4),f=a.useMemo(()=>({sessions:{activeSessionId:p.activeSessionId,byId:p.activeSessionId&&p.activeSession?{[p.activeSessionId]:p.activeSession}:{},flat:p.sessionsFlat},files:{bySessionId:p.filesBySessionId,fullscreen:p.filesFullscreen,selectedArtifactId:p.selectedArtifactId,filter:p.filesFilter},ui:{scroll:{filePreview:p.filePreviewScroll}}}),[p]),h=a.useMemo(()=>Vi(f,{listWidth:Math.max(8,d-4),previewWidth:Math.max(8,d-4)}),[d,f]),m=i||(l?h.fullscreenTitle:h.panelTitle||h.listTitle)||[{text:"Files",color:"magenta",bold:!0}],g=Math.max(9,n-4),S=Math.max(5,Math.min(10,Math.floor(g*.35)));let y=Math.max(5,Math.min(S,(h.listBodyLines||[]).length+2)),v=Math.max(5,g-y-1);const x=8;if(v<x){const O=x-v;y=Math.max(5,y-O),v=Math.max(5,g-y-1)}const E=Math.max(1,y-2),w=Math.max(0,h.selectedIndex-Math.floor(E/2)),I=!c&&o?{x:o.x+2,y:o.y+2,width:d,height:y}:null,b=!c&&o?{x:o.x+2,y:o.y+2+y+1,width:d,height:v}:null,M=et.map(O=>({text:O==="files"?`[${O}] `:`${O} `,color:O==="files"?"magenta":"gray",bold:O==="files"})),A=a.createElement(u.Column,{width:d},a.createElement(u.Lines,{lines:[M]}),a.createElement(u.Panel,{title:h.listTitle,color:"gray",focused:!1,width:d,height:y,lines:h.listBodyLines||h.listLines.slice(1),scrollOffset:w,scrollMode:"top",marginBottom:1,paneId:"files:list",paneLabel:"Files list",frame:I}),a.createElement(u.Panel,{title:h.previewTitle,color:"gray",focused:!1,width:d,height:v,lines:h.previewLines,scrollOffset:h.previewScrollOffset,scrollMode:"top",paneId:"files:preview",paneLabel:"File preview",frame:b}));return c?A:a.createElement(u.Panel,{title:m,color:"magenta",focused:r,width:s,height:n,marginBottom:pn,paneId:"inspector",paneLabel:"Inspector",frame:o},A)}),zm=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Xe(),l=Math.max(20,s-4),c=X(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null}),Ue),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:ss(c.activeSessionId,c.activeSession)},ui:{inspectorTab:"files"}}),[c.activeSession,c.activeSessionId]),p=a.useMemo(()=>mt(u,{width:l}),[l,u]);return a.createElement(o.Panel,{title:p.title,color:"magenta",focused:r.focused,width:s,height:n,marginBottom:pn,paneId:"inspector",paneLabel:"Inspector",frame:i},a.createElement(Um,{controller:e,width:s,height:n,frame:i,focused:r.focused,embedded:!0}))}),Wm=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Xe(),l=Math.max(20,s-4),c=X(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,activeOrchestration:d.sessions.activeSessionId&&d.orchestration.bySessionId?.[d.sessions.activeSessionId]||null,histories:d.history.bySessionId,expandedTurns:d.ui.sequenceExpandedTurns,selectedTurn:d.ui.sequenceSelectedTurn}),Ue),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:ss(c.activeSessionId,c.activeSession)},history:{bySessionId:c.histories},orchestration:{bySessionId:c.activeSessionId&&c.activeOrchestration?{[c.activeSessionId]:c.activeOrchestration}:{}},ui:{inspectorTab:"sequence"}}),[c.activeOrchestration,c.activeSession,c.activeSessionId,c.histories]),p=a.useMemo(()=>mt(u,{width:l,sequenceExpansion:{expandedTurns:c.expandedTurns||[],selectedTurn:c.selectedTurn??null}}),[l,u,c.expandedTurns,c.selectedTurn]);return vs(o,p,r,s,n,i)}),qm=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Xe(),l=Math.max(20,s-4),c=X(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,logs:d.logs}),Ue),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:ss(c.activeSessionId,c.activeSession)},logs:c.logs,ui:{inspectorTab:"logs"}}),[c.activeSession,c.activeSessionId,c.logs]),p=a.useMemo(()=>mt(u,{width:l}),[l,u]);return vs(o,p,r,s,n,i)}),Km=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Xe(),l=Math.max(20,s-4),c=X(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,executionHistory:d.executionHistory}),Ue),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:ss(c.activeSessionId,c.activeSession)},executionHistory:c.executionHistory,ui:{inspectorTab:"history"}}),[c.activeSession,c.activeSessionId,c.executionHistory]),p=a.useMemo(()=>mt(u,{width:l}),[l,u]);return vs(o,p,r,s,n,i)}),Vm=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Xe(),l=Math.max(20,s-4),c=X(e,d=>({activeSessionId:d.sessions.activeSessionId,sessionsById:d.sessions.byId,sessionsFlat:d.sessions.flat,histories:d.history.bySessionId}),Ue),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:c.sessionsById,flat:c.sessionsFlat},history:{bySessionId:c.histories},ui:{inspectorTab:"nodes"}}),[c.activeSessionId,c.histories,c.sessionsById,c.sessionsFlat]),p=a.useMemo(()=>mt(u,{width:l}),[l,u]);return vs(o,p,r,s,n,i)}),Ym=a.memo(function({controller:e,width:s,height:n,frame:i,meta:r}){const o=Xe(),l=Math.max(20,s-4),c=X(e,d=>({activeSessionId:d.sessions.activeSessionId,activeSession:d.sessions.activeSessionId&&d.sessions.byId[d.sessions.activeSessionId]||null,sessionStats:d.sessionStats,fleetStats:d.fleetStats,statsViewMode:d.ui.statsViewMode}),Ue),u=a.useMemo(()=>({sessions:{activeSessionId:c.activeSessionId,byId:ss(c.activeSessionId,c.activeSession)},sessionStats:c.sessionStats,fleetStats:c.fleetStats,ui:{inspectorTab:"stats",statsViewMode:c.statsViewMode}}),[c.activeSession,c.activeSessionId,c.fleetStats,c.sessionStats,c.statsViewMode]),p=a.useMemo(()=>mt(u,{width:l}),[l,u]);return vs(o,p,r,s,n,i)});a.memo(function({controller:e,width:s,height:n,frame:i}){const r=X(e,o=>({inspectorTab:o.ui.inspectorTab,inspectorScroll:o.ui.scroll.inspector,inspectorFollowBottom:o.ui.followBottom?.inspector!==!1,focused:o.ui.focusRegion==="inspector"}),Ue);return r.inspectorTab==="files"?a.createElement(zm,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="sequence"?a.createElement(Wm,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="logs"?a.createElement(qm,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="history"?a.createElement(Km,{controller:e,width:s,height:n,frame:i,meta:r}):r.inspectorTab==="stats"?a.createElement(Ym,{controller:e,width:s,height:n,frame:i,meta:r}):a.createElement(Vm,{controller:e,width:s,height:n,frame:i,meta:r})});a.memo(function({controller:e,width:s,height:n,maxLines:i,frame:r}){const o=Xe(),l=X(e,d=>{const f=d.sessions.activeSessionId;return{sessionsById:d.sessions.byId,activeSessionId:f,activeSession:f&&d.sessions.byId[f]||null,activeHistory:f&&d.history.bySessionId.get(f)||null,scroll:d.ui.scroll.activity,followBottom:d.ui.followBottom?.activity!==!1,focused:d.ui.focusRegion==="activity",inspectorTab:d.ui.inspectorTab,nodeMapSelectedNode:d.ui.nodeMapSelectedNode,adminWorkers:d.admin?.workers,branding:d.branding,historyBySessionId:d.history.bySessionId,sessionsFlat:d.sessions.flat}},Ue),c=l.inspectorTab==="nodes",u=a.useMemo(()=>{const d=new Map;return l.activeSessionId&&l.activeHistory&&d.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:d}}},[l.activeHistory,l.activeSessionId,l.sessionsById,l.adminWorkers,l.branding,l.historyBySessionId,l.nodeMapSelectedNode,l.sessionsFlat,c]),p=a.useMemo(()=>c?_l(u):Ki(u,i),[i,c,u]);return a.createElement(o.Panel,{title:p.title,color:"gray",focused:l.focused,width:s,height:n,lines:p.lines,scrollOffset:l.scroll,scrollMode:l.followBottom?"bottom":"top",paneId:"activity",paneLabel:"Activity",frame:r})});a.memo(function({controller:e,rows:s}){const n=Xe(),i=X(e,r=>{const o=r.sessions.activeSessionId,l=o&&r.sessions.byId[o]||null,c=o&&r.outbox?.bySessionId?.[o]?r.outbox.bySessionId[o]:[];return{prompt:r.ui.prompt,promptCursor:r.ui.promptCursor,focused:r.ui.focusRegion==="prompt",answeringQuestion:!!l?.pendingQuestion?.question,editingPending:r.ui.promptEdit?.sessionId===o,hasOutbox:c.length>0,hasPendingOutbox:c.some(u=>u?.phase==="pending")}},Ue);return a.createElement(n.Input,{label:i.answeringQuestion?"answer":i.editingPending?"pending":"you",value:i.prompt,cursorIndex:i.promptCursor,focused:i.focused,placeholder:i.answeringQuestion?"Type an answer and press Enter":i.editingPending?"Edit pending prompt, Enter sends batch, Esc cancels":i.hasOutbox?"Type a message and press Enter to queue it":"Type a message and press Enter",rows:s})});a.memo(function({controller:e}){const s=Xe(),n=X(e,p=>({connected:p.connection.connected,workersOnline:p.connection.workersOnline,focusRegion:p.ui.focusRegion,inspectorTab:p.ui.inspectorTab,fullscreenPane:p.ui.fullscreenPane||null,logsAvailable:p.logs.available,logsTailing:p.logs.tailing,filesFullscreen:!!p.files.fullscreen,mode:p.connection.mode,statusText:p.ui.statusText,modal:p.ui.modal,activeSessionId:p.sessions.activeSessionId,activeSession:p.sessions.activeSessionId&&p.sessions.byId[p.sessions.activeSessionId]||null,selectedIds:p.sessions.selectedIds,selectMode:p.sessions.selectMode}),Ue),i=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]),r=a.useMemo(()=>gf(i),[i]),o=typeof s.getViewport=="function"?s.getViewport():{width:120},l=Math.max(20,(o.width||120)-4),c=Math.min(Math.max(18,Math.floor(l*.45)),l-8),u=Math.max(8,l-c-3);return a.createElement(s.StatusLine,{left:Go(r.left,u),right:Go(r.right,c)})});const Xm="modulepreload",Qm=function(t){return"/"+t},Uo={},nc=function(e,s,n){let i=Promise.resolve();if(s&&s.length>0){let c=function(u){return Promise.all(u.map(p=>Promise.resolve(p).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),l=o?.nonce||o?.getAttribute("nonce");i=c(s.map(u=>{if(u=Qm(u),u in Uo)return;Uo[u]=!0;const p=u.endsWith(".css"),d=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":Xm,p||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),p)return new Promise((h,m)=>{f.addEventListener("load",h),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${u}`)))})}))}function r(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&r(l.reason);return e().catch(r)})},Zm=920,ic=7,Jm=19,nr=.24,rc=16,oc=8,eg=224,tg=190,sg=48,at=16,ac=.5,us=ac,ng=24,ig=700,rg=5e3,og=new Set(["low","medium","high","xhigh"]),ag=["pilotswarm.theme","pilotswarm.sessionOwnerFilter","pilotswarm.chatFocus","pilotswarm.layoutAdjustments","pilotswarm.pinnedSessions"],lg=["pilotswarm_theme","pilotswarm_session_owner_filter"],cg={sequence:"Sequence",logs:"Logs",nodes:"Node Map",history:"Duroxide Event History",files:"Files",stats:"Stats"},zo={sequence:eS,logs:sS,nodes:nS,history:aS,files:lS,stats:cS};function ug(t,e,s){const n=Array.isArray(t)?t.filter(Boolean):[];if(n.length===0)return e;const i=n.indexOf(e),o=((i===-1?0:i)+s+n.length)%n.length;return n[o]}function dg(t){return typeof t?.transport?.uploadArtifactFromFile=="function"}function pg(t){return typeof t?.transport?.uploadArtifactFromPath=="function"}function fg(t){return typeof t?.transport?.listArtifacts=="function"}function hg(t){return typeof t?.transport?.deleteArtifact=="function"}function mg(t){return typeof t?.transport?.openPathInDefaultApp=="function"}const gg="Session link copied to clipboard",lc="Artifact link copied to clipboard",yg=140,Sg="Only people with access can open this link.";function cc(t){return!t||typeof window>"u"||!window.location?null:`${window.location.origin}${window.location.pathname}?session=${encodeURIComponent(t)}`}function fn(t,e,{fullscreen:s=!0}={}){const n=cc(t);return!n||!e?n:`${n}&artifact=${encodeURIComponent(e)}${s?"&view=full":""}`}let pt=[];function GS(t){pt=Array.isArray(t)?t:[]}function sn(t){const e=er(Zs(t,pt));navigator?.clipboard?.writeText&&navigator.clipboard.writeText(e).catch(()=>{})}async function bg(t,e){try{const s=t.transport;if(typeof s?.getSessionAccess=="function"&&((await s.getSessionAccess(e))?.visibility||"private")==="private"){const i=typeof s.listSessionShares=="function"?await s.listSessionShares(e).catch(()=>[]):[];return!Array.isArray(i)||i.length===0}}catch{}return!1}function wg(){if(!(typeof window>"u")){try{for(const t of ag)window.localStorage.removeItem(t)}catch{}try{for(const t of lg)document.cookie=`${t}=; Path=/; Max-Age=0; SameSite=Lax`}catch{}}}function Ct(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{},s={};if(typeof e.themeId=="string"&&e.themeId.trim()&&(s.themeId=e.themeId.trim()),typeof e.touchScale=="boolean"&&(s.touchScale=e.touchScale),typeof e.touchScaleMobile=="boolean"&&(s.touchScaleMobile=e.touchScaleMobile),Se(e,"sessionOwnerFilter")&&e.sessionOwnerFilter&&typeof e.sessionOwnerFilter=="object"){const n=e.sessionOwnerFilter;s.sessionOwnerFilter=Se(n,"includeShared")?n:{...n,includeShared:!0}}if(Se(e,"layoutAdjustments")&&(s.layoutAdjustments=Mi(e.layoutAdjustments)),Se(e,"pinnedSessionIds")&&(s.pinnedSessionIds=qs(e.pinnedSessionIds)),Se(e,"sessionOrder")&&(s.sessionOrder=Pi(e.sessionOrder)),Se(e,"collapsedSessionIds")&&(s.collapsedSessionIds=vg(e.collapsedSessionIds)),Se(e,"activeSessionId")){const n=e.activeSessionId==null?null:String(e.activeSessionId).trim();s.activeSessionId=n||null}return(e.rightPaneMode==="canvas"||e.rightPaneMode==="panes")&&(s.rightPaneMode=e.rightPaneMode),Se(e,"desktopPanes")&&e.desktopPanes&&typeof e.desktopPanes=="object"&&(s.desktopPanes={canvasOpen:e.desktopPanes.canvasOpen===!0,diagnosticsOpen:e.desktopPanes.diagnosticsOpen===!0,zen:e.desktopPanes.zen===!0}),Se(e,"canvasPrefs")&&(s.canvasPrefs=Ri(e.canvasPrefs)),s}function ns(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches}function nn(){return ns()?"touchScaleMobile":"touchScale"}function rn(){return ns()?"touchScale":"touchScaleMobile"}function vg(t){if(t instanceof Set){const n=[];for(const i of t){const r=String(i||"").trim();r&&n.push(r)}return n.sort(),n}if(!Array.isArray(t))return[];const e=new Set,s=[];for(const n of t){const i=String(n||"").trim();!i||e.has(i)||(e.add(i),s.push(i))}return s.sort(),s}function Se(t,e){return!!(t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,e))}function zn(t,e=null,s=null,n=null){return Ct({themeId:t.themeId,[nn()]:t.touchScale,sessionOwnerFilter:t.ownerFilter,layoutAdjustments:{paneAdjust:t.paneAdjust,sessionPaneAdjust:t.sessionPaneAdjust,portalSessionColumnAdjust:t.portalSessionColumnAdjust,activityPaneAdjust:t.activityPaneAdjust,canvasPaneAdjust:t.canvasPaneAdjust,diagnosticsPaneAdjust:t.diagnosticsPaneAdjust,diagnosticsSplitAdjust:t.diagnosticsSplitAdjust},pinnedSessionIds:t.pinnedIds,sessionOrder:t.manualOrder,collapsedSessionIds:t.collapsedSessionIds,activeSessionId:t.activeSessionId,...ns()?{...s==="canvas"||s==="panes"?{rightPaneMode:s}:{},...n&&typeof n=="object"?{desktopPanes:n}:{}}:{rightPaneMode:t.canvasOpen?"canvas":"panes",desktopPanes:{canvasOpen:t.canvasOpen===!0,diagnosticsOpen:t.diagnosticsOpen===!0,zen:t.canvasZen===!0}},canvasPrefs:t.canvasPrefs,...typeof e=="boolean"?{[rn()]:e}:{}})}function Wo(t,e=null,s=null){return Ct({themeId:t?.ui?.themeId,[nn()]:t?.ui?.touchScale,sessionOwnerFilter:tn(t?.auth?.principal??null),layoutAdjustments:t?.ui?.layout,pinnedSessionIds:t?.sessions?.pinnedIds,sessionOrder:t?.sessions?.manualOrder,collapsedSessionIds:t?.sessions?.collapsedIds,activeSessionId:t?.sessions?.activeSessionId,...ns()?s==="canvas"||s==="panes"?{rightPaneMode:s}:{}:{rightPaneMode:t?.ui?.rightPaneMode,desktopPanes:{canvasOpen:t?.ui?.canvasOpen===!0,diagnosticsOpen:t?.ui?.diagnosticsOpen===!0,zen:t?.ui?.canvasZen===!0}},canvasPrefs:t?.canvas?.prefs,...typeof e=="boolean"?{[rn()]:e}:{}})}function Eg(t,e){const s=Ct(t),n=Ct(e);return Ct({themeId:Se(s,"themeId")?s.themeId:n.themeId,sessionOwnerFilter:Se(s,"sessionOwnerFilter")?s.sessionOwnerFilter:n.sessionOwnerFilter,layoutAdjustments:Se(s,"layoutAdjustments")?s.layoutAdjustments:n.layoutAdjustments,pinnedSessionIds:Se(s,"pinnedSessionIds")?s.pinnedSessionIds:n.pinnedSessionIds,sessionOrder:Se(s,"sessionOrder")?s.sessionOrder:n.sessionOrder,...Se(s,"collapsedSessionIds")?{collapsedSessionIds:s.collapsedSessionIds}:{},...Se(s,"activeSessionId")?{activeSessionId:s.activeSessionId}:{},...Se(s,"desktopPanes")?{desktopPanes:s.desktopPanes}:{},...Se(s,"rightPaneMode")?{rightPaneMode:s.rightPaneMode}:{},...Se(s,"canvasPrefs")?{canvasPrefs:s.canvasPrefs}:{},...Se(s,nn())?{touchScale:s[nn()]}:ns()&&Se(s,"touchScale")?{touchScale:s.touchScale}:{}})}async function xg(t,e){return typeof t?.transport?.setCurrentUserProfileSettings!="function"?null:t.transport.setCurrentUserProfileSettings({settings:Ct(e)})}function ir(t){return fg(t)?et:et.filter(e=>e!=="files")}function Oe(t,e){if(Object.is(t,e))return!0;if(!t||!e||typeof t!="object"||typeof e!="object")return!1;const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s)if(!Object.prototype.hasOwnProperty.call(e,i)||!Object.is(t[i],e[i]))return!1;return!0}function hi(t,e,s){return Math.max(e,Math.min(s,t))}const Os=120,Ig=1440;function kg(t){return!t||typeof t!="object"?!1:t.desktopPanes&&typeof t.desktopPanes=="object"?!0:t.rightPaneMode==="canvas"||t.rightPaneMode==="panes"}const rr=640,or=320;function mi(t){const e=Math.max(0,Number(t)||0),s=Math.max(0,e-rc-oc*2),n=s*nr,i=Math.max(0,s-eg);return{minAdjust:-n,maxAdjust:i-n}}function Ag(t,e){const s=mi(t),n=Math.max(0,Number(t)||0),r=Math.max(0,n-rc-oc*2)*nr;return hi(r+(Number(e)||0),0,r+s.maxAdjust)}function Cg(t){return t<=sg?"hidden":t<=tg?"compact":"wrap"}function uc(t){const e=Number(t?.ui?.promptRows);return Number.isFinite(e)&&e>0?e:Wt(t?.ui?.prompt||"")}function hn(t){return gs({width:t.ui.layout?.viewportWidth??120,height:t.ui.layout?.viewportHeight??40},t.ui.layout?.paneAdjust??0,uc(t),t.ui.layout?.sessionPaneAdjust??0)}function Tg(t,e,s=!1){return Math.max(20,t-(s?6:4))}function dc({slack:t=1,debounceMs:e=120}={}){const[s,n]=a.useState(null),i=a.useRef({node:null,observer:null,timer:null,frame:null}),r=a.useCallback(o=>{const l=i.current;if(l.observer&&(l.observer.disconnect(),l.observer=null),l.timer&&(window.clearTimeout(l.timer),l.timer=null),l.frame&&(cancelAnimationFrame(l.frame),l.frame=null),l.node=o,!o||typeof window>"u"||typeof ResizeObserver>"u")return;const c=()=>{if(l.timer=null,l.node!==o||!o.isConnected)return;const p=o.querySelector(".ps-line")||o,d=window.getComputedStyle(p),f=document.createElement("span");f.style.cssText="position:absolute;visibility:hidden;white-space:pre;",f.style.fontFamily=d.fontFamily,f.style.fontSize=d.fontSize,f.style.fontWeight=d.fontWeight,f.style.letterSpacing=d.letterSpacing,f.textContent="0".repeat(100),o.appendChild(f);const h=f.getBoundingClientRect().width/100||0;if(f.remove(),!(h>0))return;const m=window.getComputedStyle(o),g=o.clientWidth-(parseFloat(m.paddingLeft)||0)-(parseFloat(m.paddingRight)||0);if(!(g>50))return;const S=Math.max(20,Math.floor(g/h)-t);n(y=>y===S?y:S)},u=()=>{l.timer&&window.clearTimeout(l.timer),l.timer=window.setTimeout(c,e)};l.frame=requestAnimationFrame(c),l.observer=new ResizeObserver(u);try{l.observer.observe(o,{box:"content-box"})}catch{l.observer.observe(o)}},[t,e]);return[s,r]}function De(t){const e=[],s=n=>{const i=String(n||"");return!i.includes("\\n")||i.includes(`
83
+ `)?i:i.replace(/\\n/g,`
84
+ `)};for(const n of t||[]){if(n?.kind==="markup"){const i=n.splashAlt?[{text:n.value,variant:"desktop"},{text:n.splashAlt,variant:"mobile"}]:[{text:n.value,variant:null}];for(const r of i)for(const o of Aa(r.text||""))e.push({kind:"runs",runs:o,preserve:!0,splashVariant:r.variant});continue}if(n?.kind==="markdownTable"||n?.kind==="cardStart"||n?.kind==="cardEnd"||n?.kind==="imageAttachments"){e.push(n);continue}if(n?.kind==="runs"){const i=Array.isArray(n.runs)?n.runs:[];if(i.length===1){const r=i[0]||{},o=s(r.text||"");if(o.includes(`
85
+ `)){const l=o.split(`
86
+ `);for(const c of l)e.push({kind:"runs",runs:[{...r,text:c}]});continue}e.push({kind:"runs",runs:[{...r,text:o}]});continue}e.push({kind:"runs",runs:i.map(r=>({...r,text:s(r?.text||"")}))});continue}if(Array.isArray(n)){e.push({kind:"runs",runs:n});continue}if(n&&typeof n=="object"&&typeof n.text=="string"){const i=s(n.text);if(i.includes(`
87
+ `)){const r=i.split(`
88
+ `);for(const o of r)e.push({kind:"text",...n,text:o});continue}e.push({kind:"text",...n,text:i});continue}e.push({kind:"text",...n})}return e}function Ye(t,e){if(e)return t?.tui?.[e]||t?.terminal?.[e]||t?.page?.[e]||e}function pc(t=[]){return t.map(e=>String(e?.text||"")).join("")}function qo(t){return Array.isArray(t)?pc(t):String(t||"")}function Ko(t,e=40){if(!Array.isArray(t)){const r=String(t||"");return[{text:r.length>e?`${r.slice(0,e-1)}…`:r,color:"white",bold:!0}]}const s=[],n=r=>/^[\s·—-]+$/.test(String(r?.text||""));let i=Math.max(8,e);for(const r of t){if(i<=0)break;if(r?.color==="gray"&&s.length>0&&!n(r))continue;const l=String(r?.text||"");if(!l)continue;if(n(r)&&i<l.length+2)break;const c=l.length>i&&i>1?`${l.slice(0,i-1)}…`:l.slice(0,i);c&&(s.push({...r,text:c}),i-=c.length)}for(;s.length>0&&n(s[s.length-1]);)s.pop();return s.length>0?s:t}function Ng(t){typeof document>"u"||(t?document.documentElement.dataset.psTouch="1":delete document.documentElement.dataset.psTouch)}function Mg(t){const e=rt(t);if(!e||typeof document>"u")return;const s=document.documentElement;s.style.setProperty("--ps-page-background",e.page.background),s.style.setProperty("--ps-page-foreground",e.page.foreground),s.style.setProperty("--ps-surface",e.tui.surface),s.style.setProperty("--ps-background",e.tui.background),s.style.setProperty("--ps-foreground",e.tui.foreground),s.style.setProperty("--ps-muted",e.tui.gray),s.style.setProperty("--ps-border",e.tui.border||e.tui.gray),s.style.setProperty("--ps-selection-background",e.tui.selectionBackground),s.style.setProperty("--ps-selection-foreground",e.tui.selectionForeground),s.style.setProperty("--ps-highlight-background",e.tui.activeHighlightBackground),s.style.setProperty("--ps-highlight-foreground",e.tui.activeHighlightForeground),s.style.setProperty("--ps-modal-backdrop",e.page.modalBackdrop),s.style.setProperty("--ps-modal-background",e.page.modalBackground),s.style.setProperty("--ps-modal-border",e.page.modalBorder),s.style.setProperty("--ps-modal-foreground",e.page.modalForeground),s.style.setProperty("--ps-modal-muted",e.page.modalMuted),s.style.setProperty("--ps-modal-selected-background",e.page.modalSelectedBackground),s.style.setProperty("--ps-modal-selected-border",e.page.modalSelectedBorder),s.style.setProperty("--ps-modal-selected-foreground",e.page.modalSelectedForeground),s.style.setProperty("--ps-accent",e.tui.cyan),s.style.setProperty("--ps-success",e.tui.green),s.style.setProperty("--ps-warning",e.tui.yellow),s.style.setProperty("--ps-danger",e.tui.red),s.dataset.psTheme=e.id}function Vo(t){const[e,s]=a.useState({width:0,height:0});return a.useLayoutEffect(()=>{const n=t.current;if(!n)return;const i=()=>{s({width:n.clientWidth,height:n.clientHeight})};i();const r=new ResizeObserver(i);return r.observe(n),window.addEventListener("resize",i),()=>{r.disconnect(),window.removeEventListener("resize",i)}},[t]),e}function Pg(t){const e=Math.max(320,t.width||window.innerWidth||1280),s=Math.max(320,t.height||window.innerHeight||800);return{width:Math.max(40,Math.floor(e/ic)),height:Math.max(18,Math.floor(s/Jm))}}function Rg(t){if(!t)return 0;const e=Math.max(0,t.scrollHeight-t.clientHeight);return Math.max(0,e-t.scrollTop)}function _g(t){return Rg(t)<=ac}function Lg(t,e,s,n=!1){if(!t)return 0;const i=Math.max(0,t.scrollHeight-t.clientHeight);if(n)return Math.max(0,Math.min(t.scrollTop,i));const r=Math.max(0,Number(e)||0)*at;return s==="bottom"?Math.max(0,i-r):Math.min(i,r)}function Og(t,e,s,n,i,r,{stickyBottom:o=!1}={}){const l=a.useMemo(()=>De(e),[e]),c=a.useRef(null),u=a.useRef({scrollMode:n,scrollOffset:s}),p=a.useRef({touching:!1,lastUserScrollAt:0,lastDispatchedOffset:null}),d=a.useRef({width:null,height:null}),[f,h]=a.useState(0);a.useLayoutEffect(()=>{const w=t.current;if(!w||typeof ResizeObserver>"u")return;d.current={width:w.clientWidth,height:w.clientHeight};const I=new ResizeObserver(()=>{const b={width:w.clientWidth,height:w.clientHeight},M=d.current;b.width===M.width&&b.height===M.height||(d.current=b,h(A=>A+1))});return I.observe(w),()=>I.disconnect()},[t]),a.useLayoutEffect(()=>{const w=t.current;if(!w)return;const I=u.current,b=p.current,M=typeof performance<"u"?performance.now():Date.now(),A=b.touching||M-(b.lastUserScrollAt||0)<ig,O=b.lastDispatchedOffset!=null&&Math.abs((Number(s)||0)-b.lastDispatchedOffset)<2;if(A&&n===I?.scrollMode&&(s===I?.scrollOffset||O)){u.current={scrollMode:n,scrollOffset:s};return}const F=o&&n==="top"&&I?.scrollMode==="top"&&I?.scrollOffset===s,L=Lg(w,s,n,F);if(Math.abs(w.scrollTop-L)>us){const G={target:L};c.current=G,w.scrollTop=L,window.requestAnimationFrame(()=>{c.current===G&&(c.current=null)})}u.current={scrollMode:n,scrollOffset:s}},[l,t,n,s,o,f]);const m=Fg(w=>{r.dispatch({type:"ui/scroll",pane:i,offset:w})}),g=a.useCallback(()=>{const w=t.current;if(!w||!i)return;const I=c.current;if(I){if(Math.abs(w.scrollTop-I.target)<=us)return;c.current=null}p.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now();const b=Math.max(0,w.scrollHeight-w.clientHeight);if(b<=0)return;if(o&&typeof r.updatePaneScrollFromViewport=="function"){const A=Math.max(0,w.scrollTop)/at;p.current.lastDispatchedOffset=A,r.updatePaneScrollFromViewport(i,A,{atBottom:_g(w)});return}const M=n==="bottom"?Math.max(0,b-w.scrollTop):Math.max(0,w.scrollTop);p.current.lastDispatchedOffset=M/at,m(M/at),i==="chat"&&n==="bottom"&&w.scrollTop<=us&&r.armChatTopHistoryLoad?.()},[r,m,i,t,n,o]),S=a.useCallback(w=>{const I=t.current;if(!I||i!=="chat"||n!=="bottom"||w.deltaY>=0||I.scrollTop>us)return;const b=Math.max(0,I.scrollHeight-I.clientHeight);r.handleChatTopHistoryScrollIntent?.(b/at)},[r,i,t,n]),y=a.useRef({startY:null,fired:!1}),v=a.useCallback(w=>{p.current.touching=!0,!(i!=="chat"||n!=="bottom")&&(y.current={startY:w.touches?.[0]?.clientY??null,fired:!1})},[i,n]),x=a.useCallback(()=>{p.current.touching=!1,p.current.lastUserScrollAt=typeof performance<"u"?performance.now():Date.now()},[]),E=a.useCallback(w=>{const I=t.current,b=y.current;if(!I||i!=="chat"||n!=="bottom"||b.fired||b.startY==null||I.scrollTop>us)return;const M=w.touches?.[0]?.clientY;if(M==null||M-b.startY<ng)return;b.fired=!0;const A=Math.max(0,I.scrollHeight-I.clientHeight);r.handleChatTopHistoryScrollIntent?.(A/at+1,{force:!0})},[r,i,t,n]);return{normalizedLines:l,onScroll:g,onWheel:S,onTouchStart:v,onTouchMove:E,onTouchEnd:x}}function He({runs:t,theme:e}){return a.createElement(a.Fragment,null,(t||[]).map((s,n,i)=>{const r=n>0&&!!on(i[n-1]?.href),o={color:Ye(e,s.color),backgroundColor:Ye(e,s.backgroundColor),fontWeight:s.bold?700:400,textDecoration:s.underline?"underline":"none"};if(s?.trailingRule)return a.createElement("span",{key:`${n}:rule`,className:"ps-line-trailing-rule",style:o},s.text||"");const l=String(s?.href||"").trim(),c=/^https?:\/\//i.test(l),u=on(l);if(u)return a.createElement(wc,{key:`${n}:${s.text||""}`,artifactRef:u,style:o});const p=r?gc(s.text||""):s.text||"";return r&&!p?null:c?a.createElement("a",{key:`${n}:${s.text||""}`,className:"ps-md-link",href:l,target:"_blank",rel:"noreferrer",style:o},p):a.createElement("span",{key:`${n}:${s.text||""}`,style:o},p)}))}function $g({line:t,theme:e}){const s=String(t?.body||"").trim();return a.createElement("details",{className:"ps-system-notice"},a.createElement("summary",{className:"ps-system-notice-summary",style:{color:Ye(e,t?.color)||"var(--ps-muted)"}},a.createElement("span",{className:"ps-system-notice-summary-text"},t?.text||"System notice")),s?a.createElement("div",{className:"ps-system-notice-body"},a.createElement(pr,{content:s,theme:e})):null)}function Fg(t){const e=a.useRef(0),s=a.useRef(null),n=a.useRef(t);return n.current=t,a.useEffect(()=>()=>{e.current&&cancelAnimationFrame(e.current)},[]),a.useCallback((...i)=>{s.current=i,!e.current&&(e.current=requestAnimationFrame(()=>{e.current=0;const r=s.current;s.current=null,r&&n.current(...r)}))},[])}const Be=a.memo(function({line:e,theme:s,className:n=""}){const i=n?`ps-line ${n}`:"ps-line";return e?e.kind==="systemNotice"?a.createElement($g,{line:e,theme:s}):e.kind==="runs"?a.createElement("div",{className:i},a.createElement(He,{runs:e.runs,theme:s})):a.createElement("div",{className:i,style:{color:Ye(s,e.color),backgroundColor:Ye(s,e.backgroundColor),fontWeight:e.bold?700:400,textDecoration:e.underline?"underline":"none"}},e.text||" "):a.createElement("div",{className:i}," ")});function ze(t){return t?t.kind==="runs"?pc(t.runs):String(t.text||""):""}function fc(t,e,s,n){const i=a.useRef(!1);return a.useLayoutEffect(()=>{const r=t.current;if(!r||!s)return;const o=Math.max(0,r.scrollHeight-r.clientHeight),l=Math.min(o,Math.max(0,Number(e)||0)*at);Math.abs(r.scrollTop-l)>2&&(i.current=!0,r.scrollTop=l,window.requestAnimationFrame(()=>{i.current=!1}))},[t,e,s]),a.useCallback(r=>{if(i.current)return;const o=t.current;!o||!s||r&&r.target!==o||o.scrollHeight<=o.clientHeight||n.dispatch({type:"ui/scroll",pane:s,offset:Math.max(0,o.scrollTop)/at})},[n,s,t])}const Dg={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"},Bg=new Set(["diff","patch","udiff"]),Hg=/\.(patch|diff)$/i,ar=/^image\/(png|jpe?g|gif|webp|avif|bmp|svg\+xml|x-icon|vnd\.microsoft\.icon)$/i,lr=/\.(png|jpe?g|gif|webp|avif|bmp|svg|ico)$/i,jg={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 Gg(t){const e=/\.([a-z0-9]+)$/i.exec(String(t||""));return e&&jg[e[1].toLowerCase()]||null}const Ug={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 zg(t){const e=String(t||"");if(!/^---[ \t]*\r?\n/.test(e))return e;const s=/\r?\n---[ \t]*(\r?\n|$)/.exec(e.slice(3));return s?e.slice(3+s.index+s[0].length):e}const Wg=/\.(html?|xhtml)$/i;function hc(t,e){return Wg.test(String(t||""))?!0:/^(text\/html|application\/xhtml\+xml)$/i.test(String(e||"").trim().split(";")[0])}const qg=/\.(csv|tsv)$/i;function mc(t,e){return qg.test(String(t||""))?!0:/^text\/(csv|tab-separated-values)$/i.test(String(e||"").trim())}const Wn=2e3;function Kg(t){const e=String(t??"");return/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function Vg({content:t,filename:e}){const[s,n]=a.useState(null),i=a.useRef(null),r=a.useRef(null),o=a.useRef(null);a.useEffect(()=>{let E=!1;return n(null),nc(()=>import("./papaparse.min-CtrVJupf.js").then(w=>w.p),[]).then(w=>{if(E)return;const I=w.default||w,b=/\.tsv$/i.test(String(e||""))?" ":"",M=I.parse(String(t||"").trim(),{delimiter:b,skipEmptyLines:"greedy"});n({rows:M.data||[],errors:M.errors||[]})}).catch(()=>{E||n({rows:null,errors:[{message:"parser unavailable"}]})}),()=>{E=!0}},[t,e]),a.useEffect(()=>{const E=()=>{o.current=null};return window.addEventListener("mouseup",E),()=>window.removeEventListener("mouseup",E)},[]);const l=a.useCallback((E,w)=>{if(!E||!w)return;const I=window.getSelection();if(!I)return;const b=!!(E.compareDocumentPosition(w)&Node.DOCUMENT_POSITION_PRECEDING),M=document.createRange();M.setStartBefore(b?w:E),M.setEndAfter(b?E:w),I.removeAllRanges(),I.addRange(M)},[]),c=E=>E.target?.closest?E.target.closest("td,th"):null,u=a.useCallback(E=>{if(E.button!==0)return;const w=c(E);w&&(E.preventDefault(),i.current?.focus(),o.current=w,l(w,w))},[l]),p=a.useCallback(E=>{if(!o.current||!(E.buttons&1))return;const w=c(E);w&&l(o.current,w)},[l]),d=a.useCallback(E=>{if(!(E.metaKey||E.ctrlKey)||E.altKey||E.key!=="a"&&E.key!=="A")return;const w=r.current,I=window.getSelection();if(!w||!I)return;E.preventDefault(),E.stopPropagation();const b=document.createRange();b.selectNodeContents(w),I.removeAllRanges(),I.addRange(b)},[]),f=a.useCallback(E=>{const w=r.current,I=window.getSelection();if(!w||!I||I.rangeCount===0)return;const b=I.getRangeAt(0),M=new Map;for(const A of w.querySelectorAll("th,td")){if(!b.intersectsNode(A))continue;const O=A.parentElement;M.has(O)||M.set(O,[]),M.get(O).push(Kg(A.textContent))}M.size!==0&&(E.clipboardData.setData("text/plain",Array.from(M.values(),A=>A.join(" ")).join(`
89
+ `)),E.preventDefault())},[]);if(!s)return a.createElement("div",{className:"ps-csv-status"},"Parsing…");if(!s.rows||s.rows.length===0)return a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,String(t||"")));const[h,...m]=s.rows,g=m.reduce((E,w)=>Math.max(E,w.length),h.length),S=Array.from({length:g},(E,w)=>h[w]??""),y=m.length>Wn,v=y?m.slice(0,Wn):m,x=[];return y&&x.push(`showing first ${Wn} of ${m.length} rows`),s.errors.length&&x.push(`${s.errors.length} parse warning${s.errors.length===1?"":"s"}`),a.createElement("div",{className:"ps-csv-wrap",ref:i,tabIndex:0,onMouseDown:u,onMouseMove:p,onKeyDown:d,onCopy:f},a.createElement("table",{className:"ps-csv-table",ref:r},a.createElement("thead",null,a.createElement("tr",null,S.map((E,w)=>a.createElement("th",{key:`h${w}`},String(E??""))))),a.createElement("tbody",null,v.map((E,w)=>a.createElement("tr",{key:`r${w}`},S.map((I,b)=>a.createElement("td",{key:`c${b}`},String(E[b]??""))))))),x.length?a.createElement("div",{className:"ps-csv-status"},x.join(" · ")):null)}function cr(t){const e=/\.([A-Za-z0-9]+)$/.exec(String(t||""));return e&&Ug[e[1].toLowerCase()]||null}function ur(t,e){return Hg.test(String(t||""))?!0:/^text\/x-(patch|diff)$/i.test(String(e||"").trim())}function gc(t){const e=String(t??"");if(e.startsWith(Ms))return e.slice(Ms.length);const s=Ms.trimStart();return e.startsWith(s)?e.slice(s.length):e}function on(t){const e=/^artifact:\/\/([^/]+)\/(.+)$/i.exec(String(t||"").trim());if(!e)return null;try{return{sessionId:e[1],filename:decodeURIComponent(e[2])}}catch{return{sessionId:e[1],filename:e[2]}}}const yc=a.createContext(null);function Sc(t){const e=String(t||""),s=(/\.([A-Za-z0-9]+)$/.exec(e)?.[1]||"").toLowerCase();return hc(e)?{kind:"page",type:"HTML",noun:"Page"}:ur(e)?{kind:"diff",type:s.toUpperCase()||"DIFF",noun:"Diff"}:lr.test(e)?{kind:"image",type:s.toUpperCase(),noun:"Image"}:mc(e)?{kind:"table",type:s.toUpperCase(),noun:"Table"}:/\.md$/i.test(e)?{kind:"doc",type:"MD",noun:"Document"}:cr(e)?{kind:"code",type:s.toUpperCase(),noun:"Code"}:{kind:"file",type:s.toUpperCase()||"FILE",noun:"File"}}function bc(t){const e=String(t||"").replace(/\.[A-Za-z0-9]+$/,""),n=(e.replace(/[-_ ]?\d{6,8}$/,"")||e).replace(/[-_]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):String(t||"Artifact")}function Yg({kind:t}){const e={fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"},s=t==="page"?[a.createElement("rect",{key:"w",x:2.5,y:3.5,width:15,height:13,rx:2,...e}),a.createElement("path",{key:"b",d:"M2.5 7.5h15",...e}),a.createElement("circle",{key:"d",cx:5.2,cy:5.5,r:.7,fill:"currentColor",stroke:"none"})]:t==="image"?[a.createElement("rect",{key:"f",x:2.5,y:3.5,width:15,height:13,rx:2,...e}),a.createElement("path",{key:"m",d:"M2.5 13l4-4 4 3.5 3-2.5 3.5 3",...e})]:t==="table"?[a.createElement("rect",{key:"f",x:2.5,y:3.5,width:15,height:13,rx:2,...e}),a.createElement("path",{key:"g",d:"M2.5 8h15M8 8v8.5M2.5 12.5h15",...e})]:[a.createElement("path",{key:"p",d:"M5 2.5h6.5L16 7v10.5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-14a1 1 0 0 1 1-1z",...e}),a.createElement("path",{key:"c",d:"M11.5 2.5V7H16",...e}),t==="diff"?a.createElement("path",{key:"t",d:"M7 11h6M10 8.5v5",...e}):a.createElement("path",{key:"t",d:"M7 10.5h6M7 13.5h4",...e})];return a.createElement("svg",{className:"ps-artifact-card-glyph",viewBox:"0 0 20 20","aria-hidden":"true"},s)}function wc({artifactRef:t}){const e=a.useContext(yc),s=Sc(t.filename),n=a.useCallback(i=>{i.preventDefault(),i.stopPropagation(),Xg(e,t.sessionId,t.filename)},[e,t.sessionId,t.filename]);return a.createElement("button",{type:"button",className:`ps-artifact-card is-${s.kind}`,onClick:n,title:`Open ${t.filename}`},a.createElement("span",{className:"ps-artifact-card-thumb","aria-hidden":"true"},a.createElement(Yg,{kind:s.kind})),a.createElement("span",{className:"ps-artifact-card-text"},a.createElement("span",{className:"ps-artifact-card-title"},bc(t.filename)),a.createElement("span",{className:"ps-artifact-card-meta"},`${s.noun} · ${s.type}`)),a.createElement("span",{className:"ps-artifact-card-open"},"Open"))}function Xg(t,e,s){if(!t?.revealArtifact)return;const n=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;Promise.resolve(n?t.revealArtifact(e,s,{fullscreen:!0}):t.revealArtifact(e,s,{pane:!0})).catch(()=>{})}function vc(t){return Bg.has(String(t||"").trim().toLowerCase())}const Qg=/^(?: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 Zg(t){return Qg.test(t)?"meta":t.startsWith("@@")?"hunk":t.startsWith("+")?"add":t.startsWith("-")?"del":"context"}const Jg={add:"green",del:"red",hunk:"cyan",meta:"gray"};function dr(t,e){return String(t||"").replace(/\n$/,"").split(`
90
+ `).map((n,i)=>{const r=Zg(n),o=Jg[r],l=r==="add"||r==="del"||r==="context"&&n.startsWith(" "),c=l?n.slice(0,1):"",u=l?n.slice(1):n;return a.createElement("span",{key:`d:${i}`,className:`ps-diff-line is-${r}`,style:o?{color:Ye(e,o)||void 0}:void 0},a.createElement("span",{className:"ps-diff-marker","aria-hidden":"true"},c.trim()),a.createElement("span",{className:"ps-diff-text"},u))})}function Ec(t){return String(t||"").trim().toLowerCase()==="mermaid"}const Yo={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 ey(t){const e={type:"comment",re:/#[^\n]*/y},s={type:"comment",re:/\/\/[^\n]*|\/\*[\s\S]*?\*\//y},n={type:"comment",re:/--[^\n]*|\/\*[\s\S]*?\*\//y},i={type:"number",re:/\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b0[xX][0-9a-fA-F]+\b/y},r={type:"identifier",re:/[A-Za-z_$][\w$]*/y},o={type:"string",re:/"(?:\\.|[^"\\])*"?/y},l={type:"string",re:/'(?:\\.|[^'\\])*'?/y},c={type:"string",re:/`(?:\\.|[^`\\])*`?/y},u={type:"string",re:/"""[\s\S]*?"""|'''[\s\S]*?'''/y};switch(t){case"python":return[e,u,o,l,i,r];case"shell":return[e,o,l,i,r];case"sql":return[n,l,o,i,r];case"yaml":return[e,o,l,i,r];case"json":return[o,i,r];case"css":return[{type:"comment",re:/\/\*[\s\S]*?\*\//y},o,l,i,r];default:return[s,o,l,c,i,r]}}const ty={comment:"gray",string:"green",number:"yellow",keyword:"magenta",fn:"cyan"},sy=2e4,vt=new Map,ny=120;function iy(t,e){const s=`${e||""}\0${t}`,n=vt.get(s);if(n)return vt.delete(s),vt.set(s,n),n;const i=ry(t,e);return vt.set(s,i),vt.size>ny&&vt.delete(vt.keys().next().value),i}function ry(t,e){const s=Dg[String(e||"").trim().toLowerCase()]||"default",n=Yo[s]||Yo.js,i=ey(s),r=[];let o=0,l=0;const c=u=>{u>l&&r.push({type:"plain",text:t.slice(l,u)})};for(;o<t.length;){let u=null;for(const d of i){d.re.lastIndex=o;const f=d.re.exec(t);if(f&&f.index===o&&f[0].length>0){u={type:d.type,text:f[0]};break}}if(!u){o+=1;continue}let p=u.type;if(p==="identifier")if(n.has(u.text))p="keyword";else{const d=t.slice(o+u.text.length);p=/^\s*\(/.test(d)?"fn":"plain"}if(p==="plain"){o+=u.text.length;continue}c(o),r.push({type:p,text:u.text}),o+=u.text.length,l=o}return c(t.length),r}function Zt(t,e,s){const n=String(t||"");if(!n||n.length>sy)return n;let i;try{i=iy(n,e)}catch{return n}return i.map((r,o)=>{const l=ty[r.type];return l?a.createElement("span",{key:`t:${o}`,className:`ps-code-token is-${r.type}`,style:{color:Ye(s,l)||void 0}},r.text):a.createElement(a.Fragment,{key:`t:${o}`},r.text)})}let Ns=null;function oy(){return Ns||(Ns=nc(()=>import("./mermaid.core-CPN1IVjz.js").then(t=>t.bp),[]).then(t=>t.default||t).catch(t=>{throw Ns=null,t})),Ns}function ay(t,e){return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:e?"default":"dark",fontFamily:"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif"}),t}let Xo=0,Qo=Promise.resolve();function ly(t){const e=Qo.then(t,t);return Qo=e.then(()=>{},()=>{}),e}function xc({code:t,theme:e,fallback:s}){const[n,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState(""),u=a.useMemo(()=>fd(e),[e]);return a.useEffect(()=>{let p=!0;const d=String(t||"").trim();if(d)return o(!1),oy().then(f=>ly(async()=>{if(!p)return;ay(f,u),Xo+=1;const h=`ps-mermaid-${Xo}`;await f.parse(d);const{svg:m}=await f.render(h,d);p&&i(m)})).catch(f=>{p&&(i(null),o(!0),c(String(f?.message||f)))}),()=>{p=!1}},[t,u]),n&&!r?a.createElement("div",{className:"ps-mermaid",dangerouslySetInnerHTML:{__html:n}}):r&&l?a.createElement("div",{className:"ps-mermaid-failed"},a.createElement("div",{className:"ps-mermaid-error"},`Diagram could not be rendered — ${String(l).split(`
91
+ `)[0]}`),s):s}function it(t,e,s="md"){const n=Ii(t);return n.map((i,r)=>{const o=`${s}:${r}`;if(r>0&&n[r-1]?.type==="link"&&on(n[r-1]?.href)){const l=gc(i.text||"");if(!l)return null;l!==i.text&&(i={...i,text:l})}if(i.type==="code")return a.createElement("code",{key:o,className:"ps-md-inline-code"},i.text);if(i.type==="strong")return a.createElement("strong",{key:o,className:"ps-md-strong"},it(i.text,e,`${o}:strong`));if(i.type==="em")return a.createElement("em",{key:o,className:"ps-md-em"},it(i.text,e,`${o}:em`));if(i.type==="link"){const l=on(i.href);return l?a.createElement(wc,{key:o,artifactRef:l}):/^https?:\/\//i.test(String(i.href||"").trim())?a.createElement("a",{key:o,className:"ps-md-link",href:i.href,target:"_blank",rel:"noreferrer",style:{color:Ye(e,"cyan")}},i.text):a.createElement("span",{key:o,style:{color:Ye(e,"cyan")}},i.text)}return a.createElement(a.Fragment,{key:o},i.text)})}function gi(t=""){return String(t||"").replace(/\s+/g," ").trim()}const cy=["description","mechanism","details","notes","summary","message","comment","reason","body","content","explanation","rationale","one-liner"],uy=24,dy=32,py=6,Zo=30,fy=56,qn=.4,hy=1.4,my=2;function Ic(t=[]){const e=Math.max(0,...t.map(m=>m.length));if(e<=0)return null;const s=t[0]||[],n=Math.max(1,t.length-1),i=Array.from({length:e},()=>({max:0,spaceCells:0}));for(let m=0;m<t.length;m+=1){const g=t[m];for(let S=0;S<e;S+=1){const y=gi(g[S]||"");y.length>i[S].max&&(i[S].max=y.length),m>0&&/\s/.test(y)&&(i[S].spaceCells+=1)}}let r=-1,o=0;for(let m=0;m<e;m+=1){const g=i[m];if(g.max<uy||g.spaceCells/n<.4)continue;const y=gi(s[m]||"").toLowerCase(),v=cy.some(E=>y.includes(E))?60:0,x=g.max+v;x>o&&(o=x,r=m)}if(r<0)return null;const l=i.map((m,g)=>g===r?0:Math.max(py,Math.min(m.max+2,dy))),c=l.reduce((m,g)=>m+g,0),u=i[r],p=Math.max(Zo,Math.min(u.max*.45,fy,Math.max(Zo,c*hy))),d=l.map((m,g)=>g===r?p:m),f=d.reduce((m,g)=>m+g,0);if(f>0&&d[r]/f<qn){const m=f-d[r];d[r]=m*(qn/(1-qn))}const h=d.reduce((m,g)=>m+g,0);return h>0?{widths:d.map(m=>`${(m/h*100).toFixed(2)}%`),flexIndex:r,minWidth:`${Math.ceil(h+my)}ch`}:null}function kc(t=[],e=0){return Array.from({length:e},(s,n)=>(Array.isArray(t)?t:[]).map(r=>gi(r?.[n]||"")).filter(Boolean).join(" / ")||null)}function Jo(t="",e=""){const s=String(t||"");return/^\s*#{1,6}\s+/.test(s)||/^\s*>/.test(s)||/^\s*([-*]|\d+\.)\s+/.test(s)||/^\s*```/.test(s)||s.includes("|")&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(String(e||""))}function ea(t=""){return String(t||"").trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(s=>s.trim())}function gy(t=""){const s=String(t||"").replace(/\r\n?/g,`
92
+ `).split(`
93
+ `),n=[];for(let i=0;i<s.length;){const r=s[i],o=r.trim();if(!o){i+=1;continue}const l=/^```(\S*)\s*$/.exec(o);if(l){const d=l[1]||"",f=[];for(i+=1;i<s.length&&!/^```/.test(s[i].trim());)f.push(s[i]),i+=1;i<s.length&&(i+=1),n.push({type:"code",language:d,content:f.join(`
94
+ `)});continue}const c=/^(#{1,6})\s+(.*)$/.exec(r);if(c){n.push({type:"heading",level:c[1].length,text:c[2].trim()}),i+=1;continue}if(r.includes("|")&&i+1<s.length&&/^\s*\|?[\s:-]+(?:\|[\s:-]+)+\|?\s*$/.test(s[i+1].trim())){const d=ea(r);i+=2;const f=[];for(;i<s.length&&s[i].includes("|")&&s[i].trim();)f.push(ea(s[i])),i+=1;n.push({type:"table",header:d,rows:f});continue}if(/^\s*>/.test(r)){const d=[];for(;i<s.length&&/^\s*>/.test(s[i]);)d.push(s[i].replace(/^\s*>\s?/,"")),i+=1;n.push({type:"blockquote",text:d.join(`
95
+ `).trim()});continue}const u=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(r);if(u){const d=/\d+\./.test(u[2]),f=[];for(;i<s.length;){const h=s[i],m=/^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(h);if(!m||/\d+\./.test(m[2])!==d)break;const g=[m[3].trim()];for(i+=1;i<s.length&&s[i].trim()&&!/^(\s*)([-*]|\d+\.)\s+/.test(s[i])&&!Jo(s[i],s[i+1]||"");)g.push(s[i].trim()),i+=1;if(f.push(g.join(" ")),!s[i]?.trim())break}n.push({type:"list",ordered:d,items:f});continue}const p=[r.trim()];for(i+=1;i<s.length&&s[i].trim()&&!Jo(s[i],s[i+1]||"");)p.push(s[i].trim()),i+=1;n.push({type:"paragraph",text:p.join(" ")})}return n}function pr({content:t,theme:e}){const s=a.useMemo(()=>gy(t),[t]);return s.length===0?a.createElement("div",{className:"ps-empty-state"},"No preview content."):a.createElement("div",{className:"ps-markdown-preview"},s.map((n,i)=>{if(n.type==="heading")return a.createElement("div",{key:`block:${i}`,className:`ps-md-heading is-h${n.level}`},it(n.text,e,`heading:${i}`));if(n.type==="code"){const r=vc(n.language),o=a.createElement("section",{key:`block:${i}`,className:`ps-md-code-block${r?" is-diff":""}`},a.createElement("div",{className:"ps-md-code-header"},n.language||"text"),a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,r?dr(n.content,e):Zt(n.content,n.language,e))));return Ec(n.language)?a.createElement(xc,{key:`block:${i}`,code:n.content,theme:e,fallback:o}):o}if(n.type==="blockquote")return a.createElement("blockquote",{key:`block:${i}`,className:"ps-md-quote"},it(n.text,e,`quote:${i}`));if(n.type==="list"){const r=n.ordered?"ol":"ul";return a.createElement(r,{key:`block:${i}`,className:`ps-md-list${n.ordered?" is-ordered":""}`},n.items.map((o,l)=>a.createElement("li",{key:`item:${l}`,className:"ps-md-list-item"},it(o,e,`list:${i}:${l}`))))}if(n.type==="table"){const r=Math.max(n.header.length||0,...n.rows.map(m=>m.length)),o=r>0&&r<=6,l=o?Ic([n.header,...n.rows]):null,c=!!l,u=l?l.flexIndex:-1,p=m=>m===u?"is-flex-column":null,d=kc([n.header],r),f=`ps-md-table${o?" is-fit-width":""}${c?" has-flex-column":""}`,h=`ps-md-table-wrap${o?" is-fit-width":""}${c?" has-flex-column":""}`;return a.createElement("div",{key:`block:${i}`,className:h},a.createElement("table",{className:f,style:l?.minWidth?{"--ps-table-min-width":l.minWidth}:void 0},l?a.createElement("colgroup",null,l.widths.map((m,g)=>a.createElement("col",{key:`col:${g}`,className:p(g)||void 0,style:{width:m}}))):null,a.createElement("thead",null,a.createElement("tr",null,n.header.map((m,g)=>a.createElement("th",{key:`head:${g}`,className:p(g)||void 0},it(m,e,`table:${i}:head:${g}`))))),a.createElement("tbody",null,n.rows.map((m,g)=>a.createElement("tr",{key:`row:${g}`},m.map((S,y)=>a.createElement("td",{key:`cell:${g}:${y}`,className:p(y)||void 0,"data-label":d[y]||void 0},a.createElement("span",{className:"ps-table-cell-value"},it(S,e,`table:${i}:${g}:${y}`)))))))))}return a.createElement("p",{key:`block:${i}`,className:"ps-md-paragraph"},it(n.text,e,`para:${i}`))}))}function Kn({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:r,theme:o,className:l="",focusRegion:c=null,children:u}){const p=a.useRef(null),d=fc(p,i,r,t),f=a.useCallback(()=>{const h=fr(r,c);h&&t?.setFocus&&t.setFocus(h)},[t,r,c]);return a.createElement(gt,{title:e,color:s,focused:n,theme:o},a.createElement("div",{ref:p,className:`ps-scroll-panel is-preview ${l}`.trim(),onScroll:d,onMouseDown:f},u))}function yy({controller:t,title:e,color:s,focused:n,scrollOffset:i=0,paneKey:r,theme:o,content:l,focusRegion:c=null}){const u=a.useCallback(()=>{const f=fr(r,c);f&&t?.setFocus&&t.setFocus(f)},[t,r,c]),p=a.useRef(null),d=fc(p,i,r,t);return a.createElement(gt,{title:e,color:s,focused:n,theme:o},a.createElement("div",{ref:p,className:"ps-scroll-panel ps-markdown-scroll",onScroll:d,onMouseDown:u},a.createElement(pr,{content:l,theme:o})))}function Ac(t){const e=Number(t);if(!Number.isFinite(e)||e<0)return"Unknown size";if(e<1024)return`${Math.round(e)} B`;if(e<1024*1024){const n=e/1024;return`${n>=10?Math.round(n):n.toFixed(1)} KB`}const s=e/(1024*1024);return`${s>=10?Math.round(s):s.toFixed(1)} MB`}function ta({title:t,color:e,focused:s,theme:n,filename:i,contentType:r,sizeBytes:o,source:l,uploadedAt:c,controller:u=null,sessionId:p=null}){const d=[];r&&d.push(r),o!=null&&d.push(Ac(o)),l&&d.push(l);const f=c?new Date(c).toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):"",h=ar.test(String(r||""))||lr.test(String(i||"")),[m,g]=a.useState(null);return a.useEffect(()=>{if(g(null),!h||!u||!p||!i)return;let S=!1;return Rc(u,p,i).then(y=>{S||g(y)}).catch(()=>{S||g("error")}),()=>{S=!0}},[h,u,p,i]),a.createElement(gt,{title:t,color:e,focused:s,theme:n},a.createElement("div",{className:"ps-binary-preview-card"},a.createElement("div",{className:"ps-binary-preview-kicker"},h?"Image artifact":"Binary artifact"),a.createElement("h3",{className:"ps-binary-preview-title"},i||"Artifact"),d.length>0?a.createElement("div",{className:"ps-binary-preview-meta"},d.join(" • ")):null,f?a.createElement("div",{className:"ps-binary-preview-time"},`Uploaded ${f}`):null,h&&m&&m!=="error"?a.createElement("img",{className:"ps-binary-preview-image",src:m,alt:i||"artifact image",onClick:()=>{const S=fn(p,i);if(S)try{window.open(S,"_blank","noopener")}catch{}}}):a.createElement("p",{className:"ps-binary-preview-copy"},h?m==="error"?"Could not load the image preview. Use Download to save the file.":"Loading image preview…":"Preview is intentionally disabled for non-text artifacts in the browser workspace. Use Download to save the file and open it in the default app.")))}const Sy=260,by=28;function wy(t,e,s,n){const[i,r]=a.useState(null),[o,l]=a.useState(0),c=a.useRef(null),u=a.useRef(0);a.useEffect(()=>{c.current=null,u.current+=1,r(null),l(u.current)},[s]);const p=a.useRef(!0);a.useEffect(()=>{if(p.current){p.current=!1;return}e&&(c.current=null,u.current+=1,l(u.current))},[n,e]),a.useEffect(()=>{const f=t.current;if(!e||!f||typeof ResizeObserver>"u")return;let h=null;const m=new ResizeObserver(g=>{const S=Math.round(g[0]?.contentRect?.width||0);if(S){if(c.current===null){c.current=S;return}Math.abs(S-c.current)<by||(h&&clearTimeout(h),h=setTimeout(()=>{h=null,c.current=Math.round(f.getBoundingClientRect().width)||S,u.current+=1,l(u.current)},Sy))}});return m.observe(f),()=>{h&&clearTimeout(h),m.disconnect()}},[t,e]);const d=a.useCallback(f=>{const h=()=>{l(m=>m===f?null:m),r(m=>m===f?m:f)};if(typeof requestAnimationFrame!="function"){h();return}requestAnimationFrame(()=>requestAnimationFrame(h))},[]);return{live:i,pending:o,promote:d}}const Vn=1024;function Cc({fitWidth:t,setFitWidth:e}){return a.createElement(pe,{icon:t?"1:1":"⤢",label:t?"Actual size":"Fit page to width",active:t,onClick:()=>e(!t)})}const Et=[.5,.67,.8,.9,1,1.1,1.25,1.5,1.75,2,2.5,3];function an({zoom:t,setZoom:e}){const s=n=>{const i=Et.findIndex(l=>Math.abs(l-t)<.005),r=i===-1?Et.indexOf(1):i,o=Et[Math.min(Et.length-1,Math.max(0,r+n))];e(o)};return a.createElement("span",{className:"ps-html-zoom",role:"group","aria-label":"Artifact zoom"},a.createElement("button",{type:"button",className:"ps-html-zoom-btn",onClick:()=>s(-1),disabled:t<=Et[0]+.001,title:"Zoom out (artifact only)","aria-label":"Zoom out"},"−"),a.createElement("button",{type:"button",className:"ps-html-zoom-level",onClick:()=>e(1),title:"Reset zoom to 100%","aria-label":`Zoom ${Math.round(t*100)} percent, click to reset`},`${Math.round(t*100)}%`),a.createElement("button",{type:"button",className:"ps-html-zoom-btn",onClick:()=>s(1),disabled:t>=Et[Et.length-1]-.001,title:"Zoom in (artifact only)","aria-label":"Zoom in"},"+"))}function Tc({mode:t,setMode:e}){return a.createElement("span",{className:"ps-html-preview-modes",role:"group","aria-label":"Preview mode"},["rendered","source"].map(s=>a.createElement("button",{key:s,type:"button",className:`ps-html-preview-mode${t===s?" is-active":""}`,"aria-pressed":t===s,onClick:()=>e(s)},s==="rendered"?"Rendered":"Source")))}function Nc(t){const[e,s]=a.useState({width:0,height:0});return a.useLayoutEffect(()=>{const n=t.current;if(!n||typeof ResizeObserver>"u")return;const i=()=>{const o=n.getBoundingClientRect();s(l=>{const c=Math.round(o.width)||0,u=Math.round(o.height)||0;return l.width===c&&l.height===u?l:{width:c,height:u}})};i();const r=new ResizeObserver(i);return r.observe(n),()=>r.disconnect()},[t]),e}function Mc(t,e,s){const n=t?.transport?.api?.downloadArtifactResponse;return typeof n!="function"?Promise.reject(new Error("artifact download unavailable")):n.call(t.transport.api,e,s).then(async i=>{if(!i?.ok)throw new Error(`download failed (${i?.status})`);const r=await i.arrayBuffer();return URL.createObjectURL(new Blob([r],{type:"text/html;charset=utf-8"}))})}function vy({controller:t,sessionId:e,filename:s,contentType:n,sizeBytes:i,theme:r,color:o="cyan",focused:l=!1,title:c=null,chromeless:u=!1}){const p=X(t,P=>P.files.htmlViewMode||"rendered"),d=a.useCallback(P=>{t.dispatch({type:"files/htmlViewMode",mode:P})},[t]),[f,h]=a.useState(null),[m,g]=a.useState(null),S=a.useRef(null),y=X(t,P=>!!P.files.htmlFitWidth),v=a.useCallback(P=>{t.dispatch({type:"files/htmlFitWidth",enabled:P})},[t]),x=Nc(S),E=y&&x.width>0&&x.width<Vn?x.width/Vn:1,w=E<1,I=X(t,P=>Number(P.files.htmlZoom)||1),b=a.useCallback(P=>{t.dispatch({type:"files/htmlZoom",zoom:P})},[t]),M=w?E*I:I,A=wy(S,p==="rendered"&&!w,`${e}/${s}`,I);a.useEffect(()=>{if(h(null),g(null),p!=="rendered"||!t||!e||!s)return;let P=!1,H=null;return Mc(t,e,s).then(U=>{if(H=U,P){URL.revokeObjectURL(U);return}h(U)}).catch(U=>{P||g(U?.message||String(U))}),()=>{P=!0,H&&URL.revokeObjectURL(H)}},[t,e,s,p]);const O=fn(e,s),F=u?null:a.createElement(a.Fragment,null,a.createElement(Tc,{mode:p,setMode:d}),p==="rendered"?a.createElement(Cc,{fitWidth:y,setFitWidth:v}):null,p==="rendered"?a.createElement(an,{zoom:I,setZoom:b}):null,O?a.createElement(pe,{icon:"↗",label:"Open in a new tab",onClick:()=>{try{window.open(O,"_blank","noopener")}catch{}}}):null),L=p==="source"?a.createElement(Ey,{controller:t,sessionId:e,filename:s,theme:r}):m?a.createElement("div",{className:"ps-html-preview-status"},a.createElement("p",null,`Could not load ${s}: ${m}`),a.createElement("p",null,"Use Download to save the file and open it locally.")):f?[A.live,A.pending].filter((P,H,U)=>P!==null&&U.indexOf(P)===H).map(P=>a.createElement("iframe",{key:`frame:${P}`,className:`ps-html-preview-frame${P===A.live?"":" is-staging"}`,style:w?{flex:"none",width:`${Vn}px`,height:`${Math.max(1,Math.round(x.height/M))}px`,transform:`scale(${M})`,transformOrigin:"top left"}:I!==1&&x.width>0?{flex:"none",width:`${Math.max(1,Math.round(x.width/I))}px`,height:`${Math.max(1,Math.round(x.height/I))}px`,transform:`scale(${I})`,transformOrigin:"top left"}:void 0,src:f,title:s||"HTML artifact",sandbox:"allow-scripts allow-popups allow-popups-to-escape-sandbox",allow:"autoplay *",referrerPolicy:"no-referrer",onLoad:()=>A.promote(P)})):a.createElement("div",{className:"ps-html-preview-status"},a.createElement("p",null,`Rendering ${s}…`),i!=null?a.createElement("p",{className:"ps-html-preview-meta"},[n,Ac(i)].filter(Boolean).join(" • ")):null),G=p==="rendered"?a.createElement("div",{ref:S,className:`ps-html-preview-host${w||I!==1?" is-fitting":""}`},L):L;return a.createElement(gt,{title:c,color:o,focused:l,theme:r,actions:F,className:"ps-html-preview"},G)}function Ey({controller:t,sessionId:e,filename:s,theme:n}){const[i,r]=a.useState(null),[o,l]=a.useState(null);return a.useEffect(()=>{r(null),l(null);const c=t?.transport?.api?.downloadArtifactResponse;if(typeof c!="function"||!e||!s){l("artifact download unavailable");return}let u=!1;return c.call(t.transport.api,e,s).then(async p=>{if(!p?.ok)throw new Error(`download failed (${p?.status})`);return p.text()}).then(p=>{u||r(p)}).catch(p=>{u||l(p?.message||String(p))}),()=>{u=!0}},[t,e,s]),o?a.createElement("div",{className:"ps-html-preview-status"},a.createElement("p",null,`Could not load source: ${o}`)):i==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,Zt(i,"html",n))))}function $s(t){const e=String(t||"").trim();return e.startsWith("┌")&&e.endsWith("┐")}function Yn(t){const e=String(t||"").trim();return e.startsWith("└")&&e.endsWith("┘")}function xy(t){const e=String(t||"").trim();return e.startsWith("├")&&e.endsWith("┤")}function ys(t){const e=String(t||"").trim();return e.startsWith("│")&&e.endsWith("│")}function Iy(t){const e=String(ze(t)||"").trim();return $s(e)?e.slice(1,-1).replace(/^─+/u,"").replace(/─+$/u,"").trim():""}function ky(t){if(t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3)return String(t.runs[1]?.text||"").replace(/\s+$/u,"");const e=ze(t);return ys(e)?String(e).slice(1,-1).replace(/\s+$/u,""):String(e||"")}function Ay(t=[]){const e=(t||[]).map(s=>({...s}));return e.length===0?e:(e[0].text=String(e[0].text||"").replace(/^\s+/,""),e[e.length-1].text=String(e[e.length-1].text||"").replace(/\s+$/,""),e.filter((s,n)=>String(s.text||"").length>0||e.length===1||n===0))}function sa(t,{fallbackColor:e=null}={}){return t?.kind==="runs"&&Array.isArray(t.runs)&&t.runs.length>=3?Ay(t.runs.slice(1,-1)):[{text:ze(t).replace(/^\s*[┌│]\s?/,"").replace(/\s?[┐│]\s*$/,"").replace(/^─+/,"").replace(/─+$/,"").trim(),color:e}]}function Cy(t){const e=String(t||"").trim();return ys(e)?e.slice(1,-1).split("│").map(s=>s.trim()):[]}function Ty(t="",e=""){const s=String(t||"").trimEnd(),n=String(e||"").trimStart();if(!s||!n)return!1;const i=s.slice(-1),r=n[0];return!!(/^[,.;:!?%)\]}>]/u.test(r)||/^[._/\\-]/u.test(r)||/[([{<._/\\-]$/u.test(i)||/\.[A-Za-z0-9]{0,4}$/u.test(s)&&/^[A-Za-z0-9]/u.test(r))}function Ny(t=[]){const e=(Array.isArray(t)?t:[t]).map(s=>String(s||"").trim()).filter(Boolean);return e.length===0?"":e.slice(1).reduce((s,n)=>Ty(s,n)?`${s}${n}`:`${s} ${n}`,e[0])}function na(t=[]){const e=Math.max(0,...t.map(s=>s.length));return Array.from({length:e},(s,n)=>Ny(t.map(i=>String(i[n]||"").trim()).filter(Boolean)))}function Pc(t=[]){const e=[];for(let s=0;s<t.length;){const n=t[s];if(n?.preserve){const r=n.splashVariant||null,o=[];for(;s<t.length&&t[s]?.preserve&&(t[s].splashVariant||null)===r;)o.push(t[s]),s+=1;e.push({type:"preserve",lines:o,splashVariant:r});continue}if(n?.kind==="cardStart"){const r=[];for(s+=1;s<t.length&&t[s]?.kind!=="cardEnd";)r.push(t[s]),s+=1;s<t.length&&(s+=1),s<t.length&&ze(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:Array.isArray(n.runs)?n.runs:[],borderColor:n.borderColor||"gray",blocks:Pc(r)});continue}if(n?.kind==="imageAttachments"){e.push({type:"imageAttachments",sessionId:n.sessionId||null,attachments:Array.isArray(n.attachments)?n.attachments:[]}),s+=1;continue}if(n?.kind==="markdownTable"){e.push({type:"table",headerRows:Array.isArray(n.header)&&n.header.length>0?[n.header]:[],bodyRows:Array.isArray(n.rows)?n.rows:[]}),s+=1;continue}const i=ze(n);if($s(i)&&i.includes("┬")){const r=[],o=[];let l=[],c=!0;for(s+=1;s<t.length;){const u=t[s],p=ze(u);if(Yn(p)){if(l.length>0){const d=na(l);d.length>0&&(c?r.push(d):o.push(d))}s+=1;break}if(xy(p)){if(l.length>0){const d=na(l);d.length>0&&(c?r.push(d):o.push(d))}l=[],c=!1,s+=1;continue}if(ys(p)){const d=Cy(p);d.length>0&&l.push(d)}s+=1}e.push({type:"table",headerRows:r,bodyRows:o});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length===1&&$s(i)){const r=Iy(n),o=[];for(s+=1;s<t.length;){const l=t[s],c=ze(l);if(Yn(c)){s+=1;break}ys(c)?o.push(ky(l)):o.push(ze(l)),s+=1}s<t.length&&ze(t[s]).trim().length===0&&(s+=1),e.push({type:"code",language:r||"text",content:o.join(`
96
+ `)});continue}if(n?.kind==="runs"&&Array.isArray(n.runs)&&n.runs.length>2&&$s(i)){const r=sa(n),o=n.runs[0]?.color||"gray",l=[];for(s+=1;s<t.length;){const c=t[s],u=ze(c);if(Yn(u)){s+=1;break}ys(u)?l.push(sa(c)):l.push(c?.kind==="runs"?c.runs:[{text:ze(c),color:c?.color||null}]),s+=1}s<t.length&&ze(t[s]).trim().length===0&&(s+=1),e.push({type:"card",headerRuns:r,bodyLines:l,borderColor:o});continue}e.push({type:"line",line:n}),s+=1}return e}function My({lines:t,theme:e,controller:s=null}){const n=a.useMemo(()=>Pc((t||[]).filter(i=>!i?.canvasUpdate&&!i?.canvasAction)),[t]);return a.createElement(_c,{blocks:n,theme:e,controller:s})}const ot=new Map,Py=60;function Rc(t,e,s){const n=`${e}/${s}`,i=ot.get(n);if(i)return ot.delete(n),ot.set(n,i),i;const r=t?.transport?.api?.downloadArtifactResponse;if(typeof r!="function")return Promise.reject(new Error("artifact download unavailable"));const o=r.call(t.transport.api,e,s).then(async l=>{if(!l?.ok)throw new Error(`download failed (${l?.status})`);const c=await l.blob(),u=Gg(s),p=u&&!ar.test(c.type)?new Blob([c],{type:u}):c;return URL.createObjectURL(p)}).catch(l=>{throw ot.get(n)===o&&ot.delete(n),l});for(ot.set(n,o);ot.size>Py;){const[l,c]=ot.entries().next().value;ot.delete(l),Promise.resolve(c).then(u=>URL.revokeObjectURL(u)).catch(()=>{})}return o}function Ry({controller:t,sessionId:e,attachments:s}){const[n,i]=a.useState({});return a.useEffect(()=>{if(!t||!e)return;let r=!1;for(const o of s){const l=o?.filename;l&&Rc(t,e,l).then(c=>{r||i(u=>u[l]===c?u:{...u,[l]:c})}).catch(()=>{r||i(c=>c[l]==="error"?c:{...c,[l]:"error"})})}return()=>{r=!0}},[t,e,s]),a.createElement("div",{className:"ps-chat-image-strip"},s.map((r,o)=>{const l=r?.filename||`image-${o}`,c=n[l];return c&&c!=="error"?a.createElement("img",{key:`thumb:${o}:${l}`,className:"ps-chat-image-thumb",src:c,alt:l,title:`${l} — click to view full size`,onClick:()=>{try{window.open(c,"_blank","noopener")}catch{}}}):a.createElement("div",{key:`thumb:${o}:${l}`,className:`ps-chat-image-thumb is-pending${c==="error"?" is-error":""}`,title:l},c==="error"?"⚠":"🖼")}))}function _c({blocks:t,theme:e,controller:s=null}){return a.createElement(a.Fragment,null,(t||[]).map((n,i)=>{if(n.type==="imageAttachments")return a.createElement(Ry,{key:`imageAttachments:${i}`,controller:s,sessionId:n.sessionId,attachments:n.attachments});if(n.type==="preserve"){const r=n.splashVariant?` is-splash-${n.splashVariant}`:"";return a.createElement("div",{key:`preserve:${i}`,className:`ps-chat-preserve-block${r}`},n.lines.map((o,l)=>a.createElement(Be,{key:`preserve:${i}:${l}`,line:o,theme:e,className:"ps-line-preserve"})))}if(n.type==="code"){const r=vc(n.language),o=a.createElement("section",{key:`code:${i}`,className:`ps-md-code-block ps-chat-code-block${r?" is-diff":""}`},a.createElement("div",{className:"ps-md-code-header"},n.language||"text"),a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,r?dr(n.content||"",e):Zt(n.content||"",n.language,e))));return Ec(n.language)?a.createElement(xc,{key:`code:${i}`,code:n.content||"",theme:e,fallback:o}):o}if(n.type==="card")return a.createElement("section",{key:`card:${i}`,className:"ps-chat-card",style:{"--ps-chat-card-accent":Ye(e,n.borderColor)||"var(--ps-border)"}},a.createElement("header",{className:"ps-chat-card-header"},a.createElement(He,{runs:n.headerRuns,theme:e})),a.createElement("div",{className:"ps-chat-card-body"},Array.isArray(n.blocks)?a.createElement(_c,{blocks:n.blocks,theme:e,controller:s}):(n.bodyLines||[]).map((r,o)=>a.createElement("div",{key:`card:${i}:line:${o}`,className:"ps-chat-card-line"},a.createElement(He,{runs:r,theme:e})))));if(n.type==="table"){const r=n.headerRows||[],o=n.bodyRows||[],l=Math.max(1,...r.map(S=>S.length),...o.map(S=>S.length)),c=l<=6,u=c?Ic([...r,...o]):null,p=!!u,d=u?u.flexIndex:-1,f=S=>S===d?"is-flex-column":null,h=kc(r,l),m=`ps-chat-table${c?" is-fit-width":""}${p?" has-flex-column":""}`,g=`ps-chat-table-wrap${c?" is-fit-width":""}${p?" has-flex-column":""}`;return a.createElement("div",{key:`table:${i}`,className:g},a.createElement("table",{className:m,style:u?.minWidth?{"--ps-table-min-width":u.minWidth}:void 0},u?a.createElement("colgroup",null,u.widths.map((S,y)=>a.createElement("col",{key:`col:${y}`,className:f(y)||void 0,style:{width:S}}))):null,r.length>0?a.createElement("thead",null,r.map((S,y)=>a.createElement("tr",{key:`thead:${y}`},Array.from({length:l},(v,x)=>a.createElement("th",{key:`th:${y}:${x}`,className:f(x)||void 0},it(S[x]||"",e,`chat-table:${i}:head:${y}:${x}`)))))):null,a.createElement("tbody",null,o.map((S,y)=>a.createElement("tr",{key:`tbody:${y}`},Array.from({length:l},(v,x)=>a.createElement("td",{key:`td:${y}:${x}`,className:f(x)||void 0,"data-label":h[x]||void 0},a.createElement("span",{className:"ps-table-cell-value"},it(S[x]||"",e,`chat-table:${i}:${y}:${x}`)))))))))}return a.createElement(Be,{key:`line:${i}`,line:n.line,theme:e})}))}function gt({title:t,titleRight:e=null,color:s="gray",focused:n=!1,actions:i=null,children:r,theme:o,className:l=""}){const c=Ye(o,s),u=!!((Array.isArray(t)?t.length>0:String(t??"").trim())||e||i);return a.createElement("section",{className:`ps-panel${n?" is-focused":""}${u?"":" is-chromeless"}${l?` ${l}`:""}`,style:{"--ps-panel-accent":c||"var(--ps-border)"}},u?a.createElement("header",{className:"ps-panel-header"},a.createElement("div",{className:"ps-panel-title"},Array.isArray(t)?a.createElement(He,{runs:t,theme:o}):qo(t)),e||i?a.createElement("div",{className:"ps-panel-header-right"},e?a.createElement("div",{className:"ps-panel-title-right"},Array.isArray(e)?a.createElement(He,{runs:e,theme:o}):qo(e)):null,i?a.createElement("div",{className:"ps-panel-actions"},i):null):null):null,a.createElement("div",{className:"ps-panel-body"},r))}function _y({lines:t,theme:e,controller:s}){return a.createElement("div",{className:"ps-nodemap"},(t||[]).map((n,i)=>{const r=Array.isArray(n?.runs)?n.runs:Array.isArray(n)?n:[n],o=r.find(u=>u?.nodeSelect)?.nodeSelect||null,l=r.some(u=>u?.nodeSelected),c=a.createElement(He,{runs:r,theme:e});return o?a.createElement("button",{key:`line:${i}`,type:"button",className:`ps-nodemap__row${l?" is-selected":""}`,onPointerDown:u=>{u.preventDefault(),u.stopPropagation(),s.selectNodeMapNode(o)}},c):a.createElement("div",{key:`line:${i}`,className:"ps-nodemap__line"},c)}))}function Ly({lines:t,theme:e,completionByTurn:s}){const[n,i]=a.useState(()=>new Set),r=a.useCallback(p=>{i(d=>{const f=new Set(d);return f.has(p)?f.delete(p):f.add(p),f})},[]),o=p=>Number(p||0).toLocaleString("en-US"),l=p=>{const d=Number(p||0);if(!Number.isFinite(d))return"?K";const f=d/1e3,h=Math.abs(f)>=10?1:2;return`${f.toFixed(h)}K`},c=p=>{const d=Number(p||0);return Number.isFinite(d)?`${(d/1e3).toFixed(1)}s`:"?s"},u=p=>{const d=String(p||"").trim();if(!d)return"unknown";const f=d.split(":").filter(Boolean),h=f[f.length-1]||"",m=f.length>1&&og.has(h.toLowerCase())?f.length-2:f.length-1;return f[Math.max(0,m)]||f[0]||"unknown"};return a.createElement(a.Fragment,null,t.map((p,d)=>{const f=p?.kind==="runs"&&Array.isArray(p.runs)?p.runs.find(b=>b?.completedTurn!=null)?.completedTurn:null,h=f!=null?s.get(Number(f)):null;if(!h)return a.createElement(Be,{key:`line:${d}`,line:p,theme:e});const m=h.data||{},g=String(h.seq??`${m.turnIndex??f}:${h.createdAt??d}`),S=n.has(g),y=m.reasoningEffort?`${m.model||"(unknown)"}:${m.reasoningEffort}`:m.model||"(unknown)",v=u(m.model),x=m.durationMs!=null?c(m.durationMs):"duration n/a",E=m.durationMs!=null?`${o(m.durationMs)} ms`:"duration n/a",w=`${l(m.tokensInput)} / ${l(m.tokensOutput)}`,I=[["model",y],["started",m.startedAt?new Date(m.startedAt).toLocaleString():null],["ended",m.endedAt?new Date(m.endedAt).toLocaleString():null],["duration",E],["tokens",`${o(m.tokensInput)} in / ${o(m.tokensOutput)} out`],["cache",`${o(m.tokensCacheRead)} read / ${o(m.tokensCacheWrite)} write`],["tools",`${o(m.toolCalls)} calls / ${o(m.toolErrors)} errors`],["names",Array.isArray(m.toolNames)&&m.toolNames.length?m.toolNames.join(", "):null],["worker",m.workerNodeId||null],["result",m.resultType||null],["error",m.errorMessage||null]].filter(([,b])=>b!=null&&b!=="");return a.createElement(a.Fragment,{key:`seq:${d}`},a.createElement(Be,{line:p,theme:e}),a.createElement("button",{type:"button",className:"ps-sequence-turn-divider",onClick:()=>r(g)},a.createElement("span",{className:"ps-sequence-turn-caret"},S?"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"},w),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"},x),a.createElement("span",{className:"ps-sequence-turn-rule"},") ---")),S?a.createElement("div",{className:"ps-sequence-turn-details"},I.map(([b,M])=>a.createElement("div",{key:b},a.createElement("span",{className:"ps-sequence-turn-detail-label"},`${b}: `),a.createElement("span",null,String(M))))):null)}))}const Oy={chat:"chat",activity:"activity",inspector:"inspector",filePreview:"inspector"};function fr(t,e=null){return e||Oy[String(t||"")]||null}function mn({title:t,titleRight:e=null,color:s,focused:n,actions:i,lines:r,stickyLines:o=[],bottomStickyLines:l=[],scrollOffset:c=0,scrollMode:u="top",paneKey:p,controller:d,className:f="",panelClassName:h="",topContent:m=null,bottomContent:g=null,structuredBlocks:S=!1,stickyBottom:y=!1,renderBody:v=null,focusRegion:x=null,panelRef:E=null}){const w=X(d,j=>j.ui.themeId),I=rt(w),b=a.useRef(null),M=a.useCallback(j=>{b.current=j,typeof E=="function"?E(j):E&&(E.current=j)},[E]),A=a.useRef(null),O=a.useRef(!1),{normalizedLines:F,onScroll:L,onWheel:G,onTouchStart:P,onTouchMove:H,onTouchEnd:U}=Og(b,r,c,u,p,d,{stickyBottom:y}),re=a.useMemo(()=>De(o),[o]),he=a.useMemo(()=>De(l),[l]),ce=f.includes("is-preserve")&&h.includes("has-preserved-sticky"),Ge=`${p}:${t}`;a.useEffect(()=>{const j=()=>{b.current&&(b.current.scrollLeft=0),A.current&&(A.current.scrollLeft=0)};j();const T=typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{j()}):null;return()=>{T!=null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(T)}},[Ge]);const k=a.useCallback(()=>{const j=fr(p,x);j&&d?.setFocus&&d.setFocus(j)},[d,p,x]),$=a.useCallback((j,T)=>{!j||!T||Math.abs((T.scrollLeft||0)-(j.scrollLeft||0))<=1||(O.current=!0,T.scrollLeft=j.scrollLeft,window.requestAnimationFrame(()=>{O.current=!1}))},[]),[K,z]=a.useState({up:!1,down:!1}),B=a.useCallback(j=>{if(!j)return;const T=j.scrollHeight-j.scrollTop-j.clientHeight>4,Y=j.scrollTop>4;z(le=>le.up===T&&le.down===Y?le:{up:T,down:Y})},[]),Q=a.useCallback(j=>{L(),B(j.currentTarget),!(!ce||O.current)&&$(j.currentTarget,A.current)},[L,ce,$,B]);a.useEffect(()=>{B(b.current)});const V=a.useCallback(j=>{!ce||O.current||$(j.currentTarget,b.current)},[ce,$]);return a.createElement(gt,{title:t,titleRight:e,color:s,focused:n,actions:i,theme:I,className:h},m,re.length>0?a.createElement("div",{ref:A,className:`ps-panel-sticky${ce?" is-scroll-sync":""}`,onScroll:V},re.map((j,T)=>a.createElement(Be,{key:`sticky:${T}`,line:j,theme:I}))):null,a.createElement("div",{ref:M,className:`ps-scroll-panel ${f}${K.down?" is-scrolled-down":""}${K.up?" is-scrolled-up":""}`.trim(),"data-session-scroll":x==="sessions"?"1":void 0,onScroll:Q,onMouseDown:k,onTouchStart:P,onWheel:G,onTouchMove:H,onTouchEnd:U,onTouchCancel:U},typeof v=="function"?v(F,I):S?a.createElement(My,{lines:F,theme:I,controller:d}):F.map((j,T)=>a.createElement(Be,{key:`line:${T}`,line:j,theme:I}))),he.length>0?a.createElement("div",{className:"ps-panel-bottom-sticky"},he.map((j,T)=>a.createElement(Be,{key:`bottom-sticky:${T}`,line:j,theme:I}))):null,g)}const ia="—";function $y({session:t,childCount:e=0}){const s=(f,h,m="")=>{const g=h==null||h===""?ia:String(h),S=g===ia;return a.createElement("div",{className:`ps-session-detail-field${m?` ${m}`:""}${S?" is-none":""}`,key:f},a.createElement("span",{className:"ps-session-detail-label"},f),a.createElement("span",{className:"ps-session-detail-value",title:g},g))},n=t?.contextUsage,i=n&&Number.isFinite(n.currentTokens)&&Number.isFinite(n.tokenLimit)&&n.tokenLimit>0,r=i?Math.round(n.currentTokens/n.tokenLimit*100):null,o=i?`${ee(n.currentTokens)} / ${ee(n.tokenLimit)} · ${r}%`:null;let l=null;t&&!t.isGroup&&(l="off",t.cronActive===!0&&(l=t.cronKind==="wall-clock"?`next ${Ks(t.cronNextFireAt)}`:typeof t.cronInterval=="number"?`every ${Dt(t.cronInterval)}`:"on"));const c=t?.model?t.reasoningEffort&&!String(t.model).includes(String(t.reasoningEffort))?`${t.model}:${t.reasoningEffort}`:t.model:null,u=t?t.visibility==="shared_write"?"shared · write":t.visibility==="shared_read"?"shared · read":"private":null,p=t?.isGroup?t.memberCount==null?null:String(t.memberCount):e>0?String(e):null,d=Xd(t);return a.createElement("div",{className:"ps-session-detail-box"},s("Title",t?.title,"is-title"),s("ID",t?.sessionId,"is-id"),s("Owner",t?.owner?jc(t.owner):null),s("Model",c),s("Context",o,r!=null&&r>=85?"is-hot":r!=null&&r>=70?"is-warm":""),s("Cron",l,t?.cronActive===!0?"is-armed":""),s("Agent",t?.agentId),s("Updated",d?`${d.relative} (${d.status})`:null),s("Children",p),s("Access",u))}function Fy(){const t="(pointer: coarse)",e=()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(t).matches:!1,[s,n]=a.useState(e);return a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const i=window.matchMedia(t),r=o=>n(o.matches);return i.addEventListener?.("change",r),()=>i.removeEventListener?.("change",r)},[]),s}const Lc=13,Oc=11,$c=1.5,Dy=7;function By(t){return Lc+(t-1)*Oc+$c/2-Dy/2}const Hy=a.memo(function({row:e,theme:s,structuredRows:n,mobile:i,onRowClick:r,setRef:o,drag:l}){const c=Math.max(0,e.depth),u=a.useMemo(()=>{if(c<1)return;const v=Array.from({length:c},(x,E)=>E);return{backgroundImage:v.map(()=>"linear-gradient(var(--ps-rail), var(--ps-rail))").join(", "),backgroundSize:v.map(()=>`${$c}px 100%`).join(", "),backgroundPosition:v.map(x=>`${Lc+x*Oc}px 0`).join(", "),backgroundRepeat:"no-repeat"}},[c]),p=a.useCallback(v=>o(e.sessionId,v),[o,e.sessionId]),d=a.useCallback(v=>r(v,e),[r,e]),f=e.groupId||null,h=!!(l?.dragging&&l.overGroupId&&f===l.overGroupId),m=h&&!!e.isGroup,g=!!(l?.dragging&&l.insertBeforeId===e.sessionId),S=!!(l?.dragging&&l.insertAfterId&&l.insertAfterId===e.sessionId),y=a.useCallback(v=>{if(l?.onPointerDown&&v.button===0){if(v.currentTarget?.setPointerCapture&&v.pointerId!=null)try{v.currentTarget.setPointerCapture(v.pointerId)}catch{}l.onPointerDown(v,e)}},[l,e]);return a.createElement("button",{type:"button",ref:p,className:`ps-list-button ps-session-list-button${e.active?" is-selected":""}${e.selected?" is-multiselected":""}${e.pinned?" is-pinned":""}${h?" is-drop-zone":""}${m?" is-drop-target":""}${g?" is-insert-before":""}${S?" is-insert-after":""}${e.depth>0?" is-nested":""}`,style:u,tabIndex:e.active?0:-1,"aria-selected":e.active?"true":"false","data-session-id":e.sessionId,"data-group-row":e.isGroup?"1":void 0,"data-group-id":e.isGroup?e.groupId||"":void 0,"data-drop-group":f||void 0,"data-order-container":e.orderContainer??void 0,"data-orderable":e.orderable?"1":void 0,onPointerDown:y,onClick:d,onContextMenu:v=>{v.ctrlKey&&(v.preventDefault(),r(v,e))}},a.createElement("div",{className:"ps-line ps-session-row-content",style:{paddingInlineStart:c>0?`${By(c)}px`:"0px"}},a.createElement(jy,{row:e,theme:s,structured:n,showInlineDetail:i})))});function ra(t,e){if(!Array.isArray(t))return{statusColor:null,rest:t};let s=null;const n=[];for(const i of t)if(i?.role!=="depth"&&i?.role!=="selection"){if(i?.role==="status"){s=Ye(e,i.color)||null;continue}n.push(i)}return{statusColor:s,rest:n}}function oa({color:t,node:e=!1}){return a.createElement("span",{className:`ps-session-status-dot${e?" is-node":""}`,style:t?e?{borderColor:t}:{background:t}:void 0})}function yi({badge:t,size:e="sm"}){return t?a.createElement("span",{className:`ps-owner-avatar is-${e}${t.isMine?" is-mine":""}`,"data-owner-hue":String(t.hue??0),title:t.isMine?`${t.name} (you)`:t.name,"aria-label":t.name},t.initials):null}function aa(t){return Array.isArray(t)?t.filter(e=>!e?.ownerChip):t}function jy({row:t,theme:e,structured:s=!1,showInlineDetail:n=!1}){if(!(s&&Array.isArray(t.titleRuns))){if(!Array.isArray(t.runs))return t.text;const p=ra(aa(t.runs),e);return a.createElement(a.Fragment,null,p.statusColor?a.createElement(oa,{color:p.statusColor,node:t.depth>0}):null,a.createElement(yi,{badge:t.ownerBadge}),a.createElement(pa,{mark:t.canvasMark}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(He,{runs:p.rest,theme:e})))}const r=ra(aa(t.titleRuns),e),o=Array.isArray(t.ctxRuns)?t.ctxRuns:[],l=o.length>0,c=Array.isArray(t.detailRuns)?t.detailRuns:Array.isArray(t.selectedMetaRuns)?t.selectedMetaRuns:[],u=n&&t.active&&c.length>0;return a.createElement(a.Fragment,null,a.createElement("div",{className:"ps-session-row-line"},a.createElement("div",{className:"ps-session-row-title"},r.statusColor?a.createElement(oa,{color:r.statusColor,node:t.depth>0}):null,a.createElement(yi,{badge:t.ownerBadge}),a.createElement(pa,{mark:t.canvasMark}),a.createElement("span",{className:"ps-session-row-title__text"},a.createElement(He,{runs:r.rest,theme:e}))),l?a.createElement("div",{className:"ps-session-row-ctx"},a.createElement(He,{runs:o,theme:e})):null),u?a.createElement("div",{className:"ps-session-row-detail"},a.createElement(He,{runs:c,theme:e})):null)}function Gy(t){const e=a.useRef(t),s=a.useRef(null),n=a.useMemo(()=>{try{return JSON.stringify(t)}catch{return null}},[t]);return(n===null||s.current!==n)&&(s.current=n,e.current=t),e.current}const la=10,Uy=1.6;function zy(t){a.useEffect(()=>{const e=t.current;if(!e)return;let s=0,n=0,i=0,r=null;const o=u=>{if(u.touches.length!==1){r="y";return}const p=u.touches[0];s=i=p.clientX,n=p.clientY,r=null},l=u=>{if(r==="y"||u.touches.length!==1)return;const p=u.touches[0],d=p.clientX-s,f=p.clientY-n;r===null&&(Math.abs(d)<la&&Math.abs(f)<la||(r=Math.abs(d)>Math.abs(f)*Uy?"x":"y",i=p.clientX,r==="y"))||(e.scrollLeft-=p.clientX-i,i=p.clientX,u.cancelable&&u.preventDefault())},c=()=>{r=null};return e.addEventListener("touchstart",o,{passive:!0}),e.addEventListener("touchmove",l,{passive:!1}),e.addEventListener("touchend",c,{passive:!0}),e.addEventListener("touchcancel",c,{passive:!0}),()=>{e.removeEventListener("touchstart",o),e.removeEventListener("touchmove",l),e.removeEventListener("touchend",c),e.removeEventListener("touchcancel",c)}},[t])}function Si({controller:t,actions:e=null,panelClassName:s="",structuredRows:n=!1,showDetailBox:i=null}){const r=String(s).includes("ps-mobile-session-pane"),o=a.useRef(null);zy(o);const l=r||Fy(),c=X(t,D=>D.ui.themeId),u=rt(c),p=a.useRef(new Map),d=X(t,D=>({branding:D.branding,activeSessionId:D.sessions.activeSessionId,sessionsById:D.sessions.byId,sessionsFlat:D.sessions.flat,filterQuery:D.sessions.filterQuery||"",ownerFilter:D.sessions.ownerFilter,pinnedIds:D.sessions.pinnedIds,manualOrder:D.sessions.manualOrder,selectedIds:D.sessions.selectedIds,selectMode:D.sessions.selectMode,auth:D.auth,connectionMode:D.connection?.mode||"local",modalOpen:!!D.ui.modal,focused:D.ui.focusRegion==="sessions",listDeselected:!!D.sessions.listDeselected,canvasBySessionId:D.canvas?.bySessionId,canvasPrefs:D.canvas?.prefs}),Oe),f=a.useMemo(()=>Qt({sessions:{activeSessionId:d.activeSessionId,byId:d.sessionsById,flat:d.sessionsFlat,filterQuery:d.filterQuery,ownerFilter:d.ownerFilter,pinnedIds:d.pinnedIds,manualOrder:d.manualOrder,selectedIds:d.selectedIds,selectMode:d.selectMode,listDeselected:d.listDeselected},auth:d.auth,connection:{mode:d.connectionMode},branding:d.branding,canvas:{bySessionId:d.canvasBySessionId,prefs:d.canvasPrefs}}),[d.activeSessionId,d.auth,d.branding,d.canvasBySessionId,d.canvasPrefs,d.connectionMode,d.filterQuery,d.listDeselected,d.ownerFilter,d.pinnedIds,d.manualOrder,d.selectedIds,d.selectMode,d.sessionsById,d.sessionsFlat]),h=Gy(f),m=d.activeSessionId&&d.sessionsById[d.activeSessionId]||null,g=d.activeSessionId&&h.find(D=>D.sessionId===d.activeSessionId)||null,[S,y]=a.useState(!1),[v,x]=a.useState(null),E=a.useRef(!1),w=["modelPicker","reasoningEffortPicker","contextTierPicker"],I=X(t,D=>w.includes(D.ui.modal?.type));a.useEffect(()=>{!I&&E.current&&(E.current=!1,y(!0))},[I]);const b=()=>{E.current=!0,y(!1),t.openSwitchModelPicker(()=>{E.current=!1}).then(()=>{!w.includes(t.getState().ui.modal?.type)&&E.current&&(E.current=!1,y(!0))}).catch(D=>{E.current=!1,y(!0),t.dispatch({type:"ui/status",text:D?.message||String(D)||"Failed to switch model"})})},M=d.auth?.principal||null,A=d.auth?.authorization?.role,O=A==="admin"||A==="anonymous",F=!!(m?.owner&&M&&String(m.owner.provider)===String(M.provider)&&String(m.owner.subject)===String(M.subject)),L=!!(m&&!m.isGroup&&(m.isSystem?O:O||F)),G=Array.isArray(d.selectedIds)?d.selectedIds.length:0,P=G>1,H=!!(m?.isGroup&&!P),U=!!(m&&!m.isSystem&&(m.isGroup||!m.parentSessionId&&!m.groupId)),re=!!(m&&Array.isArray(d.pinnedIds)&&d.pinnedIds.includes(m.sessionId)),he=!!(m?.isGroup&&Number(m.memberCount||0)===0),ce=P?Array.isArray(d.selectedIds)&&d.selectedIds.some(D=>{const R=d.sessionsById[D];return R&&!R.isSystem&&!R.isGroup}):m?.isGroup?!0:!!m,Ge=G>0,k=!!(m&&!d.listDeselected&&!m.isSystem&&!m.isGroup&&!m.parentSessionId),$=Ge?d.selectedIds.filter(D=>{const R=d.sessionsById[D];return R&&!R.isSystem&&!R.isGroup&&!R.parentSessionId}):k?[m.sessionId]:[],K=`ps-session-pane${s?` ${s}`:""}`,z=a.useRef(null);z.current={rows:h,viewState:d,controller:t};const[B,Q]=a.useState({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),V=a.useRef(null),j=a.useRef(null),T=a.useCallback(()=>{j.current!=null&&(cancelAnimationFrame(j.current),j.current=null)},[]),Y=a.useCallback(()=>{let D=o.current;for(;D&&D!==document.body;){const R=window.getComputedStyle(D).overflowY;if(/(auto|scroll|overlay)/.test(R)&&D.scrollHeight-D.clientHeight>1)return D;D=D.parentElement}return null},[]),le=a.useCallback((D,R)=>{const q=Y();if(!q){T();return}const ne=q.getBoundingClientRect();let ie=0;if(R<ne.top+48?ie=-14*Math.min(1,(ne.top+48-R)/48):R>ne.bottom-48&&(ie=14*Math.min(1,(R-(ne.bottom-48))/48)),V.current&&(V.current.autoScrollStep=ie),!V.current){T();return}if(j.current!=null)return;const ue=()=>{const ve=V.current;if(!ve||!ve.autoScrollStep){T();return}q.scrollTop+=ve.autoScrollStep,j.current=requestAnimationFrame(ue)};j.current=requestAnimationFrame(ue)},[Y,T]),ae=a.useCallback(D=>{const R=V.current;if(V.current=null,T(),Q({dragging:!1,ids:[],titles:[],overGroupId:null,insertBeforeId:void 0,insertAfterId:null,x:0,y:0}),!(!D||!R?.started||R.ids.length===0)){if(R.intent==="reorder"){t.dispatch({type:"sessions/reorder",sessionId:R.ids[0],beforeSessionId:R.beforeSessionId});return}R.intent!=="file"&&R.intent!=="unfile"||t.moveSessionsToGroup(R.overGroupId,R.ids).catch(W=>{t.dispatch({type:"ui/status",text:`Move failed: ${W?.message||W}`})})}},[t,T]),Ce=a.useCallback((D,R)=>typeof D!="number"||typeof R!="number"?null:(document.elementFromPoint(D,R)?.closest?.("[data-drop-group]")||null)?.getAttribute("data-drop-group")||null,[]),Ie=a.useCallback((D,R,W,J)=>{if(typeof D!="number"||typeof R!="number"||W==null)return;const q=Array.from(document.querySelectorAll(`[data-order-container="${CSS.escape(W)}"][data-orderable="1"]`));if(q.length===0)return;for(const ue of q){const ve=ue.getBoundingClientRect();if(R<ve.top+ve.height/2)return{before:ue.getAttribute("data-session-id")||null,after:null}}const ie=q[q.length-1]?.getAttribute("data-session-id")||null;return{before:null,after:ie&&ie!==J?ie:null}},[]),Re=a.useCallback((D,R,W)=>{const J=Ce(D,R);if(W?.isGroup){const ue=W.ids.length===1?Ie(D,R,W.container,W.ids[0]):void 0;return ue===void 0?{kind:"none",overGroupId:null,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:ue.before,after:ue.after}}const q=W?.ownGroupId||null;if(J&&J!==q)return{kind:"file",overGroupId:J,before:void 0,after:null};if(!J&&q)return{kind:"unfile",overGroupId:null,before:void 0,after:null};const ie=W?.orderable&&W.ids.length===1?Ie(D,R,W.container,W.ids[0]):void 0;return ie===void 0?{kind:J?"file":"none",overGroupId:J,before:void 0,after:null}:{kind:"reorder",overGroupId:null,before:ie.before,after:ie.after}},[Ce,Ie]);a.useEffect(()=>{if(!B.dragging)return;const D=q=>{const ne=V.current;if(!ne)return;const ie=Re(q.clientX,q.clientY,ne);ne.intent=ie.kind,ne.overGroupId=ie.overGroupId,ne.beforeSessionId=ie.before,le(q.clientX,q.clientY),document.body.classList.toggle("ps-drop-ok",ie.kind==="file"),Q(ue=>({...ue,intent:ie.kind,overGroupId:ie.overGroupId,insertBeforeId:ie.before,insertAfterId:ie.after,x:q.clientX,y:q.clientY}))},R=q=>{const ne=V.current;if(ne&&typeof q?.clientX=="number"){const ie=Re(q.clientX,q.clientY,ne);ne.intent=ie.kind,ne.overGroupId=ie.overGroupId,ne.beforeSessionId=ie.before}ae(!0)},W=()=>ae(!1),J=q=>{q.key==="Escape"&&ae(!1)};return window.addEventListener("pointermove",D),window.addEventListener("pointerup",R),window.addEventListener("pointercancel",W),window.addEventListener("keydown",J),document.body.classList.add("ps-dragging-sessions"),()=>{window.removeEventListener("pointermove",D),window.removeEventListener("pointerup",R),window.removeEventListener("pointercancel",W),window.removeEventListener("keydown",J),document.body.classList.remove("ps-dragging-sessions"),document.body.classList.remove("ps-drop-ok")}},[B.dragging,ae,Re,le]);const ke=a.useMemo(()=>({dragging:B.dragging,overGroupId:B.overGroupId,insertBeforeId:B.insertBeforeId,insertAfterId:B.insertAfterId,onPointerDown:(D,R)=>{if(R.isSystem||!R.orderable&&!R.isGroup&&R.depth>0)return;const W=D.clientX,J=D.clientY,q={row:R,startX:W,startY:J,started:!1,ids:[],overGroupId:null,beforeSessionId:void 0,orderable:!!R.orderable,container:R.orderContainer??null,isGroup:!!R.isGroup,ownGroupId:R.groupId||null,intent:"none",autoScrollStep:0},ne=ue=>{if(q.started||Math.hypot(ue.clientX-W,ue.clientY-J)<5)return;q.started=!0;const ve=z.current.viewState,$e=Array.isArray(ve.selectedIds)?ve.selectedIds:[],yt=$e.includes(R.sessionId)&&$e.length>1?$e:[R.sessionId],rs=ve.sessionsById||{};q.ids=yt,V.current=q,Q({dragging:!0,ids:yt,titles:yt.map(St=>rs[St]?.title||String(St).slice(0,8)).slice(0,3),overGroupId:null,x:ue.clientX,y:ue.clientY})},ie=()=>{window.removeEventListener("pointermove",ne),window.removeEventListener("pointerup",ie)};window.addEventListener("pointermove",ne),window.addEventListener("pointerup",ie)}}),[B.dragging,B.overGroupId,B.insertBeforeId,B.insertAfterId]),Te=a.useCallback((D,R)=>{const{rows:W,viewState:J,controller:q}=z.current;if(D.metaKey||D.ctrlKey){D.preventDefault(),J.selectMode||q.dispatch({type:"sessions/selectMode",enabled:!0}),q.dispatch({type:"sessions/selectToggle",sessionId:R.sessionId}),q.setFocus("sessions");return}if(D.shiftKey&&J.activeSessionId){D.preventDefault();const ie=W.map($e=>$e.sessionId),ue=ie.indexOf(J.activeSessionId),ve=ie.indexOf(R.sessionId);if(ue>=0&&ve>=0){const[$e,yt]=ue<=ve?[ue,ve]:[ve,ue],rs=ie.slice($e,yt+1),St=Array.from(new Set([...J.selectedIds||[],...rs]));q.setSessionSelection(St),q.setFocus("sessions");return}}if(R.hasChildren&&R.active){q.dispatch({type:R.collapsed?"sessions/expand":"sessions/collapse",sessionId:R.sessionId}),q.setFocus("sessions");return}J.selectMode&&q.dispatch({type:"sessions/selectClear"}),q.setFocus("sessions"),R.sessionId===J.activeSessionId?q.dispatch({type:"sessions/listReselect"}):R.active||q.loadSession(R.sessionId).catch(()=>{})},[]),oe=a.useCallback((D,R)=>{D&&(R?p.current.set(D,R):p.current.delete(D))},[]),Ne=a.useRef(null),_=`${d.activeSessionId||""}${d.focused?1:0}${d.modalOpen?1:0}`;a.useEffect(()=>{if(d.modalOpen||!d.focused||!d.activeSessionId){Ne.current=null;return}const D=p.current.get(d.activeSessionId);if(!D||Ne.current===_)return;Ne.current=_;const R=document.activeElement,W=!!(R&&(R.tagName==="INPUT"||R.tagName==="TEXTAREA"||R.tagName==="SELECT"||R.isContentEditable));R!==D&&!W&&D.focus({preventScroll:!0}),D.scrollIntoView({block:"nearest"})},[_,d.activeSessionId,d.focused,d.modalOpen,d.sessionsFlat]);const se=a.createElement(a.Fragment,null,P?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."},`${G} selected`):null,P?a.createElement(pe,{className:"ps-mini-button",icon:"✕",label:"Clear multi-selection",onClick:()=>t.handleCommand(C.CLEAR_SESSION_SELECTION).catch(()=>{})}):a.createElement(pe,{className:"ps-mini-button ps-pin-icon",icon:a.createElement(dS),onClick:()=>t.handleCommand(C.PIN_SESSION).catch(()=>{}),disabled:!U,active:re,label:U?re?"Unpin this session":"Pin this session to the top of the list":"Only top-level non-system sessions can be pinned"}),a.createElement(pe,{className:"ps-mini-button",icon:$.length>1?a.createElement("span",{className:"ps-icon-badge"},a.createElement(ua),a.createElement("span",{className:"ps-icon-badge__count"},String($.length))):a.createElement(ua),onClick:()=>t.handleCommand(C.OPEN_MOVE_TO_GROUP).catch(()=>{}),label:$.length>1?`Move ${$.length} selected sessions to a group`:$.length===1?"Move this session to a group":"New group"}),a.createElement(pe,{className:"ps-mini-button",icon:a.createElement(qy),onClick:()=>{if(m?.isGroup){t.handleCommand(C.OPEN_RENAME_SESSION).catch(()=>{});return}y(!0)},disabled:!L&&!H||P,label:P?"Disabled while multiple sessions are selected":m?.isSystem?"System sessions are managed by administrators":m?.isGroup?"Rename folder":L?"Manage session — rename, switch model, and sharing":"Only this session's owner or an admin can manage it"}),a.createElement(pe,{className:"ps-mini-button",icon:a.createElement(uS),onClick:()=>{const D=m?.sessionId;if(!D)return;const R=cc(D);R&&(sn(R),x({url:R,warn:!1}),bg(t,D).then(W=>{x(J=>J&&J.url===R?{...J,warn:W}:J)}).catch(()=>{}))},disabled:!m||m.isGroup||P,label:"Copy link — copy a direct link to this session"}),a.createElement(pe,{className:"ps-mini-button",icon:a.createElement(m?.isSystem?Zy:bi),onClick:()=>t.handleCommand(m?.isGroup?C.DELETE_SESSION:C.OPEN_TERMINATE_PICKER).catch(()=>{}),disabled:!ce,label:P?`Terminate ${G} selected sessions (Mark Completed, Cancel, or Delete)`:m?.isGroup?he?"Delete this empty group":"This group cannot be deleted yet":m?.isSystem?"Restart this system session (complete, terminate, or hard delete)":"Terminate — mark completed, cancel, or delete this session"}),e),ye=B.dragging?a.createElement("div",{className:"ps-drag-ghost",style:{left:`${B.x}px`,top:`${B.y}px`}},a.createElement("div",{className:`ps-drag-ghost__stack${B.ids.length>1?" is-collection":""}`},B.ids.length>1?a.createElement("span",{className:"ps-drag-ghost__count"},String(B.ids.length)):null,a.createElement("span",{className:"ps-drag-ghost__title"},B.ids.length>1?`${B.ids.length} sessions`:B.titles[0]||"session")),a.createElement("div",{className:"ps-drag-ghost__hint"},B.intent==="file"?"Release to file here":B.intent==="unfile"?"Release to remove from folder":B.intent==="reorder"?"Release to move here":"Release to cancel")):null;return a.createElement(a.Fragment,null,ye,a.createElement(gt,{title:[{text:"Sessions",color:"yellow",bold:!0}],color:"yellow",focused:d.focused,theme:u,actions:se,className:K},a.createElement("div",{ref:o,className:`ps-action-list ps-session-list${B.dragging?" is-dragging":""}`,onClick:D=>{D.target instanceof Element&&D.target.closest(".ps-session-list-button")||t.dispatch({type:"sessions/listDeselect"})}},h.length===0?a.createElement("div",{className:"ps-empty-state"},d.filterQuery?`No sessions matched "@@${d.filterQuery}".`:"No sessions yet."):h.map(D=>a.createElement(Hy,{key:D.sessionId,row:D,theme:u,structuredRows:n,mobile:r,onRowClick:Te,setRef:oe,drag:l?null:ke}))),(i===null?!r:i)?a.createElement($y,{session:m,childCount:g?.childCount||0}):null),S&&m&&!m.isGroup?a.createElement(hS,{controller:t,sessionId:m.sessionId,initialTitle:m.title||"",currentModel:m.model||"",currentReasoningEffort:m.reasoningEffort||"",principal:d.auth?.principal||null,onClose:()=>y(!1),onSwitchModel:b,onChanged:()=>{}}):null,v?a.createElement(Wy,{url:v.url,warn:v.warn,onCopyAgain:()=>{sn(v.url),t.dispatch({type:"ui/status",text:gg})},onClose:()=>x(null)}):null)}function Wy({url:t,warn:e,onCopyAgain:s,onClose:n}){const i=a.useRef(null);a.useEffect(()=>{const o=i.current;o&&(o.focus(),o.select())},[]);const r=o=>o.stopPropagation();return a.createElement("div",{className:"ps-share-overlay",onClick:n},a.createElement("div",{className:"ps-link-modal",onClick:r},a.createElement("div",{className:"ps-share-modal-head"},a.createElement("span",null,pt.length>=2?"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"},pt.length>=2?"All entry-point links were copied — use the one reachable from the recipient's network.":"Copied to your clipboard — anyone with access can open the session from this link."),a.createElement("div",{className:"ps-link-row"},pt.length>=2?a.createElement("textarea",{ref:i,className:"ps-link-input",readOnly:!0,rows:Zs(t,pt).length,value:er(Zs(t,pt)),onFocus:()=>i.current?.select()}):a.createElement("input",{ref:i,className:"ps-link-input",readOnly:!0,value:t,onFocus:()=>i.current?.select()}),a.createElement("button",{className:"ps-mini-button",onClick:s},"Copy")),e?a.createElement("div",{className:"ps-link-warn"},Sg):null))}const ca={private:{glyph:"🔒",label:"Private"},shared_read:{glyph:"👁",label:"Shared · read"},shared_write:{glyph:"✎",label:"Shared · write"}};function Pe({children:t}){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},t)}function qy(){return a.createElement(Pe,null,a.createElement("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"}))}function hr(){return a.createElement(Pe,null,a.createElement("path",{d:"M21 4H3l7.2 8.5V19l3.6 2v-8.5L21 4z"}))}function Ky(){return a.createElement(Pe,null,a.createElement("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),a.createElement("line",{x1:"5",y1:"12",x2:"19",y2:"12"}))}function Vy(){return a.createElement(Pe,null,a.createElement("circle",{cx:"12",cy:"12",r:"9"}),a.createElement("path",{d:"M12 3a9 9 0 0 1 0 18z",fill:"currentColor"}))}function Yy(){return a.createElement(Pe,null,a.createElement("path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}),a.createElement("path",{d:"M16 3h3a2 2 0 0 1 2 2v3"}),a.createElement("path",{d:"M21 16v3a2 2 0 0 1-2 2h-3"}),a.createElement("path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}))}function Xy(){return a.createElement(Pe,null,a.createElement("path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}),a.createElement("path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}),a.createElement("path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}),a.createElement("path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}))}function Qy(){return a.createElement(Pe,null,a.createElement("circle",{cx:"12",cy:"12",r:"3"}),a.createElement("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"}))}function Zy(){return a.createElement(Pe,null,a.createElement("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"}),a.createElement("path",{d:"M21 3v5h-5"}))}function Jy(){return a.createElement(Pe,null,a.createElement("path",{d:"M12 16V4"}),a.createElement("path",{d:"M7.5 8.5L12 4l4.5 4.5"}),a.createElement("path",{d:"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"}))}function Fc(){return a.createElement(Pe,null,a.createElement("path",{d:"M12 4v12"}),a.createElement("path",{d:"M7.5 11.5L12 16l4.5-4.5"}),a.createElement("path",{d:"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"}))}function eS(){return a.createElement(Pe,null,a.createElement("line",{x1:"4.5",y1:"3",x2:"4.5",y2:"21"}),a.createElement("line",{x1:"19.5",y1:"3",x2:"19.5",y2:"21"}),a.createElement("path",{d:"M4.5 8.5h13"}),a.createElement("path",{d:"M15 6l2.5 2.5-2.5 2.5"}),a.createElement("path",{d:"M19.5 15.5h-13"}),a.createElement("path",{d:"M9 13l-2.5 2.5 2.5 2.5"}))}function tS(){return a.createElement(Pe,null,a.createElement("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),a.createElement("line",{x1:"9.5",y1:"4",x2:"9.5",y2:"20"}),a.createElement("line",{x1:"12.5",y1:"9",x2:"18",y2:"9"}),a.createElement("line",{x1:"12.5",y1:"13",x2:"18",y2:"13"}))}function sS(){return a.createElement(Pe,null,a.createElement("path",{d:"M4 17l6-6-6-6"}),a.createElement("line",{x1:"12",y1:"19",x2:"20",y2:"19"}))}function nS(){return a.createElement(Pe,null,a.createElement("circle",{cx:"6",cy:"6",r:"2.6"}),a.createElement("circle",{cx:"18",cy:"6",r:"2.6"}),a.createElement("circle",{cx:"12",cy:"18",r:"2.6"}),a.createElement("line",{x1:"8.6",y1:"6",x2:"15.4",y2:"6"}),a.createElement("line",{x1:"7.4",y1:"8.3",x2:"10.6",y2:"15.7"}),a.createElement("line",{x1:"16.6",y1:"8.3",x2:"13.4",y2:"15.7"}))}const iS="M12 2.3 20.4 7.15v9.7L12 21.7 3.6 16.85V7.15Z",rS="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",oS="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 aS(){return a.createElement("svg",{className:"ps-share-glyph",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":"true"},a.createElement("path",{d:iS,strokeWidth:"1.9",strokeLinejoin:"round"}),a.createElement("path",{d:rS,fill:"currentColor",stroke:"none",fillRule:"evenodd"}),a.createElement("path",{d:oS,fill:"currentColor",stroke:"none"}))}function lS(){return a.createElement(Pe,null,a.createElement("path",{d:"M9 2.8h4.2L17 6.6v8.6a1.8 1.8 0 0 1-1.8 1.8H15"}),a.createElement("path",{d:"M4.5 9.4a1.8 1.8 0 0 1 1.8-1.8h4.2l3.8 3.8v8a1.8 1.8 0 0 1-1.8 1.8H6.3a1.8 1.8 0 0 1-1.8-1.8z"}),a.createElement("path",{d:"M10.5 7.6v3.8h3.8"}))}function cS(){return a.createElement(Pe,null,a.createElement("rect",{x:"4.2",y:"12",width:"3.6",height:"8",rx:"0.6",fill:"currentColor",stroke:"none"}),a.createElement("rect",{x:"10.2",y:"6.5",width:"3.6",height:"13.5",rx:"0.6",fill:"currentColor",stroke:"none"}),a.createElement("rect",{x:"16.2",y:"9.5",width:"3.6",height:"10.5",rx:"0.6",fill:"currentColor",stroke:"none"}),a.createElement("path",{d:"M3 21h18"}))}function uS(){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 bi(){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 ua(){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 dS(){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 pS(){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 fS(t,e,s){const[n,i]=a.useState({access:null,loading:!1}),r=a.useCallback(()=>{if(!e||s||typeof t.transport.getSessionAccess!="function"){i({access:null,loading:!1});return}let o=!1;return i(l=>({...l,loading:!0})),t.transport.getSessionAccess(e).then(l=>{o||i({access:l,loading:!1})}).catch(()=>{o||i({access:null,loading:!1})}),()=>{o=!0}},[t,e,s]);return a.useEffect(()=>{let o;const l=setTimeout(()=>{o=r()},yg);return()=>{clearTimeout(l),typeof o=="function"&&o()}},[r]),{access:n.access,loading:n.loading,reload:r}}function hS({controller:t,sessionId:e,initialTitle:s,currentModel:n,currentReasoningEffort:i,principal:r,onClose:o,onSwitchModel:l,onChanged:c}){const[u,p]=a.useState("general"),[d,f]=a.useState(null),[h,m]=a.useState(s||""),[g,S]=a.useState([]),[y,v]=a.useState([]),[x,E]=a.useState("private"),[w,I]=a.useState(""),[b,M]=a.useState("write"),[A,O]=a.useState([]),[F,L]=a.useState(!1),[G,P]=a.useState(null);a.useEffect(()=>{let _=!1;return t.transport.getSessionAccess(e).then(se=>{!_&&se&&(f(se),E(se.visibility||"private"))}).catch(()=>{}),typeof t.transport.listKnownUsers=="function"&&t.transport.listKnownUsers({limit:500}).then(se=>{_||O(Array.isArray(se)?se:[])}).catch(()=>{}),()=>{_=!0}},[t,e]);const H=a.useCallback(()=>{t.transport.listSessionShares(e).then(_=>{const se=Array.isArray(_)?_:[];S(se),v(se)}).catch(()=>{S([]),v([])})},[t,e]);a.useEffect(()=>{H()},[H]);const U=async _=>{L(!0),P(null);try{await _(),c?.()}catch(se){P(se?.message||String(se))}finally{L(!1)}},re=()=>U(async()=>{await t.transport.renameSession(e,h.trim())}),he=_=>{const se=_.trim().toLowerCase();if(!se)return null;const ye=A.find(D=>D.displayName&&D.displayName.toLowerCase()===se||D.email&&D.email.toLowerCase()===se||D.subject&&D.subject.toLowerCase()===se);return ye||{provider:r?.provider||"dev",subject:_.trim(),email:null,displayName:null}},ce=_=>`${_.provider}${_.subject}`,Ge=_=>{const se=ce(_);v(ye=>[...ye.filter(D=>ce(D)!==se),{provider:_.provider,subject:_.subject,email:_.email??null,displayName:_.displayName??null,access:b}]),I("")},k=()=>{const _=he(w);_&&Ge(_)},$=_=>{const se=ce(_);v(ye=>ye.filter(D=>ce(D)!==se))},K=new Set(y.map(ce)),z=d?.owner?`${d.owner.provider}${d.owner.subject}`:null,B=w.trim().toLowerCase(),Q=B?A.filter(_=>{const se=ce(_);return se===z||K.has(se)?!1:_.displayName&&_.displayName.toLowerCase().includes(B)||_.email&&_.email.toLowerCase().includes(B)||_.subject&&_.subject.toLowerCase().includes(B)}).slice(0,25):[],V=!!d?.canManage,j=d?.visibility||"private",T=new Set(y.map(_=>`${ce(_)}:${_.access}`)),Y=new Set(g.map(_=>`${ce(_)}:${_.access}`)),le=T.size!==Y.size||[...T].some(_=>!Y.has(_)),ae=V&&(x!==j||le),Ce=()=>U(async()=>{x!==j&&await t.transport.setSessionVisibility(e,x);const _=new Map(g.map(R=>[ce(R),R])),se=new Map(y.map(R=>[ce(R),R]));for(const[R,W]of se){const J=_.get(R);(!J||J.access!==W.access)&&await t.transport.grantSessionShare(e,{provider:W.provider,subject:W.subject,email:W.email??null,displayName:W.displayName??null},W.access)}for(const[R,W]of _)se.has(R)||await t.transport.revokeSessionShare(e,{provider:W.provider,subject:W.subject});const ye=await t.transport.listSessionShares(e).catch(()=>null);Array.isArray(ye)&&(S(ye),v(ye));const D=await t.transport.getSessionAccess(e).catch(()=>null);D&&(f(D),E(D.visibility||"private")),t.dispatch({type:"ui/status",text:"Access updated."})}),Ie=l||(()=>{o(),t.openSwitchModelPicker().catch(_=>{t.dispatch({type:"ui/status",text:_?.message||String(_)||"Failed to switch model"})})}),Re=n?i?`${n}:${i}`:n:"—",ke=[{id:"general",label:"General"},...V?[{id:"access",label:"Access"}]:[]],Te=ke.some(_=>_.id===u)?u:"general",oe=typeof t.transport?.regenerateSession=="function",Ne=_=>_.stopPropagation();return a.createElement("div",{className:"ps-share-overlay",onClick:o},a.createElement("div",{className:"ps-share-modal",onClick:Ne},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"},ke.map(_=>a.createElement("button",{key:_.id,type:"button",role:"tab","aria-selected":Te===_.id?"true":"false",className:`ps-manage-tab${Te===_.id?" is-active":""}`,onClick:()=>p(_.id)},_.label))),a.createElement("div",{className:"ps-share-modal-body"},Te==="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:F,onChange:_=>m(_.target.value),onKeyDown:_=>{_.key==="Enter"&&re()}}),a.createElement("button",{className:"ps-mini-button",disabled:F||!h.trim(),onClick:re},"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"},Re),a.createElement("button",{className:"ps-mini-button",disabled:F,onClick:Ie},"Switch model…")),oe?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:F,onClick:()=>{o(),t.handleCommand(C.REGENERATE_SESSION).catch(()=>{})}},a.createElement(pS),a.createElement("span",null,"Regenerate context…")))):null):null,Te==="access"&&V?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(_=>a.createElement("label",{key:_,className:`ps-share-radio${x===_?" is-active":""}`},a.createElement("input",{type:"radio",name:"visibility",checked:x===_,disabled:F,onChange:()=>E(_)}),a.createElement("span",{className:"ps-share-radio-glyph"},ca[_].glyph),a.createElement("span",null,ca[_].label),a.createElement("span",{className:"ps-share-radio-hint"},_==="private"?"only you and admins":_==="shared_read"?"everyone here can view":"everyone here can view and send"))),a.createElement("div",{className:"ps-share-section-label"},"Special access"),a.createElement("div",{className:"ps-share-section-sub"},"Give specific people more than the general level. A person's grant wins over general access."),y.length===0?a.createElement("div",{className:"ps-share-empty"},"No individual grants — everyone has the general access above."):y.map(_=>a.createElement("div",{key:`${_.provider}/${_.subject}`,className:"ps-share-grant-row"},a.createElement("span",{className:"ps-share-grant-name"},_.displayName||_.subject),a.createElement("span",{className:"ps-share-grant-access"},`can ${_.access}`),a.createElement("button",{className:"ps-mini-button",disabled:F,onClick:()=>$(_)},"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:w,disabled:F,autoComplete:"off",onChange:_=>I(_.target.value),onKeyDown:_=>{_.key==="Enter"&&k()}}),a.createElement("select",{className:"ps-share-add-select",value:b,disabled:F,onChange:_=>M(_.target.value)},a.createElement("option",{value:"read"},"can read"),a.createElement("option",{value:"write"},"can write")),a.createElement("button",{className:"ps-mini-button",disabled:F||!w.trim(),onClick:k},"Add")),Q.length>0?a.createElement("div",{className:"ps-share-suggestions"},Q.map(_=>a.createElement("button",{key:`${_.provider}/${_.subject}`,type:"button",className:"ps-share-suggestion",disabled:F,onClick:()=>Ge(_)},a.createElement("span",{className:"ps-share-suggestion-name"},_.displayName||_.subject),_.email?a.createElement("span",{className:"ps-share-suggestion-email"},_.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),Te==="access"&&V?a.createElement("div",{className:"ps-manage-apply-bar is-footer"},a.createElement("span",{className:"ps-share-section-sub"},ae?"Unsaved access changes.":"No changes to apply."),a.createElement("button",{className:"ps-mini-button ps-manage-apply",disabled:F||!ae,onClick:Ce},"Apply")):null,G?a.createElement("div",{className:"ps-share-error"},G):null))}function wi({controller:t,mobile:e=!1,fullWidth:s=!1,showComposer:n=!0}){const i=X(t,P=>P.ui.themeId),r=rt(i),o=X(t,P=>{const H=P.sessions.activeSessionId,U=hn(P),re=s||e?U.totalWidth:U.leftWidth,he=Math.max(20,re-4);return{activeSessionId:H,activeHistory:H&&P.history.bySessionId.get(H)||null,activeOutbox:H&&P.outbox?.bySessionId?.[H]?P.outbox.bySessionId[H]:[],branding:P.branding,connection:P.connection,sessionsById:P.sessions.byId,sessionsFlat:P.sessions.flat,inspectorTab:P.ui.inspectorTab,activeSessionIsGroup:!!(H&&P.sessions.byId[H]?.isGroup),activeSessionStatus:H?String(P.sessions.byId[H]?.status||"").toLowerCase():"",focused:P.ui.focusRegion==="chat",scroll:P.ui.scroll.chat,authPrincipal:P.auth?.principal||null,contentWidth:he}},Oe),l=a.useMemo(()=>({branding:o.branding,connection:o.connection,auth:{principal:o.authPrincipal},sessions:{activeSessionId:o.activeSessionId,byId:o.sessionsById,flat:o.sessionsFlat},history:{bySessionId:o.activeSessionId&&o.activeHistory?new Map([[o.activeSessionId,o.activeHistory]]):new Map},outbox:{bySessionId:o.activeSessionId?{[o.activeSessionId]:o.activeOutbox}:{}},ui:{inspectorTab:o.inspectorTab}}),[o.activeHistory,o.activeSessionId,o.activeOutbox,o.authPrincipal,o.branding,o.connection,o.inspectorTab,o.sessionsById,o.sessionsFlat]),[c,u]=dc(),p=c??o.contentWidth,d=a.useMemo(()=>Rl(l,{width:p}),[l,p]),f=Ea(!!d.animateTitleRight),h=a.useMemo(()=>xa(d.titleRight,d.animateTitleRight?f:""),[f,d.animateTitleRight,d.titleRight]),[m,g]=a.useState(!1),S=!!(o.activeHistory?.hasOlderEvents&&Number(o.activeHistory?.loadedEventCount||0)>=fi),y=a.useMemo(()=>Gi(l,p,{tableMode:"sentinel"}),[l,p]),v=va(o.activeSessionStatus==="running"),E=a.useMemo(()=>ji(l,{spinnerFrame:v,maxWidth:p}),[l,v,p]),w=a.useMemo(()=>Wi(l,p,{tableMode:"sentinel"}),[l,p]),I=a.useMemo(()=>E.length>0?[...w,...E]:w,[w,E]),{access:b}=fS(t,o.activeSessionId,o.activeSessionIsGroup),M=X(t,mp,Oe),A=n&&!o.activeSessionIsGroup,O=!!o.sessionsById?.[o.activeSessionId]?.serviceKind,F=O||!!b&&b.canWrite===!1,L=A?a.createElement("div",{className:"ps-chat-composer"},F?a.createElement("div",{className:"ps-composer-readonly"},O?"⚗ Service session — runtime machinery. Its transcript is a read-only trace; it does not accept messages.":`You have view access to this session. Ask ${b.owner?.displayName||b.owner?.email||"the owner"} for write access to participate.`):a.createElement(vS,{controller:t,mobile:e,active:!0})):null,G=!!(o.activeSessionId&&o.sessionsById[o.activeSessionId]);return M&&!G?a.createElement(gt,{title:d.title,color:d.color,focused:o.focused,theme:r,className:"ps-chat-panel"},a.createElement("div",{className:"ps-empty-state ps-nav-error-state"},a.createElement("div",{className:"ps-nav-error-message"},M.message),M.retryable?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.setNavigationIntent(M.sessionId)},"Retry"):null)):a.createElement(mn,{controller:t,title:e?Ko(d.title,28):d.title,titleRight:e&&h?Ko(h,18):h,actions:null,color:d.color,focused:o.focused,lines:y,bottomStickyLines:I,scrollOffset:o.scroll,scrollMode:"bottom",paneKey:"chat",className:"is-wrapped",panelClassName:"ps-chat-panel",panelRef:u,bottomContent:L,topContent:S?a.createElement("div",{className:"ps-load-older-bar"},a.createElement("button",{type:"button",className:"ps-load-older-button",disabled:m,onClick:()=>{g(!0),t.handleCommand(C.EXPAND_HISTORY).catch(()=>{}).finally(()=>g(!1))}},m?"Loading older messages…":"↑ Load older messages")):null,structuredBlocks:!0,renderBody:null})}function mS({controller:t,onClose:e}){const s=X(t,g=>g.ui.themeId),n=rt(s),i=X(t,g=>{const S=g.files.selectedArtifactId||"",y=S.indexOf("/");return{sessionId:y>0?S.slice(0,y):null,filename:y>0?S.slice(y+1):"",canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},Oe),r=Sc(i.filename),o=X(t,g=>g.files.htmlViewMode||"rendered"),l=X(t,g=>!!g.files.htmlFitWidth),c=a.useCallback(g=>{t.dispatch({type:"files/htmlFitWidth",enabled:g})},[t]),u=a.useCallback(g=>{t.dispatch({type:"files/htmlViewMode",mode:g})},[t]),p=X(t,g=>Number(g.files.htmlZoom)||1),d=a.useCallback(g=>{t.dispatch({type:"files/htmlZoom",zoom:g})},[t]),f=a.useCallback(g=>{t.stepArtifactPreview(g).catch(()=>{})},[t]),h=a.useCallback(g=>{if(!(g.metaKey||g.ctrlKey||g.altKey)){if(g.key==="ArrowLeft"||g.key==="["){g.preventDefault(),f(-1);return}if(g.key==="ArrowRight"||g.key==="]"){g.preventDefault(),f(1);return}g.key==="Escape"&&(g.preventDefault(),e())}},[e,f]),m=fn(i.sessionId,i.filename);return a.createElement("section",{className:"ps-artifact-pane",onKeyDown:h,tabIndex:-1,role:"region","aria-label":`Artifact: ${i.filename||"none"}`},a.createElement("header",{className:"ps-artifact-pane-bar"},r.kind==="page"?a.createElement(Tc,{mode:o,setMode:u}):null,r.kind==="page"&&o==="rendered"?a.createElement(Cc,{fitWidth:l,setFitWidth:c}):null,r.kind==="page"&&o==="rendered"?a.createElement(an,{zoom:p,setZoom:d}):null,a.createElement("span",{className:"ps-artifact-pane-heading"},a.createElement("span",{className:"ps-artifact-pane-name",title:i.filename},bc(i.filename)||"Artifact"),a.createElement("span",{className:"ps-artifact-pane-type"},r.type)),a.createElement("span",{className:"ps-artifact-pane-actions"},a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",disabled:!i.canPrev,onClick:()=>f(-1),title:"Previous artifact (←)","aria-label":"Previous artifact"},"‹"),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",disabled:!i.canNext,onClick:()=>f(1),title:"Next artifact (→)","aria-label":"Next artifact"},"›"),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>{m&&(sn(m),t.dispatch({type:"ui/status",text:lc}))},disabled:!m,title:"Copy a link that reopens this artifact","aria-label":"Copy link"},"🔗"),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>t.handleCommand(C.DOWNLOAD_SELECTED_FILE).catch(()=>{}),title:"Download","aria-label":"Download"},a.createElement(Fc)),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn is-close",onClick:e,title:"Close (Esc)","aria-label":"Close artifact"},"✕"))),a.createElement("div",{className:"ps-artifact-pane-body"},a.createElement(gn,{controller:t,focused:!1,previewOnly:!0,chromeless:!0,theme:n})))}function gS({controller:t,visible:e=!0}){const[s,n]=a.useState(!1),i=a.useCallback(()=>n(r=>!r),[]);return a.useEffect(()=>{e||n(!1)},[e]),a.createElement("div",{className:`ps-mobile-canvas-layer${s?" is-maximized":""}${e?"":" is-hidden"}`,...e?{}:{inert:!0,"aria-hidden":"true"}},a.createElement(Bc,{controller:t,mobile:!0,visible:e,focusOnPromote:!0,maximized:s,onToggleMaximized:i}))}function yS({controller:t}){const e=X(t,o=>{const l=o.files.selectedArtifactId||"";return{filename:l?l.slice(l.indexOf("/")+1):"",origin:o.files.previewOrigin||null,canPrev:t.canStepArtifactPreview(-1),canNext:t.canStepArtifactPreview(1)}},Oe),s=!!cr(e.filename)||ur(e.filename),[n,i]=a.useState(!1);a.useEffect(()=>{i(!1)},[e.filename]);const r=a.useCallback(o=>{t.stepArtifactPreview(o).catch(()=>{})},[t]);return a.createElement("div",{className:"ps-artifact-overlay"},a.createElement("header",{className:"ps-artifact-overlay-bar"},a.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",onClick:()=>t.closeArtifactPreview().catch(()=>{}),"aria-label":e.origin==="chat"?"Close, back to chat":"Close, back to artifacts"},"✕"),a.createElement("span",{className:"ps-artifact-overlay-title"},e.filename||"Artifact"),s?a.createElement("button",{type:"button",className:`ps-artifact-overlay-btn${n?" is-active":""}`,onClick:()=>i(o=>!o),"aria-label":n?"Wrap lines":"Show full lines",title:n?"Wrap to screen width":"Full line width (scroll horizontally)"},n?"⇥":"↔"):null,a.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canPrev,onClick:()=>r(-1),"aria-label":"Previous artifact"},"‹"),a.createElement("button",{type:"button",className:"ps-artifact-overlay-btn",disabled:!e.canNext,onClick:()=>r(1),"aria-label":"Next artifact"},"›")),a.createElement("div",{className:`ps-artifact-overlay-body${n?" is-content-width":""}`},a.createElement(gn,{controller:t,focused:!0,mobile:!0,previewOnly:!0,nativeScroll:!0})))}function SS({controller:t,layout:e="split"}){const s=a.createElement(Si,{controller:t,panelClassName:"ps-mobile-session-pane"});return e==="chat"?a.createElement("div",{className:"ps-mobile-workspace is-chat-only"},a.createElement("div",{className:"ps-mobile-chat-pane"},a.createElement(wi,{controller:t,mobile:!0,fullWidth:!0}))):e==="sessions"?a.createElement("div",{className:"ps-mobile-workspace is-sessions-only"},a.createElement(Si,{controller:t,panelClassName:"ps-mobile-session-pane",showDetailBox:!0})):a.createElement("div",{className:"ps-mobile-workspace"},s,a.createElement("div",{className:"ps-mobile-chat-pane"},a.createElement(wi,{controller:t,mobile:!0,fullWidth:!0})))}function Dc(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:16,height:16,"aria-hidden":"true"},a.createElement("rect",{x:2.5,y:3.5,width:15,height:11,rx:1.5,...t}),a.createElement("path",{d:"M5.5 11.5l3-3.5 2.5 2.5 3.5-4",...t}),a.createElement("path",{d:"M7 17.5h6M10 14.5v3",...t}))}function da(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:20,height:20,"aria-hidden":"true"},a.createElement("path",{d:"M6.2 8.6a3.8 3.8 0 0 1 7.6 0v2.9a3.8 3.8 0 0 1-7.6 0z",...t}),a.createElement("path",{d:"M6.2 10.3h7.6",...t}),a.createElement("path",{d:"M7.6 6.5a2.4 2.4 0 0 1 4.8 0",...t}),a.createElement("path",{d:"M8 4.4 6.9 2.9M12 4.4l1.1-1.5",...t}),a.createElement("path",{d:"M6.3 8.6 3.8 7.4M6.2 10.6H3.6M6.3 12.6 3.8 13.9",...t}),a.createElement("path",{d:"M13.7 8.6 16.2 7.4M13.8 10.6h2.6M13.7 12.6l2.5 1.3",...t}))}function pa({mark:t}){if(t!=="canvas"&&t!=="unseen")return null;const e=t==="unseen",s={fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("span",{className:`ps-session-canvas-mark${e?" is-unseen":""}`,title:e?"Canvas updated since you last viewed it":"This session has a canvas","aria-label":e?"Canvas updated":"Has a canvas",role:"img"},a.createElement("svg",{viewBox:"0 0 16 16",width:12,height:12,"aria-hidden":"true"},a.createElement("rect",{x:1.6,y:2.6,width:12.8,height:9.2,rx:1.4,...s}),a.createElement("path",{d:"M6 14.4h4",...s}),e?a.createElement("circle",{cx:12.4,cy:4.6,r:2.4,fill:"currentColor",stroke:"none"}):null))}function fa(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:14,height:14,"aria-hidden":"true"},a.createElement("path",{d:"M8.5 11.5l3-3",...t}),a.createElement("path",{d:"M7 13l-1.8 1.8a2.8 2.8 0 01-4-4l3-3a2.8 2.8 0 014 0",...t}),a.createElement("path",{d:"M13 7l1.8-1.8a2.8 2.8 0 014 4l-3 3a2.8 2.8 0 01-4 0",...t}))}function bS({controller:t,sessionId:e,slot:s,onClose:n}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(!1),[p,d]=a.useState(""),[f,h]=a.useState(""),m=t.transport,g=`${window.location.origin}/?session=${encodeURIComponent(e)}&view=canvas&slot=${s}&max=1`,S=(w,I)=>{const b=Zs(w,pt);if(b.length<=1)return a.createElement("div",{className:"ps-canvas-share-row"},a.createElement("code",{className:"ps-canvas-share-url"},w),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>v(I,w)},f===I?"Copied":"Copy"));const M=er(b);return a.createElement("div",{className:"ps-canvas-share-row"},a.createElement("textarea",{className:"ps-link-input",readOnly:!0,rows:b.length,value:M,onFocus:A=>A.currentTarget.select()}),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>v(I,M)},f===I?"Copied":"Copy"))},y=a.useCallback(()=>{m.getCanvasShareLink?.(e,s).then(w=>r(w||{exists:!1})).catch(w=>{r({exists:!1}),d(w?.message||String(w))})},[m,e,s]);a.useEffect(()=>{y()},[y]);const v=(w,I)=>{navigator.clipboard?.writeText(I).then(()=>{h(w),window.setTimeout(()=>h(""),1500)}).catch(()=>d("Could not reach the clipboard — copy the link manually."))},x=w=>{u(!0),d(""),m.resetCanvasShareLink(e,s).then(({token:I})=>{l(`${window.location.origin}/?canvasShare=${encodeURIComponent(I)}`),r({exists:!0})}).catch(I=>d(I?.message||String(I))).finally(()=>u(!1))},E=()=>{u(!0),d(""),m.removeCanvasShareLink(e,s).then(()=>{l(null),r({exists:!1})}).catch(w=>d(w?.message||String(w))).finally(()=>u(!1))};return a.createElement("div",{className:"ps-canvas-share-overlay",onClick:n},a.createElement("div",{className:"ps-canvas-share-dialog",onClick:w=>w.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-canvas-share-section"},a.createElement("div",{className:"ps-canvas-share-head"},"Anyone with session access"),a.createElement("div",{className:"ps-canvas-share-sub"},"Opens the portal signed in, canvas full screen. Session visibility rules apply."),S(g,"session")),a.createElement("div",{className:"ps-canvas-share-section"},a.createElement("div",{className:"ps-canvas-share-head"},"Anyone with the link"),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."),i===null?a.createElement("div",{className:"ps-canvas-share-sub"},"Checking…"):o?a.createElement(a.Fragment,null,S(o,"public"),a.createElement("div",{className:"ps-canvas-share-sub is-warn"},"Copy it now — the link is shown only this once.")):i.exists?a.createElement("div",{className:"ps-canvas-share-sub"},`A link exists${i.createdAt?` (created ${new Date(i.createdAt).toLocaleString()})`:""}. For safety it cannot be re-shown — Reset to get a new one.`):a.createElement("div",{className:"ps-canvas-share-sub"},"No public link yet."),a.createElement("div",{className:"ps-canvas-share-actions"},a.createElement("button",{type:"button",className:"ps-mini-button",disabled:c,onClick:()=>x(i?.exists)},i?.exists?"Reset link":"Create link"),i?.exists?a.createElement("button",{type:"button",className:"ps-mini-button",disabled:c,onClick:E},"Remove link"):null)),p?a.createElement("div",{className:"ps-canvas-share-error"},p):null))}function Xn({controller:t,view:e,compact:s=!1}){const n=Array.isArray(e.slots)?e.slots:[];if(n.length<=1)return null;const i=n.map(c=>c.slot),r=Math.max(0,i.indexOf(e.slot)),o=c=>{const u=i[(r+c+i.length)%i.length];t.dispatch({type:"ui/canvasSlot",slot:u})},l=c=>(c.name?c.name:`canvas ${c.slot}`)+(c.unseen?" •":"");return a.createElement("span",{className:`ps-canvas-slot-controls${s?" is-compact":""}`},a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>o(-1),title:"Previous canvas","aria-label":"Previous canvas"},"‹"),a.createElement("select",{className:"ps-canvas-slot-select",value:e.slot,onChange:c=>t.dispatch({type:"ui/canvasSlot",slot:Number(c.target.value)}),"aria-label":"Choose canvas",title:"Choose canvas"},n.map(c=>a.createElement("option",{key:c.slot,value:c.slot},l(c)))),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>o(1),title:"Next canvas","aria-label":"Next canvas"},"›"))}function ha(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:15,height:15,"aria-hidden":"true"},a.createElement("rect",{x:2.2,y:3.4,width:3.6,height:13.2,rx:1,...t}),a.createElement("rect",{x:8.2,y:3.4,width:9.6,height:13.2,rx:1,...t}))}function ma(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.9,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:13,height:13,"aria-hidden":"true"},a.createElement("path",{d:"M8 3H3v5M12 3h5v5M12 17h5v-5M8 17H3v-5",...t}))}function ga(){const t={fill:"none",stroke:"currentColor",strokeWidth:1.9,strokeLinecap:"round",strokeLinejoin:"round"};return a.createElement("svg",{viewBox:"0 0 20 20",width:13,height:13,"aria-hidden":"true"},a.createElement("path",{d:"M3 8h5V3M17 8h-5V3M17 12h-5v5M3 12h5v5",...t}))}function wS({controller:t,sessionId:e,slot:s=1,latestRev:n,zoom:i,visible:r=!0,focusOnPromote:o=!1,dataRev:l=0,dataPayload:c=null,dataPatch:u=null}){const[p,d]=a.useState(null),[f,h]=a.useState(null),[m,g]=a.useState(null),[S,y]=a.useState(0),v=a.useRef({live:null,staging:null}),x=a.useRef({rev:0,used:!1}),E=a.useRef(null),w=a.useRef(null),I=Nc(E),b=a.useRef(null),M=a.useRef(i);M.current=i;const A=a.useRef(r);A.current=r,a.useEffect(()=>{if(!t||!e)return;const L=G=>{const P=w.current;if(!P||!G.source||G.source!==P.contentWindow)return;const H=G.data;!H||typeof H!="object"||H.type!=="canvas-action"||t.submitCanvasAction(e,H).then(U=>{U&&U.ok===!1&&typeof console<"u"&&console.warn(`canvas action rejected: ${U.reason}`)}).catch(()=>{})};return window.addEventListener("message",L),()=>window.removeEventListener("message",L)},[t,e]),a.useEffect(()=>{if(!t||!e||!n)return;let L=!1,G=null;return Mc(t,e,s<=1?"canvas.html":`canvas${s}.html`).then(P=>{if(L){URL.revokeObjectURL(P);return}v.current.staging&&v.current.staging!==v.current.live&&URL.revokeObjectURL(v.current.staging),v.current.staging=P,g(null),h({url:P,rev:n})}).catch(()=>{if(!L){if(x.current.rev!==n&&(x.current={rev:n,used:!1}),!x.current.used){x.current.used=!0,G=setTimeout(()=>{L||y(P=>P+1)},1500);return}g({rev:n})}}),()=>{L=!0,G&&clearTimeout(G)}},[t,e,s,n,S]),a.useEffect(()=>()=>{v.current.staging&&v.current.staging!==v.current.live&&URL.revokeObjectURL(v.current.staging),v.current.live&&URL.revokeObjectURL(v.current.live),v.current={live:null,staging:null},d(null),h(null),g(null)},[e]);const O=a.useCallback(L=>{if(!L||v.current.staging!==L.url)return;const G=v.current.live;v.current.live=L.url,v.current.staging=null,G&&G!==L.url&&URL.revokeObjectURL(G),d(L),h(H=>H&&H.url===L.url?null:H);const P=E.current;if(P){const H=P.getBoundingClientRect(),U=M.current||1;b.current={w:Math.round(H.width/U),h:Math.round(H.height/U)}}if(t&&e&&A.current&&t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,rev:L.rev}),o&&A.current)try{w.current?.focus({preventScroll:!0})}catch{}},[t,e,o]);a.useEffect(()=>{if(!(!p||!l||c===null)){try{w.current?.contentWindow?.postMessage({type:"canvas-data",data:c,dataRev:l},"*"),u&&w.current?.contentWindow?.postMessage({type:"canvas-patch",patch:u,dataRev:l},"*")}catch{}t&&e&&A.current&&t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,dataRev:l})}},[p,l,c,u,t,e]),a.useEffect(()=>{if(r&&p&&t&&e&&(t.dispatch({type:"canvas/viewed",sessionId:e,slot:s,rev:p.rev,...l?{dataRev:l}:{}}),o))try{w.current?.focus({preventScroll:!0})}catch{}},[r,p,t,e,o,l]),a.useEffect(()=>{if(!p||!r)return;const L=i||1,G=Math.round((I.width||0)/L),P=Math.round((I.height||0)/L);if(!G||!P)return;const H=b.current;if(H){if(!(H.w<220||H.h<170))return;const he=Math.abs(H.w-G),ce=Math.abs(H.h-P);if(he<=2&&ce<=2||he<=2&&ce/Math.max(1,H.h)<.15)return}const U=setTimeout(()=>{b.current={w:G,h:P},y(re=>re+1)},350);return()=>clearTimeout(U)},[I.width,I.height,i,p,r]);const F=i!==1&&I.width>0?{flex:"none",width:`${Math.max(1,Math.round(I.width/i))}px`,height:`${Math.max(1,Math.round(I.height/i))}px`,transform:`scale(${i})`,transformOrigin:"top left"}:void 0;return a.createElement("div",{ref:E,className:"ps-html-preview-host is-fitting"},[p,f].filter(Boolean).map(L=>a.createElement("iframe",{key:`canvas:${L.rev}:${L.url}`,ref:L===p?(G=>{w.current=G}):void 0,className:`ps-html-preview-frame${L===p?"":" is-staging"}`,style:F,src:L.url,title:"Session canvas",sandbox:"allow-scripts allow-popups allow-popups-to-escape-sandbox",allow:"autoplay *",referrerPolicy:"no-referrer",onLoad:L===f?()=>O(L):void 0})),m?a.createElement("div",{className:"ps-canvas-load-error"},a.createElement("span",null,p?`Couldn't load rev ${m.rev} — showing rev ${p.rev}.`:`Couldn't load rev ${m.rev}.`),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>{x.current={rev:0,used:!1},g(null),y(L=>L+1)}},"Retry")):null)}function Bc({controller:t,mobile:e=!1,visible:s=!0,focusOnPromote:n=!1,maximized:i=!1,onToggleMaximized:r=null}){const o=X(t,Ui,Oe),l=X(t,S=>Number(S.files.htmlZoom)||1),c=a.useCallback(S=>{t.dispatch({type:"files/htmlZoom",zoom:S})},[t]);a.useEffect(()=>{o.sessionId&&t.ensureCanvasSnapshot(o.sessionId).catch(()=>{})},[t,o.sessionId]);const u=X(t,S=>S?.ui?.canvasZen===!0),[p,d]=a.useState(!1),[f,h]=a.useState(null);a.useEffect(()=>{if(!i){h(null);return}let S=0;const y=()=>{const v=document.getElementById("ps-toolbar-canvas-slot");v?h(v):S=requestAnimationFrame(y)};return y(),()=>cancelAnimationFrame(S)},[i]),a.useCallback(()=>{t.dispatch({type:"ui/canvasOpen",open:!1,sessionId:o.sessionId,manual:!0})},[t,o.sessionId]);const m=e&&(o.exists||i),g=e?m?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(Xn,{controller:t,view:o,compact:!0}),o.exists?a.createElement("button",{type:"button",className:"ps-canvas-max-btn",onClick:()=>d(!0),title:"Share this canvas — copy a view link","aria-label":"Share canvas"},a.createElement(fa)):null,r?a.createElement("button",{type:"button",className:"ps-canvas-max-btn",onClick:r,title:i?"Back to the inset canvas":"Maximize — cover the whole screen","aria-label":i?"Restore canvas":"Maximize canvas"},a.createElement(i?ga:ma)):null):null:i?f?vi.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(Xn,{controller:t,view:o,compact:!0}),o.exists?a.createElement(an,{zoom:l,setZoom:c}):null,a.createElement("button",{type:"button",className:`ps-artifact-pane-btn${u?" is-active":""}`,onClick:()=>{t.dispatch({type:"ui/canvasMaximized",on:!1}),t.dispatch({type:"ui/canvasZen",on:!u})},title:u?"Leave zen — bring back sessions and panels":"Zen — chat rail + canvas only","aria-label":u?"Leave zen mode":"Zen mode"},a.createElement(ha)),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn ps-toolbar-canvas-restore",onClick:()=>t.dispatch({type:"ui/canvasMaximized",on:!1}),title:"Back to the workspace","aria-label":"Restore canvas"},a.createElement(ga))),f):null:a.createElement("header",{className:"ps-artifact-pane-bar"},a.createElement("span",{className:"ps-artifact-pane-heading"},a.createElement("span",{className:"ps-artifact-pane-name ps-canvas-pane-glyph",title:o.note||"Canvas"},a.createElement(Dc)),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(Xn,{controller:t,view:o})),a.createElement("span",{className:"ps-artifact-pane-actions"},o.exists?a.createElement(an,{zoom:l,setZoom:c}):null,o.exists?a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>d(!0),title:"Share this canvas — copy a view link","aria-label":"Share canvas"},a.createElement(fa)):null,a.createElement("button",{type:"button",className:`ps-artifact-pane-btn${u?" is-active":""}`,onClick:()=>t.dispatch({type:"ui/canvasZen"}),title:u?"Leave zen — bring back sessions and panels":"Zen — chat rail + canvas only","aria-label":u?"Leave zen mode":"Zen mode"},a.createElement(ha)),a.createElement("button",{type:"button",className:"ps-artifact-pane-btn",onClick:()=>t.dispatch({type:"ui/canvasMaximized",on:!0}),title:"Full screen — hide chat and sessions","aria-label":"Full screen canvas"},a.createElement(ma))));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(wS,{key:`slot:${o.slot}`,controller:t,sessionId:o.sessionId,slot:o.slot,latestRev:o.latestRev,zoom:l,visible:s,focusOnPromote:n,dataRev:o.latestDataRev,dataPayload:o.dataPayload,dataPatch:o.dataPatch}):a.createElement("div",{className:"ps-canvas-blank"},a.createElement("p",{className:"ps-canvas-blank-title"},"Nothing on the canvas yet."),a.createElement("p",null,"Ask the agent to draw — a dashboard, a chart, a diagram — or it will draw when it has something worth showing."))),p&&o.exists?a.createElement(bS,{controller:t,sessionId:o.sessionId,slot:o.slot,onClose:()=>d(!1)}):null)}function Hc({activeTab:t,controller:e}){const s=a.useMemo(()=>ir(e),[e]);return a.createElement("div",{className:"ps-tab-row ps-tab-row-icons"},s.map(n=>a.createElement(pe,{key:n,icon:zo[n]?a.createElement(zo[n]):"•",label:cg[n]||n,active:t===n,onClick:()=>{e.setFocus("inspector"),e.selectInspectorTab(n).catch(()=>{})}})))}function gn({controller:t,focused:e,mobile:s=!1,previewOnly:n=!1,nativeScroll:i=!1,chromeless:r=!1}){const o=X(t,P=>P.ui.themeId),l=rt(o),c=a.useRef(null),u=X(t,P=>{const H=P.sessions.activeSessionId,U=hn(P),re=s||P.files.fullscreen?P.ui.layout?.viewportWidth??120:U.rightWidth;return{activeSessionId:H,sessionsById:P.sessions.byId,sessionsFlat:P.sessions.flat,filesBySessionId:P.files.bySessionId,filesFilter:P.files.filter,selectedArtifactId:P.files.selectedArtifactId,markedIds:P.files.markedIds||[],previewOrigin:P.files.previewOrigin||null,focused:e,previewScroll:P.ui.scroll.filePreview,fullscreen:!!P.files.fullscreen,contentWidth:Math.max(20,re-4),canBrowserUpload:dg(t),canPathUpload:pg(t),canDeleteArtifacts:hg(t),canOpenLocally:mg(t)}},Oe),p=a.useMemo(()=>({sessions:{activeSessionId:u.activeSessionId,byId:u.sessionsById,flat:u.sessionsFlat},files:{bySessionId:u.filesBySessionId,selectedArtifactId:u.selectedArtifactId,filter:u.filesFilter,fullscreen:u.fullscreen},ui:{scroll:{filePreview:u.previewScroll}}}),[u.activeSessionId,u.filesBySessionId,u.filesFilter,u.fullscreen,u.previewScroll,u.selectedArtifactId,u.sessionsById,u.sessionsFlat]),d=a.useMemo(()=>Vi(p,{listWidth:Math.max(18,u.contentWidth-4),previewWidth:Math.max(18,u.contentWidth-4),showHints:!1}),[p,u.contentWidth]),f=a.useMemo(()=>It(p),[p]),h=f.length>0,m=a.useCallback(P=>{const H=Array.isArray(P)?P.filter(Boolean):[];H.length!==0&&t.uploadArtifactFiles(H).catch(()=>{})},[t]),g=a.useCallback(()=>{if(u.canBrowserUpload&&c.current){c.current.click();return}u.canPathUpload&&t.handleCommand(C.OPEN_ARTIFACT_UPLOAD).catch(()=>{})},[t,u.canBrowserUpload,u.canPathUpload]),S=a.useMemo(()=>new Set(u.markedIds||[]),[u.markedIds]),y=a.createElement(a.Fragment,null,S.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"},`${S.size} marked`),u.canDeleteArtifacts?a.createElement(pe,{icon:a.createElement(bi),label:`Delete ${S.size} marked`,onClick:()=>t.deleteMarkedArtifacts().catch(()=>{})}):null,a.createElement(pe,{icon:"✕",label:"Clear marks",onClick:()=>t.clearArtifactMarks()})):null,a.createElement("input",{ref:c,type:"file",className:"ps-hidden-file-input",multiple:!0,tabIndex:-1,"aria-hidden":"true",onChange:P=>{m(Array.from(P.currentTarget.files||[])),P.currentTarget.value=""}}),a.createElement(pe,{icon:a.createElement(Jy),label:"Upload",onClick:g,disabled:!u.canBrowserUpload&&!u.canPathUpload}),a.createElement(pe,{icon:a.createElement(Fc),label:"Download",onClick:()=>t.handleCommand(C.DOWNLOAD_SELECTED_FILE).catch(()=>{}),disabled:!h}),a.createElement(pe,{icon:"🔗",label:"Copy link to this artifact",onClick:()=>{const P=fn(d.selectedSessionId,d.selectedFilename);P&&(sn(P),t.dispatch({type:"ui/status",text:lc}))},disabled:!h||!d.selectedFilename}),u.canDeleteArtifacts?a.createElement(pe,{icon:a.createElement(bi),label:"Delete",onClick:()=>t.handleCommand(C.DELETE_SELECTED_FILE).catch(()=>{}),disabled:!h}):null,u.canOpenLocally?a.createElement(pe,{icon:"↗",label:"Open locally",onClick:()=>t.handleCommand(C.OPEN_SELECTED_FILE).catch(()=>{}),disabled:!h}):null,a.createElement(pe,{icon:a.createElement(hr),label:"Filter",onClick:()=>t.handleCommand(C.OPEN_FILES_FILTER).catch(()=>{})}),a.createElement(pe,{icon:a.createElement(u.fullscreen?Xy:Yy),label:u.fullscreen?"Exit fullscreen":"Fullscreen",onClick:()=>t.handleCommand(C.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})})),v=a.useRef(null);a.useEffect(()=>{const P=v.current;P&&typeof P.scrollIntoView=="function"&&P.scrollIntoView({block:"nearest"})},[d.selectedIndex,u.selectedArtifactId]);const x=f.length===0?De(d.listBodyLines||[]).map((P,H)=>a.createElement(Be,{key:`empty:${H}`,line:P,theme:l})):f.map((P,H)=>a.createElement("button",{key:P.id,type:"button",ref:H===d.selectedIndex?v:null,className:`ps-list-button${H===d.selectedIndex?" is-selected":""}`+(S.has(P.id)?" is-marked":""),onClick:U=>{if(t.setFocus("inspector"),U.metaKey||U.ctrlKey){t.toggleArtifactMark(P);return}if(U.shiftKey){t.markArtifactRange(P);return}t.clearArtifactMarks(),t.selectFileBrowserItem(P).then(()=>{s&&t.handleCommand(C.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{})}).catch(()=>{})}},a.createElement(Be,{line:De([d.listBodyLines?.[H]])[0],theme:l}))),E=!d.previewLoading&&!d.previewError,w=E&&ur(d.selectedFilename,d.previewContentType)&&!d.previewIsBinary&&!!d.previewContent,I=E&&(ar.test(String(d.previewContentType||""))||lr.test(String(d.selectedFilename||""))),b=E&&!d.previewIsBinary&&!w&&d.previewRenderMode!=="markdown"&&d.previewContent?cr(d.selectedFilename):null,M=n?"activity":null,A=i?null:"filePreview",O=E&&!d.previewIsBinary&&mc(d.selectedFilename,d.previewContentType)&&!!d.previewContent,L=E&&!d.previewIsBinary&&hc(d.selectedFilename,d.previewContentType)?a.createElement(vy,{controller:t,sessionId:d.selectedSessionId,filename:d.selectedFilename,contentType:d.previewContentType,sizeBytes:d.previewSizeBytes,theme:l,color:"cyan",focused:!1,title:null,chromeless:r}):O?a.createElement(Kn,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:A,scrollOffset:u.previewScroll,className:"ps-csv-preview",focusRegion:M},a.createElement(Vg,{content:d.previewContent,filename:d.selectedFilename})):I?a.createElement(ta,{title:null,color:"cyan",focused:!1,theme:l,filename:d.selectedFilename,contentType:d.previewContentType,sizeBytes:d.previewSizeBytes,source:d.previewSource,uploadedAt:d.previewUploadedAt,controller:t,sessionId:d.selectedSessionId}):b?a.createElement(Kn,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:A,scrollOffset:u.previewScroll,className:"ps-diff-preview",focusRegion:M},a.createElement("pre",{className:"ps-md-code-pre"},a.createElement("code",null,Zt(d.previewContent,b,l)))):w?a.createElement(Kn,{controller:t,title:null,color:"cyan",focused:!1,theme:l,paneKey:A,scrollOffset:u.previewScroll,className:"ps-diff-preview",focusRegion:M},a.createElement("pre",{className:"ps-md-code-pre is-diff"},a.createElement("code",null,dr(d.previewContent,l)))):d.previewRenderMode==="markdown"&&!d.previewLoading&&!d.previewError?a.createElement(yy,{controller:t,title:null,color:"cyan",focused:!1,scrollOffset:u.previewScroll,paneKey:A,theme:l,focusRegion:M,content:zg(d.previewContent||"")}):d.previewIsBinary&&!d.previewLoading&&!d.previewError?a.createElement(ta,{title:null,color:"cyan",focused:!1,theme:l,filename:d.selectedFilename,contentType:d.previewContentType,sizeBytes:d.previewSizeBytes,source:d.previewSource,uploadedAt:d.previewUploadedAt,controller:t,sessionId:d.selectedSessionId}):a.createElement(mn,{controller:t,title:null,color:"cyan",focused:!1,lines:d.previewLines,scrollOffset:u.previewScroll,scrollMode:"top",paneKey:A,focusRegion:M,className:"is-preview is-wrapped"}),G=u;return n?L:a.createElement(gt,{title:G.fullscreen?d.fullscreenTitle:s&&d.panelTitleMobile?d.panelTitleMobile:d.panelTitle,color:"magenta",focused:G.focused,actions:y,theme:l},a.createElement(Hc,{activeTab:"files",controller:t}),G.fullscreen?L:a.createElement("div",{className:"ps-files-grid is-list-only"},a.createElement("div",{className:"ps-action-list ps-files-list"},x)))}function ds({controller:t,mobile:e=!1,panelClassName:s="",extraActions:n=null}){const i=X(t,S=>{const y=hn(S),v=S.ui.inspectorTab,x=e?S.ui.layout?.viewportWidth??120:y.rightWidth;return{inspectorTab:v,statsViewMode:S.ui.statsViewMode,adminWorkers:S.admin?.workers,nodeMapSelectedNode:S.ui.nodeMapSelectedNode,activeSessionId:S.sessions.activeSessionId,sessionsById:S.sessions.byId,sessionsFlat:S.sessions.flat,historyBySessionId:S.history.bySessionId,sessionStats:S.sessionStats,fleetStats:S.fleetStats,connection:S.connection,orchestrationBySessionId:S.orchestration.bySessionId,executionHistoryBySessionId:S.executionHistory?.bySessionId||{},executionHistoryFormat:S.executionHistory?.format||"pretty",logs:S.logs,files:S.files,focused:S.ui.focusRegion==="inspector",scroll:S.ui.scroll.inspector,followBottom:S.ui.followBottom?.inspector!==!1,logsTailing:S.logs.tailing,filesFullscreen:!!S.files.fullscreen,contentWidth:Tg(x,v,e)}},Oe),r=a.useMemo(()=>({sessions:{activeSessionId:i.activeSessionId,byId:i.sessionsById,flat:i.sessionsFlat},history:{bySessionId:i.historyBySessionId},sessionStats:i.sessionStats,fleetStats:i.fleetStats,connection:i.connection,admin:{workers:i.adminWorkers},ui:{inspectorTab:i.inspectorTab,statsViewMode:i.statsViewMode,nodeMapSelectedNode:i.nodeMapSelectedNode,scroll:{inspector:i.scroll}},logs:i.logs,files:i.files,orchestration:{bySessionId:i.orchestrationBySessionId},executionHistory:{bySessionId:i.executionHistoryBySessionId,format:i.executionHistoryFormat}}),[i.activeSessionId,i.adminWorkers,i.connection,i.executionHistoryBySessionId,i.executionHistoryFormat,i.fleetStats,i.nodeMapSelectedNode,i.files,i.historyBySessionId,i.inspectorTab,i.sessionStats,i.statsViewMode,i.logs,i.orchestrationBySessionId,i.scroll,i.sessionsById,i.sessionsFlat]),[o,l]=dc(),c=o??i.contentWidth,u=a.useMemo(()=>mt(r,{width:c}),[r,c]),p=a.useMemo(()=>{const S=i.activeSessionId&&i.historyBySessionId?.get(i.activeSessionId)||null,y=new Map;for(const v of S?.events||[]){if(v?.eventType!=="session.turn_completed")continue;const x=Number(v?.data?.turnIndex??v?.data?.iteration);Number.isFinite(x)&&y.set(x,v)}return y},[i.activeSessionId,i.historyBySessionId]),d=a.useCallback((S,y)=>a.createElement(Ly,{lines:S,theme:y,completionByTurn:p}),[p]),f=a.useCallback((S,y)=>a.createElement(_y,{lines:S,theme:y,controller:t}),[t]);a.useEffect(()=>{if(i.inspectorTab!=="nodes")return;t.ensureInspectorData("nodes");const S=window.setInterval(()=>{t.ensureInspectorData("nodes")},1e4);return()=>window.clearInterval(S)},[t,i.inspectorTab]);const h=a.useRef(null);if(a.useEffect(()=>{if(e)return h.current=requestAnimationFrame(()=>{try{const S=document.querySelector(".ps-mobile-pane-fill .ps-inspector-pane .ps-scroll-panel"),y=S?S.querySelector(".ps-line"):null;if(!S||!y)return;const v=window.getComputedStyle(y),x=document.createElement("span");x.style.cssText="position:absolute;visibility:hidden;white-space:pre;",x.style.fontFamily=v.fontFamily,x.style.fontSize=v.fontSize,x.style.fontWeight=v.fontWeight,x.style.letterSpacing=v.letterSpacing,x.textContent="0".repeat(100),y.parentElement.appendChild(x);const E=x.getBoundingClientRect().width/100||8;x.remove();const w=window.getComputedStyle(S),I=S.clientWidth-(parseFloat(w.paddingLeft)||0)-(parseFloat(w.paddingRight)||0);if(!(I>50))return;const M=Math.floor(I/E)+6,A=t.getState().ui.layout?.viewportWidth??120;if(Math.abs(M-A)<=2)return;t.dispatch({type:"ui/viewport",width:M,height:null})}catch{}}),()=>{h.current&&cancelAnimationFrame(h.current)}},[t,e,i.inspectorTab,i.activeSessionId]),i.inspectorTab==="files"&&!u.disabled)return a.createElement(gn,{controller:t,focused:i.focused,mobile:e});const m=[];if(i.inspectorTab==="logs")m.push(a.createElement(pe,{key:"tail",icon:i.logsTailing?"■":"⇣",label:i.logsTailing?"Stop tailing":"Tail (follow)",active:i.logsTailing,onClick:()=>t.handleCommand(C.TOGGLE_LOG_TAIL).catch(()=>{})})),m.push(a.createElement(pe,{key:"filter",icon:a.createElement(hr),label:"Filter",onClick:()=>t.handleCommand(C.OPEN_LOG_FILTER).catch(()=>{})}));else if(i.inspectorTab==="history")m.push(a.createElement(pe,{key:"refresh",icon:"↻",label:"Refresh",onClick:()=>t.handleCommand(C.REFRESH_EXECUTION_HISTORY).catch(()=>{})})),m.push(a.createElement(pe,{key:"save",icon:"⇩",label:"Export as artifact",onClick:()=>t.handleCommand(C.EXPORT_EXECUTION_HISTORY).catch(()=>{})}));else if(i.inspectorTab==="stats"){const S={session:"◉",fleet:"⬢",users:"⚇"};for(const y of["session","fleet","users"])m.push(a.createElement(pe,{key:`stats-view:${y}`,icon:S[y],label:`${y.replace(/^./u,v=>v.toUpperCase())} stats`,active:i.statsViewMode===y,onClick:()=>t.setStatsViewMode(y)}))}const g=n?m.concat(n):m;return a.createElement(mn,{controller:t,title:u.title,color:"magenta",focused:i.focused,actions:g,topContent:a.createElement(Hc,{activeTab:u.activeTab,controller:t}),stickyLines:u.stickyLines||[],lines:u.lines,renderBody:u.activeTab==="sequence"?d:u.activeTab==="nodes"?f:null,scrollOffset:i.scroll,scrollMode:u.activeTab==="sequence"||u.activeTab==="logs"&&i.followBottom?"bottom":"top",stickyBottom:u.activeTab==="logs",paneKey:"inspector",panelRef:l,className:u.activeTab==="history"||u.activeTab==="logs"?"is-wrapped":"is-preserve",panelClassName:`ps-inspector-pane${u.activeTab==="sequence"?" has-preserved-sticky":""}${s?` ${s}`:""}`.trim()})}function Qn({controller:t,panelClassName:e="",extraActions:s=null}){const n=X(t,l=>{const c=l.sessions.activeSessionId,u=hn(l),p=Math.max(3,u.activityPaneHeight-2);return{activeSessionId:c,activeSession:c&&l.sessions.byId[c]||null,activeHistory:c&&l.history.bySessionId.get(c)||null,focused:l.ui.focusRegion==="activity",scroll:l.ui.scroll.activity,followBottom:l.ui.followBottom?.activity!==!1,maxLines:p,nodeMapSelectedNode:l.ui.nodeMapSelectedNode,adminWorkers:l.admin?.workers,branding:l.branding,sessionsById:l.sessions.byId,sessionsFlat:l.sessions.flat,historyBySessionId:l.history.bySessionId,inspectorTab:l.ui.inspectorTab}},Oe),i=n.inspectorTab==="nodes",r=a.useMemo(()=>({branding:n.branding,admin:{workers:n.adminWorkers},ui:{nodeMapSelectedNode:n.nodeMapSelectedNode},sessions:{activeSessionId:n.activeSessionId,byId:i?n.sessionsById:n.activeSessionId&&n.activeSession?{[n.activeSessionId]:n.activeSession}:{},flat:n.sessionsFlat},history:{bySessionId:i?n.historyBySessionId:n.activeSessionId&&n.activeHistory?new Map([[n.activeSessionId,n.activeHistory]]):new Map}}),[i,n.activeHistory,n.activeSession,n.activeSessionId,n.adminWorkers,n.branding,n.historyBySessionId,n.nodeMapSelectedNode,n.sessionsById,n.sessionsFlat]),o=a.useMemo(()=>i?_l(r):Ki(r,n.maxLines),[i,r,n.maxLines]);return a.createElement(mn,{controller:t,title:o.title,color:"gray",focused:n.focused,actions:s,lines:o.lines,scrollOffset:n.scroll,scrollMode:n.followBottom?"bottom":"top",stickyBottom:!0,paneKey:"activity",className:"is-wrapped",panelClassName:`ps-activity-pane${e?` ${e}`:""}`})}const ya=Object.freeze([]);function Sa(t){const e=Number(t)||0;return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function vS({controller:t,mobile:e,active:s=!0,onAfterSend:n=null}){const i=X(t,b=>{const M=b.sessions.activeSessionId,A=M&&b.sessions.byId[M]||null,O=M&&b.outbox?.bySessionId?.[M]?b.outbox.bySessionId[M]:[];return{value:b.ui.prompt,cursor:b.ui.promptCursor,focused:b.ui.focusRegion==="prompt",modalOpen:!!b.ui.modal,answerMode:!!A?.pendingQuestion?.question,canStopTurn:Cl(A),hasOutbox:O.length>0,hasPendingOutbox:O.some(F=>F?.phase==="pending"),pendingCount:O.filter(F=>F?.phase==="pending").length,editingPending:b.ui.promptEdit?.sessionId===M,selectedOutboxPhase:b.ui.promptEdit?.sessionId===M&&b.ui.promptEdit?.phase||null,promptAttachments:b.ui.promptAttachments||ya}},Oe),r=a.useRef(null),o=a.useRef(null),[l,c]=a.useState(!1),u=a.useCallback(()=>{const b=r.current;b&&(b.style.height="0px",b.style.height=`${b.scrollHeight+2}px`)},[]);a.useLayoutEffect(()=>{u()},[u,i.value]),a.useEffect(()=>(window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)),[u]);const p=typeof t.transport?.supportsPromptImageAttachments=="function"&&t.transport.supportsPromptImageAttachments()&&typeof t.transport?.uploadArtifactFromFile=="function",d=p?i.promptAttachments.filter(b=>b?.kind==="image"):ya,f=a.useRef(new Map);a.useEffect(()=>{const b=f.current,M=new Set(d.map(A=>A.file));for(const[A,O]of b)M.has(A)||(URL.revokeObjectURL(O),b.delete(A));for(const A of d)if(A.file&&!b.has(A.file))try{b.set(A.file,URL.createObjectURL(A.file))}catch{}},[d]),a.useEffect(()=>()=>{for(const b of f.current.values())URL.revokeObjectURL(b);f.current.clear()},[]);const h=a.useCallback(b=>{if(!p)return 0;const M=Array.from(b||[]).filter(O=>O&&typeof O.type=="string"&&O.type.startsWith("image/"));return M.length===0?0:t.addPendingImageFiles(M)?.accepted||0},[t,p]);a.useEffect(()=>{const b=r.current;if(!(!s||i.modalOpen||!i.focused||!b)){if(document.activeElement!==b){if(e)return;try{b.focus({preventScroll:!0})}catch{b.focus()}}b.value===i.value&&b.selectionStart!==i.cursor&&b.setSelectionRange(i.cursor,i.cursor)}},[s,e,i.cursor,i.value,i.focused,i.modalOpen]);const m=a.useCallback(()=>{t.handleCommand(C.SEND_PROMPT).catch(()=>{}).finally(()=>{n?.()})},[t,n]),[g,S]=a.useState(!1),y=a.useCallback(()=>{S(!0),t.handleCommand(C.STOP_TURN).catch(()=>{}).finally(()=>S(!1))},[t]),v=a.useCallback(()=>{if(t.getState().ui.promptEdit){typeof t.cancelSelectedOutboxPrompt=="function"?t.cancelSelectedOutboxPrompt().catch(()=>{}):t.cancelSelectedPendingPrompt();return}typeof t.cancelLatestQueuedOutbox=="function"&&t.cancelLatestQueuedOutbox().catch(()=>{})},[t]),x=i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"⇪":i.hasOutbox?"+":"❯",E=i.selectedOutboxPhase==="queued",w=i.selectedOutboxPhase==="cancelling",I=E||w;return a.createElement("div",{className:`ps-prompt-shell${e?" is-mobile":""}${l?" is-drag-over":""}`,...p?{onDragOver:b=>{b.dataTransfer?.types?.includes?.("Files")&&(b.preventDefault(),c(!0))},onDragLeave:b=>{b.currentTarget.contains(b.relatedTarget)||c(!1)},onDrop:b=>{c(!1),b.dataTransfer?.files?.length&&(b.preventDefault(),h(b.dataTransfer.files))}}:{}},d.length>0?a.createElement("div",{className:"ps-prompt-attachments"},d.map((b,M)=>{const A=b.file?f.current.get(b.file):null;return a.createElement("div",{key:`attach:${M}:${b.filename}`,className:"ps-attach-chip",title:`${b.filename} · ${Sa(b.sizeBytes)}`},A?a.createElement("img",{className:"ps-attach-thumb",src:A,alt:b.filename}):a.createElement("div",{className:"ps-attach-thumb is-placeholder"},"🖼"),a.createElement("div",{className:"ps-attach-size"},Sa(b.sizeBytes)),a.createElement("button",{type:"button",className:"ps-attach-remove",title:`Remove ${b.filename}`,"aria-label":`Remove attachment ${b.filename}`,onClick:()=>t.removePendingImageAttachment(M)},"✕"))})):null,(()=>{const b=i.answerMode?"answer":w?"cancelling":E?"queued":i.editingPending?"pending":"you";return a.createElement("label",{className:`ps-prompt-label${b==="you"?" is-default":""}`},b)})(),a.createElement("textarea",{ref:r,className:"ps-prompt-input",rows:1,value:i.value,readOnly:I,placeholder:i.answerMode?"Type an answer and press Enter":i.editingPending?w?"Cancellation requested":E?"Queued message selected":"Edit the pending message, then send or cancel it":i.hasOutbox?"Type a message and press Enter to queue it behind the pending batch":"Type a message and press Enter",enterKeyHint:e?"enter":"send",onFocus:()=>t.setFocus("prompt"),onSelect:b=>t.setPromptCursor(b.currentTarget.selectionStart||0),onChange:b=>t.setPrompt(b.currentTarget.value,b.currentTarget.selectionStart||b.currentTarget.value.length),onPaste:p?b=>{const A=Array.from(b.clipboardData?.items||[]).filter(O=>O.kind==="file"&&O.type.startsWith("image/")).map(O=>O.getAsFile()).filter(Boolean);A.length>0&&h(A)>0&&b.preventDefault()}:void 0,onKeyDown:b=>{if(b.key==="Tab"&&!b.shiftKey&&t.acceptPromptReferenceAutocomplete()){b.preventDefault();return}if(b.key==="Escape"&&i.editingPending){if(b.preventDefault(),I){t.exitPendingPromptEdit({restoreDraft:!0});return}v();return}b.key==="Enter"&&!b.shiftKey&&!b.metaKey&&!e&&(b.preventDefault(),m())}}),a.createElement("div",{className:"ps-prompt-actions"},p?a.createElement(a.Fragment,null,a.createElement("input",{ref:o,type:"file",accept:"image/*",multiple:!0,className:"ps-hidden-file-input","aria-hidden":!0,tabIndex:-1,onChange:b=>{h(b.currentTarget.files),b.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:b=>b.preventDefault(),onClick:()=>o.current?.click()},"📎")):null,i.editingPending&&!w?a.createElement("button",{type:"button",className:"ps-mini-button",title:E?"Delete selected queued prompt":"Cancel selected pending prompt","aria-label":E?"Delete selected queued prompt":"Cancel selected pending prompt",onPointerDown:b=>b.preventDefault(),onClick:v},E?"Delete":"Cancel"):null,i.canStopTurn||g?a.createElement("button",{type:"button",className:`ps-stop-button${g?" is-stopping":""}`,title:"Stop the current turn (the session stays alive and returns to idle)","aria-label":"Stop the current turn",disabled:g,onPointerDown:b=>b.preventDefault(),onClick:y},"■"):null,a.createElement("button",{type:"button",className:`ps-send-button${e?" is-inline":""}`,title:i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"Send all queued prompts":i.hasOutbox?"Queue prompt behind the pending batch":"Send prompt","aria-label":i.editingPending||i.hasPendingOutbox&&!i.value.trim()?"Send queued prompts":i.hasOutbox?"Queue prompt":"Send prompt",onPointerDown:b=>b.preventDefault(),onClick:m},x)))}const ES=1e3;function pe({icon:t,label:e,onClick:s,disabled:n=!1,active:i=!1,className:r="ps-toolbar-button"}){const[o,l]=a.useState(null),c=a.useRef(null),u=a.useRef(null),p=a.useRef(null),d=a.useRef(!1);a.useLayoutEffect(()=>{if(!o||!u.current||typeof window>"u")return;const b=u.current.offsetWidth/2,M=6,A=Math.max(b+M,Math.min(o.x,window.innerWidth-b-M));u.current.style.left=`${A}px`},[o]);const f=(b=!1)=>{const M=c.current;if(!M||typeof window>"u")return;const A=M.getBoundingClientRect(),O=b?A.top-44<0:A.bottom+44<window.innerHeight;l({x:A.left+A.width/2,y:O?A.bottom+6:A.top-6,placement:O?"below":"above"})},h=a.useRef(null),m=a.useRef(null),g=b=>{b.pointerType==="mouse"&&(clearTimeout(p.current),clearTimeout(h.current),p.current=setTimeout(f,ES))},S=b=>{b.pointerType==="mouse"&&(clearTimeout(p.current),clearTimeout(h.current),l(null))},y=b=>{b.pointerType!=="mouse"&&(d.current=!1,m.current={x:b.clientX,y:b.clientY},clearTimeout(p.current),clearTimeout(h.current),p.current=setTimeout(()=>{d.current=!0,f(!0)},450))},v=b=>{if(b.pointerType==="mouse"||!m.current)return;const M=b.clientX-m.current.x,A=b.clientY-m.current.y;M*M+A*A>100&&(m.current=null,clearTimeout(p.current),l(null))},x=b=>{b.pointerType!=="mouse"&&(m.current=null,clearTimeout(p.current),d.current?(clearTimeout(h.current),h.current=setTimeout(()=>l(null),3e3),setTimeout(()=>{d.current=!1},250)):l(null))};a.useEffect(()=>()=>{clearTimeout(p.current),clearTimeout(h.current)},[]);const E=b=>{if(d.current){d.current=!1,b.preventDefault?.();return}n||s?.(b)},w=b=>{b.preventDefault?.()},I=o&&typeof document<"u"&&document.body?vi.createPortal(a.createElement("span",{ref:u,className:`ps-icon-tooltip is-${o.placement}`,role:"tooltip",style:{left:`${o.x}px`,top:`${o.y}px`}},e),document.body):null;return a.createElement("button",{ref:c,type:"button",className:`${r} ps-icon-button${i?" is-active":""}`,onClick:E,disabled:n,"aria-label":e,onPointerEnter:g,onPointerLeave:S,onPointerDown:y,onPointerMove:v,onPointerUp:x,onPointerCancel:x,onContextMenu:w},a.createElement("span",{className:"ps-icon-button-glyph","aria-hidden":"true"},t),I)}function xS({controller:t,mobile:e,canvasPaneOpen:s=!1,onToggleCanvasPane:n=null,mobilePane:i="workspace",onSelectMobilePane:r=null,mobileMainLayout:o="split"}){const[l,c]=a.useState(null);a.useEffect(()=>{typeof document>"u"||c(e?null:document.getElementById("ps-header-toolbar-slot"))},[e]);const u=X(t,w=>!!w.admin?.visible),p=X(t,Ui,Oe),d=X(t,w=>w?.ui?.diagnosticsOpen===!0),f=X(t,w=>w?.ui?.canvasMaximized===!0),h=X(t,w=>!!(w?.files?.paneOpen&&w?.files?.selectedArtifactId)),m=[{key:"new",icon:a.createElement(Ky),label:"New session — choose model and agent",onClick:()=>t.handleCommand(C.OPEN_MODEL_PICKER).catch(()=>{})},{key:"filter",icon:a.createElement(hr),label:"Filter sessions",onClick:()=>t.handleCommand(C.OPEN_SESSION_FILTER).catch(()=>{})},{key:"theme",icon:a.createElement(Vy),label:"Theme",onClick:()=>t.handleCommand(C.OPEN_THEME_PICKER).catch(()=>{})},{key:"canvas",icon:a.createElement(Dc),label:(e?s:p.mode==="canvas"&&!h)?"Hide the canvas":"Show canvas",onClick:()=>{if(e){n&&n();return}t.dispatch({type:"ui/canvasOpen",open:p.mode!=="canvas",sessionId:p.sessionId,manual:!0})},active:e?s:p.mode==="canvas"&&!h,badge:e?p.exists&&(p.latestRev>(p.lastViewedRev||0)||(p.latestDataRev||0)>(p.lastViewedDataRev||0))&&!s:p.unseen,loadedDot:p.exists},...e?[]:[{key:"diagnostics",icon:a.createElement(da),label:d?"Hide diagnostics":"Show diagnostics (inspector and activity)",onClick:()=>t.dispatch({type:"ui/diagnosticsOpen"}),active:d}],...e?[]:[{key:"admin",icon:a.createElement(Qy),label:u?"Close admin console":"Admin console",onClick:()=>t.handleCommand(u?C.CLOSE_ADMIN_CONSOLE:C.OPEN_ADMIN_CONSOLE).catch(()=>{}),active:u}]],g=w=>{const I=a.createElement(pe,{key:w.badge?void 0:w.key,icon:w.icon,label:w.label,onClick:w.onClick,disabled:!!w.disabled,active:!!w.active});return w.badge||w.loadedDot?a.createElement("span",{key:w.key,className:"ps-canvas-toggle"},I,w.loadedDot?a.createElement("span",{className:"ps-canvas-loaded-dot","aria-hidden":"true"}):null,w.badge?a.createElement("span",{className:"ps-canvas-badge","aria-hidden":"true"}):null):I};if(e){const w={split:"Main — sessions and chat (tap for chat only)",chat:"Main — chat only (tap for sessions only)",sessions:"Main — sessions only (tap for both)"},I=i==="inspector"||i==="activity",b=i==="inspector"?"activity":"inspector",M=[{id:"workspace",icon:tS,label:w[o]||w.split,focus:"chat"},{id:b,icon:da,active:I,label:I?i==="inspector"?"Diagnostics — inspector (tap for activity)":"Diagnostics — activity (tap for inspector)":"Diagnostics — inspector and activity",focus:b}];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"},m.map(g)),a.createElement("div",{className:"ps-toolbar-row-actions is-panes"},M.map(A=>a.createElement(pe,{key:A.id==="workspace"?"workspace":"diagnostics",icon:a.createElement(A.icon),label:A.label,active:A.active??i===A.id,onClick:()=>{r&&r(A.id,A.focus)}})))))}const S=new Set(["diagnostics","admin"]),y=w=>!f||w.key==="canvas"?w:{...w,onClick:(...I)=>(t.dispatch({type:"ui/canvasMaximized",on:!1}),w.onClick?.(...I))},v=m.filter(w=>!S.has(w.key)).map(y),x=m.filter(w=>S.has(w.key)).map(y),E=a.createElement("div",{className:"ps-toolbar"},a.createElement("div",{className:"ps-toolbar-side is-left"},f?v.map(g):null),a.createElement("div",{className:"ps-toolbar-actions"},f?null:v.map(g)),a.createElement("div",{className:"ps-toolbar-side is-right"},a.createElement("span",{className:"ps-toolbar-meta-slot",id:"ps-toolbar-meta-slot"}),f?a.createElement("span",{className:"ps-toolbar-canvas-slot",id:"ps-toolbar-canvas-slot"}):null,f?a.createElement("span",{className:"ps-toolbar-divider","aria-hidden":"true"}):null,x.length?a.createElement("div",{className:"ps-toolbar-actions is-tools"},x.map(g)):null,a.createElement("span",{className:"ps-toolbar-signout-slot",id:"ps-toolbar-signout-slot"})));return l?vi.createPortal(E,l):E}function is(t){try{t.currentTarget?.setPointerCapture?.(t.pointerId)}catch{}}function IS({controller:t,paneAdjust:e=0}){const s=a.useRef(null),[n,i]=a.useState(!1);return a.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")};let o=0,l=0;const c=()=>{o=0;const p=s.current;if(!p)return;const d=Math.round((l-p.startX)/ic),f=d-p.appliedCells;f&&(t.adjustPaneSplit(f),p.appliedCells=d)},u=p=>{s.current&&(l=p.clientX,!o&&(o=requestAnimationFrame(c)))};return window.addEventListener("pointermove",u),window.addEventListener("pointerup",r),window.addEventListener("pointercancel",r),()=>{o&&(cancelAnimationFrame(o),o=0),window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",r),window.removeEventListener("pointercancel",r),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),a.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector column. Double-click to reset.","aria-label":"Resize inspector column",onPointerDown:r=>{r.button===0&&(r.preventDefault(),is(r),s.current={startX:r.clientX,appliedCells:0},i(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{e&&t.adjustPaneSplit(-e)},onKeyDown:r=>{if(r.key==="ArrowLeft"){r.preventDefault(),t.handleCommand(C.GROW_RIGHT_PANE).catch(()=>{});return}r.key==="ArrowRight"&&(r.preventDefault(),t.handleCommand(C.GROW_LEFT_PANE).catch(()=>{}))}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function kS({controller:t,portalSessionColumnAdjust:e=0}){const s=a.useRef(null),[n,i]=a.useState(!1);return a.useEffect(()=>{if(!n)return;const r=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-x")},o=l=>{const c=s.current;if(!c)return;const u=hi(c.startAdjust+(l.clientX-c.startX),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:u})};return window.addEventListener("pointermove",o),window.addEventListener("pointerup",r),window.addEventListener("pointercancel",r),()=>{window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",r),window.removeEventListener("pointercancel",r),document.body.classList.remove("is-resizing-pane-x")}},[t,n]),a.createElement("button",{type:"button",className:`ps-column-resizer${n?" is-dragging":""}`,title:"Drag to resize the sessions and chat columns. Double-click to reset.","aria-label":"Resize sessions and chat columns",onPointerDown:r=>{if(r.button!==0)return;r.preventDefault(),is(r);const o=r.currentTarget.closest(".ps-workspace-main-grid"),l=mi(o?.getBoundingClientRect?.().width);s.current={startX:r.clientX,startAdjust:Number(e)||0,minAdjust:l.minAdjust,maxAdjust:l.maxAdjust},i(!0),document.body.classList.add("is-resizing-pane-x")},onDoubleClick:()=>{t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:0})},onKeyDown:r=>{const o=r.currentTarget.closest(".ps-workspace-main-grid"),l=mi(o?.getBoundingClientRect?.().width),c=u=>{const p=hi((Number(e)||0)+u,l.minAdjust,l.maxAdjust);t.dispatch({type:"ui/portalSessionColumnAdjust",portalSessionColumnAdjust:p})};if(r.key==="ArrowLeft"){r.preventDefault(),c(-24);return}r.key==="ArrowRight"&&(r.preventDefault(),c(24))}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function AS({controller:t,canvasPaneAdjust:e=0,diagnosticsPaneAdjust:s=0}){const n=a.useRef(null),[i,r]=a.useState(!1),o=(c,u)=>({canvas:rr+(Number(c)||0),diag:or+(Number(u)||0)}),l=(c,u)=>{const p=o(c,u);if(p.canvas<Os||p.diag<Os){t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:0}),t.dispatch(p.canvas<Os?{type:"ui/canvasOpen",open:!1,manual:!0}:{type:"ui/diagnosticsOpen",open:!1});return}t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:c}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:u})};return a.useEffect(()=>{if(!i)return;const c=p=>{const d=n.current;if(!d)return;const f=p.clientX-d.startX;t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:d.startCanvas+f}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:d.startDiag-f})},u=()=>{const p=n.current;if(n.current=null,r(!1),document.body.classList.remove("is-resizing-pane-x"),p){const d=t.getState()?.ui?.layout||{};l(d.canvasPaneAdjust??0,d.diagnosticsPaneAdjust??0)}};return window.addEventListener("pointermove",c),window.addEventListener("pointerup",u),window.addEventListener("pointercancel",u),()=>{window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",u)}},[t,i]),a.createElement("button",{type:"button",className:`ps-column-resizer${i?" 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(),is(c),n.current={startX:c.clientX,startCanvas:Number(e)||0,startDiag:Number(s)||0},r(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>{t.dispatch({type:"ui/canvasPaneAdjust",canvasPaneAdjust:0}),t.dispatch({type:"ui/diagnosticsPaneAdjust",diagnosticsPaneAdjust:0})},onKeyDown:c=>{if(c.key!=="ArrowLeft"&&c.key!=="ArrowRight")return;c.preventDefault();const u=c.key==="ArrowRight"?24:-24;l((Number(e)||0)+u,(Number(s)||0)-u)}},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 CS({controller:t,sessionId:e,railPx:s=380}){const n=a.useRef(null),[i,r]=a.useState(!1);return a.useEffect(()=>{if(!i)return;const o=c=>{const u=n.current;u&&t.dispatch({type:"canvas/zenRail",sessionId:e,px:u.start+(c.clientX-u.startX)})},l=()=>{n.current=null,r(!1),document.body.classList.remove("is-resizing-pane-x")};return window.addEventListener("pointermove",o),window.addEventListener("pointerup",l),window.addEventListener("pointercancel",l),()=>{window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",l),window.removeEventListener("pointercancel",l)}},[t,i,e]),a.createElement("button",{type:"button",className:`ps-column-resizer${i?" 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(),is(o),n.current={startX:o.clientX,start:s},r(!0),document.body.classList.add("is-resizing-pane-x"))},onKeyDown:o=>{o.key!=="ArrowLeft"&&o.key!=="ArrowRight"||(o.preventDefault(),t.dispatch({type:"canvas/zenRail",sessionId:e,px:s+(o.key==="ArrowRight"?24:-24)}))}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function TS({controller:t,target:e,adjust:s=0}){const n=a.useRef(null),[i,r]=a.useState(!1),o=e==="canvas"?"ui/canvasPaneAdjust":"ui/diagnosticsPaneAdjust",l=e==="canvas"?"canvasPaneAdjust":"diagnosticsPaneAdjust",c=e==="canvas"?rr:or,u=p=>{if(c+p<Os){t.dispatch({type:o,[l]:0}),t.dispatch(e==="canvas"?{type:"ui/canvasOpen",open:!1,manual:!0}:{type:"ui/diagnosticsOpen",open:!1});return}t.dispatch({type:o,[l]:p})};return a.useEffect(()=>{if(!i)return;const p=f=>{const h=n.current;h&&t.dispatch({type:o,[l]:h.startAdjust-(f.clientX-h.startX)})},d=()=>{const f=n.current;n.current=null,r(!1),document.body.classList.remove("is-resizing-pane-x"),f&&u((t.getState()?.ui?.layout||{})[l]??0)};return window.addEventListener("pointermove",p),window.addEventListener("pointerup",d),window.addEventListener("pointercancel",d),()=>{window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",d)}},[t,i,o,l]),a.createElement("button",{type:"button",className:`ps-column-resizer${i?" is-dragging":""}`,title:"Drag to resize. Drag the column away to close it. Double-click to reset.","aria-label":"Resize the right column",onPointerDown:p=>{p.button===0&&(p.preventDefault(),is(p),n.current={startX:p.clientX,startAdjust:Number(s)||0},r(!0),document.body.classList.add("is-resizing-pane-x"))},onDoubleClick:()=>t.dispatch({type:o,[l]:0}),onKeyDown:p=>{p.key!=="ArrowLeft"&&p.key!=="ArrowRight"||(p.preventDefault(),u((Number(s)||0)-(p.key==="ArrowRight"?24:-24)))}},a.createElement("span",{className:"ps-column-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function NS({controller:t,splitAdjust:e=0}){const s=a.useRef(null),[n,i]=a.useState(!1);return a.useEffect(()=>{if(!n)return;const r=l=>{const c=s.current;if(!c)return;const u=clamp(c.start+(l.clientY-c.startY),c.minAdjust,c.maxAdjust);t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:u})},o=()=>{s.current=null,i(!1),document.body.classList.remove("is-resizing-pane-y")};return window.addEventListener("pointermove",r),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o),()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),document.body.classList.remove("is-resizing-pane-y")}},[t,n]),a.createElement("button",{type:"button",className:`ps-row-resizer${n?" is-dragging":""}`,title:"Drag to resize the inspector and activity panes. Double-click to reset.","aria-label":"Resize the inspector and activity panes",onPointerDown:r=>{if(r.button!==0)return;r.preventDefault(),is(r);const o=r.currentTarget.closest(".ps-workspace-column"),l=Math.max(0,o?.getBoundingClientRect?.().height||0),c=Math.max(0,r.currentTarget.getBoundingClientRect().height||0),{minAdjust:u,maxAdjust:p}=Lr(l,c);s.current={startY:r.clientY,start:clamp(Number(e)||0,u,p),minAdjust:u,maxAdjust:p},i(!0),document.body.classList.add("is-resizing-pane-y")},onDoubleClick:()=>t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:0}),onKeyDown:r=>{if(r.key!=="ArrowUp"&&r.key!=="ArrowDown")return;r.preventDefault();const o=r.currentTarget.closest(".ps-workspace-column"),l=Math.max(0,o?.getBoundingClientRect?.().height||0),c=Math.max(0,r.currentTarget.getBoundingClientRect().height||0),{minAdjust:u,maxAdjust:p}=Lr(l,c);t.dispatch({type:"ui/diagnosticsSplitAdjust",diagnosticsSplitAdjust:clamp((Number(e)||0)+(r.key==="ArrowDown"?c:-c),u,p)})}},a.createElement("span",{className:"ps-row-resizer-handle","aria-hidden":"true"},a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"}),a.createElement("span",{className:"ps-column-resizer-dot"})))}function MS({controller:t}){const e=X(t,y=>y.ui.themeId),s=X(t,y=>!!y.ui.touchScale),n=rt(e),i=X(t,y=>({rawModal:y.ui.modal,themePicker:wh(y),modelPicker:qf(y),reasoningEffortPicker:Vf(y),contextTierPicker:Yf(y),sessionAgentPicker:Kf(y),sessionGroupPicker:Xf(y),sessionGroupName:Zf(y),artifactPicker:nh(y),logFilter:th(y),filesFilter:sh(y),historyFormat:bh(y),renameSession:Qf(y),sessionOwnerFilter:eh(y),artifactUpload:Jf(y),confirm:vh(y),logsFilter:y.logs.filter,filesFilterState:y.files.filter,historyFormatState:y.executionHistory?.format||"pretty"}),Oe),r=i.rawModal,o=a.useRef(null),l=a.useRef(null),c=a.useRef(null),[u,p]=a.useState(""),d=r?.type==="sessionOwnerFilter";if(a.useEffect(()=>{d||p("")},[d]),a.useEffect(()=>{if(r?.type!=="renameSession"||!i.renameSession)return;const y=o.current;if(y){if(document.activeElement!==y)try{y.focus({preventScroll:!0})}catch{y.focus()}y.setSelectionRange(i.renameSession.cursorIndex,i.renameSession.cursorIndex)}},[r?.type,i.renameSession?.cursorIndex,i.renameSession?.value]),a.useEffect(()=>{if(r?.type!=="sessionGroupName"||!i.sessionGroupName)return;const y=l.current;if(y){if(document.activeElement!==y)try{y.focus({preventScroll:!0})}catch{y.focus()}y.setSelectionRange(i.sessionGroupName.cursorIndex,i.sessionGroupName.cursorIndex)}},[r?.type,i.sessionGroupName?.cursorIndex,i.sessionGroupName?.value]),a.useEffect(()=>{if(!r||!["themePicker","modelPicker","reasoningEffortPicker","contextTierPicker","sessionAgentPicker","sessionGroupPicker","artifactPicker","sessionOwnerFilter","logFilter","filesFilter","historyFormat"].includes(r.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"})},[r?.type,r?.selectedIndex,i.themePicker?.selectedRowIndex,i.modelPicker?.selectedRowIndex,i.reasoningEffortPicker?.selectedRowIndex,i.contextTierPicker?.selectedRowIndex,i.sessionAgentPicker?.selectedRowIndex,i.sessionGroupPicker?.selectedRowIndex,i.artifactPicker?.selectedRowIndex,i.sessionOwnerFilter?.selectedRowIndex,i.logFilter?.selectedRowIndex,i.filesFilter?.selectedRowIndex,i.historyFormat?.selectedRowIndex]),!r)return null;const f=()=>t.handleCommand(C.CLOSE_MODAL).catch(()=>{}),h=()=>a.createElement("label",{className:"ps-modal-toggle",title:"Larger type and bigger hit targets, for phones and touch screens."},a.createElement("input",{type:"checkbox",checked:s,onChange:y=>t.dispatch({type:"ui/touchScale",enabled:y.target.checked})}),a.createElement("span",null,"Mobile")),m=(y,v="Apply",x=null)=>{const E=Array.isArray(y.rows)?y.rows:[],w=Array.isArray(y.rowItemIndexes)?y.rowItemIndexes:null,I=r.type==="modelPicker"||r.type==="reasoningEffortPicker"||r.type==="contextTierPicker"||r.type==="sessionAgentPicker",b=w&&w.length===E.length?E.map((M,A)=>{const O=w[A],F=Array.isArray(M)?M:De([M])[0]?.runs||[{text:M?.text||"",color:M?.color}];if(O==null||O<0)return a.createElement("div",{key:`row:${A}`,className:"ps-line ps-modal-list-heading-line"},a.createElement(He,{runs:F,theme:n}));const L=r.items?.[O];return a.createElement("button",{key:L?.id||`row:${A}`,type:"button",className:`ps-list-button ps-modal-list-button${O===r.selectedIndex?" is-selected":""}${I?" is-hanging":""}${L?.disabled?" is-disabled":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:O}),L?.kind==="section"&&t.toggleAgentPickerSection(L.sectionKey)}},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(He,{runs:F,theme:n})))}):(r.items||[]).flatMap((M,A,O)=>{const F=a.createElement("button",{key:M.id||A,type:"button",className:`ps-list-button ps-modal-list-button${A===r.selectedIndex?" is-selected":""}${I?" is-hanging":""}${M?.disabled?" is-disabled":""}`,onClick:()=>t.dispatch({type:"ui/modalSelection",index:A})},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(He,{runs:Array.isArray(E?.[A])?E[A]:De([E?.[A]])[0]?.runs||[{text:E?.[A]?.text||"",color:E?.[A]?.color}],theme:n})));return M?.group&&M.group!==O[A-1]?.group?[a.createElement("div",{key:`group:${M.group}`,className:"ps-modal-list-group","aria-hidden":"true"},M.group),F]:[F]});return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:`ps-modal is-list${r.type==="themePicker"?" is-theme-picker":""}`,onClick:M=>M.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},y.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:c,className:"ps-modal-list"},b),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),De(y.detailsLines||[]).map((M,A)=>a.createElement(Be,{key:`detail:${A}`,line:M,theme:n,className:"ps-modal-detail-line"})))),a.createElement("div",{className:"ps-modal-footer"},x,a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(C.MODAL_CONFIRM).catch(()=>{})},v))))};if(r.type==="confirm"&&i.confirm){const y=!!r.alert,v=!y&&r.action==="deleteSession",x=r.action==="regenerateSession",E=r.extras||{};return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:w=>w.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},i.confirm.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-body",style:{padding:"16px 20px"}},a.createElement("p",{style:{color:"#94a3b8",margin:0}},i.confirm.message)),x?a.createElement("div",{className:"ps-modal-body",style:{padding:"0 20px 12px",display:"flex",flexDirection:"column",gap:10}},a.createElement("label",{style:{color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8}},"Distillation",a.createElement("select",{className:"ps-modal-input",style:{flex:"1",padding:"4px 8px"},value:E.distillMode||"llm",onChange:w=>t.updateConfirmExtras({distillMode:w.currentTarget.value})},a.createElement("option",{value:"llm"},"Intelligent (LLM reads the whole transcript)"),a.createElement("option",{value:"deterministic"},"Fast (no LLM — tail + pointers)"))),(E.distillMode||"llm")==="llm"?a.createElement(PS,{controller:t,extras:E}):null,(E.distillMode||"llm")==="llm"?a.createElement("textarea",{className:"ps-modal-input",style:{width:"100%",minHeight:"64px",resize:"vertical",fontFamily:"inherit",fontSize:"13px"},placeholder:'Distilling instructions (optional) — e.g. "preserve every SQL snippet verbatim"',value:E.instructions||"",maxLength:4e3,onChange:w=>t.updateConfirmExtras({instructions:w.currentTarget.value})}):null):null,a.createElement("div",{className:"ps-modal-footer"},y?null:a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:`ps-modal-button ${v?"is-danger":"is-primary"}`,onClick:()=>t.handleCommand(C.MODAL_CONFIRM).catch(()=>{})},i.confirm.confirmLabel))))}if(r.type==="themePicker"&&i.themePicker)return m(i.themePicker,"Apply Theme",h());const g=r.sessionOptions?.mode==="switchModel"?"Switch Model":"Create Session";if(r.type==="modelPicker"&&i.modelPicker)return m(i.modelPicker,g);if(r.type==="reasoningEffortPicker"&&i.reasoningEffortPicker)return m(i.reasoningEffortPicker,g);if(r.type==="contextTierPicker"&&i.contextTierPicker)return m(i.contextTierPicker,g);if(r.type==="sessionAgentPicker"&&i.sessionAgentPicker){const y=r.items?.[r.selectedIndex||0],v=y?.kind==="section"?y.collapsed?"Open":"Close":"Create Session";return m(i.sessionAgentPicker,v)}if(r.type==="sessionGroupPicker"&&i.sessionGroupPicker)return m(i.sessionGroupPicker,"Move");if(r.type==="artifactPicker"&&i.artifactPicker)return m(i.artifactPicker,i.artifactPicker.confirmLabel||"Open / Download");if(r.type==="sessionOwnerFilter"&&i.sessionOwnerFilter){const y=i.sessionOwnerFilter,v=Array.isArray(y.rows)?y.rows:[],x=u.trim().toLowerCase(),E=I=>{const b=v?.[I];return(Array.isArray(b)?b:De([b])[0]?.runs||[]).map(A=>A?.text||"").join("")||String(b?.text||"")},w=(r.items||[]).map((I,b)=>b).filter(I=>{if(!x)return!0;const b=(r.items||[])[I]||{};return`${E(I)} ${b.label||""} ${b.description||""}`.toLowerCase().includes(x)});return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},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:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{className:"ps-modal-input ps-modal-search",value:u,placeholder:"Search people…",autoFocus:!0,onChange:I=>p(I.currentTarget.value),onKeyDown:I=>{I.key==="Escape"&&u&&(I.stopPropagation(),p(""))}}),a.createElement("div",{className:"ps-modal-grid"},a.createElement("div",{ref:c,className:"ps-modal-list"},w.length===0?a.createElement("div",{className:"ps-empty-state"},`No one matches "${u}".`):null,w.map(I=>(b=>a.createElement("button",{key:b.id||I,type:"button",className:`ps-list-button ps-modal-list-button${I===r.selectedIndex?" is-selected":""}`,onClick:()=>t.toggleSessionOwnerFilter(I)},a.createElement("div",{className:"ps-line ps-modal-list-line"},a.createElement(He,{runs:Array.isArray(v?.[I])?v[I]:De([v?.[I]])[0]?.runs||[{text:v?.[I]?.text||"",color:v?.[I]?.color}],theme:n}))))((r.items||[])[I]||{}))),a.createElement("div",{className:"ps-modal-details"},a.createElement("div",{className:"ps-modal-details-title"},y.detailsTitle||"Details"),De(y.detailsLines||[]).map((I,b)=>a.createElement(Be,{key:`detail:${b}`,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:f},"Done"))))}if(r.type==="renameSession"&&i.renameSession)return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},i.renameSession.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{ref:o,className:"ps-modal-input",value:i.renameSession.value,placeholder:i.renameSession.placeholder,onChange:y=>t.setRenameSessionValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),t.handleCommand(C.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},De(i.renameSession.helpLines||[]).map((y,v)=>a.createElement(Be,{key:`help:${v}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(C.MODAL_CONFIRM).catch(()=>{})},"Save"))));if(r.type==="sessionGroupName"&&i.sessionGroupName)return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},i.sessionGroupName.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{ref:l,className:"ps-modal-input",value:i.sessionGroupName.value,placeholder:i.sessionGroupName.placeholder,onChange:y=>t.setSessionGroupNameValue(y.currentTarget.value,y.currentTarget.selectionStart??y.currentTarget.value.length),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),t.handleCommand(C.MODAL_CONFIRM).catch(()=>{}))},autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},De(i.sessionGroupName.helpLines||[]).map((y,v)=>a.createElement(Be,{key:`help:${v}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(C.MODAL_CONFIRM).catch(()=>{})},i.sessionGroupName.mode==="rename"?"Rename":"Create and Move"))));if(r.type==="terminatePicker"){const y=Number(r.bulkCount)>1,v=!!r.systemRestart,x=String(r.sessionTitle||"").trim()||"this session",E=Number(r.bulkCount)||0,w=y?`What should happen to the ${E} selected sessions? Choose an action; you'll be asked to confirm.`:v?`How should "${x}" be restarted? Choose a disposition; you'll be asked to confirm.`:`What should happen to "${x}"? Choose an action; you'll be asked to confirm.`,I=b=>()=>{t.pickTerminateAction(b).catch(()=>{})};return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:b=>b.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},r.title||"Session Lifecycle"),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-modal-body",style:{padding:"12px 16px 4px"}},a.createElement("p",{style:{color:"#94a3b8",margin:0}},w)),a.createElement("div",{className:"ps-modal-body",style:{padding:"10px 16px 16px",display:"flex",flexDirection:"column",gap:8}},r.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 ${E} 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 ${E} 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 ${E} Sessions`:v?"Hard Delete & Restart":"Delete Session")),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Close"))))}if(r.type==="artifactUpload"&&i.artifactUpload)return a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-narrow",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},i.artifactUpload.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("input",{className:"ps-modal-input",value:i.artifactUpload.value,placeholder:i.artifactUpload.placeholder,onChange:y=>t.setArtifactUploadValue(y.currentTarget.value,y.currentTarget.selectionStart||y.currentTarget.value.length),autoFocus:!0}),a.createElement("div",{className:"ps-modal-details"},De(i.artifactUpload.helpLines||[]).map((y,v)=>a.createElement(Be,{key:`help:${v}`,line:y,theme:n,className:"ps-modal-detail-line"}))),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button",onClick:f},"Cancel"),a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:()=>t.handleCommand(C.MODAL_CONFIRM).catch(()=>{})},"Attach"))));const S=r.type==="logFilter"?i.logFilter:r.type==="filesFilter"?i.filesFilter:r.type==="historyFormat"?i.historyFormat:null;return S?a.createElement("div",{className:"ps-modal-backdrop",onClick:f},a.createElement("div",{className:"ps-modal is-wide",onClick:y=>y.stopPropagation()},a.createElement("div",{className:"ps-modal-header"},a.createElement("div",{className:"ps-modal-title"},S.title),a.createElement("button",{type:"button",className:"ps-modal-close",onClick:f,"aria-label":"Close",title:"Close"},"✕")),a.createElement("div",{className:"ps-filter-grid"},(r.items||[]).map((y,v)=>{const x=r.type==="filesFilter"?i.filesFilterState?.[y.id]||y.options?.[0]?.id:r.type==="historyFormat"?i.historyFormatState:i.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(E=>a.createElement("button",{key:E.id,type:"button",className:`ps-filter-option${E.id===x?" is-selected":""}`,onClick:()=>{t.dispatch({type:"ui/modalSelection",index:v}),r.type==="historyFormat"?t.dispatch({type:"executionHistory/format",format:E.id}):r.type==="filesFilter"?(t.dispatch({type:"files/filter",filter:{[y.id]:E.id}}),t.ensureFilesForScope(E.id).catch(()=>{})):t.dispatch({type:"logs/filter",filter:{[y.id]:E.id}})}},E.label)))})),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-modal-button is-primary",onClick:f},"Done")))):null}function PS({controller:t,extras:e}){const s=Array.isArray(e.distillerModelOptions)?e.distillerModelOptions:[],n=s.find(u=>u.qualifiedName===e.distillerModel)||null,i=n?.supportedReasoningEfforts||[],r=n?.supportedContextTiers||[],o={color:"#94a3b8",fontSize:"12px",display:"flex",alignItems:"center",gap:8},l={flex:"1",padding:"4px 8px"},c=u=>t.updateConfirmExtras(u);return a.createElement(a.Fragment,null,a.createElement("label",{style:o},"Distiller model",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerModel||"",onChange:u=>c({distillerModel:u.currentTarget.value,distillerEffort:"",distillerContextTier:""})},a.createElement("option",{value:""},"Deployment default"),s.map(u=>a.createElement("option",{key:u.qualifiedName,value:u.qualifiedName},u.qualifiedName)))),i.length>0?a.createElement("label",{style:o},"Reasoning",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerEffort||"",onChange:u=>c({distillerEffort:u.currentTarget.value})},a.createElement("option",{value:""},"Model default"),i.map(u=>a.createElement("option",{key:u,value:u},u)))):null,r.length>0?a.createElement("label",{style:o},"Context",a.createElement("select",{className:"ps-modal-input",style:l,value:e.distillerContextTier||"",onChange:u=>c({distillerContextTier:u.currentTarget.value})},a.createElement("option",{value:""},"Model default"),r.map(u=>a.createElement("option",{key:u,value:u},u==="long_context"?"long context (fits a larger transcript)":u)))):null)}function RS(t,e){a.useEffect(()=>{const s=n=>{const i=n.target,r=i instanceof HTMLElement&&(i.tagName==="TEXTAREA"||i.tagName==="INPUT"||i.tagName==="SELECT"||i.isContentEditable),o=t.getState().ui.modal,l=ir(t),c=t.getState().ui.inspectorTab,u=t.getState().ui.focusRegion,p=!n.metaKey&&!n.ctrlKey&&!n.altKey,d=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="T"&&n.shiftKey,f=!n.metaKey&&!n.ctrlKey&&!n.altKey&&n.key==="N"&&n.shiftKey,h=m=>{const g=ug(l,c,m);t.selectInspectorTab(g).catch(()=>{})};if(!r&&d){n.preventDefault(),t.handleCommand(C.OPEN_THEME_PICKER).catch(()=>{});return}if(!r&&f){n.preventDefault(),t.handleCommand(C.OPEN_MODEL_PICKER).catch(()=>{});return}if(o&&!r){if(n.key==="Escape"||o.type==="confirm"&&n.key==="n"){n.preventDefault(),t.handleCommand(C.CLOSE_MODAL).catch(()=>{});return}if(n.key==="Enter"||o.type==="confirm"&&n.key==="y"){n.preventDefault(),t.handleCommand(C.MODAL_CONFIRM).catch(()=>{});return}if(n.key==="Tab"&&n.shiftKey){n.preventDefault(),t.handleCommand(C.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="Tab"){n.preventDefault(),t.handleCommand(C.MODAL_PANE_NEXT).catch(()=>{});return}if(o.type==="sessionAgentPicker"&&(n.key==="ArrowRight"||n.key==="ArrowLeft")){n.preventDefault(),t.handleCommand(n.key==="ArrowRight"?C.MODAL_PANE_NEXT:C.MODAL_PANE_PREV).catch(()=>{});return}if(n.key==="ArrowUp"||n.key==="k"){n.preventDefault(),t.handleCommand(C.MODAL_PREV).catch(()=>{});return}(n.key==="ArrowDown"||n.key==="j")&&(n.preventDefault(),t.handleCommand(C.MODAL_NEXT).catch(()=>{}));return}if(!r){if(n.key==="r"&&p&&u!=="prompt"){n.preventDefault(),t.handleCommand(C.REFRESH).catch(()=>{});return}if(n.key==="n"&&p){n.preventDefault(),t.handleCommand(C.NEW_SESSION).catch(()=>{});return}if(u==="inspector"&&c==="files"&&(n.key==="u"&&p||(n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")){n.preventDefault(),t.handleCommand(C.OPEN_ARTIFACT_UPLOAD).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="a"&&p){n.preventDefault(),t.handleCommand(C.DOWNLOAD_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="x"&&p){n.preventDefault(),t.handleCommand(C.DELETE_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="o"&&p){n.preventDefault(),t.handleCommand(C.OPEN_SELECTED_FILE).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(C.OPEN_FILES_FILTER).catch(()=>{});return}if(u==="inspector"&&c==="stats"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(C.TOGGLE_STATS_VIEW).catch(()=>{});return}if(u==="inspector"&&c==="files"&&n.key==="v"&&p){n.preventDefault(),t.handleCommand(C.TOGGLE_FILE_PREVIEW_FULLSCREEN).catch(()=>{});return}if(u==="inspector"&&c==="logs"&&n.key==="t"&&p){n.preventDefault(),t.handleCommand(C.TOGGLE_LOG_TAIL).catch(()=>{});return}if(u==="inspector"&&c==="logs"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(C.OPEN_LOG_FILTER).catch(()=>{});return}if(u==="inspector"&&c==="history"&&n.key==="f"&&p){n.preventDefault(),t.handleCommand(C.OPEN_HISTORY_FORMAT).catch(()=>{});return}if(u==="inspector"&&c==="history"&&n.key==="r"&&p){n.preventDefault(),t.handleCommand(C.REFRESH_EXECUTION_HISTORY).catch(()=>{});return}if(u==="inspector"&&c==="history"&&n.key==="a"&&p){n.preventDefault(),t.handleCommand(C.EXPORT_EXECUTION_HISTORY).catch(()=>{});return}if(n.key==="a"&&p){n.preventDefault(),t.handleCommand(C.OPEN_ARTIFACT_PICKER).catch(()=>{});return}if(n.key==="p"&&p){n.preventDefault(),t.handleCommand(C.FOCUS_PROMPT).catch(()=>{});return}if(n.key==="c"&&p){n.preventDefault(),t.handleCommand(C.CANCEL_SESSION).catch(()=>{});return}if(n.key==="d"&&p){n.preventDefault(),t.handleCommand(C.DONE_SESSION).catch(()=>{});return}if(n.key==="D"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(C.DELETE_SESSION).catch(()=>{});return}if(n.key==="m"&&p&&u==="inspector"){n.preventDefault(),h(1);return}if(n.key==="["&&p){n.preventDefault(),t.handleCommand(C.GROW_LEFT_PANE).catch(()=>{});return}if(n.key==="]"&&p){n.preventDefault(),t.handleCommand(C.GROW_RIGHT_PANE).catch(()=>{});return}if(n.key==="{"&&p){n.preventDefault(),t.handleCommand(C.SHRINK_SESSION_PANE).catch(()=>{});return}if(n.key==="}"&&p){n.preventDefault(),t.handleCommand(C.GROW_SESSION_PANE).catch(()=>{});return}if(u==="inspector"&&n.key==="ArrowLeft"){n.preventDefault(),h(-1);return}if(u==="inspector"&&n.key==="ArrowRight"){n.preventDefault(),h(1);return}if(u==="sessions"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(C.MOVE_SESSION_UP).catch(()=>{});return}if(u==="sessions"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(C.MOVE_SESSION_DOWN).catch(()=>{});return}if(u==="sessions"&&n.ctrlKey&&n.key.toLowerCase()==="g"&&!n.metaKey&&!n.altKey){n.preventDefault(),t.handleCommand(C.OPEN_MOVE_TO_GROUP).catch(()=>{});return}if(u==="sessions"&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(C.PAGE_UP).catch(()=>{});return}if(u==="sessions"&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(C.PAGE_DOWN).catch(()=>{});return}if(u==="sessions"&&n.key==="t"&&p){n.preventDefault(),t.handleCommand(C.OPEN_RENAME_SESSION).catch(()=>{});return}if(!e&&(n.key==="PageUp"||n.ctrlKey&&n.key.toLowerCase()==="u")){n.preventDefault(),t.handleCommand(C.PAGE_UP).catch(()=>{});return}if(!e&&(n.key==="PageDown"||n.ctrlKey&&n.key.toLowerCase()==="d")){n.preventDefault(),t.handleCommand(C.PAGE_DOWN).catch(()=>{});return}if(!e&&n.key==="g"&&p){n.preventDefault(),t.handleCommand(C.SCROLL_TOP).catch(()=>{});return}if(!e&&n.key==="G"&&n.shiftKey&&!n.metaKey&&!n.ctrlKey&&!n.altKey){n.preventDefault(),t.handleCommand(C.SCROLL_BOTTOM).catch(()=>{});return}if(u!=="prompt"&&n.key==="h"&&p){n.preventDefault(),t.handleCommand(C.FOCUS_LEFT).catch(()=>{});return}if(u!=="prompt"&&n.key==="l"&&p){n.preventDefault(),t.handleCommand(C.FOCUS_RIGHT).catch(()=>{});return}if(!e&&u==="inspector"&&c==="files"&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(C.MOVE_FILE_UP).catch(()=>{});return}if(!e&&u==="inspector"&&c==="files"&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(C.MOVE_FILE_DOWN).catch(()=>{});return}if(!e&&(n.key==="ArrowUp"||n.key==="k")){n.preventDefault(),t.handleCommand(C.SCROLL_UP).catch(()=>{});return}if(!e&&(n.key==="ArrowDown"||n.key==="j")){n.preventDefault(),t.handleCommand(C.SCROLL_DOWN).catch(()=>{});return}!e&&n.key==="Escape"&&(n.preventDefault(),t.handleCommand(C.FOCUS_SESSIONS).catch(()=>{}))}};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[t,e])}function jc(t){if(!t)return"Unknown user";const e=String(t.displayName||"").trim(),s=String(t.email||"").trim();if(e&&s&&e.toLowerCase()!==s.toLowerCase())return`${e} <${s}>`;if(e)return e;if(s)return s;const n=String(t.provider||"").trim(),i=String(t.subject||"").trim();return[n,i].filter(Boolean).join(":")||"user"}function _S({controller:t,mobile:e=!1}){const s=X(t,mf,Oe),n=a.useRef(null),i=s.packages||{},r=s.section==="packages",o=s.section==="workers",[l,c]=a.useState(()=>{const A={wsWidth:440,treePct:44,navWidth:240};try{return{...A,...JSON.parse(window.localStorage.getItem("ps-admin-ws-layout")||"{}")}}catch{return A}}),u=a.useCallback(A=>{c(O=>{const F={...O,...A};F.wsWidth=Math.min(900,Math.max(300,Math.round(F.wsWidth))),F.treePct=Math.min(85,Math.max(15,F.treePct)),F.navWidth=Math.min(420,Math.max(170,Math.round(F.navWidth??240)));try{window.localStorage.setItem("ps-admin-ws-layout",JSON.stringify(F))}catch{}return F})},[]),p=a.useCallback(A=>{A.preventDefault(),document.body.style.cursor="col-resize";const O=A.clientX,F=l.navWidth??240,L=P=>u({navWidth:F+(P.clientX-O)}),G=()=>{window.removeEventListener("pointermove",L),window.removeEventListener("pointerup",G),window.removeEventListener("pointercancel",G),document.body.style.cursor=""};window.addEventListener("pointermove",L),window.addEventListener("pointerup",G),window.addEventListener("pointercancel",G)},[l.navWidth,u]);a.useEffect(()=>{if(s.ghcpKey.editing){const A=window.requestAnimationFrame(()=>{n.current&&n.current.focus()});return()=>window.cancelAnimationFrame(A)}},[s.ghcpKey.editing]);const d=a.useCallback(()=>{t.closeAdminConsole()},[t]),f=a.useCallback(()=>{t.refreshAdminProfile().catch(()=>{})},[t]),h=a.useCallback(()=>{t.beginAdminEditGhcpKey()},[t]),m=a.useCallback(()=>{t.cancelAdminEditGhcpKey()},[t]),g=a.useCallback(()=>{t.clearAdminGhcpKey().catch(()=>{})},[t]),S=a.useCallback(A=>{A.preventDefault(),t.saveAdminGhcpKey().catch(()=>{})},[t]),y=a.useCallback(A=>{t.setAdminGhcpKeyDraft(A.target.value)},[t]),v=jc(s.principal),x=a.createElement("header",{className:"ps-admin-console__header"},a.createElement("h2",null,"Admin Console"),a.createElement("span",{className:"ps-admin-console__who"},v),a.createElement("button",{type:"button",className:"ps-mini-button is-icon",onClick:d,title:"Close the admin console","aria-label":"Close the admin console"},"✕")),E=a.createElement(HS,{view:s,draftRef:n,onBeginEdit:h,onCancelEdit:m,onClear:g,onSubmit:S,onDraftChange:y,onRefresh:f,controller:t}),w=a.createElement(LS,{controller:t,view:s}),I=a.createElement(OS,{controller:t,view:s}),b=r&&i.selectedName?a.createElement($S,{controller:t,view:s,layout:l,onLayout:u}):null,M=i.addDialog?.open?a.createElement(BS,{controller:t,dialog:i.addDialog}):null;if(e){let A;return r&&i.selectedName?A=a.createElement("div",{className:"ps-admin-mobile-stack"},a.createElement("button",{type:"button",className:"ps-mini-button ps-admin-back",onClick:()=>t.selectAdminPackage(null)},"← All packages"),I,b):r?A=w:o?A=a.createElement("div",{className:"ps-admin-mobile-stack"},w,a.createElement(ba,{controller:t,view:s})):A=a.createElement("div",{className:"ps-admin-mobile-stack"},w,E),a.createElement("div",{className:"ps-admin-console is-mobile"},x,s.loadError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,A,M)}return a.createElement("div",{className:"ps-admin-console is-workspace"},x,s.loadError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.loadError):null,a.createElement("div",{className:"ps-admin-workspace",style:b?{gridTemplateColumns:`${l.navWidth}px minmax(0, 1fr) minmax(0, ${l.wsWidth}px)`}:{gridTemplateColumns:`${l.navWidth}px minmax(0, 1fr)`}},a.createElement("div",{className:"ps-admin-nav"},w,a.createElement("div",{className:"ps-admin-nav__resize",onPointerDown:p,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings column"})),a.createElement("div",{className:"ps-admin-main"},r?I:o?a.createElement(ba,{controller:t,view:s}):E),b),M)}function ba({controller:t,view:e}){const s=e.workers||{},n=s.rows||[],i=s.counts||{};return a.useEffect(()=>{const r=window.setInterval(()=>{t.refreshAdminWorkers()},25e3);return()=>window.clearInterval(r)},[t]),a.createElement("div",{className:"ps-admin-detail ps-admin-workers"},a.createElement("div",{className:"ps-admin-workers__head"},a.createElement("h3",null,"Workers"),s.summaryText?a.createElement("span",{className:"ps-admin-workers__summary"},`${s.summaryText}${i.pools>1?` · ${i.pools} pools`:""}${i.draining?` · ${i.draining} draining`:""}`):null,a.createElement("button",{type:"button",className:"ps-mini-button is-icon",onClick:()=>t.refreshAdminWorkers(),disabled:!!s.loading,title:s.loading?"Refreshing…":"Refresh the worker list","aria-label":"Refresh the worker list"},a.createElement("svg",{viewBox:"0 0 20 20",width:15,height:15,fill:"none",stroke:"currentColor",strokeWidth:1.7,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},a.createElement("path",{d:"M16.2 8.2A6.4 6.4 0 0 0 4.6 6.4M3.8 11.8a6.4 6.4 0 0 0 11.6 1.8"}),a.createElement("path",{d:"M16.4 3.6v4.6h-4.6M3.6 16.4v-4.6h4.6"})))),s.error?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},s.error):null,s.empty?a.createElement("p",{className:"ps-admin-console__hint"},"No workers registered. Workers appear here on their first heartbeat and self-prune after an hour of silence."):a.createElement("div",{className:"ps-admin-workers__scroll"},a.createElement("table",{className:"ps-admin-workers__table"},a.createElement("thead",null,a.createElement("tr",null,["Worker","Pool","Phase","Heartbeat","Uptime","RSS","Sessions","Loop p99","Packages","SDK"].map(r=>a.createElement("th",{key:r},r)))),a.createElement("tbody",null,n.map(r=>a.createElement("tr",{key:r.id,className:r.live?"is-live":"is-stale"},a.createElement("td",{className:"ps-admin-workers__id",title:r.owner?`owner: ${r.owner}`:void 0},a.createElement("span",{className:`ps-worker-dot${r.live?" is-live":""}`}),r.id,r.substrate&&r.substrate!=="kubernetes"?a.createElement("span",{className:"ps-admin-workers__substrate"},r.substrate):null),a.createElement("td",null,r.pool),a.createElement("td",null,a.createElement("span",{className:`ps-worker-phase is-${r.phase}`},r.phase)),a.createElement("td",null,r.agoText),a.createElement("td",null,r.uptimeText??"—"),a.createElement("td",null,r.rssText??"—"),a.createElement("td",null,r.sessions??"—"),a.createElement("td",null,r.eventLoopText??"—"),a.createElement("td",{title:r.pkgEpoch!=null?`epoch ${r.pkgEpoch}`:void 0},r.pkgText??"—"),a.createElement("td",null,r.sdkVersion??"—")))))))}function LS({controller:t,view:e}){const s=e.packages||{};return a.createElement("nav",{className:"ps-admin-tree"},a.createElement("div",{className:"ps-admin-tree__label"},"Settings"),(e.settingsTree||[]).map(n=>{if(n.kind==="group")return a.createElement("div",{key:n.id,className:"ps-admin-tree__group"},`${n.label}`,a.createElement("span",{className:"ps-admin-tree__count"},String(n.count??0)));const i=n.kind==="package"?()=>t.selectAdminPackage(n.name,{scope:n.scope==="shared"?"shared":"user",...n.scope!=="shared"&&n.owner?.provider&&n.owner?.subject?{owner:{provider:n.owner.provider,subject:n.owner.subject}}:{}}):()=>t.setAdminSection(n.id==="agents"?"packages":n.id==="workers"?"workers":"ghcp");return a.createElement("button",{key:n.id,type:"button",className:`ps-admin-tree__row depth-${n.depth}${n.selected?" is-selected":""}${n.kind==="package"&&!n.enabled?" is-disabled":""}`,onClick:i},n.kind==="package"?n.ownerBadge?a.createElement(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,a.createElement("button",{type:"button",className:"ps-admin-tree__add",onClick:()=>t.openAdminAddPackage()},"+ Add package"))}function OS({controller:t,view:e}){const s=e.packages||{},n=s.detail;if(!s.selectedName)return a.createElement("div",{className:"ps-admin-detail is-empty"},a.createElement("h3",null,"Agents"),a.createElement("p",{className:"ps-admin-console__hint"},s.empty?"No agent packages yet. Add one from a GitHub/ADO repo, a tarball URL, or upload a folder — or push from a terminal with `pilotswarm agents push ./my-agents`.":"Select a package from the tree to see its detail, versions, and files."));const i=()=>{window.confirm(`Delete ${n.name}? Every version and its artifacts are removed. Live sessions using its agents will fail on their next turn.`)&&t.runAdminPackageAction("delete")},r=(l,c)=>()=>t.runAdminPackageAction(l,c),o=n.actionPending;return a.createElement("div",{className:"ps-admin-detail"},n.error?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},`Package load failed: ${n.error}`):null,n.loading?a.createElement("p",{className:"ps-admin-console__hint"},"Loading package…"):null,a.createElement("div",{className:"ps-admin-detail__head"},a.createElement("h3",null,n.name),a.createElement("span",{className:`ps-scope-badge is-${n.scope}`},n.scope),n.enabled?null:a.createElement("span",{className:"ps-scope-badge is-off"},"disabled")),n.description?a.createElement("p",{className:"ps-admin-detail__desc"},n.description):null,a.createElement("dl",{className:"ps-admin-detail__meta"},a.createElement("dt",null,"Version"),a.createElement("dd",null,n.activeSemver?`${n.activeSemver} · sha ${n.activeSha12||"?"} · ${n.sizeText}`:"no active version"),n.fleet?[a.createElement("dt",{key:"fk"},"Fleet"),a.createElement("dd",{key:"fv",className:"is-ok"},n.fleet.text)]:null,a.createElement("dt",null,"Created"),a.createElement("dd",null,`${n.createdBy||"unknown"} · ${n.createdAtText}`)),n.agents.length?a.createElement("div",null,a.createElement("div",{className:"ps-admin-detail__label"},"Agents in this package"),a.createElement("div",{className:"ps-admin-detail__chips"},n.agents.map(l=>a.createElement("span",{key:l.name,className:"ps-agent-chip",title:l.description},l.name,l.toolCount?a.createElement("i",null,` · ${l.toolCount} tools`):null)))):null,n.versions.length?a.createElement("div",null,a.createElement("div",{className:"ps-admin-detail__label"},"Versions"),a.createElement("div",{className:"ps-admin-versions"},n.versions.map(l=>a.createElement("div",{key:l.semver,className:`ps-admin-version${l.active?" is-active":""}`},a.createElement("b",null,l.semver),a.createElement("span",null,l.sha12),a.createElement("span",null,l.dateText),l.active?a.createElement("span",{className:"is-ok"},"● active"):n.canManage?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:r("pin",l.semver),disabled:!!o},"Pin"):null)))):null,n.canManage?a.createElement("div",{className:"ps-admin-detail__actions"},n.source?a.createElement("button",{type:"button",className:"ps-primary-button",onClick:r("sync"),disabled:!!o},o==="sync"?"Syncing…":"Sync now"):null,a.createElement("button",{type:"button",className:"ps-primary-button",onClick:()=>t.openAdminUpdatePackage(n.name,n.scope),disabled:!!o,title:`Publish a new version of ${n.name} from a repo folder`},"Update"),n.scope==="user"&&n.hasSharedCounterpart?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:r("republish",n.activeSemver),disabled:!!o||!n.activeSemver,title:`Publish ${n.name}@${n.activeSemver??"?"} into the existing shared package`},o==="republish"?"Publishing…":`Publish ${n.activeSemver??""} to shared`):a.createElement("button",{type:"button",className:"ps-mini-button",onClick:r(n.scope==="shared"?"demote":"promote"),disabled:!!o},n.scope==="shared"?"Demote to user":"Promote to shared"),n.scope==="shared"&&!n.hasOwnUserCounterpart?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:r("republish",n.activeSemver),disabled:!!o||!n.activeSemver,title:"Copy the active version into your user scope as a private test bench"},o==="republish"?"Copying…":"Copy to my user scope"):null,a.createElement("button",{type:"button",className:"ps-mini-button",onClick:r(n.enabled?"disable":"enable"),disabled:!!o},n.enabled?"Disable":"Enable"),a.createElement("button",{type:"button",className:"ps-mini-button is-danger",onClick:i,disabled:!!o},"Delete")):a.createElement("p",{className:"ps-admin-console__hint"},"Read-only: only the package creator or an admin can modify it."),n.actionError?a.createElement("div",{className:"ps-admin-console__error",role:"alert"},n.actionError):null)}function $S({controller:t,view:e,layout:s=null,onLayout:n=null}){const i=X(t,d=>d.ui.themeId),r=rt(i),o=e.packages?.workspace,l=a.useRef(null),c=a.useCallback((d,f)=>{if(!n)return;d.preventDefault();const h=d.clientX,m=d.clientY,g={...s},S=v=>f(g,v.clientX-h,v.clientY-m),y=()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),document.body.style.cursor=""};window.addEventListener("pointermove",S),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)},[s,n]),u=a.useCallback(d=>{document.body.style.cursor="col-resize",c(d,(f,h)=>n({wsWidth:f.wsWidth-h}))},[c,n]),p=a.useCallback(d=>{document.body.style.cursor="row-resize";const f=l.current?.getBoundingClientRect().height||600;c(d,(h,m,g)=>n({treePct:h.treePct+g/f*100}))},[c,n]);return o?a.createElement("div",{className:"ps-admin-ws",ref:l,style:s?{gridTemplateRows:`auto minmax(80px, ${s.treePct}%) auto minmax(0, 1fr)`}:void 0},n?a.createElement("div",{className:"ps-admin-ws__vdivider",title:"Drag to resize the workspace",onPointerDown:u}):null,a.createElement("div",{className:"ps-admin-ws__head"},`Package workspace${o.semver?` · ${e.packages.selectedName}@${o.semver}`:""}`),a.createElement("div",{className:"ps-admin-ws__tree"},o.loading?a.createElement("div",{className:"ps-admin-tree__hint"},"Loading files…"):null,o.error?a.createElement("div",{className:"ps-admin-tree__hint is-error"},o.error):null,o.treeRows.map(d=>a.createElement("button",{key:`${d.type}:${d.path}`,type:"button",style:{paddingLeft:`${8+(d.depth||0)*16}px`},className:`ps-admin-ws__row is-${d.type}${d.selected?" is-selected":""}`,onClick:d.type==="dir"?()=>t.toggleAdminPackageDir(d.path):()=>t.selectAdminPackageFile(d.path)},a.createElement("span",{className:"ps-admin-ws__caret"},d.type==="dir"?d.expanded?"▾":"▸":""),a.createElement("span",{className:"ps-admin-ws__name"},d.label),d.sizeText?a.createElement("span",{className:"ps-admin-ws__size"},d.sizeText):null))),a.createElement("div",{className:`ps-admin-ws__preview-head${n?" is-resizable":""}`,title:n?"Drag to resize file list vs preview":void 0,onPointerDown:n?p:void 0},o.selectedPath?`Preview · ${o.selectedPath}`:"Preview"),a.createElement("div",{className:"ps-admin-ws__preview"},o.fileLoading?a.createElement("div",{className:"ps-admin-tree__hint"},"Loading…"):null,o.fileError?a.createElement("div",{className:"ps-admin-tree__hint is-error"},o.fileError):null,o.file?o.file.isBinary?a.createElement("div",{className:"ps-admin-tree__hint"},`Binary file · ${o.file.sizeText}`):a.createElement(DS,{file:o.file,theme:r}):null)):null}function FS(t){const e=/^---\n([\s\S]*?)\n---\n?/.exec(t||"");if(!e)return{meta:null,body:t||""};const s=e[1].split(`
97
+ `).map(n=>/^([A-Za-z0-9_-]+):\s*(.*)$/.exec(n)).filter(Boolean).map(([,n,i])=>({key:n,value:i}));return s.length===0?{meta:null,body:t||""}:{meta:s,body:(t||"").slice(e[0].length)}}function DS({file:t,theme:e}){const s=t.language||"text",n=t.truncated?a.createElement("div",{className:"ps-admin-tree__hint"},"… truncated preview"):null;if(s==="markdown"){const{meta:i,body:r}=FS(t.text||"");return a.createElement("div",{className:"ps-admin-ws__doc"},i?a.createElement("div",{className:"ps-admin-ws__frontmatter"},i.map(o=>a.createElement("div",{key:o.key,className:"ps-admin-ws__fm-row"},a.createElement("span",{className:"ps-admin-ws__fm-key"},o.key),a.createElement("span",{className:"ps-admin-ws__fm-val"},o.value)))):null,a.createElement(pr,{content:r,theme:e}),n)}if(s==="json"){let i=t.text||"";if(!t.truncated)try{i=JSON.stringify(JSON.parse(i),null,2)}catch{}return a.createElement("div",{className:"ps-admin-ws__doc"},a.createElement("pre",{className:"ps-admin-ws__code lang-json"},a.createElement("code",null,Zt(i,"json",e))),n)}return a.createElement("div",{className:"ps-admin-ws__doc"},a.createElement("pre",{className:`ps-admin-ws__code lang-${s}`},a.createElement("code",null,Zt(t.text||"",s,e))),n)}function BS({controller:t,dialog:e}){const s=X(t,d=>d.docs?.agentPackageGuideUrl||null),n=d=>f=>t.setAdminAddPackageField(d,f.target.value),i=[["repo","GitHub / Azure DevOps"],["upload","Upload folder"]],r=e.kind==="repo"||e.kind==="github"||e.kind==="ado",o=a.useRef(null),[l,c]=a.useState(!1),u=2*1024*1024,p=d=>{if(d.preventDefault(),!(l||e.submitting)){if(e.kind==="upload"){const f=o.current;if(!f?.files?.length){t.failAdminAddPackage("Choose a package folder first.");return}const h=[...f.files].map(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")),m=h.reduce((g,{file:S})=>g+S.size,0);if(h.length===0){t.failAdminAddPackage("The chosen folder has no uploadable files.");return}if(m>u){t.failAdminAddPackage(`Folder is ${(m/(1024*1024)).toFixed(1)} MB after filtering — the upload envelope is 2 MB. Use a repo/URL source or 'pilotswarm agents push' for larger packages.`);return}c(!0),Promise.all(h.map(({file:g,path:S})=>new Promise((y,v)=>{const x=new FileReader;x.onerror=()=>v(new Error(`could not read ${S}`)),x.onload=()=>y({path:S,contentBase64:String(x.result).split(",",2)[1]||""}),x.readAsDataURL(g)}))).then(g=>t.submitAdminUploadPackage(g,e.scope)).catch(g=>t.failAdminAddPackage(g?.message||"Could not read the chosen folder.")).finally(()=>c(!1));return}t.submitAdminAddPackage().catch(()=>{})}};return a.createElement("div",{className:"ps-modal-backdrop",onClick:()=>t.closeAdminAddPackage()},a.createElement("form",{className:"ps-modal ps-admin-add",onClick:d=>d.stopPropagation(),autoComplete:"off",onSubmit:p},a.createElement("div",{className:"ps-modal-header"},a.createElement("span",null,e.updateName?`Update ${e.updateName}`:"Add agent package"),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage()},"✕")),a.createElement("div",{className:"ps-admin-add__body"},a.createElement("div",{className:"ps-admin-add__tabs"},i.map(([d,f])=>a.createElement("button",{key:d,type:"button",className:`ps-admin-add__tab${e.kind===d?" is-on":""}`,onClick:()=>t.setAdminAddPackageField("kind",d)},f))),r?[a.createElement("label",{key:"u",className:"ps-admin-add__field"},"Link to plugin.json (or the folder containing it)",a.createElement("input",{value:e.repoUrl,onChange:n("repoUrl"),placeholder:"https://github.com/org/repo/blob/main/my-agents/plugin.json",autoFocus:!0,type:"url",name:"agent-package-link",autoComplete:"off",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true"})),a.createElement("div",{key:"h",className:"ps-admin-add__hint"},"Paste the browser URL — branch and path are read from the link. The files are read by THIS BROWSER with your access (public GitHub needs nothing; Azure DevOps uses your signed-in account) and uploaded as a package artifact."),a.createElement("label",{key:"t",className:"ps-admin-add__field"},"PAT (only for private GitHub repos, or to override — used here, never stored)",a.createElement("input",{type:"password",value:e.authToken,onChange:n("authToken"),name:"agent-package-pat",autoComplete:"new-password","data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true"}))]:a.createElement("label",{className:"ps-admin-add__field"},"Package folder with plugin.json — the manifest (≤ 2 MB; node_modules skipped)",a.createElement("input",{ref:o,type:"file",webkitdirectory:"",directory:"",multiple:!0})),a.createElement("div",{className:"ps-admin-add__scope"},a.createElement("label",null,a.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="shared",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","shared")})," Shared — everyone can use it"),a.createElement("label",null,a.createElement("input",{type:"radio",name:"pkg-scope",checked:e.scope==="user",disabled:!!e.updateName,onChange:()=>t.setAdminAddPackageField("scope","user")})," User — only you see it")),e.updateName?a.createElement("p",{className:"ps-admin-console__hint"},`Publishes a new version of ${e.updateName}. Its scope is unchanged — use Demote/Promote on the package to move it.`):null,s?a.createElement("p",{className:"ps-admin-console__hint"},"New to this? ",a.createElement("a",{href:s,target:"_blank",rel:"noreferrer noopener"},"How to build an agent package")," — a complete guide you can also hand straight to Claude or Copilot."):null,a.createElement("p",{className:"ps-admin-console__hint"},"Same thing from a terminal: pilotswarm agents push ./my-agents --shared"),e.progress&&!e.error?a.createElement("p",{className:"ps-admin-add__progress"},e.progress):null,e.error?a.createElement("pre",{className:"ps-admin-add__error",role:"alert"},e.error):null),a.createElement("div",{className:"ps-modal-footer"},a.createElement("button",{type:"button",className:"ps-mini-button",onClick:()=>t.closeAdminAddPackage(),disabled:e.submitting},"Cancel"),a.createElement("button",{type:"submit",className:"ps-primary-button",disabled:e.submitting||l},l?"Reading folder…":e.submitting?"Importing…":e.updateName?"Import & update":"Import & publish"))))}function HS({view:t,draftRef:e,onBeginEdit:s,onCancelEdit:n,onClear:i,onSubmit:r,onDraftChange:o,onRefresh:l,controller:c}){return a.createElement("section",{className:"ps-admin-console__section"},a.createElement("h3",null,"GitHub Copilot key"),t.ghcpKey.storeAsSystem?a.createElement("p",{className:"ps-admin-console__hint"},"System-wide key for platform-managed (ownerless) system ","sessions — agent tuners, repo cache managers, and other ","sessions with no owner resolve this key for GitHub Copilot ","models. Clearing it reverts them to the worker default."):a.createElement("p",{className:"ps-admin-console__hint"},"Per-user override for the GitHub Copilot model provider token. ","When set, this key is used instead of the worker's env-supplied ","GITHUB_TOKEN for sessions you own. Clearing the key reverts to ","the worker default."),t.isAdmin&&t.systemGhcpKey.supported?a.createElement("label",{className:"ps-admin-console__system-toggle"},a.createElement("input",{type:"checkbox",checked:t.ghcpKey.storeAsSystem,disabled:t.ghcpKey.saving,onChange:u=>c.setAdminGhcpKeyStoreAsSystem(u.target.checked)}),"Store as System key"):null,a.createElement("p",{className:`ps-admin-console__status${t.ghcpKey.error?" is-error":""}`},t.ghcpKey.error||t.ghcpKey.statusText),t.ghcpKey.editing?a.createElement("form",{className:"ps-admin-console__form",onSubmit:r},a.createElement("input",{ref:e,type:"password",autoComplete:"off",spellCheck:!1,value:t.ghcpKey.draft,disabled:t.ghcpKey.saving,placeholder:"Paste GitHub Copilot key",onChange:o}),a.createElement("div",{className:"ps-admin-console__actions"},a.createElement("button",{type:"submit",className:"ps-primary-button",disabled:t.ghcpKey.saving},t.ghcpKey.saving?"Saving...":"Save"),a.createElement("button",{type:"button",className:"ps-mini-button",onClick:n,disabled:t.ghcpKey.saving},"Cancel"))):a.createElement("div",{className:"ps-admin-console__actions"},a.createElement("button",{type:"button",className:"ps-primary-button",onClick:s},t.ghcpKey.targetConfigured?t.ghcpKey.storeAsSystem?"Replace System key":"Replace key":t.ghcpKey.storeAsSystem?"Set System key":"Set key"),t.ghcpKey.targetConfigured?a.createElement("button",{type:"button",className:"ps-mini-button",onClick:i},t.ghcpKey.storeAsSystem?"Clear System key":"Clear key"):null,a.createElement("button",{type:"button",className:"ps-mini-button",onClick:l},t.loading?"Refreshing...":"Refresh")))}function US({transport:t,mode:e="remote",branding:s=null,docs:n=null}={}){wg(),typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 920px)").matches;const i=Gh(jh,ni({mode:e,branding:s,docs:n}));return new Dm({store:i,transport:t})}function zS({controller:t}){const e=a.useRef(null),s=a.useRef(null),n=Vo(e),i=Vo(s),r=Pg(n);a.useEffect(()=>{const R=()=>{try{const q=document.createElement("span");q.style.cssText="position:absolute;visibility:hidden;white-space:pre;";const ne=document.querySelector(".ps-scroll-panel .ps-line")||document.querySelector(".ps-line");if(ne){const $e=window.getComputedStyle(ne);q.style.fontFamily=$e.fontFamily,q.style.fontSize=$e.fontSize,q.style.fontWeight=$e.fontWeight,q.style.letterSpacing=$e.letterSpacing}q.textContent="0".repeat(100),(ne?.parentElement||document.body).appendChild(q);const ie=q.getBoundingClientRect().width/100||8;q.remove();const ue=document.documentElement.clientWidth||window.innerWidth,ve=document.documentElement.clientHeight||window.innerHeight;t.dispatch({type:"ui/viewport",width:Math.floor(ue/ie),height:Math.floor(ve/at)})}catch{}};R();let W;const J=()=>{clearTimeout(W),W=setTimeout(R,150)};return window.addEventListener("resize",J),window.addEventListener("orientationchange",J),()=>{clearTimeout(W),window.removeEventListener("resize",J),window.removeEventListener("orientationchange",J)}},[t]);const[o,l]=a.useState("split"),c=X(t,R=>({themeId:R.ui.themeId,touchScale:!!R.ui.touchScale,ownerFilter:R.sessions.ownerFilter,pinnedIds:R.sessions.pinnedIds,manualOrder:R.sessions.manualOrder,collapsedSessionIds:R.sessions.collapsedIds,activeSessionId:R.sessions.activeSessionId||null,promptRows:uc(R),rightPaneMode:R.ui.rightPaneMode||"panes",canvasOpen:R.ui.canvasOpen===!0,diagnosticsOpen:R.ui.diagnosticsOpen===!0,canvasMaximized:R.ui.canvasMaximized===!0,canvasZen:R.ui.canvasZen===!0,canvasPrefs:R.canvas?.prefs,activeSessionIsGroup:!!(R.sessions.activeSessionId&&R.sessions.byId[R.sessions.activeSessionId]?.isGroup),paneAdjust:R.ui.layout?.paneAdjust??0,sessionPaneAdjust:R.ui.layout?.sessionPaneAdjust??0,portalSessionColumnAdjust:R.ui.layout?.portalSessionColumnAdjust??0,activityPaneAdjust:R.ui.layout?.activityPaneAdjust??0,canvasPaneAdjust:R.ui.layout?.canvasPaneAdjust??0,diagnosticsPaneAdjust:R.ui.layout?.diagnosticsPaneAdjust??0,diagnosticsSplitAdjust:R.ui.layout?.diagnosticsSplitAdjust??0,focusRegion:R.ui.focusRegion,requestedFocusRegion:R.ui.requestedFocusRegion,inspectorTab:R.ui.inspectorTab,filesFullscreen:!!R.files.fullscreen,selectedArtifactId:R.files.selectedArtifactId||null,artifactPaneOpen:!!R.files.paneOpen,adminVisible:!!R.admin?.visible}),Oe),u=a.useRef(!1),p=a.useRef(null),d=a.useRef(null),f=a.useRef(null),h=a.useRef(null),m=a.useRef(null),g=a.useRef(null),S=a.useRef(!1),y=a.useRef(!1),v=a.useRef(null),x=a.useRef(null),[E,w]=a.useState("workspace"),I=(n.width||window.innerWidth||0)<Zm,M=c.activeSessionIsGroup?0:c.promptRows;RS(t,I);const A=X(t,Ui,Oe),O=E==="canvas",F=a.useRef("workspace"),[L,G]=a.useState(!1),[P,H]=a.useState(!1);a.useEffect(()=>{w(R=>R==="canvas"?F.current||"workspace":R),G(!1),H(!1)},[A.sessionId]),a.useEffect(()=>{if(!(typeof document>"u"))return document.body.classList.toggle("ps-canvas-lock",!!(I&&O)),()=>document.body.classList.remove("ps-canvas-lock")},[I,O]);const U=a.useCallback(()=>{E!=="canvas"&&(F.current=E),w("canvas"),G(!0),t.dispatch({type:"ui/rightPaneMode",mode:"canvas",sessionId:A.sessionId})},[t,E,A.sessionId]),re=a.useCallback(()=>{w(F.current||"workspace"),t.dispatch({type:"ui/rightPaneMode",mode:"panes",sessionId:A.sessionId,manual:!0})},[t,A.sessionId]),he=a.useRef(A.flipSeq);a.useEffect(()=>{A.flipSeq!==he.current&&(he.current=A.flipSeq,I&&U())},[A.flipSeq,I,U]);const ce=a.useCallback(()=>{if(O){re();return}U()},[O,re,U]);a.useEffect(()=>{let R=!0;u.current=!1,p.current=null,v.current=null,x.current=Wo(t.getState()),m.current&&(clearTimeout(m.current),m.current=null),g.current&&(clearInterval(g.current),g.current=null),S.current=!1,y.current=!1;const W=t.transport;if(typeof W?.getCurrentUserProfile!="function"||typeof W?.setCurrentUserProfileSettings!="function")return u.current=!0,()=>{R=!1};const J=async()=>{if(!(!R||S.current)){S.current=!0;try{const q=await W.getCurrentUserProfile();if(!R)return;const ne=Ct(q?.profileSettings);typeof ne[rn()]=="boolean"&&(d.current=ne[rn()]),(ne.rightPaneMode==="canvas"||ne.rightPaneMode==="panes")&&(f.current=ne.rightPaneMode),ne.desktopPanes&&(h.current=ne.desktopPanes),x.current=Wo(t.getState(),d.current,f.current,h.current);const ie=!kg(ne)&&!ns()&&window.innerWidth>=Ig,ue=Eg(q?.profileSettings,x.current);ie&&(ue.desktopPanes={canvasOpen:!0,diagnosticsOpen:!1});const ve=JSON.stringify(ue),$e=zn(t.getState(),d.current,f.current,h.current),yt=JSON.stringify($e),rs=u.current&&p.current!=null&&yt!==p.current,St=!!m.current||y.current||rs;if(!St&&v.current!==ve&&(t.dispatch({type:"profileSettings/apply",settings:ue}),v.current=ve),!u.current||!St){const Gc=zn(t.getState(),d.current,f.current,h.current);p.current=JSON.stringify(Gc)}u.current=!0}catch{if(!R)return;u.current=!0}finally{S.current=!1}}};return J().catch(()=>{}),g.current=setInterval(()=>{J().catch(()=>{})},rg),()=>{R=!1,m.current&&(clearTimeout(m.current),m.current=null),g.current&&(clearInterval(g.current),g.current=null),S.current=!1}},[t]),a.useEffect(()=>{if(!u.current)return;const R=zn(c,d.current,f.current,h.current),W=JSON.stringify(R);p.current!==W&&(p.current=W,m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{m.current=null,y.current=!0,xg(t,R).catch(()=>{}).finally(()=>{y.current=!1})},400))},[t,c.activeSessionId,c.activityPaneAdjust,c.canvasPrefs,c.collapsedSessionIds,c.ownerFilter,c.paneAdjust,c.manualOrder,c.pinnedIds,c.portalSessionColumnAdjust,c.rightPaneMode,c.sessionPaneAdjust,c.themeId,c.touchScale]),a.useEffect(()=>{Mg(c.themeId),Ng(c.touchScale)},[c.themeId,c.touchScale]);const Ge=a.useRef(null);a.useEffect(()=>{const R=Ge.current;if(Ge.current=c.focusRegion,R===null||R===c.focusRegion)return;const W=c.requestedFocusRegion;I&&(c.focusRegion==="inspector"||c.focusRegion==="activity")&&(W==="inspector"||W==="activity")&&w(c.focusRegion)},[I,c.focusRegion,c.requestedFocusRegion]),a.useEffect(()=>{const R=ir(t);!R.includes(c.inspectorTab)&&R.length>0&&t.selectInspectorTab(R[0]).catch(()=>{})},[t,c.inspectorTab]);const k=a.useMemo(()=>gs(r,c.paneAdjust,M,c.sessionPaneAdjust,c.activityPaneAdjust),[r,c.activityPaneAdjust,c.paneAdjust,M,c.sessionPaneAdjust]),$=c.filesFullscreen&&c.inspectorTab==="files",K=c.inspectorTab==="files"&&!!c.selectedArtifactId&&!$,z=!I&&c.artifactPaneOpen&&!!c.selectedArtifactId&&!$,B=!I&&c.canvasOpen&&!$;a.useEffect(()=>{B&&H(!0)},[B,A.sessionId]);const Q=!I&&c.diagnosticsOpen&&!$&&!z&&!(c.canvasZen&&c.canvasOpen),V=z||B||Q,j=c.canvasMaximized&&B,T=c.canvasZen&&B&&!z,Y=Math.max(260,Math.min(720,Number(c.canvasPrefs?.[c.activeSessionId]?.zenRailPx)||380));a.useEffect(()=>{if(!j&&!T)return;const R=W=>{W.key==="Escape"&&t.dispatch(j?{type:"ui/canvasMaximized",on:!1}:{type:"ui/canvasZen",on:!1})};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[t,j,T]);const le=Math.max(0,rr+(Number(c.canvasPaneAdjust)||0)),ae=Math.max(0,or+(Number(c.diagnosticsPaneAdjust)||0)),Ce=(B?le:0)+(B&&Q?1:0)+(Q?ae:0),Ie=a.useCallback(()=>{t.closeArtifactPane().catch(()=>{})},[t]),Re=Math.max(0,(n.width||0)*.68),ke=i.width||Re,Te=Ag(ke,c.portalSessionColumnAdjust),oe=T?"hidden":Cg(Te),Ne=oe==="hidden"?"0px":`clamp(0px, calc(${nr*100}% + ${Number(c.portalSessionColumnAdjust)||0}px), max(0px, calc(100% - 14rem - 32px)))`,_=a.createElement("div",{className:`ps-workspace-grid${V?"":" is-right-hidden"}`,style:{gridTemplateColumns:z?`minmax(0, ${k.leftWidth}fr) var(--ps-resizer-track, 16px) minmax(0, ${k.rightWidth}fr)`:T?`${Y}px var(--ps-resizer-track, 16px) minmax(0, 1fr)`:V?`minmax(0, 1fr) var(--ps-resizer-track, 16px) min(${Ce}px, 60%)`:"minmax(0, 1fr)"}},a.createElement("div",{ref:s,className:`ps-workspace-main-grid is-session-${oe}`,style:{gridTemplateColumns:`${Ne} var(--ps-resizer-track, 16px) minmax(14rem, 1fr)`}},oe!=="hidden"?a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"1"}},a.createElement(Si,{controller:t,structuredRows:!0})):null,a.createElement("div",{style:{gridColumn:"2",minWidth:0,display:"flex"}},a.createElement(kS,{controller:t,portalSessionColumnAdjust:c.portalSessionColumnAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridColumn:"3"}},a.createElement(wi,{controller:t}))),V?z?a.createElement(IS,{controller:t,paneAdjust:c.paneAdjust}):T?a.createElement(CS,{controller:t,sessionId:c.activeSessionId,railPx:Y}):a.createElement(TS,{controller:t,target:B?"canvas":"diagnostics",adjust:B?c.canvasPaneAdjust:c.diagnosticsPaneAdjust}):null,a.createElement("div",{className:`ps-workspace-column-host is-split${j?" has-maximized":""}`},z?a.createElement("div",{className:"ps-workspace-column is-artifact"},a.createElement(mS,{controller:t,onClose:Ie})):null,P?a.createElement("div",{key:`canvas:${c.activeSessionId||""}`,className:`ps-workspace-column is-artifact ps-canvas-layer${B&&!z?"":" is-hidden"}${j&&B&&!z?" is-maximized":""}`,style:B&&!z&&Q&&!j?{flex:`0 0 ${le}px`,minWidth:0}:void 0,...B&&!z?{}:{inert:!0,"aria-hidden":"true"}},a.createElement(Bc,{controller:t,visible:B&&!z,maximized:j})):null,B&&Q?a.createElement(AS,{controller:t,canvasPaneAdjust:c.canvasPaneAdjust,diagnosticsPaneAdjust:c.diagnosticsPaneAdjust}):null,Q?a.createElement("div",{className:"ps-workspace-column",style:{gridTemplateRows:`minmax(0px, calc(50% + ${Math.round(Number(c.diagnosticsSplitAdjust)||0)}px)) var(--ps-resizer-track, 16px) minmax(0px, 1fr)`,...B?{flex:"1 1 0%",minWidth:0}:null}},a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"1"}},a.createElement(ds,{controller:t,mobile:!1})),a.createElement("div",{style:{gridRow:"2",minHeight:0,display:"flex",flexDirection:"column"}},a.createElement(NS,{controller:t,splitAdjust:c.diagnosticsSplitAdjust})),a.createElement("div",{className:"ps-workspace-pane-slot",style:{gridRow:"3"}},K?a.createElement(gn,{controller:t,focused:!1,previewOnly:!0}):a.createElement(Qn,{controller:t}))):null)),se=a.createElement("div",{className:"ps-workspace-full"},a.createElement(ds,{controller:t,mobile:!1}));let ye=null;$&&!I?ye=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(ds,{controller:t,mobile:!0})):E==="inspector"?ye=c.inspectorTab==="nodes"?a.createElement("div",{className:"ps-mobile-pane-fill ps-mobile-node-split"},a.createElement(ds,{controller:t,mobile:!0}),a.createElement(Qn,{controller:t,panelClassName:"ps-mobile-node-detail"})):a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(ds,{controller:t,mobile:!0})):E==="activity"?ye=a.createElement("div",{className:"ps-mobile-pane-fill"},a.createElement(Qn,{controller:t})):E==="canvas"?ye=null:ye=a.createElement(SS,{controller:t,layout:o});const D=I&&L?a.createElement(gS,{key:`canvas:${A.sessionId||""}`,controller:t,visible:O}):null;return a.createElement(yc.Provider,{value:t},a.createElement("div",{ref:e,className:"ps-web-shell"},a.createElement(xS,{controller:t,mobile:I,canvasPaneOpen:O,onToggleCanvasPane:ce,mobilePane:E,mobileMainLayout:o,onSelectMobilePane:(R,W)=>{R==="workspace"&&E==="workspace"&&l(J=>J==="split"?"chat":J==="chat"?"sessions":"split"),w(R),W&&t.setFocus(W)}}),a.createElement("div",{className:"ps-workspace"},c.adminVisible?a.createElement(_S,{controller:t,mobile:I}):$?se:I?ye:_,D),I&&$?a.createElement(yS,{controller:t}):null,a.createElement(MS,{controller:t})))}export{zS as P,a as R,nc as _,Kc as a,rt as b,US as c,vi as d,jS as e,gf as f,Uc as g,wa as r,GS as s};