tide-commander 0.61.4 → 0.61.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,6 +5,7 @@
5
5
  ![Tide Commander Preview](https://raw.githubusercontent.com/deivid11/tide-commander/master/docs/preview-3d.png)
6
6
 
7
7
  [![Watch the demo](https://img.shields.io/badge/YouTube-Watch%20Demo-red?style=for-the-badge&logo=youtube)](https://www.youtube.com/watch?v=r1Op_xfhqOM)
8
+ [![npm version](https://img.shields.io/npm/v/tide-commander?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/tide-commander)
8
9
 
9
10
  Tide Commander is a Claude Code and Codex orchestrator and manager that lets you deploy, control, and monitor multiple AI coding agents from a single visual interface. Spawn agents, assign tasks, and watch them work in real-time on an RTS-inspired 3D battlefield — or switch to a lightweight 2D canvas or a metrics dashboard.
10
11
 
@@ -137,7 +137,7 @@ Error generating stack: `+y.message+`
137
137
  float h = normalize(vWorldPosition + offset).y;
138
138
  gl_FragColor = vec4(mix(bottomColor, topColor, max(pow(max(h, 0.0), exponent), 0.0)), 1.0);
139
139
  }
140
- `,side:qk});i.add(new Ce(o,r)),i.add(new vf(16777215,1));const c=n.fromScene(i,.04).texture;t.environment=c,n.dispose(),o.dispose(),r.dispose()}createInputCallbacks(){return{onAgentClick:(e,t)=>this.inputEventHandlers.handleAgentClick(e,t),onAgentDoubleClick:e=>this.inputEventHandlers.handleAgentDoubleClick(e),onAgentHover:(e,t)=>this.inputEventHandlers.handleAgentHover(e,t),onGroundClick:()=>this.inputEventHandlers.handleGroundClick(),onMoveCommand:(e,t)=>this.inputEventHandlers.handleMoveCommand(e,t),onSelectionBox:(e,t)=>this.inputEventHandlers.handleSelectionBox(e,t),onDrawStart:e=>this.drawingManager.startDrawing(e),onDrawMove:e=>this.drawingManager.updateDrawing(e),onDrawEnd:e=>this.drawingManager.finishDrawing(e),onAreaRightClick:e=>this.inputEventHandlers.handleAreaRightClick(e),onAreaClick:e=>this.inputEventHandlers.handleAreaClick(e),onAreaDoubleClick:e=>this.inputEventHandlers.handleAreaDoubleClick(e),onResizeStart:(e,t)=>this.drawingManager.startResize(e,t),onResizeMove:e=>this.drawingManager.updateResize(e),onResizeEnd:()=>this.drawingManager.finishResize(),onGroundClickOutsideArea:()=>this.inputEventHandlers.handleGroundClickOutsideArea(),onFolderIconClick:(e,t)=>{var n;t?P.openFileExplorerForAreaFolder(e,t):P.openFileExplorerForArea(e),(n=this.onFolderIconClickCallback)==null||n.call(this,e)},onBuildingClick:(e,t)=>this.inputEventHandlers.handleBuildingClick(e,t),onBuildingDoubleClick:e=>this.inputEventHandlers.handleBuildingDoubleClick(e),onBuildingHover:(e,t)=>this.inputEventHandlers.handleBuildingHover(e,t),onBuildingDragStart:()=>{},onBuildingDragMove:(e,t)=>this.buildingManager.setBuildingPosition(e,t),onBuildingDragEnd:(e,t)=>P.updateBuildingPosition(e,t),onContextMenu:(e,t,n)=>this.callbackManager.triggerContextMenu(e,t,n),onActivity:()=>this.renderLoop.markActivity(),onToggleTerminal:()=>P.toggleTerminal()}}setupInputHandlerHelpers(){this.inputHandler.setDrawingModeChecker(()=>this.drawingManager.isInDrawingMode()),this.inputHandler.setResizeHandlers(()=>this.drawingManager.getResizeHandles(),()=>this.drawingManager.isCurrentlyResizing()),this.inputHandler.setAreaAtPositionGetter(e=>this.drawingManager.getAreaAtPosition(e)),this.inputHandler.setFolderIconMeshesGetter(()=>this.drawingManager.getFolderIconMeshes()),this.inputHandler.setBuildingAtPositionGetter(e=>{const t=this.buildingManager.getBuildingAtPosition(e);return t?{id:t.id}:null}),this.inputHandler.setBuildingPositionsGetter(()=>{const e=new Map;for(const[t,n]of this.buildingManager.getBuildingMeshData())e.set(t,n.group.position.clone());return e})}setupEventListeners(e){window.addEventListener("resize",this.onWindowResize),this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),e.parentElement&&this.resizeObserver.observe(e.parentElement),e.addEventListener("webglcontextlost",this.onContextLost),e.addEventListener("webglcontextrestored",this.onContextRestored)}updateInputHandlerReferences(){this.inputHandler.setReferences(this.battlefield.getGround(),this.agentManager.getAgentMeshes())}updateBattlefield(e,t){t-this.lastTimeUpdate>6e4&&(this.battlefield.updateTimeOfDay(),this.lastTimeUpdate=t),this.battlefield.updateGalacticAnimation(e),this.battlefield.updateCloudAnimation(e)}updateAnimations(e){const t=this.movementAnimator.update(this.agentManager.getAgentMeshes(),e);return this.effectsManager.update(),this.buildingManager.update(e),t}updateProceduralAnimations(e){if(this.proceduralBodiesDirty){this.proceduralBodiesCache.clear();for(const[t,n]of this.agentManager.getAgentMeshes())if(this.proceduralAnimator.has(t)&&n.animations.size===0){const i=n.group.getObjectByName("characterBody");i&&this.proceduralBodiesCache.set(t,i)}this.proceduralBodiesDirty=!1}this.proceduralBodiesCache.size>0&&this.proceduralAnimator.update(e,this.proceduralBodiesCache)}updateIndicatorScales(e,t,n){for(const[,i]of t){const o=e.position.distanceTo(i.group.position),r=Math.max(.5,Math.min(2.5,o/15))*n,c=i.group.userData.isBoss===!0,u=i.group.getObjectByName("statusBar"),h=i.group.getObjectByName("nameLabelSprite");if(u){const f=typeof u.userData.baseIndicatorScale=="number"?u.userData.baseIndicatorScale:c?2:1.6,g=typeof u.userData.aspectRatio=="number"?u.userData.aspectRatio:2560/4096;u.scale.set(f*r,f*g*r,1)}if(h){const f=typeof h.userData.baseIndicatorScale=="number"?h.userData.baseIndicatorScale:c?1.5:1.25,v=Math.max(c?1.35:1.1,Math.min(c?1.65:1.35,f)),w=typeof h.userData.aspectRatio=="number"?h.userData.aspectRatio:1024/4096;h.scale.set(v*r,v*w*r,1)}const m=i.group.getObjectByName("combinedUI");if(m){const f=typeof m.userData.baseIndicatorScale=="number"?m.userData.baseIndicatorScale:c?3:2.4,g=typeof m.userData.aspectRatio=="number"?m.userData.aspectRatio:1024/2048;m.scale.set(f*r,f*g*r,1)}if(!u&&!m){const f=i.group.getObjectByName("nameLabel");if(f){const v=.3*r;f.scale.set(v*(f.userData.aspectRatio||2),v,1)}const g=i.group.getObjectByName("manaBar");g&&g.scale.set(.9,.14,1);const b=i.group.getObjectByName("idleTimer");b&&b.scale.set(.9*r,.14*r,1)}}for(const[,i]of this.buildingManager.getBuildingMeshData()){const o=e.position.distanceTo(i.group.position),r=Math.max(.5,Math.min(2.5,o/15))*n,c=i.group.getObjectByName("buildingLabel");if(c){const u=.3*r;c.scale.set(u*(c.userData.aspectRatio||2),u,1)}}this.effectsManager.updateWithCamera(e)}async loadCharacterModels(){await this.agentManager.loadCharacterModels()}upgradeAgentModels(){this.agentManager.upgradeAgentModels(),this.updateInputHandlerReferences()}addAgent(e){this.agentManager.addAgent(e)}removeAgent(e){this.agentManager.removeAgent(e),this.updateInputHandlerReferences()}updateAgent(e,t=!1){this.agentManager.updateAgent(e,t)}syncAgents(e){this.agentManager.syncAgents(e)}setCustomAgentClasses(e){this.agentManager.setCustomAgentClasses(e)}refreshSelectionVisuals(){this.selectionManager.refreshSelectionVisuals()}createMoveOrderEffect(e){this.effectsManager.createMoveOrderEffect(e)}showToolBubble(e,t,n){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.createSpeechBubble(e,t,n)}showDelegationEffect(e,t){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.createDelegationEffect(e,t)}addSubagentEffect(e,t,n,i){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.addSubagentEffect(e,t,n,i)}completeSubagentEffect(e){this.effectsManager.completeSubagentEffect(e)}removeSubagentEffect(e){this.effectsManager.removeSubagentEffect(e)}focusAgent(e){this.cameraManager.focusAgent(e)}callSubordinates(e){var r;const n=P.getState().agents.get(e);if(!n||!(n.isBoss||n.class==="boss")||!((r=n.subordinateIds)!=null&&r.length))return;const i=new ot(n.position.x,n.position.y,n.position.z),o=this.inputHandler.calculateFormationPositions(i,n.subordinateIds.length);this.effectsManager.createMoveOrderEffect(i.clone()),n.subordinateIds.forEach((c,u)=>{const h=this.agentManager.getAgentMeshes().get(c);P.moveAgent(c,o[u]),h&&this.movementAnimator.startMovement(c,h,o[u])})}setDrawingTool(e){this.drawingManager.setTool(e),P.setActiveTool(e)}syncAreas(){this.drawingManager.syncFromStore()}highlightArea(e){this.drawingManager.highlightArea(e)}clearAreaSelection(){this.drawingManager.highlightArea(null)}addBuilding(e){this.buildingManager.addBuilding(e)}removeBuilding(e){this.buildingManager.removeBuilding(e)}updateBuilding(e){this.buildingManager.updateBuilding(e)}syncBuildings(){this.buildingManager.syncFromStore()}highlightBuilding(e){this.buildingManager.highlightBuilding(e)}setOnBuildingClick(e){this.callbackManager.setOnBuildingClick(e)}setOnBuildingDoubleClick(e){this.callbackManager.setOnBuildingDoubleClick(e)}setOnContextMenu(e){this.callbackManager.setOnContextMenu(e)}setOnAgentHover(e){this.callbackManager.setOnAgentHover(e)}setOnBuildingHover(e){this.callbackManager.setOnBuildingHover(e)}setOnGroundClick(e){this.callbackManager.setOnGroundClick(e)}setOnAreaDoubleClick(e){this.callbackManager.setOnAreaDoubleClick(e)}setOnFolderIconClick(e){this.onFolderIconClickCallback=e}setOnToast(e){this.agentManager.setOnToast(e)}setCharacterScale(e){this.agentManager.setCharacterScale(e),this.selectionManager.setCharacterScale(e)}setIndicatorScale(e){this.renderLoop.setIndicatorScale(e),this.effectsManager.setIndicatorScale(e)}setFpsLimit(e){this.renderLoop.setFpsLimit(e)}setPowerSaving(e){this.renderLoop.setPowerSaving(e)}setGridVisible(e){this.battlefield.setGridVisible(e)}setDebugTime(e){this.battlefield.setDebugTime(e)}setTimeMode(e){this.battlefield.setTimeMode(e)}setTerrainConfig(e){this.battlefield.setTerrainConfig(e),e.brightness!==void 0&&(this.drawingManager.setBrightness(e.brightness),this.buildingManager.setBrightness(e.brightness),this.agentManager.setBrightness(e.brightness))}setFloorStyle(e,t=!1){this.battlefield.setFloorStyle(e,t)}setIdleAnimation(e){this.agentManager.setIdleAnimation(e)}setWorkingAnimation(e){this.agentManager.setWorkingAnimation(e)}setAgentModelStyle(e){this.agentManager.setModelStyle(e)}getAgentModelStyle(){return this.agentManager.getModelStyle()}setGlobalSaturation(e){this.sceneCore.setSaturation(e)}getGlobalSaturation(){return this.sceneCore.getSaturation()}setPostProcessingEnabled(e){this.sceneCore.setPostProcessingEnabled(e)}reattach(e,t){var o,r;console.log("[SceneManager] Reattaching to new canvas (HMR)"),this.isReattaching=!0,this.renderLoop.stop(),(o=this.resizeObserver)==null||o.disconnect();const n=this.sceneCore.getCanvas();n.removeEventListener("webglcontextlost",this.onContextLost),n.removeEventListener("webglcontextrestored",this.onContextRestored),this.sceneCore.reattach(e),this.cameraManager.recreateControls(this.sceneCore.getRenderer()),this.sceneCore.updateCamera(this.cameraManager.getCamera()),e.addEventListener("webglcontextlost",this.onContextLost),e.addEventListener("webglcontextrestored",this.onContextRestored),this.inputHandler.reattach(e,t,this.cameraManager.getControls()),this.updateInputHandlerReferences(),e.parentElement&&((r=this.resizeObserver)==null||r.observe(e.parentElement)),this.onWindowResize();const i=(c=0)=>{this.isReattaching=!1,e.isConnected&&this.sceneCore.getRenderer()?(console.log("[SceneManager] Restarting animation loop after HMR reattach"),this.renderLoop.start()):c<10?(console.log(`[SceneManager] Canvas not connected, retrying... (attempt ${c+1})`),this.isReattaching=!0,requestAnimationFrame(()=>i(c+1))):console.warn("[SceneManager] Failed to restart animation loop - canvas never connected")};requestAnimationFrame(()=>i())}getMemoryDiagnostics(){var t;const e=this.sceneCore.getRenderer().info;return{threeJs:e!=null&&e.memory?{geometries:e.memory.geometries,textures:e.memory.textures,programs:((t=e.programs)==null?void 0:t.length)??0}:null,heap:uT.getUsage(),agentMeshCount:this.agentManager.getAgentMeshes().size,bossLineCount:0}}getRenderStats(){var t,n;const e=(n=(t=this.sceneCore.getRenderer())==null?void 0:t.info)==null?void 0:n.render;return e?{calls:e.calls,triangles:e.triangles,points:e.points,lines:e.lines}:null}get renderer(){return this.sceneCore.getRenderer()}logMemoryDiagnostics(){const e=this.getMemoryDiagnostics(),t=this.characterLoader.getCacheStats();console.group("%c[SceneManager Memory]","color: #ff6600; font-weight: bold"),e.threeJs&&console.log(`Three.js: ${e.threeJs.geometries} geometries, ${e.threeJs.textures} textures, ${e.threeJs.programs} programs`),e.heap&&console.log(`Heap: ${e.heap.usedMB}MB / ${e.heap.totalMB}MB (limit: ${e.heap.limitMB}MB)`),console.log(`Agent meshes: ${e.agentMeshCount}`),console.log(`CharacterLoader cache: ${t.builtInModels} built-in, ${t.customModels} custom`),t.modelNames.length>0&&console.log(` Built-in models: ${t.modelNames.join(", ")}`),t.customModelIds.length>0&&console.log(` Custom models: ${t.customModelIds.join(", ")}`),console.groupEnd()}dispose(){var n;console.log("%c[SceneManager] dispose() called - starting cleanup","color: #ff0000; font-weight: bold");const e=this.characterLoader.getCacheStats();console.log(`[SceneManager] Pre-dispose: ${e.builtInModels} built-in models, ${e.customModels} custom models`),this.renderLoop.stop(),window.removeEventListener("resize",this.onWindowResize);const t=this.sceneCore.getCanvas();t.removeEventListener("webglcontextlost",this.onContextLost),t.removeEventListener("webglcontextrestored",this.onContextRestored),(n=this.resizeObserver)==null||n.disconnect(),this.resizeObserver=null,this.inputHandler.dispose(),this.drawingManager.dispose(),this.buildingManager.dispose(),this.effectsManager.dispose(),this.agentManager.dispose(),this.selectionManager.dispose(),this.battlefield.dispose(),this.characterLoader.dispose(),this.cameraManager.dispose(),this.sceneCore.dispose(),console.log("%c[SceneManager] dispose() complete - all resources freed","color: #00ff00; font-weight: bold")}}const $u="tide_webgl_active";typeof window<"u"&&(window.__tidePersistedScene===void 0&&(window.__tidePersistedScene=null),window.__tidePersistedCanvas===void 0&&(window.__tidePersistedCanvas=null),window.__tideWsConnected===void 0&&(window.__tideWsConnected=!1),window.__tideIsPageUnloading===void 0&&(window.__tideIsPageUnloading=!1));function rd(){return typeof window<"u"?window.__tidePersistedScene??null:null}function yS(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function uE(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function Vl(s){typeof window<"u"&&(window.__tidePersistedScene=s)}function Hu(s){typeof window<"u"&&(window.__tidePersistedCanvas=s)}function xS(s){typeof window<"u"&&(window.__tideWsConnected=s)}function dE(s){typeof window<"u"&&(window.__tideIsPageUnloading=s)}function hE(){sessionStorage.setItem($u,"true")}function wu(s){dE(!0),sessionStorage.removeItem($u),oS(),iT(),window.__tideScene&&(window.__tideScene=null);const e=rd();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),Vl(null)):console.log("[App] No persistedScene to dispose"),Hu(null),xS(!1);const t=document.getElementById("battlefield");t&&t.remove();const n=document.getElementById("app");n&&(n.innerHTML="")}function pE(){var i,o;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem($u)==="true"&&console.log("[App] Detected unclean shutdown from previous session - forcing cleanup"),window.__tideScene){console.log("[App] Cleaning up stale __tideScene reference");try{(o=(i=window.__tideScene).dispose)==null||o.call(i)}catch{}window.__tideScene=null}const e=rd();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}Vl(null)}const t=document.getElementById("battlefield"),n=yS();t&&t!==n&&t.remove(),sessionStorage.removeItem($u)}function mE(){typeof window>"u"||(pE(),window.addEventListener("pageshow",s=>{s.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),wu(),window.location.reload())}),window.onunload=()=>wu(),window.onbeforeunload=s=>{wu()},window.addEventListener("pagehide",s=>{wu(`pagehide (persisted=${s.persisted})`)}))}mE();const Xv={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"concrete",brightness:1,skyColor:null},Yv={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},Zv={idleAnimation:"sit",workingAnimation:"sprint"},fE=0;function vS(){const s={characterScale:2,indicatorScale:1,gridVisible:!0,timeMode:"day",terrain:Xv,modelStyle:Yv,animations:Zv,fpsLimit:fE},e=ka(rt.CONFIG,null);return e?{characterScale:e.characterScale??s.characterScale,indicatorScale:e.indicatorScale??s.indicatorScale,gridVisible:e.gridVisible??s.gridVisible,timeMode:e.timeMode??s.timeMode,terrain:{...Xv,...e.terrain},modelStyle:{...Yv,...e.modelStyle},animations:{...Zv,...e.animations},fpsLimit:e.fpsLimit??s.fpsLimit}:s}function gE(s){Xa(rt.CONFIG,s)}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function wS(){console.log("[Tide HMR] Manual scene refresh triggered");const s=rd();if(s){try{s.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}Vl(null)}Hu(null),window.__tideScene&&(window.__tideScene=null);const e=document.getElementById("battlefield");if(e){const t=e.getContext("webgl2")||e.getContext("webgl");if(t){const n=t.getExtension("WEBGL_lose_context");n&&n.loseContext()}}window.__tideHmrPendingSceneChanges=!1,window.location.reload()}typeof window<"u"&&(window.__tideHmrSceneRefresh=wS);function bE({canvasRef:s,selectionBoxRef:e,showToast:t,showAgentNotification:n,toolboxModal:i,contextMenu:o,setHoveredAgentPopup:r,setBuildingPopup:c,getBuildingPopup:u,openBuildingModal:h,openPM2LogsModal:m,openBossLogsModal:f,openDatabasePanel:g}){const b=x.useRef(null),v=x.useRef(null),w=x.useRef(null);return x.useEffect(()=>{if(!s.current||!e.current)return;let k=!1;const C=rd(),A=yS()===s.current;function _(){var M,E,F,T,R,D,I,O;(M=b.current)==null||M.setOnToast(t),(E=b.current)==null||E.setOnBuildingClick((X,W)=>{P.selectBuilding(X);const G=P.getState().buildings.get(X);(G==null?void 0:G.type)==="folder"&&G.folderPath?P.openFileExplorer(G.folderPath):(G==null?void 0:G.type)==="server"||(G==null?void 0:G.type)==="boss"||(G==null?void 0:G.type)==="database"?(v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{c({buildingId:X,screenPos:W,fromClick:!0}),v.current=null},150)):h(X)}),(F=b.current)==null||F.setOnContextMenu((X,W,G)=>{o.open(X,W,G)}),(T=b.current)==null||T.setOnAgentHover(()=>{}),(R=b.current)==null||R.setOnBuildingHover((X,W)=>{const G=u();if(X&&W){const B=P.getState().buildings.get(X);((B==null?void 0:B.type)==="server"||(B==null?void 0:B.type)==="boss"||(B==null?void 0:B.type)==="database")&&!(G!=null&&G.fromClick)&&c({buildingId:X,screenPos:W,fromClick:!1})}else G!=null&&G.fromClick||c(null)}),(D=b.current)==null||D.setOnGroundClick(()=>{c(null)}),(I=b.current)==null||I.setOnAreaDoubleClick(X=>{P.selectArea(X),i.open()}),(O=b.current)==null||O.setOnBuildingDoubleClick(X=>{var G;v.current&&(clearTimeout(v.current),v.current=null),c(null);const W=P.getState().buildings.get(X);(W==null?void 0:W.type)==="server"&&((G=W.pm2)!=null&&G.enabled)?m==null||m(X):(W==null?void 0:W.type)==="boss"?f==null||f(X):(W==null?void 0:W.type)==="database"?g==null||g(X):(W==null?void 0:W.type)==="folder"&&W.folderPath?P.openFileExplorer(W.folderPath):h(X)})}if(C&&A){b.current=C,console.log("[Tide] Reusing existing scene (StrictMode remount)");const M=P.getState();C.syncAreas(),C.syncBuildings(),M.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",M.agents.size),C.syncAgents(Array.from(M.agents.values()))),_()}else{const M=s.current,E=e.current,F=()=>{if(k){console.log("[Tide] Effect cleaned up before scene init, skipping");return}if(!M.isConnected||!E.isConnected){console.warn("[Tide] Canvas disconnected before initialization");return}(!M.clientWidth||!M.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),M.style.width="100%",M.style.height="100%",M.offsetHeight),(!M.clientWidth||!M.clientHeight)&&(M.width=window.innerWidth,M.height=window.innerHeight),hE();try{const T=new cE(M,E);b.current=T,Vl(T),Hu(M);const R=vS();T.setCharacterScale(R.characterScale),T.setIndicatorScale(R.indicatorScale),T.setGridVisible(R.gridVisible),T.setTimeMode(R.timeMode),T.setTerrainConfig(R.terrain),T.setFloorStyle(R.terrain.floorStyle,!0),T.setAgentModelStyle(R.modelStyle),T.setIdleAnimation(R.animations.idleAnimation),T.setWorkingAnimation(R.animations.workingAnimation),T.setFpsLimit(R.fpsLimit),T.syncAreas(),T.syncBuildings(),T.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const D=P.getState();D.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",D.customAgentClasses.size),T.setCustomAgentClasses(D.customAgentClasses)),D.agents.size>0&&(console.log("[Tide] Syncing agents from store:",D.agents.size),T.syncAgents(Array.from(D.agents.values()))),T.upgradeAgentModels()}).catch(D=>{console.warn("[Tide] Some models failed to load, using fallback:",D)}),_()}catch(T){console.error("[Tide] Failed to initialize 3D scene:",T)}};w.current=requestAnimationFrame(F)}return sS({onAgentCreated:M=>{var E,F;(E=b.current)==null||E.addAgent(M),(F=window.__spawnModalSuccess)==null||F.call(window)},onAgentUpdated:(M,E)=>{var F;(F=b.current)==null||F.updateAgent(M,E)},onAgentDeleted:M=>{var E;(E=b.current)==null||E.removeAgent(M)},onAgentsSync:M=>{var E;(E=b.current)==null||E.syncAgents(M)},onAreasSync:()=>{var E,F;(E=b.current)==null||E.syncAreas();const M=Array.from(P.getState().agents.values());(F=b.current)==null||F.syncAgents(M)},onSpawnError:()=>{var M;(M=window.__spawnModalError)==null||M.call(window)},onSpawnSuccess:()=>{var M;(M=window.__spawnModalSuccess)==null||M.call(window)},onDirectoryNotFound:M=>{var E;(E=window.__spawnModalDirNotFound)==null||E.call(window,M)},onToolUse:(M,E,F)=>{var T;(T=b.current)==null||T.showToolBubble(M,E,F)},onDelegation:(M,E)=>{var F;(F=b.current)==null||F.showDelegationEffect(M,E)},onCustomClassesSync:M=>{var E,F;(E=b.current)==null||E.setCustomAgentClasses(M),(F=b.current)==null||F.upgradeAgentModels()},onBuildingUpdated:M=>{var E;(E=b.current)==null||E.updateBuilding(M)},onSubagentStarted:M=>{var E;(E=b.current)==null||E.addSubagentEffect(M.id,M.parentAgentId,M.name,M.subagentType)},onSubagentCompleted:M=>{var T;const E=P.getSubagent(M)||P.getSubagentByToolUseId(M),F=(E==null?void 0:E.id)||M;(T=b.current)==null||T.completeSubagentEffect(F),setTimeout(()=>{var R;(R=b.current)==null||R.removeSubagentEffect(F)},3e4)}}),()=>{var M;k=!0,w.current!==null&&(cancelAnimationFrame(w.current),w.current=null),!((M=s.current)!=null&&M.isConnected)&&b.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),oT(),b.current.dispose(),b.current=null,Vl(null),Hu(null))}},[s.current,e.current]),b}let Xl,dr;try{Xl=require("@capacitor/local-notifications").LocalNotifications,dr=require("@capacitor/core").Capacitor}catch{}let yE=1;const xE="agent_alerts",kS="tide-notification-tap";function vE(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function SS(s){if(vE()){P.openTerminalOnMobile(s);return}P.selectAgent(s),P.setTerminalOpen(!0)}function Ef(){var s;return((s=dr==null?void 0:dr.isNativePlatform)==null?void 0:s.call(dr))??!1}async function wE(){return Ef()?(await Xl.requestPermissions()).display==="granted":"Notification"in window?await Notification.requestPermission()==="granted":!1}async function kE(s){const{title:e,body:t,icon:n,data:i}=s;if(Ef())await Xl.schedule({notifications:[{id:yE++,title:e,body:t,schedule:{at:new Date(Date.now()+100)},extra:i,channelId:xE,smallIcon:"ic_launcher",autoCancel:!0}]});else if("Notification"in window&&Notification.permission==="granted"){const o=new Notification(e,{body:t,icon:n,data:i});o.onclick=()=>{window.focus(),i&&window.dispatchEvent(new CustomEvent(kS,{detail:i}))}}}async function SE(s){s&&window.addEventListener(kS,e=>{const t=e;t.detail&&s(t.detail)}),Ef()&&Xl&&await Xl.addListener("localNotificationActionPerformed",e=>{s&&e.notification.extra&&s(e.notification.extra)})}function jE({showToast:s,showAgentNotification:e}){const t=x.useRef(!1);x.useEffect(()=>{if(t.current||uE())return;t.current=!0,sS({onToast:s,onReconnect:()=>{P.triggerReconnect()},onAgentNotification:i=>{e(i)}}),Kl(),xS(!0),wE(),SE(i=>{i.type==="agent_notification"&&typeof i.agentId=="string"&&SS(i.agentId)});const n=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>Kl(),100)};return window.addEventListener("tideAppResume",n),()=>{window.removeEventListener("tideAppResume",n)}},[s,e])}function CE(s){x.useEffect(()=>{let e="",t="",n=new Map;const i=o=>{var u;let r=!1;const c=new Map;for(const[h,m]of o){const g=`${m.position.x.toFixed(2)},${m.position.z.toFixed(2)},${m.status},${m.class},${m.isBoss},${((u=m.subordinateIds)==null?void 0:u.length)??0}`.split("").reduce((b,v)=>(b<<5)-b+v.charCodeAt(0),0);c.set(h,g),n.get(h)!==g&&(r=!0)}return c.size!==n.size&&(r=!0),{newVersion:c,changed:r}};return P.subscribe(()=>{var g;const o=P.getState(),r=Array.from(o.selectedAgentIds).sort().join(","),c=Array.from(o.selectedBuildingIds).sort().join(","),u=r!==e,h=c!==t,{newVersion:m,changed:f}=i(o.agents);(u||h||f)&&(e=r,t=c,n=m,(g=s.current)==null||g.refreshSelectionVisuals())})},[s])}function AE(s){x.useEffect(()=>{var n;(n=s.current)==null||n.syncAreas();let e=0,t=0;return P.subscribe(()=>{var c,u;const o=P.getState().areas;if(o.size!==e){e=o.size,t=Date.now(),(c=s.current)==null||c.syncAreas();return}let r=0;for(const[h,m]of o){let f=h.charCodeAt(0);f+=(m.width??0)+(m.height??0)+(m.radius??0),f+=Math.floor(m.center.x*100)+Math.floor(m.center.z*100),f+=(m.zIndex??0)*1e3;for(let g=0;g<m.name.length;g++)f+=m.name.charCodeAt(g);for(let g=0;g<m.color.length;g++)f+=m.color.charCodeAt(g);if(m.directoryGitCounts)for(const g of m.directoryGitCounts)f+=(g+1)*7;r^=f|0}r!==t&&(t=r,(u=s.current)==null||u.syncAreas())})},[s])}function NE(s){x.useEffect(()=>{var n;(n=s.current)==null||n.syncBuildings();let e=0,t=0;return P.subscribe(()=>{var c,u;const o=P.getState().buildings;if(o.size!==e){e=o.size,t=Date.now(),(c=s.current)==null||c.syncBuildings();return}let r=0;for(const[h,m]of o){r^=m.position.x*1e3+m.position.z|0,r^=(m.scale||1)*1e4|0;const f=`${m.style||""}${m.name}${m.status}${m.gitChangesCount||0}`;for(let g=0;g<f.length;g++)r=(r<<5)-r+f.charCodeAt(g)|0}r!==t&&(t=r,(u=s.current)==null||u.syncBuildings())})},[s])}function TE(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.highlightArea(e)},[s,e])}function ME(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.setPowerSaving(e)},[s,e])}function EE({sceneRef:s,spawnModal:e,commanderModal:t,explorerModal:n,spotlightModal:i,deleteConfirmModal:o,onRequestBuildingDelete:r}){x.useEffect(()=>{const c=u=>{var F,T,R,D;const h=P.getShortcuts(),m=u.target,f=m.tagName==="INPUT"||m.tagName==="TEXTAREA",g=h.find(I=>I.id==="deselect-all");if(ut(u,g)){if(Mm()){u.preventDefault();return}const I=P.getState();if(I.activeTool==="rectangle"||I.activeTool==="circle"){(F=s.current)==null||F.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():I.terminalOpen?(P.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(P.deselectAll(),(T=s.current)==null||T.refreshSelectionVisuals())}for(let I=1;I<=9;I++){const O=h.find(X=>X.id===`select-agent-${I}`);if(ut(u,O)){u.preventDefault();const X=P.getState(),W=I-1,G=Array.from(X.agents.keys());W<G.length&&(P.selectAgent(G[W]),(R=s.current)==null||R.refreshSelectionVisuals());return}}const b=h.find(I=>I.id==="spawn-agent");if(ut(u,b)){u.preventDefault(),e.open();return}const v=h.find(I=>I.id==="toggle-commander-tab");if(ut(u,v)&&!f){u.preventDefault(),t.toggle();return}const w=h.find(I=>I.id==="toggle-commander");if(ut(u,w)){u.preventDefault(),t.toggle();return}const k=h.find(I=>I.id==="toggle-file-explorer");if(ut(u,k)){u.preventDefault();const I=P.getState();if(n.isOpen||I.explorerFolderPath!==null||I.explorerAreaId!==null)n.close(),P.closeFileExplorer();else{const X=P.getLastExplorerState();if((X==null?void 0:X.type)==="folder")P.openFileExplorer(X.path);else if((X==null?void 0:X.type)==="area")if(I.areas.has(X.areaId))n.open(X.areaId);else{const W=Array.from(I.areas.values()).filter(G=>G.directories&&G.directories.length>0);W.length>0&&n.open(W[0].id)}else{const W=Array.from(I.areas.values()).filter(G=>G.directories&&G.directories.length>0);W.length>0&&n.open(W[0].id)}}return}const C=h.find(I=>I.id==="toggle-spotlight");if(ut(u,C)||u.altKey&&!u.ctrlKey&&!u.metaKey&&u.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:C,altKey:u.altKey,code:u.code}),u.preventDefault(),i.toggle();return}const j=h.find(I=>I.id==="toggle-2d-view");if(ut(u,j)){u.preventDefault();const I=P.getState().viewMode,O=I==="3d"?"2d":I==="2d"?"dashboard":"3d";P.setViewMode(O);return}const A=h.find(I=>I.id==="next-working-agent"),_=h.find(I=>I.id==="prev-working-agent");if((ut(u,A)||ut(u,_))&&!f){const I=P.getState();if(I.terminalOpen)return;const X=Array.from(I.agents.values()).filter(q=>q.status==="working");if(X.length===0)return;u.preventDefault();const W=I.selectedAgentIds.size===1?Array.from(I.selectedAgentIds)[0]:null,G=W?X.findIndex(q=>q.id===W):-1;let B;ut(u,A)?B=G===-1?0:(G+1)%X.length:B=G===-1?X.length-1:(G-1+X.length)%X.length,P.selectAgent(X[B].id),(D=s.current)==null||D.refreshSelectionVisuals();return}const M=h.find(I=>I.id==="delete-selected"),E=h.find(I=>I.id==="delete-selected-backspace");if((ut(u,M)||ut(u,E))&&!f){const I=P.getState();if(I.selectedAgentIds.size>0){u.preventDefault(),o.open();return}if(I.selectedBuildingIds.size>0){u.preventDefault(),r();return}return}};return document.addEventListener("keydown",c,!0),()=>document.removeEventListener("keydown",c,!0)},[s,e,t,n,i,o,r])}function _E(){const[s,e]=x.useState(!1);return window.__tideSetBackNavModal=e,x.useEffect(()=>{if(!(window.innerWidth<=768))return;if(window.__tideBackNavSetup){window.location.hash.includes("app")||(window.location.hash="#app");return}window.__tideBackNavSetup=!0,window.location.hash.includes("app")||(window.location.hash="#app");const i=()=>{var r;window.innerWidth>768||window.location.hash.includes("app")||(window.location.hash="#app",Mm()||(r=window.__tideSetBackNavModal)==null||r.call(window,!0))},o=()=>{var r;window.innerWidth>768||(window.location.hash.includes("app")||(window.location.hash="#app"),window.location.hash==="#app"&&setTimeout(()=>{window.location.hash==="#app"&&!window.location.hash.includes("app2")&&(window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"))},50),Mm()||(r=window.__tideSetBackNavModal)==null||r.call(window,!0))};window.history.pushState(null,"","#app1"),window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"),window.addEventListener("hashchange",i),window.addEventListener("popstate",o)},[]),{showBackNavModal:s,setShowBackNavModal:e,handleLeave:()=>{e(!1);const n=window.__tideHistoryDepth??2;window.history.go(-(n+1))}}}const Gp="agent-order-change";function jS(s){const e=x.useMemo(()=>new Set(s.map(u=>u.id)),[s]),[t,n]=x.useState(()=>ka(rt.AGENT_ORDER,[]));x.useEffect(()=>{const u=h=>{n(h.detail)};return window.addEventListener(Gp,u),()=>{window.removeEventListener(Gp,u)}},[]);const i=x.useMemo(()=>{const u=t.filter(g=>e.has(g)),h=s.filter(g=>!u.includes(g.id)).map(g=>g.id),m=[...u,...h],f=new Map(s.map(g=>[g.id,g]));return m.map(g=>f.get(g)).filter(g=>g!==void 0)},[s,t,e]),o=x.useCallback(u=>{n(u),Xa(rt.AGENT_ORDER,u),window.dispatchEvent(new CustomEvent(Gp,{detail:u}))},[]),r=x.useCallback((u,h)=>{const m=i.map(g=>g.id),[f]=m.splice(u,1);m.splice(h,0,f),o(m)},[i,o]),c=x.useCallback(()=>{n([]),Xa(rt.AGENT_ORDER,[])},[]);return x.useEffect(()=>{if(e.size===0)return;const u=t.filter(h=>e.has(h));u.length!==t.length&&o(u)},[e,t,o]),{orderedAgents:i,moveAgent:r,resetOrder:c}}let ba,Hm;try{ba=require("@capacitor/core").Capacitor,Hm=require("@capacitor/core").CapacitorHttp}catch{}const _f="deivid11/tide-commander",DE=`https://api.github.com/repos/${_f}/releases/latest`,RE=`https://api.github.com/repos/${_f}/releases?per_page=3`,LE=3600*1e3,Qv="app_update_dismissed_version",Jv="0.61.4";function CS(){var m;const[s,e]=x.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Jv}),t=((m=ba==null?void 0:ba.getPlatform)==null?void 0:m.call(ba))==="android"||!1,n=f=>f.replace(/^v/,"").split(".").map(b=>parseInt(b,10)||0),i=(f,g)=>{const b=n(f),v=n(g),w=Math.max(b.length,v.length);for(let k=0;k<w;k++){const C=b[k]||0,j=v[k]||0;if(C>j)return 1;if(C<j)return-1}return 0},o=async f=>{var b;if(ba&&Hm&&((b=ba.isNativePlatform)==null?void 0:b.call(ba))===!0){const v=await Hm.get({url:f,headers:{Accept:"application/vnd.github.v3+json"}});return{data:v.data,status:v.status}}else{const v=await fetch(f,{headers:{Accept:"application/vnd.github.v3+json"}});return v.ok?{data:await v.json(),status:v.status}:{data:null,status:v.status}}},r=x.useCallback(async(f=!1)=>{e(g=>({...g,isChecking:!0,error:null}));try{const[g,b]=await Promise.all([o(DE),o(RE)]);if(g.status!==200)throw new Error(`GitHub API error: ${g.status}`);const v=g.data,w=v.tag_name;let k=[];b.status===200&&b.data&&(k=b.data.map(M=>({version:M.tag_name,name:M.name,publishedAt:M.published_at,releaseUrl:M.html_url})));const C=localStorage.getItem(Qv);if(!f&&C===w)return e(M=>({...M,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;if(!(i(w,Jv)>0))return e(M=>({...M,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;const A=v.assets.find(M=>M.name.endsWith(".apk")&&M.content_type==="application/vnd.android.package-archive"),_={version:w,name:v.name,changelog:v.body,releaseUrl:v.html_url,apkUrl:(A==null?void 0:A.browser_download_url)||null,apkSize:(A==null?void 0:A.size)||null,publishedAt:v.published_at};return e(M=>({...M,isChecking:!1,updateAvailable:!0,updateInfo:_,recentReleases:k})),_}catch(g){const b=g instanceof Error?g.message:"Failed to check for updates";return e(v=>({...v,isChecking:!1,error:b})),null}},[]),c=x.useCallback(async()=>{var f,g,b;if(!((f=s.updateInfo)!=null&&f.apkUrl)){(g=s.updateInfo)!=null&&g.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(b=s.updateInfo)!=null&&b.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),e(v=>({...v,error:null}))}catch(v){const w=v instanceof Error?v.message:"Failed to open download";e(k=>({...k,error:w}))}},[s.updateInfo,t]),u=x.useCallback(()=>{s.updateInfo&&localStorage.setItem(Qv,s.updateInfo.version),e(f=>({...f,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),h=x.useCallback(()=>{var f;(f=s.updateInfo)!=null&&f.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${_f}/releases`,"_blank")},[s.updateInfo]);return x.useEffect(()=>{if(!t)return;const f=setTimeout(()=>{r()},5e3),g=setInterval(()=>{r()},LE);return()=>{clearTimeout(f),clearInterval(g)}},[t,r]),{...s,isAndroid:t,checkForUpdate:r,downloadAndInstall:c,dismissUpdate:u,openReleasePage:h}}function Qs(s){const e=x.useRef(null),t=x.useCallback(i=>{e.current=i.target,i.target===i.currentTarget&&i.stopPropagation()},[]),n=x.useCallback(i=>{i.target===i.currentTarget&&e.current===i.currentTarget&&(i.stopPropagation(),s()),e.current=null},[s]);return{handleMouseDown:t,handleClick:n}}const BE=3e4;function PE(){const s=x.useRef(null);x.useEffect(()=>{const e=async()=>{var r,c;const t=P.getState(),n=new Map,i=new Map;for(const[u,h]of t.buildings){const m=h.folderPath||h.cwd;m&&(i.has(m)||i.set(m,[]),i.get(m).push(u))}for(const[u,h]of i)try{const m=await dt(Qe(`/api/files/git-status?path=${encodeURIComponent(u)}`));if(!m.ok)continue;const g=((r=(await m.json()).files)==null?void 0:r.length)||0;n.set(u,g);for(const b of h){const v=P.getState().buildings.get(b);v&&v.gitChangesCount!==g&&P.updateBuildingLocal(b,{gitChangesCount:g})}}catch{}const o=new Map;for(const[u,h]of t.areas)h.archived||!h.directories||h.directories.forEach((m,f)=>{m&&(o.has(m)||o.set(m,[]),o.get(m).push({areaId:u,dirIndex:f}))});if(o.size!==0)for(const[u,h]of o)try{let m;if(n.has(u))m=n.get(u);else{const g=await dt(Qe(`/api/files/git-status?path=${encodeURIComponent(u)}`));if(!g.ok)continue;m=((c=(await g.json()).files)==null?void 0:c.length)||0,n.set(u,m)}const f=new Map;for(const g of h)f.has(g.areaId)||f.set(g.areaId,[]),f.get(g.areaId).push({dirIndex:g.dirIndex,count:m});for(const[g,b]of f){const v=P.getState().areas.get(g);if(!v)continue;const w=v.directoryGitCounts?[...v.directoryGitCounts]:new Array(v.directories.length).fill(0);let k=!1;for(const{dirIndex:C,count:j}of b)w[C]!==j&&(w[C]=j,k=!0);k&&P.updateAreaLocal(g,{directoryGitCounts:w})}}catch{}};return e(),s.current=setInterval(e,BE),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[])}const e0={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,externalEditorCommand:""};function IE(s,e,t,n){return{setAgents(i){const o=new Map;for(const c of i)o.set(c.id,c),(c.class==="boss"||c.isBoss)&&console.log("[Store.setAgents] Boss agent:",c.name,"subordinateIds:",c.subordinateIds);const r=i.find(c=>c.status==="working");e(c=>{c.agents=o,r&&c.selectedAgentIds.size===0&&(c.selectedAgentIds.add(r.id),c.terminalOpen=!0)}),t()},addAgent(i){e(o=>{const r=new Map(o.agents);r.set(i.id,i),o.agents=r}),t()},updateAgent(i){var u;const r=s().agents.get(i.id),c=(r==null?void 0:r.status)!==i.status;c&&console.log(`[Store] Agent ${i.name} status update: ${r==null?void 0:r.status} → ${i.status}`),e(h=>{const m=new Map(h.agents);m.set(i.id,i),h.agents=m}),t(),c&&console.log(`[Store] Agent ${i.name} status now in store: ${(u=s().agents.get(i.id))==null?void 0:u.status}`)},updateAgentContextStats(i,o){const c=s().agents.get(i);c&&(e(u=>{const h=new Map(u.agents);h.set(i,{...c,contextStats:o,contextUsed:o.totalTokens,contextLimit:o.contextWindow}),u.agents=h}),t())},removeAgent(i){e(o=>{const r=new Map(o.agents);r.delete(i),o.agents=r,o.selectedAgentIds.delete(i),o.agentOutputs.delete(i)}),t()},selectAgent(i){e(o=>{o.selectedAgentIds.clear(),i&&(o.selectedAgentIds.add(i),o.lastSelectedAgentId=i),o.currentSnapshot=null}),t()},addToSelection(i){e(o=>{o.selectedAgentIds.has(i)?o.selectedAgentIds.delete(i):o.selectedAgentIds.add(i)}),t()},selectMultiple(i){e(o=>{o.selectedAgentIds.clear();for(const r of i)o.selectedAgentIds.add(r)}),t()},deselectAll(){e(i=>{i.selectedAgentIds.clear()}),t()},spawnAgent(i,o,r,c,u,h,m,f,g,b,v,w,k){console.log("[Store] spawnAgent called with:",{name:i,agentClass:o,cwd:r,position:c,sessionId:u,useChrome:h,permissionMode:m,initialSkillIds:f,provider:g,codexConfig:b,codexModel:v,model:w,customInstructions:k?`${k.length} chars`:void 0});const C=c?{x:c.x,y:0,z:c.z}:void 0,j={type:"spawn_agent",payload:{name:i,class:o,cwd:r,position:C,sessionId:u,useChrome:h,permissionMode:m,initialSkillIds:f,provider:g,codexConfig:b,codexModel:v,model:w,customInstructions:k}},A=n();if(!A){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}A(j),console.log("[Store] Message sent to WebSocket")},createDirectoryAndSpawn(i,o,r){var c;(c=n())==null||c({type:"create_directory",payload:{path:i,name:o,class:r}})},sendCommand(i,o){var r;e(c=>{c.lastPrompts.set(i,{text:o,timestamp:Date.now()})}),t(),(r=n())==null||r({type:"send_command",payload:{agentId:i,command:o}})},refreshAgentContext(i){var o;(o=n())==null||o({type:"request_context_stats",payload:{agentId:i}})},moveAgent(i,o){var u;const c=s().agents.get(i);c&&(e(h=>{const m={...c,position:o},f=new Map(h.agents);f.set(i,m),h.agents=f}),t()),(u=n())==null||u({type:"move_agent",payload:{agentId:i,position:o}})},killAgent(i){var o;(o=n())==null||o({type:"kill_agent",payload:{agentId:i}})},stopAgent(i){var o;(o=n())==null||o({type:"stop_agent",payload:{agentId:i}})},clearContext(i){var o;(o=n())==null||o({type:"clear_context",payload:{agentId:i}}),e(r=>{const c=new Map(r.agentOutputs);c.delete(i),r.agentOutputs=c}),t()},collapseContext(i){var o;(o=n())==null||o({type:"collapse_context",payload:{agentId:i}})},removeAgentFromServer(i){var o;(o=n())==null||o({type:"remove_agent",payload:{agentId:i}})},renameAgent(i,o){var u;const c=s().agents.get(i);c&&(e(h=>{const m={...c,name:o},f=new Map(h.agents);f.set(i,m),h.agents=f}),t()),(u=n())==null||u({type:"rename_agent",payload:{agentId:i,name:o}})},updateAgentProperties(i,o){var u;const c=s().agents.get(i);c&&(e(h=>{const m={...c};o.class!==void 0&&(m.class=o.class),o.permissionMode!==void 0&&(m.permissionMode=o.permissionMode),o.model!==void 0&&(m.model=o.model),o.provider!==void 0&&(m.provider=o.provider),o.codexConfig!==void 0&&(m.codexConfig=o.codexConfig),o.codexModel!==void 0&&(m.codexModel=o.codexModel),o.useChrome!==void 0&&(m.useChrome=o.useChrome),o.cwd!==void 0&&(m.cwd=o.cwd);const f=new Map(h.agents);f.set(i,m),h.agents=f}),t()),(u=n())==null||u({type:"update_agent_properties",payload:{agentId:i,updates:o}})},getTotalTokens(){let i=0;for(const o of s().agents.values())i+=o.tokensUsed;return i},getSelectedAgents(){const i=s(),o=[];for(const r of i.selectedAgentIds){const c=i.agents.get(r);c&&o.push(c)}return o},addActivity(i){e(o=>{o.activities.unshift(i),o.activities.length>100&&o.activities.pop()}),t()},addToolExecution(i,o,r){const u=s().agents.get(i);e(h=>{h.toolExecutions.unshift({agentId:i,agentName:(u==null?void 0:u.name)||"Unknown",toolName:o,toolInput:r,timestamp:Date.now()}),h.toolExecutions.length>200&&h.toolExecutions.pop()}),t()},addFileChange(i,o,r){const u=s().agents.get(i);e(h=>{h.fileChanges.unshift({agentId:i,agentName:(u==null?void 0:u.name)||"Unknown",action:o,filePath:r,timestamp:Date.now()}),h.fileChanges.length>200&&h.fileChanges.pop()}),t()},async loadToolHistory(){try{const o=await(await dt(Qe("/api/agents/tool-history?limit=100"))).json();e(r=>{o.toolExecutions&&(r.toolExecutions=o.toolExecutions),o.fileChanges&&(r.fileChanges=o.fileChanges)}),t()}catch(i){console.error("[Store] Failed to load tool history:",i)}}}}function OE(s,e,t,n){return{addOutput(i,o){const r=n();e(c=>{const u=c.agentOutputs.get(i)||[];if(o.uuid&&u.some(g=>g.uuid===o.uuid))return;let h=[...u,o];h.length>200&&(h=h.slice(-200)),ql.info(`Store: ${u.length} -> ${h.length}`,{agentId:i,text:o.text.slice(0,60),isStreaming:o.isStreaming,listeners:r},"store:addOutput");const m=new Map(c.agentOutputs);m.set(i,h),c.agentOutputs=m}),t()},clearOutputs(i){e(o=>{const r=new Map(o.agentOutputs);r.delete(i),o.agentOutputs=r}),t()},getOutputs(i){return s().agentOutputs.get(i)||[]},addUserPromptToOutput(i,o){this.addOutput(i,{text:o,isStreaming:!1,timestamp:Date.now(),isUserPrompt:!0})},getLastPrompt(i){return s().lastPrompts.get(i)},setLastPrompt(i,o){e(r=>{r.lastPrompts.set(i,{text:o,timestamp:Date.now()})}),t()},preserveOutputs(){const i=s(),o=new Map;for(const[r,c]of i.agentOutputs)o.set(r,c.map(u=>({...u})));return o},mergeOutputsWithHistory(i,o,r){const c=[...o,...r];return c.sort((u,h)=>u.timestamp-h.timestamp),e(u=>{const h=new Map(u.agentOutputs);h.set(i,c),u.agentOutputs=h}),t(),c}}}function zE(s,e,t,n){return{setSupervisorReport(i){e(o=>{o.supervisor.lastReport=i,o.supervisor.lastReportTime=i.timestamp;const r=new Map(o.supervisor.agentHistories);for(const c of i.agentSummaries){const u=r.get(c.agentId)||[],h={id:`${i.id}-${c.agentId}`,timestamp:i.timestamp,reportId:i.id,analysis:c};if(!u.some(m=>m.reportId===i.id)){const m=[h,...u];m.length>50&&m.pop(),r.set(c.agentId,m)}}o.supervisor.agentHistories=r,o.supervisor.generatingReport=!1}),t()},addNarrative(i,o){e(r=>{const c=r.supervisor.narratives.get(i)||[];c.unshift(o),c.length>50&&c.pop();const u=new Map(r.supervisor.narratives);u.set(i,c),r.supervisor.narratives=u}),t()},getNarratives(i){return s().supervisor.narratives.get(i)||[]},setSupervisorStatus(i){e(o=>{o.supervisor.enabled=i.enabled,i.autoReportOnComplete!==void 0&&(o.supervisor.autoReportOnComplete=i.autoReportOnComplete),o.supervisor.lastReportTime=i.lastReportTime,o.supervisor.nextReportTime=i.nextReportTime}),t()},setSupervisorConfig(i){var o;(o=n())==null||o({type:"set_supervisor_config",payload:i})},requestSupervisorReport(){var i;e(o=>{o.supervisor.generatingReport=!0}),t(),(i=n())==null||i({type:"request_supervisor_report",payload:{}})},requestAgentSupervisorHistory(i){var o;e(r=>{r.supervisor.loadingHistoryForAgent=i}),t(),(o=n())==null||o({type:"request_agent_supervisor_history",payload:{agentId:i}})},setAgentSupervisorHistory(i){e(o=>{const r=new Map(o.supervisor.agentHistories);r.set(i.agentId,i.entries),o.supervisor.agentHistories=r,o.supervisor.historyFetchedForAgents.add(i.agentId),o.supervisor.loadingHistoryForAgent===i.agentId&&(o.supervisor.loadingHistoryForAgent=null)}),t()},getAgentSupervisorHistory(i){return s().supervisor.agentHistories.get(i)||[]},addAgentAnalysis(i,o){e(r=>{const c=new Map(r.supervisor.agentHistories),u=c.get(i)||[],h={id:`single-${Date.now()}-${i}`,timestamp:Date.now(),reportId:`single-${Date.now()}`,analysis:o};if(!u.some(f=>Math.abs(f.timestamp-h.timestamp)<5e3&&f.analysis.statusDescription===o.statusDescription)){const f=[h,...u];f.length>50&&f.pop(),c.set(i,f),r.supervisor.agentHistories=c}}),t()},isLoadingHistoryForAgent(i){return s().supervisor.loadingHistoryForAgent===i},hasHistoryBeenFetched(i){return s().supervisor.historyFetchedForAgents.has(i)},setGlobalUsage(i){console.log("[Supervisor] setGlobalUsage called with:",i),e(o=>{o.supervisor.globalUsage=i,o.supervisor.refreshingUsage=!1}),t()},requestGlobalUsage(){console.log("[Supervisor] requestGlobalUsage called"),e(o=>{o.supervisor.refreshingUsage=!0}),t();const i=n();console.log("[Supervisor] sendMessage function:",i?"available":"null"),i?(console.log("[Supervisor] Sending request_global_usage message"),i({type:"request_global_usage",payload:{}})):console.warn("[Supervisor] Cannot send request_global_usage - no sendMessage function")},getGlobalUsage(){return s().supervisor.globalUsage}}}function FE(s,e,t,n){const i=()=>{var r;const o=Array.from(s().areas.values());(r=n())==null||r({type:"sync_areas",payload:o})};return{setActiveTool(o){e(r=>{r.activeTool=o,o!=="select"&&(r.selectedAreaId=null)}),t()},selectArea(o){e(r=>{r.selectedAreaId=o}),t()},addArea(o){if(o.zIndex===void 0||o.zIndex===null){const r=Array.from(s().areas.values()),c=r.length===0?-1:Math.max(...r.map(u=>u.zIndex??0));o.zIndex=c+1}e(r=>{r.areas.set(o.id,o)}),i(),t()},updateArea(o,r){s().areas.get(o)&&(e(h=>{Object.assign(h.areas.get(o),r)}),i(),t())},updateAreaLocal(o,r){s().areas.get(o)&&(e(h=>{Object.assign(h.areas.get(o),r)}),t())},deleteArea(o){e(r=>{r.areas.delete(o),r.selectedAreaId===o&&(r.selectedAreaId=null)}),i(),t()},assignAgentToArea(o,r){const u=s().areas.get(r);u&&!u.assignedAgentIds.includes(o)&&(e(h=>{for(const m of h.areas.values()){const f=m.assignedAgentIds.indexOf(o);f!==-1&&m.assignedAgentIds.splice(f,1)}h.areas.get(r).assignedAgentIds.push(o)}),i(),t())},unassignAgentFromArea(o,r){const u=s().areas.get(r);if(u){const h=u.assignedAgentIds.indexOf(o);h!==-1&&(e(m=>{m.areas.get(r).assignedAgentIds.splice(h,1)}),i(),t())}},addDirectoryToArea(o,r){const u=s().areas.get(o);u&&!u.directories.includes(r)&&(e(h=>{h.areas.get(o).directories.push(r)}),i(),t())},removeDirectoryFromArea(o,r){const u=s().areas.get(o);if(u){const h=u.directories.indexOf(r);h!==-1&&(e(m=>{m.areas.get(o).directories.splice(h,1)}),i(),t())}},getAreaDirectories(o){const r=s().areas.get(o);return(r==null?void 0:r.directories)||[]},isPositionInArea(o,r){if(r.type==="rectangle"&&r.width&&r.height){const c=r.width/2,u=r.height/2;return o.x>=r.center.x-c&&o.x<=r.center.x+c&&o.z>=r.center.z-u&&o.z<=r.center.z+u}else if(r.type==="circle"&&r.radius){const c=o.x-r.center.x,u=o.z-r.center.z;return c*c+u*u<=r.radius*r.radius}return!1},getAreaForAgent(o){const r=s(),c=r.agents.get(o);if(!c)return null;for(const u of r.areas.values())if(this.isPositionInArea({x:c.position.x,z:c.position.z},u))return u;return null},setAreasFromServer(o){e(r=>{const c=new Map;for(let u=0;u<o.length;u++){const h=o[u];h.directories||(h.directories=[]),(h.zIndex===void 0||h.zIndex===null)&&(h.zIndex=u),h.archived===void 0&&(h.archived=!1),c.set(h.id,h)}r.areas=c}),t()},getAreasInZOrder(){return Array.from(s().areas.values()).sort((r,c)=>(r.zIndex??0)-(c.zIndex??0))},getNextZIndex(){const o=Array.from(s().areas.values());return o.length===0?0:Math.max(...o.map(c=>c.zIndex??0))+1},bringAreaToFront(o){const r=s(),c=r.areas.get(o);if(!c)return;const u=Array.from(r.areas.values()),h=u.length===0?-1:Math.max(...u.map(b=>b.zIndex??0)),m=h+1,f=c.zIndex??0,g=u.filter(b=>(b.zIndex??0)===h);f===h&&g.length===1||(e(b=>{b.areas.get(o).zIndex=m}),i(),t())},sendAreaToBack(o){const r=s(),c=r.areas.get(o);if(!c)return;const u=Array.from(r.areas.values()),h=Math.min(...u.map(g=>g.zIndex??0)),m=c.zIndex??0,f=u.filter(g=>(g.zIndex??0)===h);m===h&&f.length===1||(e(g=>{for(const b of g.areas.values())b.id!==o&&(b.zIndex=(b.zIndex??0)+1);g.areas.get(o).zIndex=0}),i(),t())},setAreaZIndex(o,r){s().areas.get(o)&&(e(h=>{h.areas.get(o).zIndex=r}),i(),t())},archiveArea(o,r){const u=s().areas.get(o);if(!(!u||u.archived)){if(r)for(const h of u.assignedAgentIds)r(h);e(h=>{const m=h.areas.get(o);m.archived=!0,m.archivedAt=Date.now(),m.originalCenter={...m.center},h.selectedAreaId===o&&(h.selectedAreaId=null)}),i(),t()}},restoreArchivedArea(o,r){const c=s(),u=c.areas.get(o);if(!u||!u.archived)return;const h=u.center,m=r||u.originalCenter||u.center,f=m.x-h.x,g=m.z-h.z,b=Array.from(c.areas.values()),w=(b.length===0?-1:Math.max(...b.map(k=>k.zIndex??0)))+1;e(k=>{const C=k.areas.get(o);if(C.archived=!1,C.archivedAt=void 0,C.center=m,C.zIndex=w,f!==0||g!==0)for(const j of C.assignedAgentIds){const A=k.agents.get(j);A&&(A.position={x:A.position.x+f,y:A.position.y,z:A.position.z+g})}}),i(),t()},getArchivedAreas(){return Array.from(s().areas.values()).filter(o=>o.archived===!0)},getVisibleAreas(){return Array.from(s().areas.values()).filter(o=>!o.archived)},isAgentInArchivedArea(o){const r=s();for(const c of r.areas.values())if(c.archived&&c.assignedAgentIds.includes(o))return!0;return!1}}}function $E(s,e,t,n){const i=()=>{var c;const r=Array.from(s().buildings.values());(c=n())==null||c({type:"sync_buildings",payload:r})},o={selectBuilding(r){e(c=>{c.selectedBuildingIds.clear(),r&&c.selectedBuildingIds.add(r)}),t()},selectMultipleBuildings(r){e(c=>{c.selectedBuildingIds.clear();for(const u of r)c.selectedBuildingIds.add(u)}),t()},toggleBuildingSelection(r){e(c=>{c.selectedBuildingIds.has(r)?c.selectedBuildingIds.delete(r):c.selectedBuildingIds.add(r)}),t()},isBuildingSelected(r){return s().selectedBuildingIds.has(r)},getSelectedBuildingIds(){return Array.from(s().selectedBuildingIds)},deleteSelectedBuildings(){var c,u,h;const r=s();for(const m of r.selectedBuildingIds){const f=r.buildings.get(m);((c=f==null?void 0:f.pm2)!=null&&c.enabled||(u=f==null?void 0:f.docker)!=null&&u.enabled)&&((h=n())==null||h({type:"building_command",payload:{buildingId:m,command:"delete"}}))}e(m=>{const f=new Map(m.buildings);for(const g of m.selectedBuildingIds)f.delete(g);m.buildings=f,m.selectedBuildingIds.clear()}),i(),t()},addBuilding(r){e(c=>{const u=new Map(c.buildings);u.set(r.id,r),c.buildings=u}),i(),t()},updateBuilding(r,c){const h=s().buildings.get(r);h&&(e(m=>{const f=new Map(m.buildings);f.set(r,{...h,...c}),m.buildings=f}),i(),t())},updateBuildingLocal(r,c){const h=s().buildings.get(r);h&&(e(m=>{const f=new Map(m.buildings);f.set(r,{...h,...c}),m.buildings=f}),t())},deleteBuilding(r){var h,m,f;const u=s().buildings.get(r);((h=u==null?void 0:u.pm2)!=null&&h.enabled||(m=u==null?void 0:u.docker)!=null&&m.enabled)&&((f=n())==null||f({type:"building_command",payload:{buildingId:r,command:"delete"}})),e(g=>{const b=new Map(g.buildings);b.delete(r),g.buildings=b,g.selectedBuildingIds.delete(r)}),i(),t()},moveBuilding(r,c){const h=s().buildings.get(r);h&&(e(m=>{const f=new Map(m.buildings);f.set(r,{...h,position:c}),m.buildings=f}),i(),t())},updateBuildingPosition(r,c){o.moveBuilding(r,c)},createBuilding(r){const c={...r,id:`building_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,status:"stopped",createdAt:Date.now()};o.addBuilding(c)},sendBuildingCommand(r,c){var u;(u=n())==null||u({type:"building_command",payload:{buildingId:r,command:c}})},addBuildingLogs(r,c){e(u=>{const m=[...u.buildingLogs.get(r)||[],c];m.length>500&&m.splice(0,m.length-500);const f=new Map(u.buildingLogs);f.set(r,m),u.buildingLogs=f}),t()},getBuildingLogs(r){return s().buildingLogs.get(r)||[]},clearBuildingLogs(r){e(c=>{const u=new Map(c.buildingLogs);u.delete(r),c.buildingLogs=u}),t()},setBuildingsFromServer(r){e(c=>{const u=new Map;for(const h of r)u.set(h.id,h);c.buildings=u}),t()},updateBuildingFromServer(r){e(c=>{const u=new Map(c.buildings);u.set(r.id,r),c.buildings=u}),t()},removeBuildingFromServer(r){e(c=>{const u=new Map(c.buildings);u.delete(r),c.buildings=u,c.selectedBuildingIds.delete(r)}),t()},startLogStreaming(r,c=100){var h,m,f;const u=s().buildings.get(r);e(g=>{const b=new Map(g.streamingBuildingLogs);b.set(r,""),g.streamingBuildingLogs=b}),(h=u==null?void 0:u.docker)!=null&&h.enabled?(m=n())==null||m({type:"docker_logs_start",payload:{buildingId:r,lines:c}}):(f=n())==null||f({type:"pm2_logs_start",payload:{buildingId:r,lines:c}})},stopLogStreaming(r){var u,h,m;const c=s().buildings.get(r);(u=c==null?void 0:c.docker)!=null&&u.enabled?(h=n())==null||h({type:"docker_logs_stop",payload:{buildingId:r}}):(m=n())==null||m({type:"pm2_logs_stop",payload:{buildingId:r}})},appendStreamingLogChunk(r,c){e(u=>{const h=u.streamingBuildingLogs.get(r)||"",m=500*1024;let f=h+c;if(f.length>m){const b=f.indexOf(`
140
+ `,side:qk});i.add(new Ce(o,r)),i.add(new vf(16777215,1));const c=n.fromScene(i,.04).texture;t.environment=c,n.dispose(),o.dispose(),r.dispose()}createInputCallbacks(){return{onAgentClick:(e,t)=>this.inputEventHandlers.handleAgentClick(e,t),onAgentDoubleClick:e=>this.inputEventHandlers.handleAgentDoubleClick(e),onAgentHover:(e,t)=>this.inputEventHandlers.handleAgentHover(e,t),onGroundClick:()=>this.inputEventHandlers.handleGroundClick(),onMoveCommand:(e,t)=>this.inputEventHandlers.handleMoveCommand(e,t),onSelectionBox:(e,t)=>this.inputEventHandlers.handleSelectionBox(e,t),onDrawStart:e=>this.drawingManager.startDrawing(e),onDrawMove:e=>this.drawingManager.updateDrawing(e),onDrawEnd:e=>this.drawingManager.finishDrawing(e),onAreaRightClick:e=>this.inputEventHandlers.handleAreaRightClick(e),onAreaClick:e=>this.inputEventHandlers.handleAreaClick(e),onAreaDoubleClick:e=>this.inputEventHandlers.handleAreaDoubleClick(e),onResizeStart:(e,t)=>this.drawingManager.startResize(e,t),onResizeMove:e=>this.drawingManager.updateResize(e),onResizeEnd:()=>this.drawingManager.finishResize(),onGroundClickOutsideArea:()=>this.inputEventHandlers.handleGroundClickOutsideArea(),onFolderIconClick:(e,t)=>{var n;t?P.openFileExplorerForAreaFolder(e,t):P.openFileExplorerForArea(e),(n=this.onFolderIconClickCallback)==null||n.call(this,e)},onBuildingClick:(e,t)=>this.inputEventHandlers.handleBuildingClick(e,t),onBuildingDoubleClick:e=>this.inputEventHandlers.handleBuildingDoubleClick(e),onBuildingHover:(e,t)=>this.inputEventHandlers.handleBuildingHover(e,t),onBuildingDragStart:()=>{},onBuildingDragMove:(e,t)=>this.buildingManager.setBuildingPosition(e,t),onBuildingDragEnd:(e,t)=>P.updateBuildingPosition(e,t),onContextMenu:(e,t,n)=>this.callbackManager.triggerContextMenu(e,t,n),onActivity:()=>this.renderLoop.markActivity(),onToggleTerminal:()=>P.toggleTerminal()}}setupInputHandlerHelpers(){this.inputHandler.setDrawingModeChecker(()=>this.drawingManager.isInDrawingMode()),this.inputHandler.setResizeHandlers(()=>this.drawingManager.getResizeHandles(),()=>this.drawingManager.isCurrentlyResizing()),this.inputHandler.setAreaAtPositionGetter(e=>this.drawingManager.getAreaAtPosition(e)),this.inputHandler.setFolderIconMeshesGetter(()=>this.drawingManager.getFolderIconMeshes()),this.inputHandler.setBuildingAtPositionGetter(e=>{const t=this.buildingManager.getBuildingAtPosition(e);return t?{id:t.id}:null}),this.inputHandler.setBuildingPositionsGetter(()=>{const e=new Map;for(const[t,n]of this.buildingManager.getBuildingMeshData())e.set(t,n.group.position.clone());return e})}setupEventListeners(e){window.addEventListener("resize",this.onWindowResize),this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),e.parentElement&&this.resizeObserver.observe(e.parentElement),e.addEventListener("webglcontextlost",this.onContextLost),e.addEventListener("webglcontextrestored",this.onContextRestored)}updateInputHandlerReferences(){this.inputHandler.setReferences(this.battlefield.getGround(),this.agentManager.getAgentMeshes())}updateBattlefield(e,t){t-this.lastTimeUpdate>6e4&&(this.battlefield.updateTimeOfDay(),this.lastTimeUpdate=t),this.battlefield.updateGalacticAnimation(e),this.battlefield.updateCloudAnimation(e)}updateAnimations(e){const t=this.movementAnimator.update(this.agentManager.getAgentMeshes(),e);return this.effectsManager.update(),this.buildingManager.update(e),t}updateProceduralAnimations(e){if(this.proceduralBodiesDirty){this.proceduralBodiesCache.clear();for(const[t,n]of this.agentManager.getAgentMeshes())if(this.proceduralAnimator.has(t)&&n.animations.size===0){const i=n.group.getObjectByName("characterBody");i&&this.proceduralBodiesCache.set(t,i)}this.proceduralBodiesDirty=!1}this.proceduralBodiesCache.size>0&&this.proceduralAnimator.update(e,this.proceduralBodiesCache)}updateIndicatorScales(e,t,n){for(const[,i]of t){const o=e.position.distanceTo(i.group.position),r=Math.max(.5,Math.min(2.5,o/15))*n,c=i.group.userData.isBoss===!0,u=i.group.getObjectByName("statusBar"),h=i.group.getObjectByName("nameLabelSprite");if(u){const f=typeof u.userData.baseIndicatorScale=="number"?u.userData.baseIndicatorScale:c?2:1.6,g=typeof u.userData.aspectRatio=="number"?u.userData.aspectRatio:2560/4096;u.scale.set(f*r,f*g*r,1)}if(h){const f=typeof h.userData.baseIndicatorScale=="number"?h.userData.baseIndicatorScale:c?1.5:1.25,v=Math.max(c?1.35:1.1,Math.min(c?1.65:1.35,f)),w=typeof h.userData.aspectRatio=="number"?h.userData.aspectRatio:1024/4096;h.scale.set(v*r,v*w*r,1)}const m=i.group.getObjectByName("combinedUI");if(m){const f=typeof m.userData.baseIndicatorScale=="number"?m.userData.baseIndicatorScale:c?3:2.4,g=typeof m.userData.aspectRatio=="number"?m.userData.aspectRatio:1024/2048;m.scale.set(f*r,f*g*r,1)}if(!u&&!m){const f=i.group.getObjectByName("nameLabel");if(f){const v=.3*r;f.scale.set(v*(f.userData.aspectRatio||2),v,1)}const g=i.group.getObjectByName("manaBar");g&&g.scale.set(.9,.14,1);const b=i.group.getObjectByName("idleTimer");b&&b.scale.set(.9*r,.14*r,1)}}for(const[,i]of this.buildingManager.getBuildingMeshData()){const o=e.position.distanceTo(i.group.position),r=Math.max(.5,Math.min(2.5,o/15))*n,c=i.group.getObjectByName("buildingLabel");if(c){const u=.3*r;c.scale.set(u*(c.userData.aspectRatio||2),u,1)}}this.effectsManager.updateWithCamera(e)}async loadCharacterModels(){await this.agentManager.loadCharacterModels()}upgradeAgentModels(){this.agentManager.upgradeAgentModels(),this.updateInputHandlerReferences()}addAgent(e){this.agentManager.addAgent(e)}removeAgent(e){this.agentManager.removeAgent(e),this.updateInputHandlerReferences()}updateAgent(e,t=!1){this.agentManager.updateAgent(e,t)}syncAgents(e){this.agentManager.syncAgents(e)}setCustomAgentClasses(e){this.agentManager.setCustomAgentClasses(e)}refreshSelectionVisuals(){this.selectionManager.refreshSelectionVisuals()}createMoveOrderEffect(e){this.effectsManager.createMoveOrderEffect(e)}showToolBubble(e,t,n){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.createSpeechBubble(e,t,n)}showDelegationEffect(e,t){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.createDelegationEffect(e,t)}addSubagentEffect(e,t,n,i){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.addSubagentEffect(e,t,n,i)}completeSubagentEffect(e){this.effectsManager.completeSubagentEffect(e)}removeSubagentEffect(e){this.effectsManager.removeSubagentEffect(e)}focusAgent(e){this.cameraManager.focusAgent(e)}callSubordinates(e){var r;const n=P.getState().agents.get(e);if(!n||!(n.isBoss||n.class==="boss")||!((r=n.subordinateIds)!=null&&r.length))return;const i=new ot(n.position.x,n.position.y,n.position.z),o=this.inputHandler.calculateFormationPositions(i,n.subordinateIds.length);this.effectsManager.createMoveOrderEffect(i.clone()),n.subordinateIds.forEach((c,u)=>{const h=this.agentManager.getAgentMeshes().get(c);P.moveAgent(c,o[u]),h&&this.movementAnimator.startMovement(c,h,o[u])})}setDrawingTool(e){this.drawingManager.setTool(e),P.setActiveTool(e)}syncAreas(){this.drawingManager.syncFromStore()}highlightArea(e){this.drawingManager.highlightArea(e)}clearAreaSelection(){this.drawingManager.highlightArea(null)}addBuilding(e){this.buildingManager.addBuilding(e)}removeBuilding(e){this.buildingManager.removeBuilding(e)}updateBuilding(e){this.buildingManager.updateBuilding(e)}syncBuildings(){this.buildingManager.syncFromStore()}highlightBuilding(e){this.buildingManager.highlightBuilding(e)}setOnBuildingClick(e){this.callbackManager.setOnBuildingClick(e)}setOnBuildingDoubleClick(e){this.callbackManager.setOnBuildingDoubleClick(e)}setOnContextMenu(e){this.callbackManager.setOnContextMenu(e)}setOnAgentHover(e){this.callbackManager.setOnAgentHover(e)}setOnBuildingHover(e){this.callbackManager.setOnBuildingHover(e)}setOnGroundClick(e){this.callbackManager.setOnGroundClick(e)}setOnAreaDoubleClick(e){this.callbackManager.setOnAreaDoubleClick(e)}setOnFolderIconClick(e){this.onFolderIconClickCallback=e}setOnToast(e){this.agentManager.setOnToast(e)}setCharacterScale(e){this.agentManager.setCharacterScale(e),this.selectionManager.setCharacterScale(e)}setIndicatorScale(e){this.renderLoop.setIndicatorScale(e),this.effectsManager.setIndicatorScale(e)}setFpsLimit(e){this.renderLoop.setFpsLimit(e)}setPowerSaving(e){this.renderLoop.setPowerSaving(e)}setGridVisible(e){this.battlefield.setGridVisible(e)}setDebugTime(e){this.battlefield.setDebugTime(e)}setTimeMode(e){this.battlefield.setTimeMode(e)}setTerrainConfig(e){this.battlefield.setTerrainConfig(e),e.brightness!==void 0&&(this.drawingManager.setBrightness(e.brightness),this.buildingManager.setBrightness(e.brightness),this.agentManager.setBrightness(e.brightness))}setFloorStyle(e,t=!1){this.battlefield.setFloorStyle(e,t)}setIdleAnimation(e){this.agentManager.setIdleAnimation(e)}setWorkingAnimation(e){this.agentManager.setWorkingAnimation(e)}setAgentModelStyle(e){this.agentManager.setModelStyle(e)}getAgentModelStyle(){return this.agentManager.getModelStyle()}setGlobalSaturation(e){this.sceneCore.setSaturation(e)}getGlobalSaturation(){return this.sceneCore.getSaturation()}setPostProcessingEnabled(e){this.sceneCore.setPostProcessingEnabled(e)}reattach(e,t){var o,r;console.log("[SceneManager] Reattaching to new canvas (HMR)"),this.isReattaching=!0,this.renderLoop.stop(),(o=this.resizeObserver)==null||o.disconnect();const n=this.sceneCore.getCanvas();n.removeEventListener("webglcontextlost",this.onContextLost),n.removeEventListener("webglcontextrestored",this.onContextRestored),this.sceneCore.reattach(e),this.cameraManager.recreateControls(this.sceneCore.getRenderer()),this.sceneCore.updateCamera(this.cameraManager.getCamera()),e.addEventListener("webglcontextlost",this.onContextLost),e.addEventListener("webglcontextrestored",this.onContextRestored),this.inputHandler.reattach(e,t,this.cameraManager.getControls()),this.updateInputHandlerReferences(),e.parentElement&&((r=this.resizeObserver)==null||r.observe(e.parentElement)),this.onWindowResize();const i=(c=0)=>{this.isReattaching=!1,e.isConnected&&this.sceneCore.getRenderer()?(console.log("[SceneManager] Restarting animation loop after HMR reattach"),this.renderLoop.start()):c<10?(console.log(`[SceneManager] Canvas not connected, retrying... (attempt ${c+1})`),this.isReattaching=!0,requestAnimationFrame(()=>i(c+1))):console.warn("[SceneManager] Failed to restart animation loop - canvas never connected")};requestAnimationFrame(()=>i())}getMemoryDiagnostics(){var t;const e=this.sceneCore.getRenderer().info;return{threeJs:e!=null&&e.memory?{geometries:e.memory.geometries,textures:e.memory.textures,programs:((t=e.programs)==null?void 0:t.length)??0}:null,heap:uT.getUsage(),agentMeshCount:this.agentManager.getAgentMeshes().size,bossLineCount:0}}getRenderStats(){var t,n;const e=(n=(t=this.sceneCore.getRenderer())==null?void 0:t.info)==null?void 0:n.render;return e?{calls:e.calls,triangles:e.triangles,points:e.points,lines:e.lines}:null}get renderer(){return this.sceneCore.getRenderer()}logMemoryDiagnostics(){const e=this.getMemoryDiagnostics(),t=this.characterLoader.getCacheStats();console.group("%c[SceneManager Memory]","color: #ff6600; font-weight: bold"),e.threeJs&&console.log(`Three.js: ${e.threeJs.geometries} geometries, ${e.threeJs.textures} textures, ${e.threeJs.programs} programs`),e.heap&&console.log(`Heap: ${e.heap.usedMB}MB / ${e.heap.totalMB}MB (limit: ${e.heap.limitMB}MB)`),console.log(`Agent meshes: ${e.agentMeshCount}`),console.log(`CharacterLoader cache: ${t.builtInModels} built-in, ${t.customModels} custom`),t.modelNames.length>0&&console.log(` Built-in models: ${t.modelNames.join(", ")}`),t.customModelIds.length>0&&console.log(` Custom models: ${t.customModelIds.join(", ")}`),console.groupEnd()}dispose(){var n;console.log("%c[SceneManager] dispose() called - starting cleanup","color: #ff0000; font-weight: bold");const e=this.characterLoader.getCacheStats();console.log(`[SceneManager] Pre-dispose: ${e.builtInModels} built-in models, ${e.customModels} custom models`),this.renderLoop.stop(),window.removeEventListener("resize",this.onWindowResize);const t=this.sceneCore.getCanvas();t.removeEventListener("webglcontextlost",this.onContextLost),t.removeEventListener("webglcontextrestored",this.onContextRestored),(n=this.resizeObserver)==null||n.disconnect(),this.resizeObserver=null,this.inputHandler.dispose(),this.drawingManager.dispose(),this.buildingManager.dispose(),this.effectsManager.dispose(),this.agentManager.dispose(),this.selectionManager.dispose(),this.battlefield.dispose(),this.characterLoader.dispose(),this.cameraManager.dispose(),this.sceneCore.dispose(),console.log("%c[SceneManager] dispose() complete - all resources freed","color: #00ff00; font-weight: bold")}}const $u="tide_webgl_active";typeof window<"u"&&(window.__tidePersistedScene===void 0&&(window.__tidePersistedScene=null),window.__tidePersistedCanvas===void 0&&(window.__tidePersistedCanvas=null),window.__tideWsConnected===void 0&&(window.__tideWsConnected=!1),window.__tideIsPageUnloading===void 0&&(window.__tideIsPageUnloading=!1));function rd(){return typeof window<"u"?window.__tidePersistedScene??null:null}function yS(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function uE(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function Vl(s){typeof window<"u"&&(window.__tidePersistedScene=s)}function Hu(s){typeof window<"u"&&(window.__tidePersistedCanvas=s)}function xS(s){typeof window<"u"&&(window.__tideWsConnected=s)}function dE(s){typeof window<"u"&&(window.__tideIsPageUnloading=s)}function hE(){sessionStorage.setItem($u,"true")}function wu(s){dE(!0),sessionStorage.removeItem($u),oS(),iT(),window.__tideScene&&(window.__tideScene=null);const e=rd();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),Vl(null)):console.log("[App] No persistedScene to dispose"),Hu(null),xS(!1);const t=document.getElementById("battlefield");t&&t.remove();const n=document.getElementById("app");n&&(n.innerHTML="")}function pE(){var i,o;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem($u)==="true"&&console.log("[App] Detected unclean shutdown from previous session - forcing cleanup"),window.__tideScene){console.log("[App] Cleaning up stale __tideScene reference");try{(o=(i=window.__tideScene).dispose)==null||o.call(i)}catch{}window.__tideScene=null}const e=rd();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}Vl(null)}const t=document.getElementById("battlefield"),n=yS();t&&t!==n&&t.remove(),sessionStorage.removeItem($u)}function mE(){typeof window>"u"||(pE(),window.addEventListener("pageshow",s=>{s.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),wu(),window.location.reload())}),window.onunload=()=>wu(),window.onbeforeunload=s=>{wu()},window.addEventListener("pagehide",s=>{wu(`pagehide (persisted=${s.persisted})`)}))}mE();const Xv={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"concrete",brightness:1,skyColor:null},Yv={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},Zv={idleAnimation:"sit",workingAnimation:"sprint"},fE=0;function vS(){const s={characterScale:2,indicatorScale:1,gridVisible:!0,timeMode:"day",terrain:Xv,modelStyle:Yv,animations:Zv,fpsLimit:fE},e=ka(rt.CONFIG,null);return e?{characterScale:e.characterScale??s.characterScale,indicatorScale:e.indicatorScale??s.indicatorScale,gridVisible:e.gridVisible??s.gridVisible,timeMode:e.timeMode??s.timeMode,terrain:{...Xv,...e.terrain},modelStyle:{...Yv,...e.modelStyle},animations:{...Zv,...e.animations},fpsLimit:e.fpsLimit??s.fpsLimit}:s}function gE(s){Xa(rt.CONFIG,s)}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function wS(){console.log("[Tide HMR] Manual scene refresh triggered");const s=rd();if(s){try{s.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}Vl(null)}Hu(null),window.__tideScene&&(window.__tideScene=null);const e=document.getElementById("battlefield");if(e){const t=e.getContext("webgl2")||e.getContext("webgl");if(t){const n=t.getExtension("WEBGL_lose_context");n&&n.loseContext()}}window.__tideHmrPendingSceneChanges=!1,window.location.reload()}typeof window<"u"&&(window.__tideHmrSceneRefresh=wS);function bE({canvasRef:s,selectionBoxRef:e,showToast:t,showAgentNotification:n,toolboxModal:i,contextMenu:o,setHoveredAgentPopup:r,setBuildingPopup:c,getBuildingPopup:u,openBuildingModal:h,openPM2LogsModal:m,openBossLogsModal:f,openDatabasePanel:g}){const b=x.useRef(null),v=x.useRef(null),w=x.useRef(null);return x.useEffect(()=>{if(!s.current||!e.current)return;let k=!1;const C=rd(),A=yS()===s.current;function _(){var M,E,F,T,R,D,I,O;(M=b.current)==null||M.setOnToast(t),(E=b.current)==null||E.setOnBuildingClick((X,W)=>{P.selectBuilding(X);const G=P.getState().buildings.get(X);(G==null?void 0:G.type)==="folder"&&G.folderPath?P.openFileExplorer(G.folderPath):(G==null?void 0:G.type)==="server"||(G==null?void 0:G.type)==="boss"||(G==null?void 0:G.type)==="database"?(v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{c({buildingId:X,screenPos:W,fromClick:!0}),v.current=null},150)):h(X)}),(F=b.current)==null||F.setOnContextMenu((X,W,G)=>{o.open(X,W,G)}),(T=b.current)==null||T.setOnAgentHover(()=>{}),(R=b.current)==null||R.setOnBuildingHover((X,W)=>{const G=u();if(X&&W){const B=P.getState().buildings.get(X);((B==null?void 0:B.type)==="server"||(B==null?void 0:B.type)==="boss"||(B==null?void 0:B.type)==="database")&&!(G!=null&&G.fromClick)&&c({buildingId:X,screenPos:W,fromClick:!1})}else G!=null&&G.fromClick||c(null)}),(D=b.current)==null||D.setOnGroundClick(()=>{c(null)}),(I=b.current)==null||I.setOnAreaDoubleClick(X=>{P.selectArea(X),i.open()}),(O=b.current)==null||O.setOnBuildingDoubleClick(X=>{var G;v.current&&(clearTimeout(v.current),v.current=null),c(null);const W=P.getState().buildings.get(X);(W==null?void 0:W.type)==="server"&&((G=W.pm2)!=null&&G.enabled)?m==null||m(X):(W==null?void 0:W.type)==="boss"?f==null||f(X):(W==null?void 0:W.type)==="database"?g==null||g(X):(W==null?void 0:W.type)==="folder"&&W.folderPath?P.openFileExplorer(W.folderPath):h(X)})}if(C&&A){b.current=C,console.log("[Tide] Reusing existing scene (StrictMode remount)");const M=P.getState();C.syncAreas(),C.syncBuildings(),M.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",M.agents.size),C.syncAgents(Array.from(M.agents.values()))),_()}else{const M=s.current,E=e.current,F=()=>{if(k){console.log("[Tide] Effect cleaned up before scene init, skipping");return}if(!M.isConnected||!E.isConnected){console.warn("[Tide] Canvas disconnected before initialization");return}(!M.clientWidth||!M.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),M.style.width="100%",M.style.height="100%",M.offsetHeight),(!M.clientWidth||!M.clientHeight)&&(M.width=window.innerWidth,M.height=window.innerHeight),hE();try{const T=new cE(M,E);b.current=T,Vl(T),Hu(M);const R=vS();T.setCharacterScale(R.characterScale),T.setIndicatorScale(R.indicatorScale),T.setGridVisible(R.gridVisible),T.setTimeMode(R.timeMode),T.setTerrainConfig(R.terrain),T.setFloorStyle(R.terrain.floorStyle,!0),T.setAgentModelStyle(R.modelStyle),T.setIdleAnimation(R.animations.idleAnimation),T.setWorkingAnimation(R.animations.workingAnimation),T.setFpsLimit(R.fpsLimit),T.syncAreas(),T.syncBuildings(),T.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const D=P.getState();D.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",D.customAgentClasses.size),T.setCustomAgentClasses(D.customAgentClasses)),D.agents.size>0&&(console.log("[Tide] Syncing agents from store:",D.agents.size),T.syncAgents(Array.from(D.agents.values()))),T.upgradeAgentModels()}).catch(D=>{console.warn("[Tide] Some models failed to load, using fallback:",D)}),_()}catch(T){console.error("[Tide] Failed to initialize 3D scene:",T)}};w.current=requestAnimationFrame(F)}return sS({onAgentCreated:M=>{var E,F;(E=b.current)==null||E.addAgent(M),(F=window.__spawnModalSuccess)==null||F.call(window)},onAgentUpdated:(M,E)=>{var F;(F=b.current)==null||F.updateAgent(M,E)},onAgentDeleted:M=>{var E;(E=b.current)==null||E.removeAgent(M)},onAgentsSync:M=>{var E;(E=b.current)==null||E.syncAgents(M)},onAreasSync:()=>{var E,F;(E=b.current)==null||E.syncAreas();const M=Array.from(P.getState().agents.values());(F=b.current)==null||F.syncAgents(M)},onSpawnError:()=>{var M;(M=window.__spawnModalError)==null||M.call(window)},onSpawnSuccess:()=>{var M;(M=window.__spawnModalSuccess)==null||M.call(window)},onDirectoryNotFound:M=>{var E;(E=window.__spawnModalDirNotFound)==null||E.call(window,M)},onToolUse:(M,E,F)=>{var T;(T=b.current)==null||T.showToolBubble(M,E,F)},onDelegation:(M,E)=>{var F;(F=b.current)==null||F.showDelegationEffect(M,E)},onCustomClassesSync:M=>{var E,F;(E=b.current)==null||E.setCustomAgentClasses(M),(F=b.current)==null||F.upgradeAgentModels()},onBuildingUpdated:M=>{var E;(E=b.current)==null||E.updateBuilding(M)},onSubagentStarted:M=>{var E;(E=b.current)==null||E.addSubagentEffect(M.id,M.parentAgentId,M.name,M.subagentType)},onSubagentCompleted:M=>{var T;const E=P.getSubagent(M)||P.getSubagentByToolUseId(M),F=(E==null?void 0:E.id)||M;(T=b.current)==null||T.completeSubagentEffect(F),setTimeout(()=>{var R;(R=b.current)==null||R.removeSubagentEffect(F)},3e4)}}),()=>{var M;k=!0,w.current!==null&&(cancelAnimationFrame(w.current),w.current=null),!((M=s.current)!=null&&M.isConnected)&&b.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),oT(),b.current.dispose(),b.current=null,Vl(null),Hu(null))}},[s.current,e.current]),b}let Xl,dr;try{Xl=require("@capacitor/local-notifications").LocalNotifications,dr=require("@capacitor/core").Capacitor}catch{}let yE=1;const xE="agent_alerts",kS="tide-notification-tap";function vE(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function SS(s){if(vE()){P.openTerminalOnMobile(s);return}P.selectAgent(s),P.setTerminalOpen(!0)}function Ef(){var s;return((s=dr==null?void 0:dr.isNativePlatform)==null?void 0:s.call(dr))??!1}async function wE(){return Ef()?(await Xl.requestPermissions()).display==="granted":"Notification"in window?await Notification.requestPermission()==="granted":!1}async function kE(s){const{title:e,body:t,icon:n,data:i}=s;if(Ef())await Xl.schedule({notifications:[{id:yE++,title:e,body:t,schedule:{at:new Date(Date.now()+100)},extra:i,channelId:xE,smallIcon:"ic_launcher",autoCancel:!0}]});else if("Notification"in window&&Notification.permission==="granted"){const o=new Notification(e,{body:t,icon:n,data:i});o.onclick=()=>{window.focus(),i&&window.dispatchEvent(new CustomEvent(kS,{detail:i}))}}}async function SE(s){s&&window.addEventListener(kS,e=>{const t=e;t.detail&&s(t.detail)}),Ef()&&Xl&&await Xl.addListener("localNotificationActionPerformed",e=>{s&&e.notification.extra&&s(e.notification.extra)})}function jE({showToast:s,showAgentNotification:e}){const t=x.useRef(!1);x.useEffect(()=>{if(t.current||uE())return;t.current=!0,sS({onToast:s,onReconnect:()=>{P.triggerReconnect()},onAgentNotification:i=>{e(i)}}),Kl(),xS(!0),wE(),SE(i=>{i.type==="agent_notification"&&typeof i.agentId=="string"&&SS(i.agentId)});const n=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>Kl(),100)};return window.addEventListener("tideAppResume",n),()=>{window.removeEventListener("tideAppResume",n)}},[s,e])}function CE(s){x.useEffect(()=>{let e="",t="",n=new Map;const i=o=>{var u;let r=!1;const c=new Map;for(const[h,m]of o){const g=`${m.position.x.toFixed(2)},${m.position.z.toFixed(2)},${m.status},${m.class},${m.isBoss},${((u=m.subordinateIds)==null?void 0:u.length)??0}`.split("").reduce((b,v)=>(b<<5)-b+v.charCodeAt(0),0);c.set(h,g),n.get(h)!==g&&(r=!0)}return c.size!==n.size&&(r=!0),{newVersion:c,changed:r}};return P.subscribe(()=>{var g;const o=P.getState(),r=Array.from(o.selectedAgentIds).sort().join(","),c=Array.from(o.selectedBuildingIds).sort().join(","),u=r!==e,h=c!==t,{newVersion:m,changed:f}=i(o.agents);(u||h||f)&&(e=r,t=c,n=m,(g=s.current)==null||g.refreshSelectionVisuals())})},[s])}function AE(s){x.useEffect(()=>{var n;(n=s.current)==null||n.syncAreas();let e=0,t=0;return P.subscribe(()=>{var c,u;const o=P.getState().areas;if(o.size!==e){e=o.size,t=Date.now(),(c=s.current)==null||c.syncAreas();return}let r=0;for(const[h,m]of o){let f=h.charCodeAt(0);f+=(m.width??0)+(m.height??0)+(m.radius??0),f+=Math.floor(m.center.x*100)+Math.floor(m.center.z*100),f+=(m.zIndex??0)*1e3;for(let g=0;g<m.name.length;g++)f+=m.name.charCodeAt(g);for(let g=0;g<m.color.length;g++)f+=m.color.charCodeAt(g);if(m.directoryGitCounts)for(const g of m.directoryGitCounts)f+=(g+1)*7;r^=f|0}r!==t&&(t=r,(u=s.current)==null||u.syncAreas())})},[s])}function NE(s){x.useEffect(()=>{var n;(n=s.current)==null||n.syncBuildings();let e=0,t=0;return P.subscribe(()=>{var c,u;const o=P.getState().buildings;if(o.size!==e){e=o.size,t=Date.now(),(c=s.current)==null||c.syncBuildings();return}let r=0;for(const[h,m]of o){r^=m.position.x*1e3+m.position.z|0,r^=(m.scale||1)*1e4|0;const f=`${m.style||""}${m.name}${m.status}${m.gitChangesCount||0}`;for(let g=0;g<f.length;g++)r=(r<<5)-r+f.charCodeAt(g)|0}r!==t&&(t=r,(u=s.current)==null||u.syncBuildings())})},[s])}function TE(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.highlightArea(e)},[s,e])}function ME(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.setPowerSaving(e)},[s,e])}function EE({sceneRef:s,spawnModal:e,commanderModal:t,explorerModal:n,spotlightModal:i,deleteConfirmModal:o,onRequestBuildingDelete:r}){x.useEffect(()=>{const c=u=>{var F,T,R,D;const h=P.getShortcuts(),m=u.target,f=m.tagName==="INPUT"||m.tagName==="TEXTAREA",g=h.find(I=>I.id==="deselect-all");if(ut(u,g)){if(Mm()){u.preventDefault();return}const I=P.getState();if(I.activeTool==="rectangle"||I.activeTool==="circle"){(F=s.current)==null||F.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():I.terminalOpen?(P.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(P.deselectAll(),(T=s.current)==null||T.refreshSelectionVisuals())}for(let I=1;I<=9;I++){const O=h.find(X=>X.id===`select-agent-${I}`);if(ut(u,O)){u.preventDefault();const X=P.getState(),W=I-1,G=Array.from(X.agents.keys());W<G.length&&(P.selectAgent(G[W]),(R=s.current)==null||R.refreshSelectionVisuals());return}}const b=h.find(I=>I.id==="spawn-agent");if(ut(u,b)){u.preventDefault(),e.open();return}const v=h.find(I=>I.id==="toggle-commander-tab");if(ut(u,v)&&!f){u.preventDefault(),t.toggle();return}const w=h.find(I=>I.id==="toggle-commander");if(ut(u,w)){u.preventDefault(),t.toggle();return}const k=h.find(I=>I.id==="toggle-file-explorer");if(ut(u,k)){u.preventDefault();const I=P.getState();if(n.isOpen||I.explorerFolderPath!==null||I.explorerAreaId!==null)n.close(),P.closeFileExplorer();else{const X=P.getLastExplorerState();if((X==null?void 0:X.type)==="folder")P.openFileExplorer(X.path);else if((X==null?void 0:X.type)==="area")if(I.areas.has(X.areaId))n.open(X.areaId);else{const W=Array.from(I.areas.values()).filter(G=>G.directories&&G.directories.length>0);W.length>0&&n.open(W[0].id)}else{const W=Array.from(I.areas.values()).filter(G=>G.directories&&G.directories.length>0);W.length>0&&n.open(W[0].id)}}return}const C=h.find(I=>I.id==="toggle-spotlight");if(ut(u,C)||u.altKey&&!u.ctrlKey&&!u.metaKey&&u.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:C,altKey:u.altKey,code:u.code}),u.preventDefault(),i.toggle();return}const j=h.find(I=>I.id==="toggle-2d-view");if(ut(u,j)){u.preventDefault();const I=P.getState().viewMode,O=I==="3d"?"2d":I==="2d"?"dashboard":"3d";P.setViewMode(O);return}const A=h.find(I=>I.id==="next-working-agent"),_=h.find(I=>I.id==="prev-working-agent");if((ut(u,A)||ut(u,_))&&!f){const I=P.getState();if(I.terminalOpen)return;const X=Array.from(I.agents.values()).filter(q=>q.status==="working");if(X.length===0)return;u.preventDefault();const W=I.selectedAgentIds.size===1?Array.from(I.selectedAgentIds)[0]:null,G=W?X.findIndex(q=>q.id===W):-1;let B;ut(u,A)?B=G===-1?0:(G+1)%X.length:B=G===-1?X.length-1:(G-1+X.length)%X.length,P.selectAgent(X[B].id),(D=s.current)==null||D.refreshSelectionVisuals();return}const M=h.find(I=>I.id==="delete-selected"),E=h.find(I=>I.id==="delete-selected-backspace");if((ut(u,M)||ut(u,E))&&!f){const I=P.getState();if(I.selectedAgentIds.size>0){u.preventDefault(),o.open();return}if(I.selectedBuildingIds.size>0){u.preventDefault(),r();return}return}};return document.addEventListener("keydown",c,!0),()=>document.removeEventListener("keydown",c,!0)},[s,e,t,n,i,o,r])}function _E(){const[s,e]=x.useState(!1);return window.__tideSetBackNavModal=e,x.useEffect(()=>{if(!(window.innerWidth<=768))return;if(window.__tideBackNavSetup){window.location.hash.includes("app")||(window.location.hash="#app");return}window.__tideBackNavSetup=!0,window.location.hash.includes("app")||(window.location.hash="#app");const i=()=>{var r;window.innerWidth>768||window.location.hash.includes("app")||(window.location.hash="#app",Mm()||(r=window.__tideSetBackNavModal)==null||r.call(window,!0))},o=()=>{var r;window.innerWidth>768||(window.location.hash.includes("app")||(window.location.hash="#app"),window.location.hash==="#app"&&setTimeout(()=>{window.location.hash==="#app"&&!window.location.hash.includes("app2")&&(window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"))},50),Mm()||(r=window.__tideSetBackNavModal)==null||r.call(window,!0))};window.history.pushState(null,"","#app1"),window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"),window.addEventListener("hashchange",i),window.addEventListener("popstate",o)},[]),{showBackNavModal:s,setShowBackNavModal:e,handleLeave:()=>{e(!1);const n=window.__tideHistoryDepth??2;window.history.go(-(n+1))}}}const Gp="agent-order-change";function jS(s){const e=x.useMemo(()=>new Set(s.map(u=>u.id)),[s]),[t,n]=x.useState(()=>ka(rt.AGENT_ORDER,[]));x.useEffect(()=>{const u=h=>{n(h.detail)};return window.addEventListener(Gp,u),()=>{window.removeEventListener(Gp,u)}},[]);const i=x.useMemo(()=>{const u=t.filter(g=>e.has(g)),h=s.filter(g=>!u.includes(g.id)).map(g=>g.id),m=[...u,...h],f=new Map(s.map(g=>[g.id,g]));return m.map(g=>f.get(g)).filter(g=>g!==void 0)},[s,t,e]),o=x.useCallback(u=>{n(u),Xa(rt.AGENT_ORDER,u),window.dispatchEvent(new CustomEvent(Gp,{detail:u}))},[]),r=x.useCallback((u,h)=>{const m=i.map(g=>g.id),[f]=m.splice(u,1);m.splice(h,0,f),o(m)},[i,o]),c=x.useCallback(()=>{n([]),Xa(rt.AGENT_ORDER,[])},[]);return x.useEffect(()=>{if(e.size===0)return;const u=t.filter(h=>e.has(h));u.length!==t.length&&o(u)},[e,t,o]),{orderedAgents:i,moveAgent:r,resetOrder:c}}let ba,Hm;try{ba=require("@capacitor/core").Capacitor,Hm=require("@capacitor/core").CapacitorHttp}catch{}const _f="deivid11/tide-commander",DE=`https://api.github.com/repos/${_f}/releases/latest`,RE=`https://api.github.com/repos/${_f}/releases?per_page=3`,LE=3600*1e3,Qv="app_update_dismissed_version",Jv="0.61.5";function CS(){var m;const[s,e]=x.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:Jv}),t=((m=ba==null?void 0:ba.getPlatform)==null?void 0:m.call(ba))==="android"||!1,n=f=>f.replace(/^v/,"").split(".").map(b=>parseInt(b,10)||0),i=(f,g)=>{const b=n(f),v=n(g),w=Math.max(b.length,v.length);for(let k=0;k<w;k++){const C=b[k]||0,j=v[k]||0;if(C>j)return 1;if(C<j)return-1}return 0},o=async f=>{var b;if(ba&&Hm&&((b=ba.isNativePlatform)==null?void 0:b.call(ba))===!0){const v=await Hm.get({url:f,headers:{Accept:"application/vnd.github.v3+json"}});return{data:v.data,status:v.status}}else{const v=await fetch(f,{headers:{Accept:"application/vnd.github.v3+json"}});return v.ok?{data:await v.json(),status:v.status}:{data:null,status:v.status}}},r=x.useCallback(async(f=!1)=>{e(g=>({...g,isChecking:!0,error:null}));try{const[g,b]=await Promise.all([o(DE),o(RE)]);if(g.status!==200)throw new Error(`GitHub API error: ${g.status}`);const v=g.data,w=v.tag_name;let k=[];b.status===200&&b.data&&(k=b.data.map(M=>({version:M.tag_name,name:M.name,publishedAt:M.published_at,releaseUrl:M.html_url})));const C=localStorage.getItem(Qv);if(!f&&C===w)return e(M=>({...M,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;if(!(i(w,Jv)>0))return e(M=>({...M,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;const A=v.assets.find(M=>M.name.endsWith(".apk")&&M.content_type==="application/vnd.android.package-archive"),_={version:w,name:v.name,changelog:v.body,releaseUrl:v.html_url,apkUrl:(A==null?void 0:A.browser_download_url)||null,apkSize:(A==null?void 0:A.size)||null,publishedAt:v.published_at};return e(M=>({...M,isChecking:!1,updateAvailable:!0,updateInfo:_,recentReleases:k})),_}catch(g){const b=g instanceof Error?g.message:"Failed to check for updates";return e(v=>({...v,isChecking:!1,error:b})),null}},[]),c=x.useCallback(async()=>{var f,g,b;if(!((f=s.updateInfo)!=null&&f.apkUrl)){(g=s.updateInfo)!=null&&g.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}if(!t){(b=s.updateInfo)!=null&&b.releaseUrl&&window.open(s.updateInfo.releaseUrl,"_blank");return}try{window.open(s.updateInfo.apkUrl,"_system"),e(v=>({...v,error:null}))}catch(v){const w=v instanceof Error?v.message:"Failed to open download";e(k=>({...k,error:w}))}},[s.updateInfo,t]),u=x.useCallback(()=>{s.updateInfo&&localStorage.setItem(Qv,s.updateInfo.version),e(f=>({...f,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),h=x.useCallback(()=>{var f;(f=s.updateInfo)!=null&&f.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${_f}/releases`,"_blank")},[s.updateInfo]);return x.useEffect(()=>{if(!t)return;const f=setTimeout(()=>{r()},5e3),g=setInterval(()=>{r()},LE);return()=>{clearTimeout(f),clearInterval(g)}},[t,r]),{...s,isAndroid:t,checkForUpdate:r,downloadAndInstall:c,dismissUpdate:u,openReleasePage:h}}function Qs(s){const e=x.useRef(null),t=x.useCallback(i=>{e.current=i.target,i.target===i.currentTarget&&i.stopPropagation()},[]),n=x.useCallback(i=>{i.target===i.currentTarget&&e.current===i.currentTarget&&(i.stopPropagation(),s()),e.current=null},[s]);return{handleMouseDown:t,handleClick:n}}const BE=3e4;function PE(){const s=x.useRef(null);x.useEffect(()=>{const e=async()=>{var r,c;const t=P.getState(),n=new Map,i=new Map;for(const[u,h]of t.buildings){const m=h.folderPath||h.cwd;m&&(i.has(m)||i.set(m,[]),i.get(m).push(u))}for(const[u,h]of i)try{const m=await dt(Qe(`/api/files/git-status?path=${encodeURIComponent(u)}`));if(!m.ok)continue;const g=((r=(await m.json()).files)==null?void 0:r.length)||0;n.set(u,g);for(const b of h){const v=P.getState().buildings.get(b);v&&v.gitChangesCount!==g&&P.updateBuildingLocal(b,{gitChangesCount:g})}}catch{}const o=new Map;for(const[u,h]of t.areas)h.archived||!h.directories||h.directories.forEach((m,f)=>{m&&(o.has(m)||o.set(m,[]),o.get(m).push({areaId:u,dirIndex:f}))});if(o.size!==0)for(const[u,h]of o)try{let m;if(n.has(u))m=n.get(u);else{const g=await dt(Qe(`/api/files/git-status?path=${encodeURIComponent(u)}`));if(!g.ok)continue;m=((c=(await g.json()).files)==null?void 0:c.length)||0,n.set(u,m)}const f=new Map;for(const g of h)f.has(g.areaId)||f.set(g.areaId,[]),f.get(g.areaId).push({dirIndex:g.dirIndex,count:m});for(const[g,b]of f){const v=P.getState().areas.get(g);if(!v)continue;const w=v.directoryGitCounts?[...v.directoryGitCounts]:new Array(v.directories.length).fill(0);let k=!1;for(const{dirIndex:C,count:j}of b)w[C]!==j&&(w[C]=j,k=!0);k&&P.updateAreaLocal(g,{directoryGitCounts:w})}}catch{}};return e(),s.current=setInterval(e,BE),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[])}const e0={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,externalEditorCommand:""};function IE(s,e,t,n){return{setAgents(i){const o=new Map;for(const c of i)o.set(c.id,c),(c.class==="boss"||c.isBoss)&&console.log("[Store.setAgents] Boss agent:",c.name,"subordinateIds:",c.subordinateIds);const r=i.find(c=>c.status==="working");e(c=>{c.agents=o,r&&c.selectedAgentIds.size===0&&(c.selectedAgentIds.add(r.id),c.terminalOpen=!0)}),t()},addAgent(i){e(o=>{const r=new Map(o.agents);r.set(i.id,i),o.agents=r}),t()},updateAgent(i){var u;const r=s().agents.get(i.id),c=(r==null?void 0:r.status)!==i.status;c&&console.log(`[Store] Agent ${i.name} status update: ${r==null?void 0:r.status} → ${i.status}`),e(h=>{const m=new Map(h.agents);m.set(i.id,i),h.agents=m}),t(),c&&console.log(`[Store] Agent ${i.name} status now in store: ${(u=s().agents.get(i.id))==null?void 0:u.status}`)},updateAgentContextStats(i,o){const c=s().agents.get(i);c&&(e(u=>{const h=new Map(u.agents);h.set(i,{...c,contextStats:o,contextUsed:o.totalTokens,contextLimit:o.contextWindow}),u.agents=h}),t())},removeAgent(i){e(o=>{const r=new Map(o.agents);r.delete(i),o.agents=r,o.selectedAgentIds.delete(i),o.agentOutputs.delete(i)}),t()},selectAgent(i){e(o=>{o.selectedAgentIds.clear(),i&&(o.selectedAgentIds.add(i),o.lastSelectedAgentId=i),o.currentSnapshot=null}),t()},addToSelection(i){e(o=>{o.selectedAgentIds.has(i)?o.selectedAgentIds.delete(i):o.selectedAgentIds.add(i)}),t()},selectMultiple(i){e(o=>{o.selectedAgentIds.clear();for(const r of i)o.selectedAgentIds.add(r)}),t()},deselectAll(){e(i=>{i.selectedAgentIds.clear()}),t()},spawnAgent(i,o,r,c,u,h,m,f,g,b,v,w,k){console.log("[Store] spawnAgent called with:",{name:i,agentClass:o,cwd:r,position:c,sessionId:u,useChrome:h,permissionMode:m,initialSkillIds:f,provider:g,codexConfig:b,codexModel:v,model:w,customInstructions:k?`${k.length} chars`:void 0});const C=c?{x:c.x,y:0,z:c.z}:void 0,j={type:"spawn_agent",payload:{name:i,class:o,cwd:r,position:C,sessionId:u,useChrome:h,permissionMode:m,initialSkillIds:f,provider:g,codexConfig:b,codexModel:v,model:w,customInstructions:k}},A=n();if(!A){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}A(j),console.log("[Store] Message sent to WebSocket")},createDirectoryAndSpawn(i,o,r){var c;(c=n())==null||c({type:"create_directory",payload:{path:i,name:o,class:r}})},sendCommand(i,o){var r;e(c=>{c.lastPrompts.set(i,{text:o,timestamp:Date.now()})}),t(),(r=n())==null||r({type:"send_command",payload:{agentId:i,command:o}})},refreshAgentContext(i){var o;(o=n())==null||o({type:"request_context_stats",payload:{agentId:i}})},moveAgent(i,o){var u;const c=s().agents.get(i);c&&(e(h=>{const m={...c,position:o},f=new Map(h.agents);f.set(i,m),h.agents=f}),t()),(u=n())==null||u({type:"move_agent",payload:{agentId:i,position:o}})},killAgent(i){var o;(o=n())==null||o({type:"kill_agent",payload:{agentId:i}})},stopAgent(i){var o;(o=n())==null||o({type:"stop_agent",payload:{agentId:i}})},clearContext(i){var o;(o=n())==null||o({type:"clear_context",payload:{agentId:i}}),e(r=>{const c=new Map(r.agentOutputs);c.delete(i),r.agentOutputs=c}),t()},collapseContext(i){var o;(o=n())==null||o({type:"collapse_context",payload:{agentId:i}})},removeAgentFromServer(i){var o;(o=n())==null||o({type:"remove_agent",payload:{agentId:i}})},renameAgent(i,o){var u;const c=s().agents.get(i);c&&(e(h=>{const m={...c,name:o},f=new Map(h.agents);f.set(i,m),h.agents=f}),t()),(u=n())==null||u({type:"rename_agent",payload:{agentId:i,name:o}})},updateAgentProperties(i,o){var u;const c=s().agents.get(i);c&&(e(h=>{const m={...c};o.class!==void 0&&(m.class=o.class),o.permissionMode!==void 0&&(m.permissionMode=o.permissionMode),o.model!==void 0&&(m.model=o.model),o.provider!==void 0&&(m.provider=o.provider),o.codexConfig!==void 0&&(m.codexConfig=o.codexConfig),o.codexModel!==void 0&&(m.codexModel=o.codexModel),o.useChrome!==void 0&&(m.useChrome=o.useChrome),o.cwd!==void 0&&(m.cwd=o.cwd);const f=new Map(h.agents);f.set(i,m),h.agents=f}),t()),(u=n())==null||u({type:"update_agent_properties",payload:{agentId:i,updates:o}})},getTotalTokens(){let i=0;for(const o of s().agents.values())i+=o.tokensUsed;return i},getSelectedAgents(){const i=s(),o=[];for(const r of i.selectedAgentIds){const c=i.agents.get(r);c&&o.push(c)}return o},addActivity(i){e(o=>{o.activities.unshift(i),o.activities.length>100&&o.activities.pop()}),t()},addToolExecution(i,o,r){const u=s().agents.get(i);e(h=>{h.toolExecutions.unshift({agentId:i,agentName:(u==null?void 0:u.name)||"Unknown",toolName:o,toolInput:r,timestamp:Date.now()}),h.toolExecutions.length>200&&h.toolExecutions.pop()}),t()},addFileChange(i,o,r){const u=s().agents.get(i);e(h=>{h.fileChanges.unshift({agentId:i,agentName:(u==null?void 0:u.name)||"Unknown",action:o,filePath:r,timestamp:Date.now()}),h.fileChanges.length>200&&h.fileChanges.pop()}),t()},async loadToolHistory(){try{const o=await(await dt(Qe("/api/agents/tool-history?limit=100"))).json();e(r=>{o.toolExecutions&&(r.toolExecutions=o.toolExecutions),o.fileChanges&&(r.fileChanges=o.fileChanges)}),t()}catch(i){console.error("[Store] Failed to load tool history:",i)}}}}function OE(s,e,t,n){return{addOutput(i,o){const r=n();e(c=>{const u=c.agentOutputs.get(i)||[];if(o.uuid&&u.some(g=>g.uuid===o.uuid))return;let h=[...u,o];h.length>200&&(h=h.slice(-200)),ql.info(`Store: ${u.length} -> ${h.length}`,{agentId:i,text:o.text.slice(0,60),isStreaming:o.isStreaming,listeners:r},"store:addOutput");const m=new Map(c.agentOutputs);m.set(i,h),c.agentOutputs=m}),t()},clearOutputs(i){e(o=>{const r=new Map(o.agentOutputs);r.delete(i),o.agentOutputs=r}),t()},getOutputs(i){return s().agentOutputs.get(i)||[]},addUserPromptToOutput(i,o){this.addOutput(i,{text:o,isStreaming:!1,timestamp:Date.now(),isUserPrompt:!0})},getLastPrompt(i){return s().lastPrompts.get(i)},setLastPrompt(i,o){e(r=>{r.lastPrompts.set(i,{text:o,timestamp:Date.now()})}),t()},preserveOutputs(){const i=s(),o=new Map;for(const[r,c]of i.agentOutputs)o.set(r,c.map(u=>({...u})));return o},mergeOutputsWithHistory(i,o,r){const c=[...o,...r];return c.sort((u,h)=>u.timestamp-h.timestamp),e(u=>{const h=new Map(u.agentOutputs);h.set(i,c),u.agentOutputs=h}),t(),c}}}function zE(s,e,t,n){return{setSupervisorReport(i){e(o=>{o.supervisor.lastReport=i,o.supervisor.lastReportTime=i.timestamp;const r=new Map(o.supervisor.agentHistories);for(const c of i.agentSummaries){const u=r.get(c.agentId)||[],h={id:`${i.id}-${c.agentId}`,timestamp:i.timestamp,reportId:i.id,analysis:c};if(!u.some(m=>m.reportId===i.id)){const m=[h,...u];m.length>50&&m.pop(),r.set(c.agentId,m)}}o.supervisor.agentHistories=r,o.supervisor.generatingReport=!1}),t()},addNarrative(i,o){e(r=>{const c=r.supervisor.narratives.get(i)||[];c.unshift(o),c.length>50&&c.pop();const u=new Map(r.supervisor.narratives);u.set(i,c),r.supervisor.narratives=u}),t()},getNarratives(i){return s().supervisor.narratives.get(i)||[]},setSupervisorStatus(i){e(o=>{o.supervisor.enabled=i.enabled,i.autoReportOnComplete!==void 0&&(o.supervisor.autoReportOnComplete=i.autoReportOnComplete),o.supervisor.lastReportTime=i.lastReportTime,o.supervisor.nextReportTime=i.nextReportTime}),t()},setSupervisorConfig(i){var o;(o=n())==null||o({type:"set_supervisor_config",payload:i})},requestSupervisorReport(){var i;e(o=>{o.supervisor.generatingReport=!0}),t(),(i=n())==null||i({type:"request_supervisor_report",payload:{}})},requestAgentSupervisorHistory(i){var o;e(r=>{r.supervisor.loadingHistoryForAgent=i}),t(),(o=n())==null||o({type:"request_agent_supervisor_history",payload:{agentId:i}})},setAgentSupervisorHistory(i){e(o=>{const r=new Map(o.supervisor.agentHistories);r.set(i.agentId,i.entries),o.supervisor.agentHistories=r,o.supervisor.historyFetchedForAgents.add(i.agentId),o.supervisor.loadingHistoryForAgent===i.agentId&&(o.supervisor.loadingHistoryForAgent=null)}),t()},getAgentSupervisorHistory(i){return s().supervisor.agentHistories.get(i)||[]},addAgentAnalysis(i,o){e(r=>{const c=new Map(r.supervisor.agentHistories),u=c.get(i)||[],h={id:`single-${Date.now()}-${i}`,timestamp:Date.now(),reportId:`single-${Date.now()}`,analysis:o};if(!u.some(f=>Math.abs(f.timestamp-h.timestamp)<5e3&&f.analysis.statusDescription===o.statusDescription)){const f=[h,...u];f.length>50&&f.pop(),c.set(i,f),r.supervisor.agentHistories=c}}),t()},isLoadingHistoryForAgent(i){return s().supervisor.loadingHistoryForAgent===i},hasHistoryBeenFetched(i){return s().supervisor.historyFetchedForAgents.has(i)},setGlobalUsage(i){console.log("[Supervisor] setGlobalUsage called with:",i),e(o=>{o.supervisor.globalUsage=i,o.supervisor.refreshingUsage=!1}),t()},requestGlobalUsage(){console.log("[Supervisor] requestGlobalUsage called"),e(o=>{o.supervisor.refreshingUsage=!0}),t();const i=n();console.log("[Supervisor] sendMessage function:",i?"available":"null"),i?(console.log("[Supervisor] Sending request_global_usage message"),i({type:"request_global_usage",payload:{}})):console.warn("[Supervisor] Cannot send request_global_usage - no sendMessage function")},getGlobalUsage(){return s().supervisor.globalUsage}}}function FE(s,e,t,n){const i=()=>{var r;const o=Array.from(s().areas.values());(r=n())==null||r({type:"sync_areas",payload:o})};return{setActiveTool(o){e(r=>{r.activeTool=o,o!=="select"&&(r.selectedAreaId=null)}),t()},selectArea(o){e(r=>{r.selectedAreaId=o}),t()},addArea(o){if(o.zIndex===void 0||o.zIndex===null){const r=Array.from(s().areas.values()),c=r.length===0?-1:Math.max(...r.map(u=>u.zIndex??0));o.zIndex=c+1}e(r=>{r.areas.set(o.id,o)}),i(),t()},updateArea(o,r){s().areas.get(o)&&(e(h=>{Object.assign(h.areas.get(o),r)}),i(),t())},updateAreaLocal(o,r){s().areas.get(o)&&(e(h=>{Object.assign(h.areas.get(o),r)}),t())},deleteArea(o){e(r=>{r.areas.delete(o),r.selectedAreaId===o&&(r.selectedAreaId=null)}),i(),t()},assignAgentToArea(o,r){const u=s().areas.get(r);u&&!u.assignedAgentIds.includes(o)&&(e(h=>{for(const m of h.areas.values()){const f=m.assignedAgentIds.indexOf(o);f!==-1&&m.assignedAgentIds.splice(f,1)}h.areas.get(r).assignedAgentIds.push(o)}),i(),t())},unassignAgentFromArea(o,r){const u=s().areas.get(r);if(u){const h=u.assignedAgentIds.indexOf(o);h!==-1&&(e(m=>{m.areas.get(r).assignedAgentIds.splice(h,1)}),i(),t())}},addDirectoryToArea(o,r){const u=s().areas.get(o);u&&!u.directories.includes(r)&&(e(h=>{h.areas.get(o).directories.push(r)}),i(),t())},removeDirectoryFromArea(o,r){const u=s().areas.get(o);if(u){const h=u.directories.indexOf(r);h!==-1&&(e(m=>{m.areas.get(o).directories.splice(h,1)}),i(),t())}},getAreaDirectories(o){const r=s().areas.get(o);return(r==null?void 0:r.directories)||[]},isPositionInArea(o,r){if(r.type==="rectangle"&&r.width&&r.height){const c=r.width/2,u=r.height/2;return o.x>=r.center.x-c&&o.x<=r.center.x+c&&o.z>=r.center.z-u&&o.z<=r.center.z+u}else if(r.type==="circle"&&r.radius){const c=o.x-r.center.x,u=o.z-r.center.z;return c*c+u*u<=r.radius*r.radius}return!1},getAreaForAgent(o){const r=s(),c=r.agents.get(o);if(!c)return null;for(const u of r.areas.values())if(this.isPositionInArea({x:c.position.x,z:c.position.z},u))return u;return null},setAreasFromServer(o){e(r=>{const c=new Map;for(let u=0;u<o.length;u++){const h=o[u];h.directories||(h.directories=[]),(h.zIndex===void 0||h.zIndex===null)&&(h.zIndex=u),h.archived===void 0&&(h.archived=!1),c.set(h.id,h)}r.areas=c}),t()},getAreasInZOrder(){return Array.from(s().areas.values()).sort((r,c)=>(r.zIndex??0)-(c.zIndex??0))},getNextZIndex(){const o=Array.from(s().areas.values());return o.length===0?0:Math.max(...o.map(c=>c.zIndex??0))+1},bringAreaToFront(o){const r=s(),c=r.areas.get(o);if(!c)return;const u=Array.from(r.areas.values()),h=u.length===0?-1:Math.max(...u.map(b=>b.zIndex??0)),m=h+1,f=c.zIndex??0,g=u.filter(b=>(b.zIndex??0)===h);f===h&&g.length===1||(e(b=>{b.areas.get(o).zIndex=m}),i(),t())},sendAreaToBack(o){const r=s(),c=r.areas.get(o);if(!c)return;const u=Array.from(r.areas.values()),h=Math.min(...u.map(g=>g.zIndex??0)),m=c.zIndex??0,f=u.filter(g=>(g.zIndex??0)===h);m===h&&f.length===1||(e(g=>{for(const b of g.areas.values())b.id!==o&&(b.zIndex=(b.zIndex??0)+1);g.areas.get(o).zIndex=0}),i(),t())},setAreaZIndex(o,r){s().areas.get(o)&&(e(h=>{h.areas.get(o).zIndex=r}),i(),t())},archiveArea(o,r){const u=s().areas.get(o);if(!(!u||u.archived)){if(r)for(const h of u.assignedAgentIds)r(h);e(h=>{const m=h.areas.get(o);m.archived=!0,m.archivedAt=Date.now(),m.originalCenter={...m.center},h.selectedAreaId===o&&(h.selectedAreaId=null)}),i(),t()}},restoreArchivedArea(o,r){const c=s(),u=c.areas.get(o);if(!u||!u.archived)return;const h=u.center,m=r||u.originalCenter||u.center,f=m.x-h.x,g=m.z-h.z,b=Array.from(c.areas.values()),w=(b.length===0?-1:Math.max(...b.map(k=>k.zIndex??0)))+1;e(k=>{const C=k.areas.get(o);if(C.archived=!1,C.archivedAt=void 0,C.center=m,C.zIndex=w,f!==0||g!==0)for(const j of C.assignedAgentIds){const A=k.agents.get(j);A&&(A.position={x:A.position.x+f,y:A.position.y,z:A.position.z+g})}}),i(),t()},getArchivedAreas(){return Array.from(s().areas.values()).filter(o=>o.archived===!0)},getVisibleAreas(){return Array.from(s().areas.values()).filter(o=>!o.archived)},isAgentInArchivedArea(o){const r=s();for(const c of r.areas.values())if(c.archived&&c.assignedAgentIds.includes(o))return!0;return!1}}}function $E(s,e,t,n){const i=()=>{var c;const r=Array.from(s().buildings.values());(c=n())==null||c({type:"sync_buildings",payload:r})},o={selectBuilding(r){e(c=>{c.selectedBuildingIds.clear(),r&&c.selectedBuildingIds.add(r)}),t()},selectMultipleBuildings(r){e(c=>{c.selectedBuildingIds.clear();for(const u of r)c.selectedBuildingIds.add(u)}),t()},toggleBuildingSelection(r){e(c=>{c.selectedBuildingIds.has(r)?c.selectedBuildingIds.delete(r):c.selectedBuildingIds.add(r)}),t()},isBuildingSelected(r){return s().selectedBuildingIds.has(r)},getSelectedBuildingIds(){return Array.from(s().selectedBuildingIds)},deleteSelectedBuildings(){var c,u,h;const r=s();for(const m of r.selectedBuildingIds){const f=r.buildings.get(m);((c=f==null?void 0:f.pm2)!=null&&c.enabled||(u=f==null?void 0:f.docker)!=null&&u.enabled)&&((h=n())==null||h({type:"building_command",payload:{buildingId:m,command:"delete"}}))}e(m=>{const f=new Map(m.buildings);for(const g of m.selectedBuildingIds)f.delete(g);m.buildings=f,m.selectedBuildingIds.clear()}),i(),t()},addBuilding(r){e(c=>{const u=new Map(c.buildings);u.set(r.id,r),c.buildings=u}),i(),t()},updateBuilding(r,c){const h=s().buildings.get(r);h&&(e(m=>{const f=new Map(m.buildings);f.set(r,{...h,...c}),m.buildings=f}),i(),t())},updateBuildingLocal(r,c){const h=s().buildings.get(r);h&&(e(m=>{const f=new Map(m.buildings);f.set(r,{...h,...c}),m.buildings=f}),t())},deleteBuilding(r){var h,m,f;const u=s().buildings.get(r);((h=u==null?void 0:u.pm2)!=null&&h.enabled||(m=u==null?void 0:u.docker)!=null&&m.enabled)&&((f=n())==null||f({type:"building_command",payload:{buildingId:r,command:"delete"}})),e(g=>{const b=new Map(g.buildings);b.delete(r),g.buildings=b,g.selectedBuildingIds.delete(r)}),i(),t()},moveBuilding(r,c){const h=s().buildings.get(r);h&&(e(m=>{const f=new Map(m.buildings);f.set(r,{...h,position:c}),m.buildings=f}),i(),t())},updateBuildingPosition(r,c){o.moveBuilding(r,c)},createBuilding(r){const c={...r,id:`building_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,status:"stopped",createdAt:Date.now()};o.addBuilding(c)},sendBuildingCommand(r,c){var u;(u=n())==null||u({type:"building_command",payload:{buildingId:r,command:c}})},addBuildingLogs(r,c){e(u=>{const m=[...u.buildingLogs.get(r)||[],c];m.length>500&&m.splice(0,m.length-500);const f=new Map(u.buildingLogs);f.set(r,m),u.buildingLogs=f}),t()},getBuildingLogs(r){return s().buildingLogs.get(r)||[]},clearBuildingLogs(r){e(c=>{const u=new Map(c.buildingLogs);u.delete(r),c.buildingLogs=u}),t()},setBuildingsFromServer(r){e(c=>{const u=new Map;for(const h of r)u.set(h.id,h);c.buildings=u}),t()},updateBuildingFromServer(r){e(c=>{const u=new Map(c.buildings);u.set(r.id,r),c.buildings=u}),t()},removeBuildingFromServer(r){e(c=>{const u=new Map(c.buildings);u.delete(r),c.buildings=u,c.selectedBuildingIds.delete(r)}),t()},startLogStreaming(r,c=100){var h,m,f;const u=s().buildings.get(r);e(g=>{const b=new Map(g.streamingBuildingLogs);b.set(r,""),g.streamingBuildingLogs=b}),(h=u==null?void 0:u.docker)!=null&&h.enabled?(m=n())==null||m({type:"docker_logs_start",payload:{buildingId:r,lines:c}}):(f=n())==null||f({type:"pm2_logs_start",payload:{buildingId:r,lines:c}})},stopLogStreaming(r){var u,h,m;const c=s().buildings.get(r);(u=c==null?void 0:c.docker)!=null&&u.enabled?(h=n())==null||h({type:"docker_logs_stop",payload:{buildingId:r}}):(m=n())==null||m({type:"pm2_logs_stop",payload:{buildingId:r}})},appendStreamingLogChunk(r,c){e(u=>{const h=u.streamingBuildingLogs.get(r)||"",m=500*1024;let f=h+c;if(f.length>m){const b=f.indexOf(`
141
141
  `,f.length-m);b>0?f=f.slice(b+1):f=f.slice(-m)}const g=new Map(u.streamingBuildingLogs);g.set(r,f),u.streamingBuildingLogs=g}),t()},setStreamingStatus(r,c){e(u=>{const h=new Set(u.streamingBuildingIds);c?h.add(r):h.delete(r),u.streamingBuildingIds=h}),t()},getStreamingLogs(r){return s().streamingBuildingLogs.get(r)||""},clearStreamingLogs(r){e(c=>{const u=new Map(c.streamingBuildingLogs);u.delete(r),c.streamingBuildingLogs=u}),t()},isLogStreaming(r){return s().streamingBuildingIds.has(r)},sendBossBuildingCommand(r,c){var u;(u=n())==null||u({type:"boss_building_command",payload:{buildingId:r,command:c}})},assignBuildingsToBoSS(r,c){var m;const h=s().buildings.get(r);h&&(e(f=>{const g=new Map(f.buildings);g.set(r,{...h,subordinateBuildingIds:c}),f.buildings=g}),i(),t()),(m=n())==null||m({type:"assign_buildings",payload:{bossBuildingId:r,subordinateBuildingIds:c}})},startBossLogStreaming(r,c=50){var u;e(h=>{const m=new Map(h.bossStreamingLogs);m.set(r,[]),h.bossStreamingLogs=m}),(u=n())==null||u({type:"boss_building_logs_start",payload:{buildingId:r,lines:c}})},stopBossLogStreaming(r){var c;(c=n())==null||c({type:"boss_building_logs_stop",payload:{buildingId:r}})},appendBossStreamingLogChunk(r,c,u,h,m){e(f=>{const g=f.bossStreamingLogs.get(r)||[],b={subordinateId:c,subordinateName:u,chunk:h,timestamp:Date.now(),isError:m},v=[...g,b];v.length>1e3&&v.splice(0,v.length-1e3);const w=new Map(f.bossStreamingLogs);w.set(r,v),f.bossStreamingLogs=w}),t()},getBossStreamingLogs(r){return s().bossStreamingLogs.get(r)||[]},clearBossStreamingLogs(r){e(c=>{const u=new Map(c.bossStreamingLogs);u.delete(r),c.bossStreamingLogs=u}),t()},requestDockerContainersList(){var r;(r=n())==null||r({type:"docker_list_containers",payload:{}})},setDockerContainersList(r,c){e(u=>{u.dockerContainersList=r,u.dockerComposeProjectsList=c}),t()},getDockerContainersList(){return s().dockerContainersList},getDockerComposeProjectsList(){return s().dockerComposeProjectsList}};return o}function HE(s,e,t,n){return{addPermissionRequest(i){e(o=>{const r=new Map(o.permissionRequests);r.set(i.id,i),o.permissionRequests=r}),t()},resolvePermissionRequest(i,o){const c=s().permissionRequests.get(i);c&&(e(u=>{const h=new Map(u.permissionRequests);h.set(i,{...c,status:o?"approved":"denied"}),u.permissionRequests=h}),t(),setTimeout(()=>{e(u=>{const h=new Map(u.permissionRequests);h.delete(i),u.permissionRequests=h}),t()},2e3))},respondToPermissionRequest(i,o,r,c){var u;(u=n())==null||u({type:"permission_response",payload:{requestId:i,approved:o,reason:r,remember:c}})},getPendingPermissionsForAgent(i){return Array.from(s().permissionRequests.values()).filter(o=>o.agentId===i&&o.status==="pending")},clearAllPermissions(){e(i=>{i.permissionRequests=new Map}),t()}}}function UE(s,e,t,n){return{spawnBossAgent(i,o,r,c,u,h,m,f,g,b,v,w,k){var j;const C=c?{x:c.x,y:0,z:c.z}:void 0;(j=n())==null||j({type:"spawn_boss_agent",payload:{name:i,class:o,cwd:r,position:C,subordinateIds:u,useChrome:h,permissionMode:m,provider:f,codexConfig:g,codexModel:b,model:v,customInstructions:w,initialSkillIds:k}})},assignSubordinates(i,o){var r;(r=n())==null||r({type:"assign_subordinates",payload:{bossId:i,subordinateIds:o}})},removeSubordinate(i,o){var r;(r=n())==null||r({type:"remove_subordinate",payload:{bossId:i,subordinateId:o}})},sendBossCommand(i,o){var r;e(c=>{c.pendingDelegation={bossId:i,command:o}}),t(),(r=n())==null||r({type:"send_boss_command",payload:{bossId:i,command:o}})},requestDelegationHistory(i){var o;(o=n())==null||o({type:"request_delegation_history",payload:{bossId:i}})},handleDelegationDecision(i){e(o=>{var h;const r=new Map(o.delegationHistories),c=r.get(i.bossId)||[],u=c.findIndex(m=>m.id===i.id);if(u!==-1?c[u]=i:(c.unshift(i),c.length>100&&c.pop()),r.set(i.bossId,c),o.delegationHistories=r,i.status==="sent"&&i.selectedAgentId){const m=o.agents.get(i.bossId),f=new Map(o.lastDelegationReceived);f.set(i.selectedAgentId,{bossName:(m==null?void 0:m.name)||"Boss",taskCommand:i.userCommand,timestamp:Date.now()}),o.lastDelegationReceived=f}((h=o.pendingDelegation)==null?void 0:h.bossId)===i.bossId&&i.status!=="pending"&&(o.pendingDelegation=null)}),t()},setDelegationHistory(i,o){e(r=>{const c=new Map(r.delegationHistories);c.set(i,o),r.delegationHistories=c}),t()},getDelegationHistory(i){return s().delegationHistories.get(i)||[]},getLastDelegationReceived(i){return s().lastDelegationReceived.get(i)||null},clearLastDelegationReceived(i){s().lastDelegationReceived.has(i)&&(e(r=>{const c=new Map(r.lastDelegationReceived);c.delete(i),r.lastDelegationReceived=c}),t())},updateBossSubordinates(i,o){const c=s().agents.get(i);c&&(e(u=>{const h={...c,subordinateIds:o},m=new Map(u.agents);m.set(i,h),u.agents=m}),t())},getSubordinates(i){const o=s(),r=o.agents.get(i),c=(r==null?void 0:r.isBoss)===!0||(r==null?void 0:r.class)==="boss";return!r||!c||!r.subordinateIds?[]:r.subordinateIds.map(u=>o.agents.get(u)).filter(u=>u!==void 0)},isBossAgent(i){const o=s().agents.get(i);return(o==null?void 0:o.isBoss)===!0||(o==null?void 0:o.class)==="boss"},getBossForAgent(i){const o=s(),r=o.agents.get(i);return r!=null&&r.bossId&&o.agents.get(r.bossId)||null},getAvailableSubordinates(){return Array.from(s().agents.values()).filter(i=>i.class!=="boss")},handleAgentTaskStarted(i,o,r,c){e(u=>{const h=new Map(u.agentTaskProgress);let m=h.get(i);m||(m=new Map,h.set(i,m)),m.set(o,{agentId:o,agentName:r,taskDescription:c,status:"working",output:[],startedAt:Date.now()}),u.agentTaskProgress=h}),t()},handleAgentTaskOutput(i,o,r){e(c=>{const u=c.agentTaskProgress.get(i);if(!u)return;const h=u.get(o);if(!h)return;const m=new Map(c.agentTaskProgress),f=new Map(u);f.set(o,{...h,output:[...h.output,r]}),m.set(i,f),c.agentTaskProgress=m}),t()},handleAgentTaskCompleted(i,o,r){e(c=>{const u=c.agentTaskProgress.get(i);if(!u)return;const h=u.get(o);if(!h)return;const m=new Map(c.agentTaskProgress),f=new Map(u);f.set(o,{...h,status:r?"completed":"failed",completedAt:Date.now()}),m.set(i,f),c.agentTaskProgress=m}),t()},getAgentTaskProgress(i){return s().agentTaskProgress.get(i)||new Map},clearAgentTaskProgress(i,o){e(r=>{if(o){const c=r.agentTaskProgress.get(i);if(c){const u=new Map(r.agentTaskProgress),h=new Map(c);h.delete(o),u.set(i,h),r.agentTaskProgress=u}}else{const c=new Map(r.agentTaskProgress);c.delete(i),r.agentTaskProgress=c}}),t()},clearAllSubordinatesContext(i){const r=s().agents.get(i),c=(r==null?void 0:r.isBoss)===!0||(r==null?void 0:r.class)==="boss";if(console.log("[Store] clearAllSubordinatesContext called:",{bossId:i,bossName:r==null?void 0:r.name,isBoss:c,subordinateIds:r==null?void 0:r.subordinateIds}),!r||!c||!r.subordinateIds||r.subordinateIds.length===0){console.log("[Store] clearAllSubordinatesContext: No boss or subordinates found, returning early");return}const u=n();console.log("[Store] clearAllSubordinatesContext: sendMessage available:",!!u);for(const h of r.subordinateIds)console.log("[Store] clearAllSubordinatesContext: Sending clear_context for subordinate:",h),u==null||u({type:"clear_context",payload:{agentId:h}});e(h=>{const m=new Map(h.agentOutputs);for(const f of r.subordinateIds||[])m.delete(f);h.agentOutputs=m}),t(),console.log("[Store] clearAllSubordinatesContext: Completed")}}}function GE(s,e,t,n){return{setSkillsFromServer(i){e(o=>{const r=new Map;for(const c of i)r.set(c.id,c);o.skills=r}),t()},addSkillFromServer(i){e(o=>{const r=new Map(o.skills);r.set(i.id,i),o.skills=r}),t()},updateSkillFromServer(i){e(o=>{const r=new Map(o.skills);r.set(i.id,i),o.skills=r}),t()},removeSkillFromServer(i){e(o=>{const r=new Map(o.skills);r.delete(i),o.skills=r}),t()},getSkill(i){return s().skills.get(i)},getAllSkills(){return Array.from(s().skills.values())},getSkillsForAgent(i){const o=s(),r=o.agents.get(i);return r?Array.from(o.skills.values()).filter(c=>c.enabled?!!(c.assignedAgentIds.includes(i)||c.assignedAgentClasses.includes(r.class)):!1):[]},createSkill(i){var o;(o=n())==null||o({type:"create_skill",payload:i})},updateSkill(i,o){var r;(r=n())==null||r({type:"update_skill",payload:{id:i,updates:o}})},deleteSkill(i){var o;(o=n())==null||o({type:"delete_skill",payload:{id:i}})},assignSkillToAgent(i,o){var r;(r=n())==null||r({type:"assign_skill",payload:{skillId:i,agentId:o}})},unassignSkillFromAgent(i,o){var r;(r=n())==null||r({type:"unassign_skill",payload:{skillId:i,agentId:o}})},requestAgentSkills(i){var o;(o=n())==null||o({type:"request_agent_skills",payload:{agentId:i}})},setCustomAgentClassesFromServer(i){e(o=>{const r=new Map;for(const c of i)r.set(c.id,c);o.customAgentClasses=r}),t()},addCustomAgentClassFromServer(i){e(o=>{const r=new Map(o.customAgentClasses);r.set(i.id,i),o.customAgentClasses=r}),t()},updateCustomAgentClassFromServer(i){e(o=>{const r=new Map(o.customAgentClasses);r.set(i.id,i),o.customAgentClasses=r}),t()},removeCustomAgentClassFromServer(i){e(o=>{const r=new Map(o.customAgentClasses);r.delete(i),o.customAgentClasses=r}),t()},getCustomAgentClass(i){return s().customAgentClasses.get(i)},getAllCustomAgentClasses(){return Array.from(s().customAgentClasses.values())},createCustomAgentClass(i){var o;(o=n())==null||o({type:"create_custom_agent_class",payload:i})},updateCustomAgentClass(i,o){var r;(r=n())==null||r({type:"update_custom_agent_class",payload:{id:i,updates:o}})},deleteCustomAgentClass(i){var o;(o=n())==null||o({type:"delete_custom_agent_class",payload:{id:i}})}}}function WE(s,e,t){return{handleExecTaskStarted(n,i,o,r,c){e(u=>{const h={taskId:n,agentId:i,agentName:o,command:r,cwd:c,status:"running",output:[],startedAt:Date.now()};u.execTasks||(u.execTasks=new Map),u.execTasks.set(n,h)}),t()},handleExecTaskOutput(n,i,o,r){e(c=>{var h;const u=(h=c.execTasks)==null?void 0:h.get(n);if(u){const m=o.split(`
142
142
  `);for(const f of m)f.length>0&&u.output.push(r?`[stderr] ${f}`:f);u.output.length>500&&(u.output=u.output.slice(-500))}}),t()},handleExecTaskCompleted(n,i,o,r){e(c=>{var h;const u=(h=c.execTasks)==null?void 0:h.get(n);u&&(u.status=r?"completed":"failed",u.exitCode=o,u.completedAt=Date.now())}),t()},async stopExecTask(n){try{return(await fetch(`/api/exec/tasks/${n}`,{method:"DELETE"})).ok?(e(o=>{var c;const r=(c=o.execTasks)==null?void 0:c.get(n);r&&r.status==="running"&&(r.status="failed",r.exitCode=-15,r.completedAt=Date.now(),r.output.push("[Task stopped by user]"))}),t(),!0):!1}catch(i){return console.error("Failed to stop exec task:",i),!1}},getExecTasks(n){const i=s();return i.execTasks?Array.from(i.execTasks.values()).filter(o=>o.agentId===n):[]},getAllExecTasks(){const n=s();return n.execTasks?Array.from(n.execTasks.values()):[]},getExecTask(n){var o;return(o=s().execTasks)==null?void 0:o.get(n)},clearCompletedExecTasks(n){e(i=>{if(i.execTasks)for(const[o,r]of i.execTasks.entries())r.agentId===n&&r.status!=="running"&&i.execTasks.delete(o)}),t()},clearAllExecTasks(n){e(i=>{if(i.execTasks)for(const[o,r]of i.execTasks.entries())r.agentId===n&&i.execTasks.delete(o)}),t()},removeExecTask(n){e(i=>{i.execTasks&&i.execTasks.delete(n)}),t()}}}function qE(s,e,t,n){return{setSecretsFromServer(i){e(o=>{const r=new Map;for(const c of i)r.set(c.id,c);o.secrets=r}),t()},addSecretFromServer(i){e(o=>{const r=new Map(o.secrets);r.set(i.id,i),o.secrets=r}),t()},updateSecretFromServer(i){e(o=>{const r=new Map(o.secrets);r.set(i.id,i),o.secrets=r}),t()},removeSecretFromServer(i){e(o=>{const r=new Map(o.secrets);r.delete(i),o.secrets=r}),t()},getSecret(i){return s().secrets.get(i)},getSecretByKey(i){return Array.from(s().secrets.values()).find(o=>o.key===i)},getAllSecrets(){return Array.from(s().secrets.values())},createSecret(i){var o;(o=n())==null||o({type:"create_secret",payload:i})},updateSecret(i,o){var r;(r=n())==null||r({type:"update_secret",payload:{id:i,updates:o}})},deleteSecret(i){var o;(o=n())==null||o({type:"delete_secret",payload:{id:i}})}}}function t0(){return{connectionStatus:new Map,databases:new Map,tables:new Map,tableSchemas:new Map,queryResults:[],queryHistory:[],executingQuery:!1,activeConnectionId:null,activeDatabase:null}}function KE(s,e,t,n){const i=r=>{s().databaseState.has(r)||e(u=>{const h=new Map(u.databaseState);h.set(r,t0()),u.databaseState=h})};return{testDatabaseConnection(r,c){var u;(u=n())==null||u({type:"test_database_connection",payload:{buildingId:r,connectionId:c}})},setConnectionStatus(r,c,u){i(r),e(h=>{const m=h.databaseState.get(r);if(m){const f=new Map(m.connectionStatus);f.set(c,u);const g={...m,connectionStatus:f},b=new Map(h.databaseState);b.set(r,g),h.databaseState=b}}),t()},listDatabases(r,c){var u;(u=n())==null||u({type:"list_databases",payload:{buildingId:r,connectionId:c}})},setDatabases(r,c,u){i(r),e(h=>{const m=h.databaseState.get(r);if(m){const f=new Map(m.databases);f.set(c,u);const g={...m,databases:f},b=new Map(h.databaseState);b.set(r,g),h.databaseState=b}}),t()},listTables(r,c,u){var h;(h=n())==null||h({type:"list_tables",payload:{buildingId:r,connectionId:c,database:u}})},setTables(r,c,u,h){i(r);const m=`${c}:${u}`;e(f=>{const g=f.databaseState.get(r);if(g){const b=new Map(g.tables);b.set(m,h);const v={...g,tables:b},w=new Map(f.databaseState);w.set(r,v),f.databaseState=w}}),t()},getTableSchema(r,c,u,h){var m;(m=n())==null||m({type:"get_table_schema",payload:{buildingId:r,connectionId:c,database:u,table:h}})},setTableSchema(r,c,u,h,m){i(r);const f=`${c}:${u}:${h}`;e(g=>{const b=g.databaseState.get(r);if(b){const v=new Map(b.tableSchemas);v.set(f,m);const w={...b,tableSchemas:v},k=new Map(g.databaseState);k.set(r,w),g.databaseState=k}}),t()},executeQuery(r,c,u,h,m=1e3){var f;i(r),e(g=>{const b=g.databaseState.get(r);if(b){const v={...b,executingQuery:!0},w=new Map(g.databaseState);w.set(r,v),g.databaseState=w}}),t(),(f=n())==null||f({type:"execute_query",payload:{buildingId:r,connectionId:c,database:u,query:h,limit:m}})},setQueryResult(r,c){i(r),e(u=>{const h=u.databaseState.get(r);if(h){const m=[c,...h.queryResults].slice(0,20),f={...h,queryResults:m,executingQuery:!1},g=new Map(u.databaseState);g.set(r,f),u.databaseState=g}}),t()},setExecutingQuery(r,c){i(r),e(u=>{const h=u.databaseState.get(r);if(h){const m={...h,executingQuery:c},f=new Map(u.databaseState);f.set(r,m),u.databaseState=f}}),t()},requestQueryHistory(r,c=100){var u;(u=n())==null||u({type:"request_query_history",payload:{buildingId:r,limit:c}})},setQueryHistory(r,c){i(r),e(u=>{const h=u.databaseState.get(r);if(h){const m={...h,queryHistory:c},f=new Map(u.databaseState);f.set(r,m),u.databaseState=f}}),t()},toggleQueryFavorite(r,c){var u;(u=n())==null||u({type:"toggle_query_favorite",payload:{buildingId:r,queryId:c}})},deleteQueryFromHistory(r,c){var u;(u=n())==null||u({type:"delete_query_history",payload:{buildingId:r,queryId:c}})},clearQueryHistory(r){var c;(c=n())==null||c({type:"clear_query_history",payload:{buildingId:r}})},setActiveConnection(r,c){i(r),e(u=>{const h=u.databaseState.get(r);if(h){const m={...h,activeConnectionId:c,activeDatabase:null},f=new Map(u.databaseState);f.set(r,m),u.databaseState=f}}),t()},setActiveDatabase(r,c){i(r),e(u=>{const h=u.databaseState.get(r);if(h){const m={...h,activeDatabase:c},f=new Map(u.databaseState);f.set(r,m),u.databaseState=f}}),t()},getDatabaseState(r){return s().databaseState.get(r)||t0()},clearDatabaseState(r){e(c=>{const u=new Map(c.databaseState);u.delete(r),c.databaseState=u}),t()}}}function VE(s,e,t){return{async fetchSnapshots(){e(n=>{n.snapshotsLoading=!0,n.snapshotsError=null}),t();try{const n=await dt(Qe("/api/snapshots"));if(!n.ok)throw new Error(`Failed to fetch snapshots: ${n.statusText}`);const i=await n.json(),o=Array.isArray(i)?i:i.snapshots||[];this.setSnapshots(o)}catch(n){const i=n instanceof Error?n.message:"Failed to fetch snapshots";this.setError(i),console.error("Snapshot fetch error:",n)}finally{e(n=>{n.snapshotsLoading=!1}),t()}},setSnapshots(n){e(i=>{const o=new Map;n.forEach(r=>{o.set(r.id,r)}),i.snapshots=o}),t()},async createSnapshot(n,i,o,r,c,u){e(h=>{h.snapshotsLoading=!0,h.snapshotsError=null}),t();try{const h={agentId:n,agentName:i,title:o,description:r,outputs:c||[],files:u||[]},m=await dt(Qe("/api/snapshots"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!m.ok)throw new Error(`Failed to create snapshot: ${m.statusText}`);const f=await m.json();return await this.fetchSnapshots(),f}catch(h){const m=h instanceof Error?h.message:"Failed to create snapshot";throw this.setError(m),console.error("Snapshot creation error:",h),h}finally{e(h=>{h.snapshotsLoading=!1}),t()}},async loadSnapshot(n){e(i=>{i.snapshotsLoading=!0,i.snapshotsError=null}),t();try{const i=await dt(Qe(`/api/snapshots/${n}`));if(!i.ok)throw new Error(`Failed to load snapshot: ${i.statusText}`);const o=await i.json();this.setCurrentSnapshot(o)}catch(i){const o=i instanceof Error?i.message:"Failed to load snapshot";this.setError(o),console.error("Snapshot load error:",i)}finally{e(i=>{i.snapshotsLoading=!1}),t()}},setCurrentSnapshot(n){e(i=>{i.currentSnapshot=n}),t()},async deleteSnapshot(n){var i;e(o=>{o.snapshotsLoading=!0,o.snapshotsError=null}),t();try{const o=await dt(Qe(`/api/snapshots/${n}`),{method:"DELETE"});if(!o.ok)throw new Error(`Failed to delete snapshot: ${o.statusText}`);await this.fetchSnapshots(),((i=s().currentSnapshot)==null?void 0:i.id)===n&&this.setCurrentSnapshot(null)}catch(o){const r=o instanceof Error?o.message:"Failed to delete snapshot";throw this.setError(r),console.error("Snapshot deletion error:",o),o}finally{e(o=>{o.snapshotsLoading=!1}),t()}},async restoreFiles(n,i){e(o=>{o.snapshotsLoading=!0,o.snapshotsError=null}),t();try{const o=i?{filePaths:i}:{},r=await dt(Qe(`/api/snapshots/${n}/restore`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!r.ok)throw new Error(`Failed to restore files: ${r.statusText}`)}catch(o){const r=o instanceof Error?o.message:"Failed to restore files";throw this.setError(r),console.error("File restoration error:",o),o}finally{e(o=>{o.snapshotsLoading=!1}),t()}},setLoading(n){e(i=>{i.snapshotsLoading=n}),t()},setError(n){e(i=>{i.snapshotsError=n}),t()},clearError(){this.setError(null)},reset(){e(n=>{n.snapshots=new Map,n.currentSnapshot=null,n.snapshotsLoading=!1,n.snapshotsError=null}),t()}}}function XE(s,e,t){return{addSubagent(n){e(i=>{const o=new Map(i.subagents);o.set(n.id,n),i.subagents=o}),t(),console.log(`[Subagent] Added: ${n.name} (${n.id}) for agent ${n.parentAgentId}`)},completeSubagent(n,i,o){e(r=>{let c=r.subagents.get(n);if(!c){for(const[,u]of r.subagents)if(u.toolUseId===n&&u.parentAgentId===i){c=u;break}}if(c){const u=new Map(r.subagents);u.set(c.id,{...c,status:o?"completed":"failed",completedAt:Date.now()}),r.subagents=u,console.log(`[Subagent] Completed: ${c.name} (${c.id}) success=${o}`),setTimeout(()=>{e(h=>{const m=h.subagents.get(c.id);if(m&&(m.status==="completed"||m.status==="failed")){const f=new Map(h.subagents);f.delete(c.id),h.subagents=f}}),t()},3e4)}}),t()},getSubagentsForAgent(n){const i=s();return Array.from(i.subagents.values()).filter(o=>o.parentAgentId===n)},getSubagent(n){return s().subagents.get(n)},removeSubagent(n){e(i=>{const o=new Map(i.subagents);o.delete(n),i.subagents=o}),t()},getSubagentByToolUseId(n){const i=s();for(const[,o]of i.subagents)if(o.toolUseId===n)return o}}}function xn(s,e){if(s===e)return!0;if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]!==e[t])return!1;return!0}function Qa(s,e){if(s===e)return!0;if(s.size!==e.size)return!1;for(const[t,n]of s)if(e.get(t)!==n)return!1;return!0}function YE(s,e){if(s===e)return!0;if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function Nt(s,e=Object.is){const[t,n]=x.useState(()=>s(P.getState())),i=x.useRef(t);return x.useEffect(()=>{i.current=t},[t]),x.useEffect(()=>{const o=()=>{const r=s(P.getState());e(i.current,r)||(i.current=r,n(r))};return o(),P.subscribe(o)},[s,e]),t}function cs(){const[,s]=x.useState({});return x.useEffect(()=>P.subscribe(()=>s({})),[]),P.getState()}function Ja(){return Nt(x.useCallback(s=>s.agents,[]),Qa)}function ld(){const s=Ja(),e=x.useRef([]),t=Array.from(s.values());return xn(e.current,t)||(e.current=t),e.current}function Df(s){return Nt(x.useCallback(e=>s?e.agents.get(s):void 0,[s]))}function AS(){return Nt(x.useCallback(s=>s.selectedAgentIds,[]),YE)}function Rf(s){const e=x.useRef([]),t=x.useRef(0),n=Nt(x.useCallback(i=>s&&i.agentOutputs.get(s)||e.current,[s]),xn);return n.length!==t.current&&(ql.info(`Selector: ${t.current} -> ${n.length}`,{agentId:s,lastText:n.length>0?n[n.length-1].text.slice(0,40):null},"useAgentOutputs"),t.current=n.length),n}function Lf(){return Nt(x.useCallback(s=>s.lastPrompts,[]),Qa)}function cd(){return Nt(x.useCallback(s=>s.areas,[]),Qa)}function ZE(){return Nt(x.useCallback(s=>s.buildings,[]),Qa)}function NS(){return Nt(x.useCallback(s=>s.supervisor,[]))}function So(){return Nt(x.useCallback(s=>s.settings,[]))}function TS(){return Nt(x.useCallback(s=>s.settings.hideCost,[]))}function QE(){return Nt(x.useCallback(s=>s.settings.customAgentNames,[]),xn)}function JE(){return Nt(x.useCallback(s=>s.shortcuts,[]),xn)}function MS(){return Nt(x.useCallback(s=>s.mouseControls,[]))}function e_(){return Nt(x.useCallback(s=>s.mouseControls.trackpad,[]))}function ES(){return Nt(x.useCallback(s=>s.terminalOpen,[]))}function _S(){return Nt(x.useCallback(s=>s.mobileView,[]))}function Bf(){return Nt(x.useCallback(s=>s.fileViewerPath,[]))}function t_(){return Nt(x.useCallback(s=>s.fileViewerEditData,[]))}function s_(){return Nt(x.useCallback(s=>s.explorerFolderPath,[]))}function Pf(){return Nt(x.useCallback(s=>s.contextModalAgentId,[]))}function DS(){return Nt(x.useCallback(s=>s.toolExecutions,[]),xn)}function n_(){return Nt(x.useCallback(s=>s.fileChanges,[]),xn)}function RS(){return Nt(x.useCallback(s=>s.skills,[]),Qa)}function ud(){const s=RS(),e=x.useRef([]),t=Array.from(s.values());return xn(e.current,t)||(e.current=t),e.current}function a_(s){return Nt(x.useCallback(e=>s?e.skills.get(s):void 0,[s]))}function i_(s){const e=x.useRef([]),t=Ja(),n=RS();if(!s)return e.current;const i=t.get(s);return i?Array.from(n.values()).filter(r=>r.enabled?!!(r.assignedAgentIds.includes(s)||r.assignedAgentClasses.includes(i.class)):!1):e.current}function o_(){return Nt(x.useCallback(s=>s.customAgentClasses,[]),Qa)}function ua(){const s=o_(),e=x.useRef([]),t=Array.from(s.values());return xn(e.current,t)||(e.current=t),e.current}function LS(s){return Nt(x.useCallback(e=>s?e.customAgentClasses.get(s):void 0,[s]))}function If(){return Nt(x.useCallback(s=>s.reconnectCount,[]))}function r_(){return Nt(x.useCallback(s=>s.supervisor.globalUsage,[]))}function l_(){return Nt(x.useCallback(s=>s.supervisor.refreshingUsage,[]))}function c_(s){const e=x.useRef(new Map);return Nt(x.useCallback(t=>s&&t.agentTaskProgress.get(s)||e.current,[s]),Qa)}function u_(s){return Nt(x.useCallback(e=>!s||!e.execTasks?[]:Array.from(e.execTasks.values()).filter(t=>t.agentId===s),[s]),xn)}function d_(){return Nt(x.useCallback(s=>s.secrets,[]),Qa)}function h_(){const s=d_(),e=x.useRef([]),t=Array.from(s.values());return xn(e.current,t)||(e.current=t),e.current}const p_={connectionStatus:new Map,databases:new Map,tables:new Map,tableSchemas:new Map,queryResults:[],queryHistory:[],executingQuery:!1,activeConnectionId:null,activeDatabase:null};function Of(s){return Nt(x.useCallback(e=>(s?e.databaseState.get(s):void 0)??p_,[s]))}function m_(s){return Nt(x.useCallback(e=>{if(!s)return[];const t=e.databaseState.get(s);return(t==null?void 0:t.queryResults)??[]},[s]),xn)}function f_(s){return Nt(x.useCallback(e=>{if(!s)return[];const t=e.databaseState.get(s);return(t==null?void 0:t.queryHistory)??[]},[s]),xn)}function g_(s){return Nt(x.useCallback(e=>{if(!s)return!1;const t=e.databaseState.get(s);return(t==null?void 0:t.executingQuery)??!1},[s]))}function b_(){return Nt(s=>s.dockerContainersList,xn)}function y_(){return Nt(s=>s.currentSnapshot)}function x_(){return Nt(s=>s.subagents,Qa)}function v_(s){return Nt(x.useCallback(e=>s?Array.from(e.subagents.values()).filter(t=>t.parentAgentId===s):[],[s]),xn)}function w_(){return Nt(s=>s.viewMode)}function k_(){return Nt(x.useCallback(s=>s.overviewPanelOpen,[]))}class s0{constructor(){K(this,"state");K(this,"listeners",new Set);K(this,"sendMessage",null);K(this,"agentActions");K(this,"outputActions");K(this,"supervisorActions");K(this,"areaActions");K(this,"buildingActions");K(this,"permissionActions");K(this,"delegationActions");K(this,"skillActions");K(this,"execTaskActions");K(this,"secretActions");K(this,"databaseActions");K(this,"snapshotActions");K(this,"subagentActions");K(this,"statusPollInterval",null);this.state={agents:new Map,selectedAgentIds:new Set,lastSelectedAgentId:null,activities:[],isConnected:!1,areas:new Map,activeTool:null,selectedAreaId:null,buildings:new Map,selectedBuildingIds:new Set,buildingLogs:new Map,streamingBuildingLogs:new Map,streamingBuildingIds:new Set,bossStreamingLogs:new Map,agentOutputs:new Map,lastPrompts:new Map,toolExecutions:[],fileChanges:[],terminalOpen:!1,terminalResizing:!1,mobileView:this.loadMobileView(),settings:this.loadSettings(),shortcuts:this.loadShortcuts(),mouseControls:this.loadMouseControls(),fileViewerPath:null,fileViewerEditData:null,explorerFolderPath:null,explorerAreaId:null,contextModalAgentId:null,supervisor:{enabled:!0,autoReportOnComplete:!1,lastReport:null,narratives:new Map,lastReportTime:null,nextReportTime:null,agentHistories:new Map,loadingHistoryForAgent:null,historyFetchedForAgents:new Set,generatingReport:!1,globalUsage:null,refreshingUsage:!1},permissionRequests:new Map,delegationHistories:new Map,pendingDelegation:null,lastDelegationReceived:new Map,agentTaskProgress:new Map,skills:new Map,customAgentClasses:new Map,reconnectCount:0,execTasks:new Map,secrets:new Map,databaseState:new Map,dockerContainersList:[],dockerComposeProjectsList:[],snapshots:new Map,currentSnapshot:null,snapshotsLoading:!1,snapshotsError:null,lastSelectionViaSwipe:!1,lastSelectionViaDirectClick:!1,subagents:new Map,viewMode:(()=>{const r=tn(rt.SCENE_VIEW_MODE,"3d");return r==="2d"||r==="3d"||r==="dashboard"?r:"3d"})(),overviewPanelOpen:!1};const e=()=>this.state,t=r=>{r(this.state)},n=()=>this.notify(),i=()=>this.sendMessage,o=()=>this.listeners.size;this.agentActions=IE(e,t,n,i),this.outputActions=OE(e,t,n,o),this.supervisorActions=zE(e,t,n,i),this.areaActions=FE(e,t,n,i),this.buildingActions=$E(e,t,n,i),this.permissionActions=HE(e,t,n,i),this.delegationActions=UE(e,t,n,i),this.skillActions=GE(e,t,n,i),this.execTaskActions=WE(e,t,n),this.secretActions=qE(e,t,n,i),this.databaseActions=KE(e,t,n,i),this.snapshotActions=VE(e,t,n),this.subagentActions=XE(e,t,n)}loadSettings(){const e=ka(rt.SETTINGS,null);return e?{...e0,...e}:{...e0}}loadShortcuts(){const e=ka(rt.SHORTCUTS,null);return e?Fp.map(n=>{const i=e.find(o=>o.id===n.id);return i?{...n,...i}:n}):[...Fp]}loadMouseControls(){var t;const e=ka(rt.MOUSE_CONTROLS,null);return e?{bindings:Hp.map(i=>{var r;const o=(r=e.bindings)==null?void 0:r.find(c=>c.id===i.id);return o?{...i,...o}:i}),sensitivity:{...$p,...e.sensitivity},trackpad:{...xu,...e.trackpad,sensitivity:{...xu.sensitivity,...(t=e.trackpad)==null?void 0:t.sensitivity}}}:{bindings:[...Hp],sensitivity:{...$p},trackpad:{...xu}}}loadMobileView(){const e=tn(rt.MOBILE_VIEW,"");return e==="terminal"||e==="3d"?e:typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window?"3d":"terminal"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){this.listeners.forEach(e=>e())}getState(){return this.state}setSendMessage(e){this.sendMessage=e}setConnected(e){this.state.isConnected=e,this.notify()}triggerReconnect(){this.state.reconnectCount++,this.notify()}toggleTerminal(e){e&&!this.state.selectedAgentIds.has(e)&&(this.state.selectedAgentIds.clear(),this.state.selectedAgentIds.add(e)),this.state.terminalOpen=!this.state.terminalOpen,this.notify()}setTerminalOpen(e){if(console.log("[Store] setTerminalOpen called with:",e,"current:",this.state.terminalOpen),!e&&this.state.terminalOpen&&console.trace("[Store] Closing terminal - stack trace:"),this.state.terminalOpen=e,e&&(this.state.mobileView="terminal",this.state.selectedAgentIds.size===0&&this.state.agents.size>0&&!this.state.currentSnapshot)){const t=Array.from(this.state.agents.keys())[0];console.log("[Store] Auto-selecting first agent for terminal open:",t),this.state.selectedAgentIds=new Set([t])}this.notify(),console.log("[Store] After notify, terminalOpen:",this.state.terminalOpen)}setOverviewPanelOpen(e){this.state.overviewPanelOpen=e,this.notify()}setMobileView(e){if(console.log("[Store] setMobileView called:",e,"previous:",this.state.mobileView),this.state.mobileView=e,Yn(rt.MOBILE_VIEW,e),e==="terminal"&&this.state.selectedAgentIds.size===0&&this.state.agents.size>0&&!this.state.currentSnapshot){const t=Array.from(this.state.agents.keys())[0];console.log("[Store] Auto-selecting first agent for terminal view:",t),this.state.selectedAgentIds=new Set([t]),this.state.terminalOpen=!0}this.notify()}setViewMode(e){this.state.viewMode=e,Yn(rt.SCENE_VIEW_MODE,e),this.state.settings.experimental2DView=e==="2d",this.notify()}openTerminalOnMobile(e){console.log("[Store] openTerminalOnMobile called for agent:",e),XN("terminal"),this.state.selectedAgentIds.clear(),this.state.selectedAgentIds.add(e),this.state.terminalOpen=!0,this.state.mobileView="terminal",this.notify()}setTerminalResizing(e){this.state.terminalResizing=e,this.notify()}setLastSelectionViaSwipe(e){this.state.lastSelectionViaSwipe=e}consumeSwipeSelectionFlag(){const e=this.state.lastSelectionViaSwipe;return this.state.lastSelectionViaSwipe=!1,e}setLastSelectionViaDirectClick(e){this.state.lastSelectionViaDirectClick=e}consumeDirectClickSelectionFlag(){const e=this.state.lastSelectionViaDirectClick;return this.state.lastSelectionViaDirectClick=!1,e}setFileViewerPath(e,t){this.state.fileViewerPath=e,this.state.fileViewerEditData=t||null,this.notify()}clearFileViewerPath(){this.state.fileViewerPath=null,this.state.fileViewerEditData=null,this.notify()}getLastExplorerState(){try{const e=localStorage.getItem("file-explorer-last-opened");return e?JSON.parse(e):null}catch{return null}}setExplorerFolderPath(e){this.state.explorerFolderPath=e,this.notify()}openFileExplorer(e){this.state.explorerFolderPath=e,this.state.explorerAreaId=null,this.notify()}closeFileExplorer(){this.state.explorerFolderPath=null,this.state.explorerAreaId=null,this.notify()}openFileExplorerForArea(e){this.state.explorerFolderPath=null,this.state.explorerAreaId=e,this.notify()}openFileExplorerForAreaFolder(e,t){this.state.explorerAreaId=e,this.state.explorerFolderPath=t,this.notify()}setContextModalAgentId(e){this.state.contextModalAgentId=e,this.notify()}closeContextModal(){this.state.contextModalAgentId=null,this.notify()}updateSettings(e){this.state.settings={...this.state.settings,...e},Xa(rt.SETTINGS,this.state.settings),this.notify()}getSettings(){return this.state.settings}getShortcuts(){return this.state.shortcuts}getShortcut(e){return this.state.shortcuts.find(t=>t.id===e)}updateShortcut(e,t){const n=this.state.shortcuts.findIndex(i=>i.id===e);n!==-1&&(this.state.shortcuts=[...this.state.shortcuts.slice(0,n),{...this.state.shortcuts[n],...t},...this.state.shortcuts.slice(n+1)],this.saveShortcuts(),this.notify())}resetShortcuts(){this.state.shortcuts=[...Fp],this.saveShortcuts(),this.notify()}saveShortcuts(){Xa(rt.SHORTCUTS,this.state.shortcuts)}getMouseControls(){return this.state.mouseControls}getMouseBinding(e){return this.state.mouseControls.bindings.find(t=>t.id===e)}updateMouseBinding(e,t){const n=this.state.mouseControls.bindings.findIndex(i=>i.id===e);n!==-1&&(this.state.mouseControls.bindings=[...this.state.mouseControls.bindings.slice(0,n),{...this.state.mouseControls.bindings[n],...t},...this.state.mouseControls.bindings.slice(n+1)],this.saveMouseControls(),this.notify())}updateCameraSensitivity(e){this.state.mouseControls.sensitivity={...this.state.mouseControls.sensitivity,...e},this.saveMouseControls(),this.notify()}resetMouseControls(){this.state.mouseControls={bindings:[...Hp],sensitivity:{...$p},trackpad:{...xu}},this.saveMouseControls(),this.notify()}getTrackpadConfig(){return this.state.mouseControls.trackpad}updateTrackpadConfig(e){this.state.mouseControls.trackpad={...this.state.mouseControls.trackpad,...e,sensitivity:{...this.state.mouseControls.trackpad.sensitivity,...e.sensitivity||{}}},this.saveMouseControls(),this.notify()}saveMouseControls(){Xa(rt.MOUSE_CONTROLS,this.state.mouseControls)}startStatusPolling(){}stopStatusPolling(){this.statusPollInterval&&(clearInterval(this.statusPollInterval),this.statusPollInterval=null)}setAgents(...e){return this.agentActions.setAgents(...e)}addAgent(...e){return this.agentActions.addAgent(...e)}updateAgent(...e){return this.agentActions.updateAgent(...e)}updateAgentContextStats(...e){return this.agentActions.updateAgentContextStats(...e)}removeAgent(...e){return this.agentActions.removeAgent(...e)}selectAgent(...e){return this.agentActions.selectAgent(...e)}addToSelection(...e){return this.agentActions.addToSelection(...e)}selectMultiple(...e){return this.agentActions.selectMultiple(...e)}deselectAll(...e){return this.agentActions.deselectAll(...e)}spawnAgent(...e){return this.agentActions.spawnAgent(...e)}createDirectoryAndSpawn(...e){return this.agentActions.createDirectoryAndSpawn(...e)}sendCommand(...e){return this.agentActions.sendCommand(...e)}refreshAgentContext(...e){return this.agentActions.refreshAgentContext(...e)}moveAgent(...e){return this.agentActions.moveAgent(...e)}killAgent(...e){return this.agentActions.killAgent(...e)}stopAgent(...e){return this.agentActions.stopAgent(...e)}clearContext(...e){return this.agentActions.clearContext(...e)}collapseContext(...e){return this.agentActions.collapseContext(...e)}removeAgentFromServer(...e){return this.agentActions.removeAgentFromServer(...e)}renameAgent(...e){return this.agentActions.renameAgent(...e)}updateAgentProperties(...e){return this.agentActions.updateAgentProperties(...e)}getTotalTokens(){return this.agentActions.getTotalTokens()}getSelectedAgents(){return this.agentActions.getSelectedAgents()}addActivity(...e){return this.agentActions.addActivity(...e)}addToolExecution(...e){return this.agentActions.addToolExecution(...e)}addFileChange(...e){return this.agentActions.addFileChange(...e)}loadToolHistory(){return this.agentActions.loadToolHistory()}addOutput(...e){return this.outputActions.addOutput(...e)}clearOutputs(...e){return this.outputActions.clearOutputs(...e)}getOutputs(...e){return this.outputActions.getOutputs(...e)}addUserPromptToOutput(...e){return this.outputActions.addUserPromptToOutput(...e)}getLastPrompt(...e){return this.outputActions.getLastPrompt(...e)}setLastPrompt(...e){return this.outputActions.setLastPrompt(...e)}preserveOutputs(){return this.outputActions.preserveOutputs()}mergeOutputsWithHistory(...e){return this.outputActions.mergeOutputsWithHistory(...e)}setSupervisorReport(...e){return this.supervisorActions.setSupervisorReport(...e)}addNarrative(...e){return this.supervisorActions.addNarrative(...e)}getNarratives(...e){return this.supervisorActions.getNarratives(...e)}setSupervisorStatus(...e){return this.supervisorActions.setSupervisorStatus(...e)}setSupervisorConfig(...e){return this.supervisorActions.setSupervisorConfig(...e)}requestSupervisorReport(){return this.supervisorActions.requestSupervisorReport()}requestAgentSupervisorHistory(...e){return this.supervisorActions.requestAgentSupervisorHistory(...e)}setAgentSupervisorHistory(...e){return this.supervisorActions.setAgentSupervisorHistory(...e)}getAgentSupervisorHistory(...e){return this.supervisorActions.getAgentSupervisorHistory(...e)}addAgentAnalysis(...e){return this.supervisorActions.addAgentAnalysis(...e)}isLoadingHistoryForAgent(...e){return this.supervisorActions.isLoadingHistoryForAgent(...e)}hasHistoryBeenFetched(...e){return this.supervisorActions.hasHistoryBeenFetched(...e)}setGlobalUsage(...e){return this.supervisorActions.setGlobalUsage(...e)}requestGlobalUsage(){return this.supervisorActions.requestGlobalUsage()}getGlobalUsage(){return this.supervisorActions.getGlobalUsage()}setActiveTool(...e){return this.areaActions.setActiveTool(...e)}selectArea(...e){return this.areaActions.selectArea(...e)}addArea(...e){return this.areaActions.addArea(...e)}updateArea(...e){return this.areaActions.updateArea(...e)}updateAreaLocal(...e){return this.areaActions.updateAreaLocal(...e)}deleteArea(...e){return this.areaActions.deleteArea(...e)}assignAgentToArea(...e){return this.areaActions.assignAgentToArea(...e)}unassignAgentFromArea(...e){return this.areaActions.unassignAgentFromArea(...e)}addDirectoryToArea(...e){return this.areaActions.addDirectoryToArea(...e)}removeDirectoryFromArea(...e){return this.areaActions.removeDirectoryFromArea(...e)}getAreaDirectories(...e){return this.areaActions.getAreaDirectories(...e)}isPositionInArea(...e){return this.areaActions.isPositionInArea(...e)}getAreaForAgent(...e){return this.areaActions.getAreaForAgent(...e)}setAreasFromServer(...e){return this.areaActions.setAreasFromServer(...e)}getAreasInZOrder(...e){return this.areaActions.getAreasInZOrder(...e)}getNextZIndex(...e){return this.areaActions.getNextZIndex(...e)}bringAreaToFront(...e){return this.areaActions.bringAreaToFront(...e)}sendAreaToBack(...e){return this.areaActions.sendAreaToBack(...e)}setAreaZIndex(...e){return this.areaActions.setAreaZIndex(...e)}archiveArea(...e){return this.areaActions.archiveArea(...e)}restoreArchivedArea(...e){return this.areaActions.restoreArchivedArea(...e)}getArchivedAreas(...e){return this.areaActions.getArchivedAreas(...e)}getVisibleAreas(...e){return this.areaActions.getVisibleAreas(...e)}isAgentInArchivedArea(...e){return this.areaActions.isAgentInArchivedArea(...e)}selectBuilding(...e){return this.buildingActions.selectBuilding(...e)}selectMultipleBuildings(...e){return this.buildingActions.selectMultipleBuildings(...e)}toggleBuildingSelection(...e){return this.buildingActions.toggleBuildingSelection(...e)}isBuildingSelected(...e){return this.buildingActions.isBuildingSelected(...e)}getSelectedBuildingIds(){return this.buildingActions.getSelectedBuildingIds()}deleteSelectedBuildings(){return this.buildingActions.deleteSelectedBuildings()}addBuilding(...e){return this.buildingActions.addBuilding(...e)}updateBuilding(...e){return this.buildingActions.updateBuilding(...e)}updateBuildingLocal(...e){return this.buildingActions.updateBuildingLocal(...e)}deleteBuilding(...e){return this.buildingActions.deleteBuilding(...e)}moveBuilding(...e){return this.buildingActions.moveBuilding(...e)}updateBuildingPosition(...e){return this.buildingActions.updateBuildingPosition(...e)}createBuilding(...e){return this.buildingActions.createBuilding(...e)}sendBuildingCommand(...e){return this.buildingActions.sendBuildingCommand(...e)}addBuildingLogs(...e){return this.buildingActions.addBuildingLogs(...e)}getBuildingLogs(...e){return this.buildingActions.getBuildingLogs(...e)}clearBuildingLogs(...e){return this.buildingActions.clearBuildingLogs(...e)}setBuildingsFromServer(...e){return this.buildingActions.setBuildingsFromServer(...e)}updateBuildingFromServer(...e){return this.buildingActions.updateBuildingFromServer(...e)}removeBuildingFromServer(...e){return this.buildingActions.removeBuildingFromServer(...e)}startLogStreaming(...e){return this.buildingActions.startLogStreaming(...e)}stopLogStreaming(...e){return this.buildingActions.stopLogStreaming(...e)}appendStreamingLogChunk(...e){return this.buildingActions.appendStreamingLogChunk(...e)}setStreamingStatus(...e){return this.buildingActions.setStreamingStatus(...e)}getStreamingLogs(...e){return this.buildingActions.getStreamingLogs(...e)}clearStreamingLogs(...e){return this.buildingActions.clearStreamingLogs(...e)}isLogStreaming(...e){return this.buildingActions.isLogStreaming(...e)}sendBossBuildingCommand(...e){return this.buildingActions.sendBossBuildingCommand(...e)}assignBuildingsToBoSS(...e){return this.buildingActions.assignBuildingsToBoSS(...e)}startBossLogStreaming(...e){return this.buildingActions.startBossLogStreaming(...e)}stopBossLogStreaming(...e){return this.buildingActions.stopBossLogStreaming(...e)}appendBossStreamingLogChunk(...e){return this.buildingActions.appendBossStreamingLogChunk(...e)}getBossStreamingLogs(...e){return this.buildingActions.getBossStreamingLogs(...e)}clearBossStreamingLogs(...e){return this.buildingActions.clearBossStreamingLogs(...e)}requestDockerContainersList(){return this.buildingActions.requestDockerContainersList()}setDockerContainersList(...e){return this.buildingActions.setDockerContainersList(...e)}getDockerContainersList(){return this.buildingActions.getDockerContainersList()}getDockerComposeProjectsList(){return this.buildingActions.getDockerComposeProjectsList()}addPermissionRequest(...e){return this.permissionActions.addPermissionRequest(...e)}resolvePermissionRequest(...e){return this.permissionActions.resolvePermissionRequest(...e)}respondToPermissionRequest(...e){return this.permissionActions.respondToPermissionRequest(...e)}getPendingPermissionsForAgent(...e){return this.permissionActions.getPendingPermissionsForAgent(...e)}clearAllPermissions(...e){return this.permissionActions.clearAllPermissions(...e)}spawnBossAgent(...e){return this.delegationActions.spawnBossAgent(...e)}assignSubordinates(...e){return this.delegationActions.assignSubordinates(...e)}removeSubordinate(...e){return this.delegationActions.removeSubordinate(...e)}sendBossCommand(...e){return this.delegationActions.sendBossCommand(...e)}requestDelegationHistory(...e){return this.delegationActions.requestDelegationHistory(...e)}handleDelegationDecision(...e){return this.delegationActions.handleDelegationDecision(...e)}setDelegationHistory(...e){return this.delegationActions.setDelegationHistory(...e)}getDelegationHistory(...e){return this.delegationActions.getDelegationHistory(...e)}getLastDelegationReceived(...e){return this.delegationActions.getLastDelegationReceived(...e)}clearLastDelegationReceived(...e){return this.delegationActions.clearLastDelegationReceived(...e)}updateBossSubordinates(...e){return this.delegationActions.updateBossSubordinates(...e)}getSubordinates(...e){return this.delegationActions.getSubordinates(...e)}isBossAgent(...e){return this.delegationActions.isBossAgent(...e)}getBossForAgent(...e){return this.delegationActions.getBossForAgent(...e)}getAvailableSubordinates(){return this.delegationActions.getAvailableSubordinates()}handleAgentTaskStarted(...e){return this.delegationActions.handleAgentTaskStarted(...e)}handleAgentTaskOutput(...e){return this.delegationActions.handleAgentTaskOutput(...e)}handleAgentTaskCompleted(...e){return this.delegationActions.handleAgentTaskCompleted(...e)}getAgentTaskProgress(...e){return this.delegationActions.getAgentTaskProgress(...e)}clearAgentTaskProgress(...e){return this.delegationActions.clearAgentTaskProgress(...e)}clearAllSubordinatesContext(...e){return this.delegationActions.clearAllSubordinatesContext(...e)}setSkillsFromServer(...e){return this.skillActions.setSkillsFromServer(...e)}addSkillFromServer(...e){return this.skillActions.addSkillFromServer(...e)}updateSkillFromServer(...e){return this.skillActions.updateSkillFromServer(...e)}removeSkillFromServer(...e){return this.skillActions.removeSkillFromServer(...e)}getSkill(...e){return this.skillActions.getSkill(...e)}getAllSkills(){return this.skillActions.getAllSkills()}getSkillsForAgent(...e){return this.skillActions.getSkillsForAgent(...e)}createSkill(...e){return this.skillActions.createSkill(...e)}updateSkill(...e){return this.skillActions.updateSkill(...e)}deleteSkill(...e){return this.skillActions.deleteSkill(...e)}assignSkillToAgent(...e){return this.skillActions.assignSkillToAgent(...e)}unassignSkillFromAgent(...e){return this.skillActions.unassignSkillFromAgent(...e)}requestAgentSkills(...e){return this.skillActions.requestAgentSkills(...e)}setCustomAgentClassesFromServer(...e){return this.skillActions.setCustomAgentClassesFromServer(...e)}addCustomAgentClassFromServer(...e){return this.skillActions.addCustomAgentClassFromServer(...e)}updateCustomAgentClassFromServer(...e){return this.skillActions.updateCustomAgentClassFromServer(...e)}removeCustomAgentClassFromServer(...e){return this.skillActions.removeCustomAgentClassFromServer(...e)}getCustomAgentClass(...e){return this.skillActions.getCustomAgentClass(...e)}getAllCustomAgentClasses(){return this.skillActions.getAllCustomAgentClasses()}createCustomAgentClass(...e){return this.skillActions.createCustomAgentClass(...e)}updateCustomAgentClass(...e){return this.skillActions.updateCustomAgentClass(...e)}deleteCustomAgentClass(...e){return this.skillActions.deleteCustomAgentClass(...e)}handleExecTaskStarted(...e){return this.execTaskActions.handleExecTaskStarted(...e)}handleExecTaskOutput(...e){return this.execTaskActions.handleExecTaskOutput(...e)}handleExecTaskCompleted(...e){return this.execTaskActions.handleExecTaskCompleted(...e)}stopExecTask(...e){return this.execTaskActions.stopExecTask(...e)}getExecTasks(...e){return this.execTaskActions.getExecTasks(...e)}getAllExecTasks(){return this.execTaskActions.getAllExecTasks()}getExecTask(...e){return this.execTaskActions.getExecTask(...e)}clearCompletedExecTasks(...e){return this.execTaskActions.clearCompletedExecTasks(...e)}clearAllExecTasks(...e){return this.execTaskActions.clearAllExecTasks(...e)}removeExecTask(...e){return this.execTaskActions.removeExecTask(...e)}setSecretsFromServer(...e){return this.secretActions.setSecretsFromServer(...e)}addSecretFromServer(...e){return this.secretActions.addSecretFromServer(...e)}updateSecretFromServer(...e){return this.secretActions.updateSecretFromServer(...e)}removeSecretFromServer(...e){return this.secretActions.removeSecretFromServer(...e)}getSecret(...e){return this.secretActions.getSecret(...e)}getSecretByKey(...e){return this.secretActions.getSecretByKey(...e)}getAllSecrets(){return this.secretActions.getAllSecrets()}createSecret(...e){return this.secretActions.createSecret(...e)}updateSecret(...e){return this.secretActions.updateSecret(...e)}deleteSecret(...e){return this.secretActions.deleteSecret(...e)}testDatabaseConnection(...e){return this.databaseActions.testDatabaseConnection(...e)}setConnectionStatus(...e){return this.databaseActions.setConnectionStatus(...e)}listDatabases(...e){return this.databaseActions.listDatabases(...e)}setDatabases(...e){return this.databaseActions.setDatabases(...e)}listTables(...e){return this.databaseActions.listTables(...e)}setTables(...e){return this.databaseActions.setTables(...e)}getTableSchema(...e){return this.databaseActions.getTableSchema(...e)}setTableSchema(...e){return this.databaseActions.setTableSchema(...e)}executeQuery(...e){return this.databaseActions.executeQuery(...e)}setQueryResult(...e){return this.databaseActions.setQueryResult(...e)}setExecutingQuery(...e){return this.databaseActions.setExecutingQuery(...e)}requestQueryHistory(...e){return this.databaseActions.requestQueryHistory(...e)}setQueryHistory(...e){return this.databaseActions.setQueryHistory(...e)}toggleQueryFavorite(...e){return this.databaseActions.toggleQueryFavorite(...e)}deleteQueryFromHistory(...e){return this.databaseActions.deleteQueryFromHistory(...e)}clearQueryHistory(...e){return this.databaseActions.clearQueryHistory(...e)}setActiveConnection(...e){return this.databaseActions.setActiveConnection(...e)}setActiveDatabase(...e){return this.databaseActions.setActiveDatabase(...e)}getDatabaseState(...e){return this.databaseActions.getDatabaseState(...e)}clearDatabaseState(...e){return this.databaseActions.clearDatabaseState(...e)}fetchSnapshots(...e){return this.snapshotActions.fetchSnapshots(...e)}setSnapshots(...e){return this.snapshotActions.setSnapshots(...e)}createSnapshot(...e){return this.snapshotActions.createSnapshot(...e)}loadSnapshot(...e){return this.snapshotActions.loadSnapshot(...e)}setCurrentSnapshot(...e){return this.snapshotActions.setCurrentSnapshot(...e)}deleteSnapshot(...e){return this.snapshotActions.deleteSnapshot(...e)}restoreFiles(...e){return this.snapshotActions.restoreFiles(...e)}setLoading(...e){return this.snapshotActions.setLoading(...e)}setError(...e){return this.snapshotActions.setError(...e)}clearError(...e){return this.snapshotActions.clearError(...e)}reset(...e){return this.snapshotActions.reset(...e)}addSubagent(...e){return this.subagentActions.addSubagent(...e)}completeSubagent(...e){return this.subagentActions.completeSubagent(...e)}getSubagentsForAgent(...e){return this.subagentActions.getSubagentsForAgent(...e)}getSubagent(...e){return this.subagentActions.getSubagent(...e)}removeSubagent(...e){return this.subagentActions.removeSubagent(...e)}getSubagentByToolUseId(...e){return this.subagentActions.getSubagentByToolUseId(...e)}}const n0=1;function S_(){return typeof window<"u"?(window.__tideStore&&window.__tideStoreVersion===n0||(window.__tideStore=new s0,window.__tideStoreVersion=n0),window.__tideStore):new s0}const P=S_(),BS=x.createContext(null),j_={error:"❌",success:"✅",warning:"⚠️",info:"ℹ️"};let C_=0;function A_({children:s}){const[e,t]=x.useState(null),n=x.useRef([]),i=x.useRef(null),o=x.useCallback(()=>{if(n.current.length>0&&!e){const u=n.current.shift();t(u)}},[e]);x.useEffect(()=>{e||o()},[e,o]),x.useEffect(()=>{if(e&&e.duration>0)return i.current=window.setTimeout(()=>{t(null)},e.duration),()=>{i.current&&clearTimeout(i.current)}},[e]);const r=x.useCallback((u,h,m,f=5e3)=>{const b={id:++C_,type:u,title:h,message:m,duration:f};if(n.current.push(b),!e){const v=n.current.shift();t(v)}},[e]),c=x.useCallback(()=>{i.current&&clearTimeout(i.current),t(null)},[]);return a.jsxs(BS.Provider,{value:{showToast:r},children:[s,a.jsx("div",{id:"toast-container",children:e&&a.jsxs("div",{className:`toast ${e.type}`,children:[a.jsx("span",{className:"toast-icon",children:j_[e.type]}),a.jsxs("div",{className:"toast-content",children:[a.jsx("div",{className:"toast-title",children:e.title}),a.jsx("div",{className:"toast-message",children:e.message})]}),a.jsx("button",{className:"toast-close",onClick:c,children:"×"})]},e.id)})]})}function zf(){const s=x.useContext(BS);if(!s)throw new Error("useToast must be used within ToastProvider");return s}const Ya={scout:{icon:"🔍",color:"#4a9eff",description:"Codebase exploration, file discovery"},builder:{icon:"🔨",color:"#ff9e4a",description:"Feature implementation, writing code"},debugger:{icon:"🐛",color:"#ff4a4a",description:"Bug hunting, fixing issues"},architect:{icon:"📐",color:"#9e4aff",description:"Planning, design decisions"},warrior:{icon:"⚔️",color:"#ff4a9e",description:"Aggressive refactoring, migrations"},support:{icon:"💚",color:"#4aff9e",description:"Documentation, tests, cleanup"},boss:{icon:"👑",color:"#ffd700",description:"Team leader, delegates tasks to subordinates"}},Sa=Ya,ra={bypass:{label:"Permissionless",description:"Skip all permission prompts (less safe, faster)"},interactive:{label:"Interactive",description:"Ask for approval before sensitive operations"}},Vn={"gpt-5.3-codex":{label:"GPT-5.3 Codex",description:"Latest frontier agentic coding model",icon:"⚙️"},"gpt-5.2-codex":{label:"GPT-5.2 Codex",description:"Frontier agentic coding model",icon:"🧠"},"gpt-5.1-codex-max":{label:"GPT-5.1 Codex Max",description:"Codex-optimized flagship for deep and fast reasoning",icon:"🚀"},"gpt-5.1-codex-mini":{label:"GPT-5.1 Codex Mini",description:"Optimized for codex, cheaper and faster",icon:"⚡"},"gpt-5.2":{label:"GPT-5.2",description:"General frontier model with strong reasoning and coding",icon:"🧩"}},Xn={sonnet:{label:"Sonnet",description:"Balanced performance and cost (recommended)",icon:"⚡"},opus:{label:"Opus",description:"Most capable, higher cost",icon:"🧠"},haiku:{label:"Haiku",description:"Fast and economical",icon:"🚀"}},Um="<<<BOSS_CONTEXT_START>>>",a0="<<<BOSS_CONTEXT_END>>>",xr={server:{icon:"🖥️",color:"#4aff9e",description:"Service with start/stop commands and logs"},link:{icon:"🔗",color:"#4a9eff",description:"Quick links to URLs"},database:{icon:"🗄️",color:"#ff9e4a",description:"Database connection and queries"},docker:{icon:"🐳",color:"#4ac1ff",description:"Docker container management"},monitor:{icon:"📊",color:"#ff4a9e",description:"System metrics and monitoring"},folder:{icon:"📁",color:"#ffd700",description:"Folder shortcut - opens file explorer on click"},boss:{icon:"👑",color:"#ffd700",description:"Boss building - manages multiple buildings with unified controls"}},Eu={"server-rack":{label:"Server Rack",description:"Classic server rack with blinking LEDs"},tower:{label:"Control Tower",description:"Tall tower with rotating antenna"},dome:{label:"Data Dome",description:"Futuristic dome with energy ring"},pyramid:{label:"Power Pyramid",description:"Egyptian-style pyramid with glowing core"},desktop:{label:"Desktop PC",description:"Retro computer with monitor and keyboard"},"filing-cabinet":{label:"Filing Cabinet",description:"Office cabinet with sliding drawers"},satellite:{label:"Satellite Dish",description:"Communication dish with rotating receiver"},crystal:{label:"Data Crystal",description:"Floating crystal with energy particles"},factory:{label:"Mini Factory",description:"Industrial building with smoking chimney"},"command-center":{label:"Command Center",description:"Grand central hub for boss buildings with holographic rings"}},i0={"":{label:"Auto-detect",description:"Let PM2 detect the interpreter"},node:{label:"Node.js",description:"JavaScript/TypeScript runtime"},bun:{label:"Bun",description:"Bun JavaScript runtime"},python3:{label:"Python 3",description:"Python 3 interpreter"},python:{label:"Python 2",description:"Python 2 interpreter (legacy)"},java:{label:"Java",description:"Java runtime (use with -jar args)"},php:{label:"PHP",description:"PHP interpreter"},bash:{label:"Bash",description:"Bash shell script"},none:{label:"None (Binary)",description:"Direct execution (compiled binaries)"}},o0={no:{label:"No",description:"Do not automatically restart"},always:{label:"Always",description:"Always restart when stopped"},"unless-stopped":{label:"Unless Stopped",description:"Restart unless manually stopped"},"on-failure":{label:"On Failure",description:"Restart only on failure"}},r0={always:{label:"Always",description:"Always pull the image"},missing:{label:"If Missing",description:"Pull only if image not present"},never:{label:"Never",description:"Never pull, use local only"}},jl={mysql:{label:"MySQL",icon:"🐬",defaultPort:3306},postgresql:{label:"PostgreSQL",icon:"🐘",defaultPort:5432},oracle:{label:"Oracle",icon:"🔶",defaultPort:1521}},PS=x.createContext(null);function N_(s){const e=Ya[s];if(e)return e.icon;const n=P.getState().customAgentClasses.get(s);return n?n.icon:"🤖"}function T_(s){const e=Ya[s];if(e)return e.color;const n=P.getState().customAgentClasses.get(s);return n?n.color:"#888888"}const M_=3;function E_({children:s}){const[e,t]=x.useState([]),n=x.useRef(new Map);x.useEffect(()=>()=>{n.current.forEach(c=>clearTimeout(c))},[]);const i=x.useCallback(c=>{t(h=>h.filter(m=>m.id!==c));const u=n.current.get(c);u&&(clearTimeout(u),n.current.delete(c))},[]),o=x.useCallback(c=>{t(h=>{const m=[...h,c];if(m.length>M_){const f=m.shift();if(f){const g=n.current.get(f.id);g&&(clearTimeout(g),n.current.delete(f.id))}}return m});const u=window.setTimeout(()=>{i(c.id)},8e3);n.current.set(c.id,u),kE({title:`${c.agentName}: ${c.title}`,body:c.message,data:{type:"agent_notification",agentId:c.agentId,notificationId:c.id}})},[i]),r=x.useCallback(c=>{SS(c.agentId),i(c.id)},[i]);return a.jsxs(PS.Provider,{value:{showAgentNotification:o},children:[s,a.jsx("div",{id:"agent-notification-container",children:e.map(c=>{const u=N_(c.agentClass),h=T_(c.agentClass);return a.jsxs("div",{className:"agent-notification",onClick:()=>r(c),style:{"--agent-color":h},children:[a.jsx("div",{className:"agent-notification-avatar",children:a.jsx("span",{className:"agent-notification-icon",children:u})}),a.jsxs("div",{className:"agent-notification-content",children:[a.jsxs("div",{className:"agent-notification-header",children:[a.jsx("span",{className:"agent-notification-name",children:c.agentName}),a.jsx("span",{className:"agent-notification-hint",children:"Click to focus"})]}),a.jsx("div",{className:"agent-notification-title",children:c.title}),a.jsx("div",{className:"agent-notification-message",children:c.message})]}),a.jsx("button",{className:"agent-notification-close",onClick:m=>{m.stopPropagation(),i(c.id)},children:"×"})]},c.id)})})]})}function __(){const s=x.useContext(PS);if(!s)throw new Error("useAgentNotification must be used within AgentNotificationProvider");return s}function D_(s){return typeof s=="string"?s:"#"+s.toString(16).padStart(6,"0")}function Bi(s,e){const t=Zn[s];if(t)return{icon:t.icon,color:D_(t.color),description:t.description};const n=e.find(i=>i.id===s);return n?{icon:n.icon,color:n.color,description:n.description}:{icon:"🤖",color:"#888888"}}function R_(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function Gm(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toString()}function IS(s){const e=Math.floor((Date.now()-s)/1e3);return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m`:e<86400?`${Math.floor(e/3600)}h`:`${Math.floor(e/86400)}d`}function dd(s){const e=Math.floor((Date.now()-s)/1e3);if(e<5)return"just now";if(e<60)return`${e}s ago`;const t=Math.floor(e/60);if(t<60){const c=e%60;return c>0?`${t}m ${c}s ago`:`${t}m ago`}const n=Math.floor(t/60),i=t%60;if(n<24)return i>0?`${n}h ${i}m ago`:`${n}h ago`;const o=Math.floor(n/24),r=n%24;return r>0?`${o}d ${r}h ago`:`${o}d ago`}function Ei(s,e){return s?e?s.replace(/\s*\(?\s*~?\$[\d,.]+\s*\)?/g,"").replace(/\s*cost[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*price[:\s]+~?\$[\d,.]+/gi,"").replace(/\s*\(~?\$[\d,.]+\s*(?:USD|cost|spent)?\)/gi,"").replace(/\s*-\s*~?\$[\d,.]+\s*$/g,"").replace(/[^\S\n]+/g," ").trim():s:""}function L_(s){const e=Math.floor((Date.now()-s)/1e3);if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60);return n<24?`${n}h`:`${Math.floor(n/24)}d`}function Uu(s){const e=Math.floor((Date.now()-s)/1e3);if(e<60)return"just now";const t=Math.floor(e/60);if(t<60)return`${t}m ago`;const n=Math.floor(t/60);return n<24?`${n}h ago`:`${Math.floor(n/24)}d ago`}function OS(s){const e=s.contextStats;if(e){const o=e.usedPercent,r=100-o,c=e.contextWindow-e.totalTokens;return{remainingPercent:r,usedPercent:o,hasData:!0,totalTokens:e.totalTokens,contextWindow:e.contextWindow,freeTokens:c}}const t=s.contextUsed||0,n=s.contextLimit||2e5,i=Math.max(0,n-t);return{remainingPercent:i/n*100,usedPercent:t/n*100,hasData:!1,totalTokens:t,contextWindow:n,freeTokens:i}}function B_(s){return s<20?"#c85858":s<50?"#c89858":"#6a9a78"}function P_(s,e){const t=new Map;for(const n of s){const i=e(n.id),o=(i==null?void 0:i.id)||null;t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function I_(s,e){return[...s].sort((t,n)=>{if(t===null)return 1;if(n===null)return-1;const i=t?e(t):void 0,o=n?e(n):void 0;return((i==null?void 0:i.name)||"").localeCompare((o==null?void 0:o.name)||"")})}function l0({onOpenAreaExplorer:s}){const e=cs(),t=Array.from(e.agents.values()),n=Array.from(e.areas.values()),i=x.useMemo(()=>t.map(u=>u.id).sort().join(","),[t]),o=x.useRef(new Set);x.useEffect(()=>{for(const u of t){if(o.current.has(u.id))continue;P.getAgentSupervisorHistory(u.id).length===0&&!P.isLoadingHistoryForAgent(u.id)&&(o.current.add(u.id),P.requestAgentSupervisorHistory(u.id))}},[i]);const r=P_(t,u=>P.getAreaForAgent(u));for(const u of n)r.has(u.id)||r.set(u.id,[]);const c=I_(Array.from(r.keys()),u=>e.areas.get(u));return t.length===0&&n.length===0?a.jsxs("div",{className:"empty-state",children:[a.jsx("div",{className:"empty-state-icon",children:"⚔️"}),a.jsx("div",{className:"empty-state-title",children:"No Agents Deployed"}),a.jsx("div",{className:"empty-state-desc",children:'Click "+ New Agent" to deploy your first agent'})]}):a.jsxs("div",{className:"agents-list",children:[a.jsx("div",{className:"agents-list-header",children:"Areas & Agents"}),c.map(u=>{const h=r.get(u),m=u?e.areas.get(u):null;return a.jsxs("div",{className:"agents-group",children:[a.jsxs("div",{className:"agents-group-header",style:m?{borderLeftColor:m.color,background:`${m.color}15`}:void 0,children:[m?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"agents-group-dot",style:{background:m.color}}),a.jsx("span",{className:"agents-group-name",children:m.name}),m.directories.length>0&&a.jsx("button",{className:"area-browse-btn",onClick:()=>s==null?void 0:s(m.id),title:"Browse files",children:"📂"})]}):a.jsx("span",{className:"agents-group-name unassigned",children:"Unassigned"}),a.jsx("span",{className:"agents-group-count",children:h.length})]}),h.length>0&&a.jsx("div",{className:"agents-group-items",style:m?{background:`${m.color}08`}:void 0,children:h.map(f=>a.jsx(O_,{agent:f,area:m},f.id))})]},u||"unassigned")}),t.length>0&&a.jsx(z_,{agents:t})]})}const O_=x.memo(function({agent:e,area:t}){const n=cs(),i=ua(),o=Bi(e.class,i),r=n.selectedAgentIds.has(e.id),[,c]=x.useState(0);x.useEffect(()=>{if(e.status==="idle"){const f=setInterval(()=>{c(g=>g+1)},15e3);return()=>clearInterval(f)}},[e.status]);const u=()=>{P.selectAgent(e.id)},h=e.status==="idle"&&e.lastActivity>0,m=e.lastActivity>0?id(e.lastActivity):void 0;return a.jsxs("div",{className:`agent-item ${r?"selected":""}`,onClick:u,children:[a.jsx("div",{className:"agent-item-icon",style:{background:`${o.color}20`},children:o.icon}),a.jsxs("div",{className:"agent-item-info",children:[a.jsx("div",{className:"agent-item-name",children:e.name}),a.jsxs("div",{className:"agent-item-status",children:[e.status,e.currentTool?` • ${e.currentTool}`:"",h&&a.jsxs("span",{className:"agent-item-idle",style:{color:m},title:dd(e.lastActivity),children:[" ","⏱ ",L_(e.lastActivity)]})]})]}),a.jsx("div",{className:`agent-status-dot ${e.status}`})]})}),z_=x.memo(function({agents:e}){const t=cs(),n=ua(),i=t.settings.hideCost,[o,r]=x.useState(()=>Nm(rt.GLOBAL_SUPERVISOR_COLLAPSED)),c=()=>{const m=!o;r(m),Tm(rt.GLOBAL_SUPERVISOR_COLLAPSED,m)},u=x.useMemo(()=>e.map(m=>{const f=P.getAgentSupervisorHistory(m.id),g=f.length>0?f[0]:null;return{agent:m,entry:g,timestamp:(g==null?void 0:g.timestamp)||m.lastActivity||0}}).filter(m=>m.entry!==null).sort((m,f)=>f.timestamp-m.timestamp),[e,t.supervisor.agentHistories]),h=u.length>0?u[0].timestamp:Date.now();return u.length===0?null:a.jsxs("div",{className:"global-supervisor-status",children:[a.jsxs("div",{className:"global-supervisor-header",onClick:c,children:[a.jsx("span",{className:"global-supervisor-toggle",children:o?"▶":"▼"}),a.jsx("span",{className:"global-supervisor-title",children:"Supervisor Status"}),a.jsx("span",{className:"global-supervisor-time",children:Uu(h)})]}),!o&&a.jsx("div",{className:"global-supervisor-list",children:u.map(({agent:m,entry:f})=>{const g=Bi(m.class,n),b=f.analysis;return a.jsxs("div",{className:"global-supervisor-item",onClick:()=>P.selectAgent(m.id),children:[a.jsxs("div",{className:"global-supervisor-item-header",children:[a.jsx("span",{className:"global-supervisor-progress-dot",style:{background:dS[b.progress]||"#888"}}),a.jsx("span",{className:"global-supervisor-agent-icon",children:g.icon}),a.jsx("span",{className:"global-supervisor-agent-name",children:m.name}),a.jsx("span",{className:"global-supervisor-item-time",children:Uu(f.timestamp)})]}),a.jsx("div",{className:"global-supervisor-status-line",children:Ei(b.statusDescription,i)}),a.jsx("div",{className:"global-supervisor-summary-text",children:Ei(b.recentWorkSummary,i)})]},m.id)})})]})}),F_={idle:"idle",working:"walk",waiting:"sit",waiting_permission:"idle",error:"emote-no",offline:"static",orphaned:"idle"},c0={idle:4915102,working:4890367,waiting:16752202,waiting_permission:16763904,error:16730698,offline:8947848,orphaned:16752202};function kr({agentClass:s,modelFile:e,customModelFile:t,customModelUrl:n,modelScale:i=1,modelOffset:o,idleAnimation:r,status:c="idle",width:u=150,height:h=200}){const m=x.useRef(null),f=x.useRef(null),g=x.useRef(null),b=x.useRef(null),v=x.useRef(null),w=x.useRef(null),k=x.useRef(new Map),C=x.useRef(null),j=x.useRef(null),A=x.useRef(0),_=x.useRef(new Kk),[M,E]=x.useState(!1),[F,T]=x.useState(!1),R=x.useRef(!1),D=x.useRef(0),I=x.useRef(new ot),O=x.useRef(!1),X=x.useRef({x:0,y:0}),W=x.useRef({x:0,y:0});x.useEffect(()=>{const B=m.current;if(!B)return;T(!1);const q=new wf;q.background=new Et(1710628),g.current=q;const Y=new xf(45,u/h,.1,100);Y.position.set(0,1.2,1.4),Y.lookAt(0,.4,0),b.current=Y;let z;try{z=new Vk({antialias:!0,alpha:!0})}catch{console.warn("[ModelPreview] WebGL context creation failed — too many active contexts"),T(!0);return}z.setSize(u,h),z.setPixelRatio(Math.min(window.devicePixelRatio,2)),z.setClearColor(1710628,1),B.appendChild(z.domElement),f.current=z;const L=new vf(16777215,1);q.add(L);const Z=new gr(16777215,1.5);Z.position.set(2,3,2),q.add(Z);const V=new gr(4890367,.6);V.position.set(-2,1,-1),q.add(V);const U=new Cm(1,32),H=new Ye({color:2763322,roughness:.8}),Q=new Ce(U,H);Q.rotation.x=-Math.PI/2,Q.position.y=0,q.add(Q);const te=new xo(.35,.42,32),ie=new Ie({color:c0.idle,side:Zs,transparent:!0,opacity:.8}),ne=new Ce(te,ie);ne.rotation.x=-Math.PI/2,ne.position.y=.01,q.add(ne),j.current=ne,E(!0);const ce=re=>{O.current=!0,X.current={x:re.clientX,y:re.clientY},B.style.cursor="grabbing"},de=re=>{if(!O.current||!v.current)return;const he=re.clientX-X.current.x,ue=re.clientY-X.current.y;W.current.y+=he*.01,W.current.x+=ue*.01,W.current.x=Math.max(-Math.PI/4,Math.min(Math.PI/4,W.current.x)),v.current.rotation.y=W.current.y,v.current.rotation.x=W.current.x,X.current={x:re.clientX,y:re.clientY}},oe=()=>{O.current=!1,B.style.cursor="grab"},ae=()=>{O.current=!1,B.style.cursor="grab"};B.addEventListener("mousedown",ce),window.addEventListener("mousemove",de),window.addEventListener("mouseup",oe),B.addEventListener("mouseleave",ae),B.style.cursor="grab";const ye=()=>{A.current=requestAnimationFrame(ye);const re=_.current.getDelta();if(w.current)w.current.update(re);else if(v.current&&!R.current){D.current+=re;const he=D.current,ge=Math.sin(he*1.5)*.02,ke=Math.sin(he*.8)*.01;v.current.position.set(I.current.x+ke,I.current.y+ge,I.current.z)}f.current&&g.current&&b.current&&f.current.render(g.current,b.current)};return ye(),()=>{if(cancelAnimationFrame(A.current),B.removeEventListener("mousedown",ce),window.removeEventListener("mousemove",de),window.removeEventListener("mouseup",oe),B.removeEventListener("mouseleave",ae),v.current&&g.current&&(g.current.remove(v.current),v.current.traverse(re=>{var he,ue;re instanceof Ce&&((he=re.geometry)==null||he.dispose(),Array.isArray(re.material)?re.material.forEach(se=>{se.map&&se.map.dispose(),se.dispose()}):re.material&&(re.material.map&&((ue=re.material.map)==null||ue.dispose()),re.material.dispose()))}),v.current=null),j.current&&g.current&&(g.current.remove(j.current),j.current.geometry.dispose(),j.current.material.dispose(),j.current=null),g.current&&(g.current.traverse(re=>{var he;re instanceof Ce&&((he=re.geometry)==null||he.dispose(),re.material instanceof Mi&&re.material.dispose())}),g.current.clear()),w.current=null,C.current=null,k.current.clear(),f.current){try{const he=f.current.getContext().getExtension("WEBGL_lose_context");he&&he.loseContext()}catch{}f.current.dispose(),B.contains(f.current.domElement)&&B.removeChild(f.current.domElement),f.current=null}g.current=null,b.current=null,E(!1)}},[u,h]),x.useEffect(()=>{if(!M||!g.current)return;const B=new Cf,q=new Af;q.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.7/"),B.setDRACOLoader(q),B.setMeshoptDecoder(Nf);let Y=null;const z=L=>{v.current&&g.current&&(g.current.remove(v.current),v.current=null,w.current=null,C.current=null);const Z=L.scene;Z.scale.setScalar(i);const V=(o==null?void 0:o.x)??0,U=(o==null?void 0:o.y)??0,H=(o==null?void 0:o.z)??0;if(Z.position.set(V,H,U),Z.visible=!0,W.current={x:0,y:0},Z.rotation.set(0,0,0),Z.traverse(Q=>{if(Q instanceof Ce&&(Q.castShadow=!0,Q.receiveShadow=!0,Q.material)){const te=Q.material;te.map&&(te.map.colorSpace=ia)}}),g.current)if(g.current.add(Z),v.current=Z,I.current.copy(Z.position),L.animations.length>0){R.current=!0;const Q=new Ol(Z);w.current=Q,k.current.clear();for(const te of L.animations)k.current.set(te.name.toLowerCase(),te);if(r!==""){const te=r?k.current.get(r.toLowerCase())||L.animations[0]:k.current.get("idle")||L.animations[0];if(te){const ie=Q.clipAction(te);ie.reset().play(),C.current=ie}}}else R.current=!1,w.current=null,k.current.clear()};if(t)Y=URL.createObjectURL(t),console.log("[ModelPreview] Loading custom model from file:",t.name,"blob URL:",Y),B.load(Y,L=>{console.log("[ModelPreview] Successfully loaded custom model file, animations:",L.animations.length),z(L)},void 0,L=>{console.error("[ModelPreview] Failed to load custom model file:",L)});else if(n){const L=Qk(n);console.log("[ModelPreview] Loading custom model from URL:",n),B.load(L,Z=>{console.log("[ModelPreview] Successfully loaded custom model URL, animations:",Z.animations.length),z(Z)},void 0,Z=>{console.error("[ModelPreview] Failed to load custom model URL:",n,Z)})}else{const L=e||(s?mr[s]:void 0)||"character-male-a.glb";B.load(`/assets/characters/${L}`,z,void 0,Z=>{console.error("[ModelPreview] Failed to load model:",L,Z)})}return()=>{Y&&URL.revokeObjectURL(Y),q.dispose()}},[s,e,t,n,i,o,M]);const G=B=>{if(!w.current)return;const q=F_[B],Y=k.current.get(q);if(!Y){const L=k.current.get("idle");if(L){const Z=w.current.clipAction(L);Z.reset().play(),C.current=Z}return}const z=w.current.clipAction(Y);B==="working"?z.timeScale=1.5:B==="error"&&(z.setLoop(Uk,1),z.clampWhenFinished=!0),C.current&&C.current!==z?(C.current.fadeOut(.3),z.reset().fadeIn(.3).play()):z.reset().play(),C.current=z};return x.useEffect(()=>{if(M){if(j.current){const B=j.current.material;B.color.setHex(c0[c]),c==="working"?B.opacity=.6+Math.sin(Date.now()*.005)*.4:B.opacity=.8}G(c)}},[c,M]),x.useEffect(()=>{if(!M||!w.current||c!=="idle")return;if(r===""){C.current&&(C.current.stop(),C.current=null);return}const B=r?r.toLowerCase():"idle",q=k.current.get(B);if(q){const Y=w.current.clipAction(q);C.current&&C.current!==Y?(C.current.fadeOut(.3),Y.reset().fadeIn(.3).play()):Y.reset().play(),C.current=Y}else C.current&&(C.current.stop(),C.current=null)},[r,M,c]),F?a.jsx("div",{className:"model-preview",style:{width:u,height:h,borderRadius:8,overflow:"hidden",background:"#1a1a24",display:"flex",alignItems:"center",justifyContent:"center",color:"#666",fontSize:12,textAlign:"center",padding:8},children:"3D preview unavailable"}):a.jsx("div",{ref:m,className:"model-preview",style:{width:u,height:h,borderRadius:8,overflow:"hidden",background:"#1a1a24"}})}function Pi({value:s,onChange:e,onSubmit:t,placeholder:n="/path/to/folder",className:i="",directoriesOnly:o=!0,autoFocus:r=!1,hasError:c=!1,disabled:u=!1}){const[h,m]=x.useState([]),[f,g]=x.useState(-1),[b,v]=x.useState(!1),[w,k]=x.useState(!1),C=x.useRef(null),j=x.useRef(null),A=x.useRef(null),_=x.useCallback(async I=>{if(!I){m([]);return}k(!0);try{const O=new URLSearchParams({path:I,dirs:o?"true":"false",limit:"15"}),X=await dt(Qe(`/api/files/autocomplete?${O}`));if(X.ok){const W=await X.json();m(W.suggestions||[]),g(-1)}}catch(O){console.error("Failed to fetch path suggestions:",O)}finally{k(!1)}},[o]);x.useEffect(()=>(A.current&&clearTimeout(A.current),s&&b?A.current=setTimeout(()=>{_(s)},150):m([]),()=>{A.current&&clearTimeout(A.current)}),[s,b,_]);const M=I=>{e(I.target.value),v(!0)},E=x.useCallback(I=>{var X;const O=I.isDirectory?I.path+"/":I.path;e(O),v(I.isDirectory),g(-1),(X=C.current)==null||X.focus(),I.isDirectory&&_(O)},[e,_]),F=I=>{if(!b||h.length===0){I.key==="Enter"&&t&&(I.preventDefault(),t()),I.key==="Escape"&&v(!1);return}switch(I.key){case"ArrowDown":I.preventDefault(),g(O=>O<h.length-1?O+1:O);break;case"ArrowUp":I.preventDefault(),g(O=>O>0?O-1:-1);break;case"Tab":if(I.preventDefault(),h.length>0){const O=f>=0?f:0;E(h[O])}break;case"Enter":I.preventDefault(),f>=0&&h[f]?E(h[f]):t&&(v(!1),t());break;case"Escape":I.preventDefault(),v(!1),g(-1);break}},T=()=>{v(!0),s&&_(s)},R=()=>{setTimeout(()=>{v(!1),g(-1)},200)};x.useEffect(()=>{if(f>=0&&j.current){const O=j.current.querySelectorAll(".folder-input-suggestion")[f];O&&O.scrollIntoView({block:"nearest"})}},[f]);const D=["folder-input",i,c?"error":""].filter(Boolean).join(" ");return a.jsxs("div",{className:"folder-input-container",children:[a.jsx("input",{ref:C,type:"text",className:D,value:s,onChange:M,onKeyDown:F,onFocus:T,onBlur:R,placeholder:n,autoFocus:r,disabled:u,autoComplete:"off",spellCheck:!1}),b&&(h.length>0||w)&&a.jsx("div",{ref:j,className:"folder-input-suggestions",children:w&&h.length===0?a.jsx("div",{className:"folder-input-loading",children:"Loading..."}):h.map((I,O)=>a.jsxs("div",{className:`folder-input-suggestion ${O===f?"selected":""}`,onClick:()=>E(I),onMouseEnter:()=>g(O),children:[a.jsx("span",{className:"folder-input-suggestion-icon",children:I.isDirectory?"📁":"📄"}),a.jsx("span",{className:"folder-input-suggestion-name",children:I.name}),I.isDirectory&&a.jsx("span",{className:"folder-input-suggestion-hint",children:"/"})]},I.path))})]})}function zS({agent:s,isOpen:e,onClose:t}){const n=ud(),i=ua(),[o,r]=x.useState(s.name),[c,u]=x.useState(s.class),[h,m]=x.useState(s.permissionMode),[f,g]=x.useState(s.provider||"claude"),[b,v]=x.useState(s.codexConfig||{fullAuto:!0,sandbox:"workspace-write",approvalMode:"on-request",search:!1}),[w,k]=x.useState(s.model||"sonnet"),[C,j]=x.useState(s.codexModel||"gpt-5.3-codex"),[A,_]=x.useState(s.useChrome||!1),[M,E]=x.useState(s.cwd),[F,T]=x.useState(new Set),[R,D]=x.useState("");x.useMemo(()=>n.filter(H=>H.enabled&&(H.assignedAgentIds.includes(s.id)||H.assignedAgentClasses.includes(s.class))),[n,s.id,s.class]),x.useEffect(()=>{const H=n.filter(Q=>Q.assignedAgentIds.includes(s.id)).map(Q=>Q.id);T(new Set(H))},[n,s.id]),x.useEffect(()=>{if(e){r(s.name),u(s.class),m(s.permissionMode),g(s.provider||"claude"),v(s.codexConfig||{fullAuto:!0,sandbox:"workspace-write",approvalMode:"on-request",search:!1}),k(s.model||"sonnet"),j(s.codexModel||"gpt-5.3-codex"),_(s.useChrome||!1),E(s.cwd);const H=n.filter(Q=>Q.assignedAgentIds.includes(s.id)).map(Q=>Q.id);T(new Set(H))}},[e,s,n]);const I=x.useMemo(()=>n.filter(H=>H.enabled),[n]),O=x.useMemo(()=>{if(!R.trim())return I;const H=R.toLowerCase();return I.filter(Q=>Q.name.toLowerCase().includes(H)||Q.description.toLowerCase().includes(H)||Q.slug.toLowerCase().includes(H))},[I,R]),X=x.useMemo(()=>I.filter(H=>H.assignedAgentClasses.includes(c)),[I,c]),W=x.useCallback(H=>{T(Q=>{const te=new Set(Q);return te.has(H)?te.delete(H):te.add(H),te})},[]),G=x.useMemo(()=>{const H=i.find(Q=>Q.id===c);if(H!=null&&H.model)return H.model},[i,c]),B=x.useMemo(()=>{const H=i.find(Q=>Q.id===c);if(H!=null&&H.customModelPath)return Qe(`/api/custom-models/${H.id}`)},[i,c]),q=x.useMemo(()=>{const H=i.find(Q=>Q.id===c);return H==null?void 0:H.modelScale},[i,c]),Y=x.useMemo(()=>i.find(H=>H.id===c),[i,c]),z=x.useMemo(()=>i.find(Q=>Q.id===c)?"scout":c,[i,c]),L=x.useMemo(()=>{const H=o.trim();if(H&&H!==s.name||c!==s.class||h!==s.permissionMode||f!==(s.provider||"claude")||f==="claude"&&w!==(s.model||"sonnet")||f==="codex"&&C!==(s.codexModel||"gpt-5.3-codex")||f==="codex"&&JSON.stringify(b||{})!==JSON.stringify(s.codexConfig||{})||A!==(s.useChrome||!1)||M!==s.cwd)return!0;const Q=n.filter(ie=>ie.assignedAgentIds.includes(s.id)).map(ie=>ie.id).sort().join(","),te=Array.from(F).sort().join(",");return Q!==te},[o,c,h,f,w,C,b,A,M,F,s,n]),Z=()=>{const H=o.trim(),Q={};H&&H!==s.name&&P.renameAgent(s.id,H),c!==s.class&&(Q.class=c),h!==s.permissionMode&&(Q.permissionMode=h),f!==(s.provider||"claude")&&(Q.provider=f),f==="codex"&&JSON.stringify(b||{})!==JSON.stringify(s.codexConfig||{})&&(Q.codexConfig=b),f==="codex"&&C!==(s.codexModel||"gpt-5.3-codex")&&(Q.codexModel=C),f==="claude"&&w!==(s.model||"sonnet")&&(Q.model=w),A!==(s.useChrome||!1)&&(Q.useChrome=A),M!==s.cwd&&(Q.cwd=M);const te=n.filter(ne=>ne.assignedAgentIds.includes(s.id)).map(ne=>ne.id).sort().join(","),ie=Array.from(F).sort().join(",");te!==ie&&(Q.skillIds=Array.from(F)),Object.keys(Q).length>0&&P.updateAgentProperties(s.id,Q),t()},{handleMouseDown:V,handleClick:U}=Qs(t);return e?a.jsx("div",{className:"modal-overlay visible",onMouseDown:V,onClick:U,children:a.jsxs("div",{className:"modal agent-edit-modal",children:[a.jsxs("div",{className:"modal-header",children:["Edit Agent: ",o.trim()||s.name]}),a.jsxs("div",{className:"modal-body spawn-modal-body",children:[a.jsxs("div",{className:"spawn-top-section",children:[a.jsx("div",{className:"spawn-preview-compact",children:a.jsx(kr,{agentClass:z,modelFile:G,customModelUrl:B,modelScale:q,width:100,height:120})}),a.jsxs("div",{className:"spawn-class-section",children:[a.jsx("div",{className:"spawn-class-label",children:"Agent Class"}),a.jsxs("div",{className:"class-selector-inline",children:[i.map(H=>a.jsxs("button",{className:`class-chip ${c===H.id?"selected":""}`,onClick:()=>u(H.id),title:H.description,children:[a.jsx("span",{className:"class-chip-icon",children:H.icon}),a.jsx("span",{className:"class-chip-name",children:H.name})]},H.id)),Object.entries(Ya).filter(([H])=>H!=="boss").map(([H,Q])=>a.jsxs("button",{className:`class-chip ${c===H?"selected":""}`,onClick:()=>u(H),title:Q.description,children:[a.jsx("span",{className:"class-chip-icon",children:Q.icon}),a.jsx("span",{className:"class-chip-name",children:H.charAt(0).toUpperCase()+H.slice(1)})]},H))]})]})]}),(Y==null?void 0:Y.instructions)&&a.jsxs("div",{className:"custom-class-notice",children:[a.jsxs("div",{className:"custom-class-notice-header",children:[a.jsx("span",{children:"📋"}),a.jsx("span",{children:"This class has custom instructions"})]}),a.jsxs("div",{className:"custom-class-notice-info",children:[Y.instructions.length," characters of CLAUDE.md instructions will be injected as system prompt"]})]}),a.jsxs("div",{className:"spawn-form-section",children:[a.jsx("div",{className:"spawn-form-row",children:a.jsxs("div",{className:"spawn-field",children:[a.jsx("label",{className:"spawn-label",children:"Name"}),a.jsx("input",{type:"text",className:"spawn-input",value:o,onChange:H=>r(H.target.value),placeholder:"Agent name"})]})}),a.jsxs("div",{className:"spawn-form-row",children:[a.jsxs("div",{className:"spawn-field",children:[a.jsx("label",{className:"spawn-label",children:"Runtime"}),a.jsxs("div",{className:"spawn-select-row",children:[a.jsxs("button",{className:`spawn-select-btn ${f==="claude"?"selected":""}`,onClick:()=>g("claude"),children:[a.jsx("span",{children:"🧠"}),a.jsx("span",{children:"Claude"})]}),a.jsxs("button",{className:`spawn-select-btn ${f==="codex"?"selected":""}`,onClick:()=>g("codex"),children:[a.jsx("span",{children:"⚙️"}),a.jsx("span",{children:"Codex"})]})]})]}),a.jsxs("div",{className:"spawn-field",children:[a.jsx("label",{className:"spawn-label",children:"Permissions"}),a.jsx("div",{className:"spawn-select-row",children:Object.keys(ra).map(H=>a.jsxs("button",{className:`spawn-select-btn ${h===H?"selected":""}`,onClick:()=>m(H),title:ra[H].description,children:[a.jsx("span",{children:H==="bypass"?"⚡":"🔐"}),a.jsx("span",{children:ra[H].label})]},H))})]})]}),a.jsx("div",{className:"spawn-form-row",children:a.jsxs("div",{className:"spawn-field",children:[a.jsx("label",{className:"spawn-label",children:"Model"}),f==="claude"?a.jsx("div",{className:"spawn-select-row",children:Object.keys(Xn).map(H=>a.jsxs("button",{className:`spawn-select-btn ${w===H?"selected":""}`,onClick:()=>k(H),title:Xn[H].description,children:[a.jsx("span",{children:Xn[H].icon}),a.jsx("span",{children:Xn[H].label})]},H))}):f==="codex"?a.jsx("div",{className:"spawn-select-row spawn-select-row--codex-models",children:Object.keys(Vn).map(H=>a.jsxs("button",{className:`spawn-select-btn ${C===H?"selected":""}`,onClick:()=>j(H),title:Vn[H].description,children:[a.jsx("span",{children:Vn[H].icon}),a.jsx("span",{children:Vn[H].label})]},H))}):a.jsx("div",{className:"spawn-inline-hint",children:"Choose the Codex model for this agent."})]})}),f==="codex"&&a.jsx("div",{className:"spawn-form-row",children:a.jsxs("div",{className:"spawn-field",children:[a.jsx("label",{className:"spawn-label",children:"Codex Config"}),a.jsxs("div",{className:"spawn-options-row",style:{display:"flex",flexDirection:"column",gap:8},children:[a.jsxs("label",{className:"spawn-checkbox",children:[a.jsx("input",{type:"checkbox",checked:b.fullAuto!==!1,onChange:H=>v(Q=>({...Q,fullAuto:H.target.checked}))}),a.jsx("span",{children:"Use `--full-auto`"})]}),a.jsxs("label",{className:"spawn-checkbox",children:[a.jsx("input",{type:"checkbox",checked:!!b.search,onChange:H=>v(Q=>({...Q,search:H.target.checked}))}),a.jsx("span",{children:"Enable live web search (`--search`)"})]}),b.fullAuto===!1&&a.jsxs(a.Fragment,{children:[a.jsxs("select",{className:"spawn-input",value:b.sandbox||"workspace-write",onChange:H=>v(Q=>({...Q,sandbox:H.target.value})),children:[a.jsx("option",{value:"read-only",children:"Sandbox: read-only"}),a.jsx("option",{value:"workspace-write",children:"Sandbox: workspace-write"}),a.jsx("option",{value:"danger-full-access",children:"Sandbox: danger-full-access"})]}),a.jsxs("select",{className:"spawn-input",value:b.approvalMode||"on-request",onChange:H=>v(Q=>({...Q,approvalMode:H.target.value})),children:[a.jsx("option",{value:"untrusted",children:"Approvals: untrusted"}),a.jsx("option",{value:"on-failure",children:"Approvals: on-failure"}),a.jsx("option",{value:"on-request",children:"Approvals: on-request"}),a.jsx("option",{value:"never",children:"Approvals: never"})]})]}),a.jsx("input",{type:"text",className:"spawn-input",placeholder:"Profile (optional)",value:b.profile||"",onChange:H=>v(Q=>({...Q,profile:H.target.value||void 0}))})]})]})}),f==="claude"&&w!==(s.model||"sonnet")&&a.jsx("div",{className:"model-change-notice",children:"Context preserved - will resume with new model"}),a.jsx("div",{className:"spawn-form-row spawn-options-row",children:a.jsxs("label",{className:"spawn-checkbox",children:[a.jsx("input",{type:"checkbox",checked:A,onChange:H=>_(H.target.checked),disabled:f!=="claude"}),a.jsx("span",{children:"🌐 Chrome Browser"})]})}),a.jsx("div",{className:"spawn-form-row",children:a.jsxs("div",{className:"spawn-field",children:[a.jsx("label",{className:"spawn-label",children:"Working Directory"}),a.jsx(Pi,{value:M,onChange:E,placeholder:"/path/to/directory",className:"spawn-input",directoriesOnly:!0})]})}),M!==s.cwd&&a.jsx("div",{className:"model-change-notice warning",children:"New session will start - context cannot be preserved across directory changes"}),a.jsxs("div",{className:"spawn-skills-section",children:[a.jsxs("label",{className:"spawn-label",children:["Skills ",a.jsx("span",{className:"spawn-label-hint",children:"(click to toggle)"})]}),I.length>6&&a.jsx("input",{type:"text",className:"spawn-input skill-search-input",placeholder:"Filter skills...",value:R,onChange:H=>D(H.target.value)}),a.jsx("div",{className:"skills-chips-compact",children:I.length===0?a.jsx("div",{className:"skills-empty",children:"No enabled skills available"}):O.length===0?a.jsxs("div",{className:"skills-empty",children:['No skills match "',R,'"']}):O.map(H=>{const Q=X.includes(H),ie=F.has(H.id)||Q;return a.jsxs("button",{className:`skill-chip ${ie?"selected":""} ${Q?"class-based":""}`,onClick:()=>!Q&&W(H.id),title:Q?"Assigned via class":H.name,children:[ie&&a.jsx("span",{className:"skill-check",children:"✓"}),a.jsx("span",{className:"skill-chip-name",children:H.name}),H.builtin&&a.jsx("span",{className:"skill-chip-badge builtin",children:"TC"}),Q&&a.jsx("span",{className:"skill-chip-badge",children:"class"})]},H.id)})})]})]})]}),a.jsxs("div",{className:"modal-footer",children:[a.jsx("button",{className:"btn btn-secondary",onClick:t,children:"Cancel"}),a.jsx("button",{className:"btn btn-primary",onClick:Z,disabled:!L,children:"Save Changes"})]})]})}):null}var hd=Dk();function jo({children:s}){return typeof document>"u"?null:hd.createPortal(s,document.body)}function Cl(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}function u0(s){return`${s.toFixed(1)}%`}function $_(s){return s>=80?"#ff4a4a":s>=60?"#ff9e4a":s>=40?"#ffd700":"#4aff9e"}const H_={systemPrompt:"#4a9eff",systemTools:"#9e4aff",messages:"#4aff9e",freeSpace:"rgba(255,255,255,0.1)",autocompactBuffer:"#ff9e4a"},U_={systemPrompt:"System Prompt",systemTools:"System Tools",messages:"Messages",freeSpace:"Free Space",autocompactBuffer:"Autocompact Buffer"},G_={systemPrompt:"Base instructions and persona for the agent",systemTools:"Tool definitions and capabilities available",messages:"Conversation history and user messages",freeSpace:"Available space for more conversation",autocompactBuffer:"Reserved for automatic context compaction"};function FS({agent:s,isOpen:e,onClose:t,onRefresh:n}){const i=s.contextStats,[o,r]=x.useState(!1),c=()=>{n&&!o&&(r(!0),n(),setTimeout(()=>r(!1),3e3))},u=["systemPrompt","systemTools","messages","autocompactBuffer","freeSpace"],h=x.useMemo(()=>i?u.map(b=>({key:b,...i.categories[b],label:U_[b],description:G_[b],color:H_[b]})):[],[i]),m=x.useMemo(()=>h.filter(b=>b.key!=="freeSpace"),[h]),{handleMouseDown:f,handleClick:g}=Qs(t);return e?a.jsx(jo,{children:a.jsx("div",{className:"modal-overlay visible",onMouseDown:f,onClick:g,children:a.jsxs("div",{className:"modal context-view-modal",style:{maxWidth:"520px"},children:[a.jsxs("div",{className:"modal-header",style:{display:"flex",alignItems:"center",gap:"12px"},children:[a.jsxs("span",{style:{flex:1},children:["Context Window: ",s.name]}),n&&a.jsxs("button",{className:"btn btn-primary",onClick:c,disabled:o||s.status!=="idle",style:{padding:"6px 12px",fontSize:"12px",display:"flex",alignItems:"center",gap:"6px"},title:s.status!=="idle"?"Agent must be idle to refresh":"Fetch context stats via /context command",children:[a.jsx("span",{style:{display:"inline-block",animation:o?"spin 1s linear infinite":"none"},children:o?"⟳":"↻"}),o?"Loading...":"Refresh"]})]}),a.jsx("div",{className:"modal-body",style:{padding:"16px"},children:i?a.jsxs(a.Fragment,{children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px",padding:"8px 12px",background:"var(--bg-secondary)",borderRadius:"6px"},children:[a.jsxs("div",{children:[a.jsx("div",{style:{fontSize:"11px",color:"var(--text-secondary)"},children:"Model"}),a.jsx("div",{style:{fontSize:"13px",fontWeight:500},children:i.model})]}),a.jsxs("div",{style:{textAlign:"right"},children:[a.jsx("div",{style:{fontSize:"11px",color:"var(--text-secondary)"},children:"Context Window"}),a.jsx("div",{style:{fontSize:"13px",fontWeight:500},children:Cl(i.contextWindow)})]})]}),a.jsxs("div",{style:{marginBottom:"24px"},children:[a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"8px",fontSize:"13px"},children:[a.jsx("span",{children:"Context Usage"}),a.jsxs("span",{style:{color:$_(i.usedPercent)},children:[Cl(i.totalTokens)," / ",Cl(i.contextWindow)," (",i.usedPercent,"%)"]})]}),a.jsx("div",{style:{height:"28px",background:"var(--bg-tertiary)",borderRadius:"6px",overflow:"hidden",display:"flex"},children:m.map(b=>b.percent>0&&a.jsx("div",{style:{width:`${b.percent}%`,background:b.color,height:"100%",minWidth:b.percent>.5?"2px":"0",transition:"width 0.3s ease"},title:`${b.label}: ${Cl(b.tokens)} (${u0(b.percent)})`},b.key))})]}),a.jsxs("div",{style:{marginBottom:"16px"},children:[a.jsx("div",{style:{fontSize:"12px",color:"var(--text-secondary)",marginBottom:"8px",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Token Breakdown"}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:h.map(b=>a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px",padding:"10px 12px",background:b.key==="freeSpace"?"transparent":"var(--bg-secondary)",borderRadius:"6px",borderLeft:b.key==="freeSpace"?"3px dashed rgba(255,255,255,0.2)":`3px solid ${b.color}`,opacity:b.key==="freeSpace"?.7:1},children:[a.jsx("div",{style:{width:"12px",height:"12px",borderRadius:"3px",background:b.color,flexShrink:0,border:b.key==="freeSpace"?"1px dashed rgba(255,255,255,0.3)":"none"}}),a.jsxs("div",{style:{flex:1},children:[a.jsx("div",{style:{fontSize:"13px",fontWeight:500},children:b.label}),a.jsx("div",{style:{fontSize:"11px",color:"var(--text-secondary)"},children:b.description})]}),a.jsxs("div",{style:{textAlign:"right"},children:[a.jsx("div",{style:{fontSize:"13px",fontWeight:500},children:Cl(b.tokens)}),a.jsx("div",{style:{fontSize:"11px",color:"var(--text-secondary)"},children:u0(b.percent)})]})]},b.key))})]}),a.jsxs("div",{style:{fontSize:"11px",color:"var(--text-muted)",textAlign:"center"},children:["Last updated: ",new Date(i.lastUpdated).toLocaleTimeString()]})]}):a.jsxs("div",{style:{textAlign:"center",color:"var(--text-secondary)",padding:"32px"},children:[a.jsx("div",{style:{fontSize:"48px",marginBottom:"16px",opacity:.5},children:"📊"}),a.jsx("div",{style:{fontSize:"14px",marginBottom:"8px"},children:"No context data available yet"}),a.jsx("div",{style:{fontSize:"12px",marginBottom:"20px",opacity:.7},children:"Click the Refresh button above to fetch detailed stats"}),n&&a.jsxs("button",{className:"btn btn-primary",onClick:c,disabled:o||s.status!=="idle",style:{padding:"10px 24px",fontSize:"14px",display:"inline-flex",alignItems:"center",gap:"8px"},children:[a.jsx("span",{style:{display:"inline-block",animation:o?"spin 1s linear infinite":"none"},children:o?"⟳":"↻"}),o?"Fetching Stats...":"Fetch Context Stats"]}),s.status!=="idle"&&a.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"12px"},children:"Agent must be idle to fetch stats"})]})}),a.jsx("div",{className:"modal-footer",style:{display:"flex",justifyContent:"flex-end",padding:"12px 16px",borderTop:"1px solid var(--border-color)"},children:a.jsx("button",{className:"btn btn-secondary",onClick:t,children:"Close"})})]})})}):null}const W_=x.memo(function({tokensUsed:e,createdAt:t}){return a.jsxs("div",{className:"unit-stats",children:[a.jsxs("div",{className:"unit-stat",children:[a.jsx("div",{className:"unit-stat-label",children:"Tokens"}),a.jsx("div",{className:"unit-stat-value",children:Gm(e)})]}),a.jsxs("div",{className:"unit-stat",children:[a.jsx("div",{className:"unit-stat-label",children:"Uptime"}),a.jsx("div",{className:"unit-stat-value",children:IS(t)})]})]})}),$S=x.memo(function({contextInfo:e,onClick:t}){const{remainingPercent:n,hasData:i}=e;return a.jsxs("div",{className:"unit-context unit-context-clickable",onClick:t,title:i?"Click for detailed context breakdown":"Click to fetch context stats",style:{cursor:"pointer"},children:[a.jsxs("div",{className:"unit-stat-label",style:{display:"flex",alignItems:"center",gap:"4px"},children:[a.jsx("span",{children:"Remaining Context"}),i?a.jsx("span",{style:{fontSize:"10px",opacity:.6},children:"📊"}):a.jsx("span",{style:{fontSize:"9px",color:"#ff9e4a",opacity:.8},title:"Click to fetch accurate stats",children:"⚠️"})]}),i?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"unit-context-bar",children:a.jsx("div",{className:"unit-context-fill",style:{width:`${n}%`,background:B_(n)}})}),a.jsxs("span",{className:"unit-context-value",children:[Math.round(n),"%"]})]}):a.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",fontStyle:"italic"},children:"Not retrieved yet"})]})}),q_=x.memo(function({lastActivity:e}){return a.jsxs("div",{className:"unit-idle-timer",title:"Time since last activity",style:{color:id(e)},children:["⏱ ",dd(e)]})}),K_=x.memo(function({toolName:e}){return a.jsxs("div",{className:"unit-current-tool",children:[a.jsx("span",{className:"unit-stat-label",children:"Using:"}),a.jsx("span",{className:"unit-tool-name",children:e})]})}),V_=x.memo(function({task:e}){return a.jsxs("div",{className:"unit-task",children:[a.jsx("div",{className:"unit-stat-label",children:"Task"}),a.jsx("div",{className:"unit-task-text",children:e})]})}),X_=x.memo(function({cwd:e}){return a.jsxs("div",{className:"unit-cwd",children:[a.jsx("div",{className:"unit-stat-label",children:"CWD"}),a.jsx("div",{className:"unit-cwd-path",title:e,children:e})]})}),Y_=x.memo(function({text:e,maxLength:t=150}){return a.jsxs("div",{className:"unit-last-prompt",children:[a.jsx("div",{className:"unit-stat-label",children:"Last Prompt"}),a.jsx("div",{className:"unit-last-prompt-text",children:e.length>t?e.slice(0,t)+"...":e})]})}),Z_=x.memo(function({text:e,maxLength:t=200}){return a.jsxs("div",{className:"unit-last-message",children:[a.jsx("div",{className:"unit-stat-label",children:"Last Response"}),a.jsx("div",{className:"unit-last-message-text",children:e.length>t?e.slice(0,t)+"...":e})]})});function Q_({agent:s,onFocusAgent:e,onKillAgent:t,onCallSubordinates:n,onOpenAreaExplorer:i}){var ne,ce;const o=cs(),r=ua(),{showToast:c}=zf(),u=o.agents.get(s.id)||s,h=Bi(u.class,r),m=r.find(de=>de.id===u.class),f=m==null?void 0:m.model,g=m!=null&&m.customModelPath?Qe(`/api/custom-models/${m.id}`):void 0,b=m==null?void 0:m.modelScale,[v,w]=x.useState(!1),[k,C]=x.useState(u.name),j=x.useRef(null),[,A]=x.useState(0),[_,M]=x.useState(!0),[E,F]=x.useState(!1),[T,R]=x.useState([]),[D,I]=x.useState(null),[O,X]=x.useState(!1),[W,G]=x.useState(!1),B=P.getAgentSupervisorHistory(u.id),q=P.isLoadingHistoryForAgent(u.id);x.useEffect(()=>{!P.hasHistoryBeenFetched(u.id)&&!q&&P.requestAgentSupervisorHistory(u.id)},[u.id,q]),x.useEffect(()=>{C(u.name)},[u.name]),x.useEffect(()=>{v&&j.current&&(j.current.focus(),j.current.select())},[v]),x.useEffect(()=>{if(u.status==="idle"){const de=setInterval(()=>{A(oe=>oe+1)},15e3);return()=>clearInterval(de)}},[u.status]),x.useEffect(()=>{u.permissionMode==="interactive"&&dt(Qe("/api/remembered-patterns")).then(de=>de.json()).then(R).catch(de=>console.error("Failed to fetch remembered patterns:",de))},[u.permissionMode]);const Y=x.useMemo(()=>OS(u),[u.contextStats,u.contextUsed,u.contextLimit]),z=P.getAreaForAgent(u.id),L=o.agentOutputs.get(u.id)||[],Z=L.length>0?L[L.length-1]:null,V=o.lastPrompts.get(u.id),U=async(de,oe)=>{try{(await dt(Qe(`/api/remembered-patterns/${de}/${encodeURIComponent(oe)}`),{method:"DELETE"})).ok&&R(ye=>ye.filter(re=>!(re.tool===de&&re.pattern===oe)))}catch(ae){console.error("Failed to remove pattern:",ae)}},H=async()=>{if(confirm("Clear all remembered permission patterns?"))try{(await dt(Qe("/api/remembered-patterns"),{method:"DELETE"})).ok&&R([])}catch(de){console.error("Failed to clear patterns:",de)}},Q=()=>{confirm("Are you sure you want to terminate this agent?")&&t(u.id)},te=()=>{const de=k.trim();de&&de!==u.name?P.renameAgent(u.id,de):C(u.name),w(!1)},ie=de=>{de.key==="Enter"?te():de.key==="Escape"&&(C(u.name),w(!1))};return a.jsxs("div",{className:"unit-panel",children:[a.jsx("div",{className:"unit-model-preview",children:a.jsx(kr,{agentClass:u.class,modelFile:f,customModelUrl:g,modelScale:b,status:u.status,width:80,height:80})}),a.jsxs("div",{className:"unit-panel-header",children:[a.jsx("div",{className:"unit-class-icon",style:{background:`${h.color}20`},children:h.icon}),a.jsxs("div",{className:"unit-header-info",children:[v?a.jsx("input",{ref:j,type:"text",className:"unit-name-input",value:k,onChange:de=>C(de.target.value),onBlur:te,onKeyDown:ie}):a.jsx("div",{className:"unit-name unit-name-editable",onClick:()=>w(!0),title:"Click to rename",children:u.name}),a.jsxs("div",{className:"unit-status",children:[a.jsx("span",{style:{color:Iu[u.status]||Iu.default},children:u.status}),a.jsxs("span",{children:[" • ",u.class," • ",u.provider]})]}),u.status==="idle"&&u.lastActivity>0&&a.jsx(q_,{lastActivity:u.lastActivity})]}),a.jsxs("div",{className:"unit-header-actions",children:[a.jsx("button",{className:"unit-action-icon",onClick:()=>e(u.id),title:"Focus on agent",children:"🎯"}),a.jsx("button",{className:"unit-action-icon",onClick:()=>X(!0),title:"Edit agent properties",children:"✏️"}),(u.isBoss||u.class==="boss")&&u.subordinateIds&&u.subordinateIds.length>0&&a.jsx("button",{className:"unit-action-icon",onClick:()=>n==null?void 0:n(u.id),title:"Call subordinates",children:"📢"}),a.jsx("button",{className:"unit-action-icon",onClick:()=>I("collapse"),title:"Collapse context",disabled:u.status!=="idle",children:"📦"}),a.jsx("button",{className:"unit-action-icon warning",onClick:()=>I("clear"),title:"Clear context",children:"🗑️"}),a.jsx("button",{className:"unit-action-icon danger",onClick:Q,title:"Kill agent",children:"☠️"})]})]}),z&&a.jsxs("div",{className:"unit-area",children:[a.jsx("span",{className:"unit-area-dot",style:{background:z.color}}),a.jsx("span",{className:"unit-area-name",children:z.name})]}),V&&a.jsx(Y_,{text:V.text}),Z&&a.jsx(Z_,{text:Z.text}),a.jsx(W_,{tokensUsed:u.tokensUsed,createdAt:u.createdAt}),a.jsx($S,{contextInfo:Y,onClick:()=>G(!0)}),u.currentTool&&a.jsx(K_,{toolName:u.currentTool}),u.currentTask&&a.jsx(V_,{task:u.currentTask}),a.jsx(X_,{cwd:u.cwd}),a.jsxs("div",{className:"unit-permission-mode",children:[a.jsx("div",{className:"unit-stat-label",children:"Permissions"}),a.jsxs("div",{className:"unit-permission-mode-value",title:(ne=ra[u.permissionMode])==null?void 0:ne.description,children:[a.jsx("span",{className:"unit-permission-mode-icon",children:u.permissionMode==="bypass"?"⚡":"🔐"}),a.jsx("span",{className:"unit-permission-mode-label",children:((ce=ra[u.permissionMode])==null?void 0:ce.label)||u.permissionMode})]})]}),u.permissionMode==="interactive"&&a.jsx(J_,{patterns:T,showPatterns:E,onToggle:()=>F(!E),onRemovePattern:U,onClearAll:H}),u.sessionId?a.jsxs("div",{className:"unit-resume-cmd",children:[a.jsx("div",{className:"unit-stat-label",children:"Resume Session"}),a.jsxs("div",{className:"unit-resume-cmd-text",title:"Click to copy",onClick:async()=>{try{await navigator.clipboard.writeText(`codex resume ${u.sessionId}`),c("success","Copied!","Resume command copied to clipboard",2e3)}catch{c("error","Error","Failed to copy to clipboard",3e3)}},children:["codex resume ",u.sessionId]})]}):a.jsxs("div",{className:"unit-resume-cmd",children:[a.jsx("div",{className:"unit-stat-label",children:"Session"}),a.jsx("div",{className:"unit-new-session-indicator",children:"New agent, new session"})]}),a.jsxs("div",{className:"unit-supervisor-history",children:[a.jsxs("div",{className:"unit-supervisor-history-header",onClick:()=>M(!_),children:[a.jsx("div",{className:"unit-stat-label",children:"Supervisor History"}),a.jsxs("span",{className:"unit-supervisor-history-toggle",children:[B.length>0&&a.jsx("span",{className:"unit-supervisor-history-count",children:B.length}),_?"▼":"▶"]})]}),_&&a.jsx("div",{className:"unit-supervisor-history-list",children:q?a.jsx("div",{className:"unit-supervisor-history-loading",children:"Loading..."}):B.length===0?a.jsx("div",{className:"unit-supervisor-history-empty",children:"No supervisor reports yet"}):B.slice(0,10).map((de,oe)=>a.jsx(tD,{entry:de,defaultExpanded:oe===0},de.id))})]}),(u.isBoss||u.class==="boss")&&a.jsx(sD,{agent:u}),u.bossId&&a.jsx(aD,{agentId:u.id,bossId:u.bossId}),u.class!=="boss"&&!u.isBoss&&!u.bossId&&a.jsx(iD,{agentId:u.id}),D&&a.jsx(eD,{action:D,agentName:u.name,onClose:()=>I(null),onConfirm:()=>{D==="collapse"?P.collapseContext(u.id):P.clearContext(u.id),I(null)}}),a.jsx(zS,{agent:u,isOpen:O,onClose:()=>X(!1)}),a.jsx(FS,{agent:u,isOpen:W,onClose:()=>G(!1),onRefresh:()=>{P.refreshAgentContext(u.id)}})]})}const J_=x.memo(function({patterns:e,showPatterns:t,onToggle:n,onRemovePattern:i,onClearAll:o}){return a.jsxs("div",{className:"unit-remembered-patterns",children:[a.jsxs("div",{className:"unit-remembered-patterns-header",onClick:n,children:[a.jsx("div",{className:"unit-stat-label",children:"Allowed Patterns"}),a.jsxs("span",{className:"unit-remembered-patterns-toggle",children:[e.length>0&&a.jsx("span",{className:"unit-remembered-patterns-count",children:e.length}),t?"▼":"▶"]})]}),t&&a.jsx("div",{className:"unit-remembered-patterns-list",children:e.length===0?a.jsx("div",{className:"unit-remembered-patterns-empty",children:"No patterns remembered yet. Click ✓+ when approving to remember."}):a.jsxs(a.Fragment,{children:[e.map((r,c)=>a.jsxs("div",{className:"unit-remembered-pattern-item",children:[a.jsx("span",{className:"unit-pattern-tool",children:r.tool}),a.jsx("span",{className:"unit-pattern-desc",title:r.pattern,children:r.description}),a.jsx("button",{className:"unit-pattern-remove",onClick:()=>i(r.tool,r.pattern),title:"Remove this pattern",children:"×"})]},c)),a.jsx("button",{className:"unit-patterns-clear-all",onClick:o,children:"Clear All"})]})})]})}),eD=x.memo(function({action:e,agentName:t,onClose:n,onConfirm:i}){const{handleMouseDown:o,handleClick:r}=Qs(n);return a.jsx("div",{className:"modal-overlay visible",onMouseDown:o,onClick:r,children:a.jsxs("div",{className:"modal confirm-modal",children:[a.jsx("div",{className:"modal-header",children:e==="collapse"?"Collapse Context":"Clear Context"}),a.jsx("div",{className:"modal-body confirm-modal-body",children:e==="collapse"?a.jsxs(a.Fragment,{children:[a.jsxs("p",{children:["Collapse the conversation context for ",a.jsx("strong",{children:t}),"?"]}),a.jsx("p",{className:"confirm-modal-note",children:"This will summarize the conversation to save tokens while preserving important information."})]}):a.jsxs(a.Fragment,{children:[a.jsxs("p",{children:["Clear all context for ",a.jsx("strong",{children:t}),"?"]}),a.jsx("p",{className:"confirm-modal-note",children:"This will start a fresh session on the next command. All conversation history will be lost."})]})}),a.jsxs("div",{className:"modal-footer",children:[a.jsx("button",{className:"btn btn-secondary",onClick:n,children:"Cancel"}),a.jsx("button",{className:`btn ${e==="clear"?"btn-danger":"btn-primary"}`,onClick:i,autoFocus:!0,children:e==="collapse"?"Collapse":"Clear Context"})]})]})})}),tD=x.memo(function({entry:e,defaultExpanded:t=!1}){var f;const[n,i]=x.useState(t),o=cs(),{analysis:r}=e,c=o.settings.hideCost,u=Ei(r.statusDescription,c),h=Ei(r.recentWorkSummary,c),m=(f=r.concerns)==null?void 0:f.map(g=>Ei(g,c)).filter(g=>g.length>0);return a.jsxs("div",{className:"supervisor-history-item",children:[a.jsxs("div",{className:"supervisor-history-item-header",onClick:()=>i(!n),children:[a.jsx("span",{className:"supervisor-history-progress-dot",style:{background:dS[r.progress]||"#888"},title:r.progress}),a.jsx("span",{className:"supervisor-history-status",children:u}),a.jsx("span",{className:"supervisor-history-time",children:Uu(e.timestamp)})]}),n&&a.jsxs("div",{className:"supervisor-history-item-details",children:[a.jsxs("div",{className:"supervisor-history-summary",children:[a.jsx("strong",{children:"Summary:"})," ",h]}),m&&m.length>0&&a.jsxs("div",{className:"supervisor-history-concerns",children:[a.jsx("strong",{children:"Concerns:"}),a.jsx("ul",{children:m.map((g,b)=>a.jsx("li",{children:g},b))})]})]})]})}),sD=x.memo(function({agent:e}){const t=cs(),n=ua(),[i,o]=x.useState(!0),[r,c]=x.useState(!0),u=x.useMemo(()=>{const b=t.agents.get(e.id);return!b||!b.isBoss&&b.class!=="boss"||!b.subordinateIds?[]:b.subordinateIds.map(v=>t.agents.get(v)).filter(v=>v!==void 0)},[t.agents,e.id]),h=P.getDelegationHistory(e.id),m=t.pendingDelegation,f=(m==null?void 0:m.bossId)===e.id;x.useEffect(()=>{P.requestDelegationHistory(e.id)},[e.id]);const g=Sa.boss;return a.jsxs("div",{className:"boss-section",children:[a.jsxs("div",{className:"boss-header",children:[a.jsx("span",{className:"boss-crown-icon",style:{color:g.color},children:g.icon}),a.jsx("span",{className:"boss-title",children:"Boss Agent"})]}),a.jsxs("div",{className:"boss-subordinates",children:[a.jsxs("div",{className:"boss-subordinates-header",onClick:()=>o(!i),children:[a.jsxs("div",{className:"unit-stat-label",children:["Team (",u.length,")"]}),a.jsx("span",{className:"boss-toggle",children:i?"▼":"▶"})]}),i&&a.jsx("div",{className:"boss-subordinates-list",children:u.length===0?a.jsx("div",{className:"boss-subordinates-empty",children:'No subordinates assigned. Use "Manage Team" to add agents.'}):u.map(b=>{const v=Bi(b.class,n);return a.jsxs("div",{className:"boss-subordinate-item",onClick:()=>P.selectAgent(b.id),children:[a.jsx("span",{className:"boss-subordinate-icon",style:{color:v.color},children:v.icon}),a.jsx("span",{className:"boss-subordinate-name",children:b.name}),a.jsx("span",{className:`boss-subordinate-status status-${b.status}`,children:b.status}),a.jsx("button",{className:"boss-subordinate-unlink",onClick:w=>{w.stopPropagation(),P.removeSubordinate(e.id,b.id)},title:"Unlink subordinate",children:"✕"})]},b.id)})})]}),a.jsxs("div",{className:"boss-delegation-history",children:[a.jsxs("div",{className:"boss-delegation-history-header",onClick:()=>c(!r),children:[a.jsxs("div",{className:"unit-stat-label",children:["Delegation History (",h.length,")"]}),a.jsx("span",{className:"boss-toggle",children:r?"▼":"▶"})]}),r&&a.jsxs("div",{className:"boss-delegation-history-list",children:[f&&a.jsxs("div",{className:"boss-delegation-pending",children:[a.jsx("span",{className:"delegation-spinner",children:"⏳"}),"Analyzing request..."]}),h.length===0&&!f?a.jsx("div",{className:"boss-delegation-empty",children:"No delegation history yet. Send commands to this boss to delegate tasks."}):h.slice(0,10).map(b=>a.jsx(nD,{decision:b},b.id))]})]})]})}),nD=x.memo(function({decision:e}){const[t,n]=x.useState(!1),o=cs().agents.get(e.selectedAgentId),r=o?Sa[o.class]:null,c={high:"#4aff9e",medium:"#ff9e4a",low:"#ff4a4a"};return a.jsxs("div",{className:"delegation-decision-item",children:[a.jsxs("div",{className:"delegation-decision-header",onClick:()=>n(!t),children:[a.jsx("span",{className:"delegation-decision-arrow",children:t?"▼":"▶"}),r&&a.jsx("span",{className:"delegation-decision-icon",style:{color:r.color},children:r.icon}),a.jsxs("span",{className:"delegation-decision-agent",children:["→ ",e.selectedAgentName]}),a.jsx("span",{className:"delegation-decision-confidence",style:{color:c[e.confidence]},title:`Confidence: ${e.confidence}`,children:e.confidence==="high"?"●●●":e.confidence==="medium"?"●●○":"●○○"}),a.jsx("span",{className:"delegation-decision-time",children:Uu(e.timestamp)})]}),t&&a.jsxs("div",{className:"delegation-decision-details",children:[a.jsxs("div",{className:"delegation-decision-command",children:[a.jsx("strong",{children:"Command:"}),a.jsx("div",{className:"delegation-command-text",children:e.userCommand.length>200?e.userCommand.slice(0,200)+"...":e.userCommand})]}),a.jsxs("div",{className:"delegation-decision-reasoning",children:[a.jsx("strong",{children:"Reasoning:"})," ",e.reasoning]}),e.alternativeAgents.length>0&&a.jsxs("div",{className:"delegation-decision-alternatives",children:[a.jsx("strong",{children:"Alternatives:"})," ",e.alternativeAgents.join(", ")]})]})]})}),aD=x.memo(function({agentId:e,bossId:t}){const i=cs().agents.get(t);if(!i)return null;const o=Sa.boss,r=c=>{c.stopPropagation(),P.removeSubordinate(t,e)};return a.jsxs("div",{className:"subordinate-badge",children:[a.jsx("span",{className:"subordinate-badge-icon",style:{color:o.color},children:o.icon}),a.jsxs("span",{className:"subordinate-badge-text",children:["Reports to: ",a.jsx("strong",{children:i.name})]}),a.jsx("button",{className:"subordinate-badge-goto",onClick:()=>P.selectAgent(t),title:"Go to boss",children:"→"}),a.jsx("button",{className:"subordinate-badge-unlink",onClick:r,title:"Unlink from boss",children:"✕"})]})}),iD=x.memo(function({agentId:e}){const t=cs(),[n,i]=x.useState(!1),o=Array.from(t.agents.values()).filter(u=>u.isBoss===!0||u.class==="boss");if(o.length===0)return null;const r=Sa.boss,c=u=>{const h=t.agents.get(u);if(!h)return;const m=h.subordinateIds||[];P.assignSubordinates(u,[...m,e]),i(!1)};return a.jsx("div",{className:"link-to-boss-section",children:n?a.jsxs("div",{className:"link-to-boss-dropdown",children:[a.jsxs("div",{className:"link-to-boss-header",children:[a.jsx("span",{children:"Select a Boss"}),a.jsx("button",{className:"link-to-boss-close",onClick:()=>i(!1),children:"✕"})]}),a.jsx("div",{className:"link-to-boss-list",children:o.map(u=>{var h;return a.jsxs("div",{className:"link-to-boss-item",onClick:()=>c(u.id),children:[a.jsx("span",{className:"link-to-boss-item-icon",style:{color:r.color},children:r.icon}),a.jsx("span",{className:"link-to-boss-item-name",children:u.name}),a.jsxs("span",{className:"link-to-boss-item-count",children:[((h=u.subordinateIds)==null?void 0:h.length)||0," agents"]})]},u.id)})})]}):a.jsxs("button",{className:"link-to-boss-btn",onClick:()=>i(!0),children:[a.jsx("span",{className:"link-to-boss-icon",style:{color:r.color},children:r.icon}),a.jsx("span",{children:"Link to Boss"})]})})}),oD=x.memo(function({agents:e}){const t=ua(),n=e.reduce((o,r)=>o+r.tokensUsed,0),i=e.filter(o=>o.status==="working").length;return a.jsxs("div",{className:"unit-panel",children:[a.jsxs("div",{className:"unit-panel-header",children:[a.jsx("div",{className:"unit-class-icon",style:{background:"#4a9eff20"},children:"👥"}),a.jsxs("div",{children:[a.jsxs("div",{className:"unit-name",children:[e.length," Agents Selected"]}),a.jsx("div",{className:"unit-status",children:"Group selection"})]})]}),a.jsxs("div",{className:"unit-stats",children:[a.jsxs("div",{className:"unit-stat",children:[a.jsx("div",{className:"unit-stat-label",children:"Total Tokens"}),a.jsx("div",{className:"unit-stat-value",children:R_(n)})]}),a.jsxs("div",{className:"unit-stat",children:[a.jsx("div",{className:"unit-stat-label",children:"Working"}),a.jsx("div",{className:"unit-stat-value",children:i})]})]}),a.jsx("div",{style:{padding:"8px 0",maxHeight:100,overflowY:"auto"},children:e.map(o=>a.jsx(rD,{agent:o,customClasses:t},o.id))}),a.jsx("div",{className:"unit-actions",children:a.jsx("button",{className:"unit-action-btn",onClick:()=>P.deselectAll(),children:"Deselect All"})})]})}),rD=x.memo(function({agent:e,customClasses:t}){const n=Bi(e.class,t);return a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 0",fontSize:12},children:[a.jsx("span",{children:n.icon}),a.jsx("span",{style:{flex:1},children:e.name}),a.jsx("span",{style:{color:"var(--text-secondary)"},children:e.status})]})});function d0({onFocusAgent:s,onKillAgent:e,onCallSubordinates:t,onOpenAreaExplorer:n}){const i=cs(),o=P.getSelectedAgents();if(i.selectedAgentIds.size===0)return a.jsx(l0,{onOpenAreaExplorer:n});if(i.selectedAgentIds.size===1){const r=o[0];return r?a.jsx(Q_,{agent:r,onFocusAgent:s,onKillAgent:e,onCallSubordinates:t,onOpenAreaExplorer:n}):a.jsx(l0,{onOpenAreaExplorer:n})}return a.jsx(oD,{agents:o})}function lD(s,e){const t={};return(s[s.length-1]===""?[...s,""]:s).join((t.padRight?" ":"")+","+(t.padLeft===!1?"":" ")).trim()}const cD=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,uD=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,dD={};function h0(s,e){return(dD.jsx?uD:cD).test(s)}const hD=/[ \t\n\f\r]/g;function pD(s){return typeof s=="object"?s.type==="text"?p0(s.value):!1:p0(s)}function p0(s){return s.replace(hD,"")===""}class tc{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}}tc.prototype.normal={};tc.prototype.property={};tc.prototype.space=void 0;function HS(s,e){const t={},n={};for(const i of s)Object.assign(t,i.property),Object.assign(n,i.normal);return new tc(t,n,e)}function Wm(s){return s.toLowerCase()}class vn{constructor(e,t){this.attribute=t,this.property=e}}vn.prototype.attribute="";vn.prototype.booleanish=!1;vn.prototype.boolean=!1;vn.prototype.commaOrSpaceSeparated=!1;vn.prototype.commaSeparated=!1;vn.prototype.defined=!1;vn.prototype.mustUseProperty=!1;vn.prototype.number=!1;vn.prototype.overloadedBoolean=!1;vn.prototype.property="";vn.prototype.spaceSeparated=!1;vn.prototype.space=void 0;let mD=0;const Mt=Co(),zs=Co(),qm=Co(),Ke=Co(),ms=Co(),vr=Co(),Mn=Co();function Co(){return 2**++mD}const Km=Object.freeze(Object.defineProperty({__proto__:null,boolean:Mt,booleanish:zs,commaOrSpaceSeparated:Mn,commaSeparated:vr,number:Ke,overloadedBoolean:qm,spaceSeparated:ms},Symbol.toStringTag,{value:"Module"})),Wp=Object.keys(Km);class Ff extends vn{constructor(e,t,n,i){let o=-1;if(super(e,t),m0(this,"space",i),typeof n=="number")for(;++o<Wp.length;){const r=Wp[o];m0(this,Wp[o],(n&Km[r])===Km[r])}}}Ff.prototype.defined=!0;function m0(s,e,t){t&&(s[e]=t)}function Ar(s){const e={},t={};for(const[n,i]of Object.entries(s.properties)){const o=new Ff(n,s.transform(s.attributes||{},n),i,s.space);s.mustUseProperty&&s.mustUseProperty.includes(n)&&(o.mustUseProperty=!0),e[n]=o,t[Wm(n)]=n,t[Wm(o.attribute)]=n}return new tc(e,t,s.space)}const US=Ar({properties:{ariaActiveDescendant:null,ariaAtomic:zs,ariaAutoComplete:null,ariaBusy:zs,ariaChecked:zs,ariaColCount:Ke,ariaColIndex:Ke,ariaColSpan:Ke,ariaControls:ms,ariaCurrent:null,ariaDescribedBy:ms,ariaDetails:null,ariaDisabled:zs,ariaDropEffect:ms,ariaErrorMessage:null,ariaExpanded:zs,ariaFlowTo:ms,ariaGrabbed:zs,ariaHasPopup:null,ariaHidden:zs,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ms,ariaLevel:Ke,ariaLive:null,ariaModal:zs,ariaMultiLine:zs,ariaMultiSelectable:zs,ariaOrientation:null,ariaOwns:ms,ariaPlaceholder:null,ariaPosInSet:Ke,ariaPressed:zs,ariaReadOnly:zs,ariaRelevant:null,ariaRequired:zs,ariaRoleDescription:ms,ariaRowCount:Ke,ariaRowIndex:Ke,ariaRowSpan:Ke,ariaSelected:zs,ariaSetSize:Ke,ariaSort:null,ariaValueMax:Ke,ariaValueMin:Ke,ariaValueNow:Ke,ariaValueText:null,role:null},transform(s,e){return e==="role"?e:"aria-"+e.slice(4).toLowerCase()}});function GS(s,e){return e in s?s[e]:e}function WS(s,e){return GS(s,e.toLowerCase())}const fD=Ar({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:vr,acceptCharset:ms,accessKey:ms,action:null,allow:null,allowFullScreen:Mt,allowPaymentRequest:Mt,allowUserMedia:Mt,alt:null,as:null,async:Mt,autoCapitalize:null,autoComplete:ms,autoFocus:Mt,autoPlay:Mt,blocking:ms,capture:null,charSet:null,checked:Mt,cite:null,className:ms,cols:Ke,colSpan:null,content:null,contentEditable:zs,controls:Mt,controlsList:ms,coords:Ke|vr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Mt,defer:Mt,dir:null,dirName:null,disabled:Mt,download:qm,draggable:zs,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Mt,formTarget:null,headers:ms,height:Ke,hidden:qm,high:Ke,href:null,hrefLang:null,htmlFor:ms,httpEquiv:ms,id:null,imageSizes:null,imageSrcSet:null,inert:Mt,inputMode:null,integrity:null,is:null,isMap:Mt,itemId:null,itemProp:ms,itemRef:ms,itemScope:Mt,itemType:ms,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Mt,low:Ke,manifest:null,max:null,maxLength:Ke,media:null,method:null,min:null,minLength:Ke,multiple:Mt,muted:Mt,name:null,nonce:null,noModule:Mt,noValidate:Mt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Mt,optimum:Ke,pattern:null,ping:ms,placeholder:null,playsInline:Mt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Mt,referrerPolicy:null,rel:ms,required:Mt,reversed:Mt,rows:Ke,rowSpan:Ke,sandbox:ms,scope:null,scoped:Mt,seamless:Mt,selected:Mt,shadowRootClonable:Mt,shadowRootDelegatesFocus:Mt,shadowRootMode:null,shape:null,size:Ke,sizes:null,slot:null,span:Ke,spellCheck:zs,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Ke,step:null,style:null,tabIndex:Ke,target:null,title:null,translate:null,type:null,typeMustMatch:Mt,useMap:null,value:zs,width:Ke,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ms,axis:null,background:null,bgColor:null,border:Ke,borderColor:null,bottomMargin:Ke,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Mt,declare:Mt,event:null,face:null,frame:null,frameBorder:null,hSpace:Ke,leftMargin:Ke,link:null,longDesc:null,lowSrc:null,marginHeight:Ke,marginWidth:Ke,noResize:Mt,noHref:Mt,noShade:Mt,noWrap:Mt,object:null,profile:null,prompt:null,rev:null,rightMargin:Ke,rules:null,scheme:null,scrolling:zs,standby:null,summary:null,text:null,topMargin:Ke,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Ke,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Mt,disableRemotePlayback:Mt,prefix:null,property:null,results:Ke,security:null,unselectable:null},space:"html",transform:WS}),gD=Ar({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Mn,accentHeight:Ke,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Ke,amplitude:Ke,arabicForm:null,ascent:Ke,attributeName:null,attributeType:null,azimuth:Ke,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Ke,by:null,calcMode:null,capHeight:Ke,className:ms,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Ke,diffuseConstant:Ke,direction:null,display:null,dur:null,divisor:Ke,dominantBaseline:null,download:Mt,dx:null,dy:null,edgeMode:null,editable:null,elevation:Ke,enableBackground:null,end:null,event:null,exponent:Ke,externalResourcesRequired:null,fill:null,fillOpacity:Ke,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:vr,g2:vr,glyphName:vr,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Ke,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Ke,horizOriginX:Ke,horizOriginY:Ke,id:null,ideographic:Ke,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Ke,k:Ke,k1:Ke,k2:Ke,k3:Ke,k4:Ke,kernelMatrix:Mn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Ke,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Ke,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Ke,overlineThickness:Ke,paintOrder:null,panose1:null,path:null,pathLength:Ke,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ms,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Ke,pointsAtY:Ke,pointsAtZ:Ke,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Mn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Mn,rev:Mn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Mn,requiredFeatures:Mn,requiredFonts:Mn,requiredFormats:Mn,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Ke,specularExponent:Ke,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Ke,strikethroughThickness:Ke,string:null,stroke:null,strokeDashArray:Mn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Ke,strokeOpacity:Ke,strokeWidth:null,style:null,surfaceScale:Ke,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Mn,tabIndex:Ke,tableValues:null,target:null,targetX:Ke,targetY:Ke,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Mn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Ke,underlineThickness:Ke,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Ke,values:null,vAlphabetic:Ke,vMathematical:Ke,vectorEffect:null,vHanging:Ke,vIdeographic:Ke,version:null,vertAdvY:Ke,vertOriginX:Ke,vertOriginY:Ke,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Ke,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:GS}),qS=Ar({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(s,e){return"xlink:"+e.slice(5).toLowerCase()}}),KS=Ar({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:WS}),VS=Ar({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(s,e){return"xml:"+e.slice(3).toLowerCase()}}),bD={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},yD=/[A-Z]/g,f0=/-[a-z]/g,xD=/^data[-\w.:]+$/i;function vD(s,e){const t=Wm(e);let n=e,i=vn;if(t in s.normal)return s.property[s.normal[t]];if(t.length>4&&t.slice(0,4)==="data"&&xD.test(e)){if(e.charAt(4)==="-"){const o=e.slice(5).replace(f0,kD);n="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=e.slice(4);if(!f0.test(o)){let r=o.replace(yD,wD);r.charAt(0)!=="-"&&(r="-"+r),e="data"+r}}i=Ff}return new i(n,e)}function wD(s){return"-"+s.toLowerCase()}function kD(s){return s.charAt(1).toUpperCase()}const SD=HS([US,fD,qS,KS,VS],"html"),$f=HS([US,gD,qS,KS,VS],"svg");function jD(s){return s.join(" ").trim()}var rr={},qp,g0;function CD(){if(g0)return qp;g0=1;var s=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,e=/\n/g,t=/^\s*/,n=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,r=/^[;\s]*/,c=/^\s+|\s+$/g,u=`
143
143
  `,h="/",m="*",f="",g="comment",b="declaration";function v(k,C){if(typeof k!="string")throw new TypeError("First argument must be a string");if(!k)return[];C=C||{};var j=1,A=1;function _(W){var G=W.match(e);G&&(j+=G.length);var B=W.lastIndexOf(u);A=~B?W.length-B:A+W.length}function M(){var W={line:j,column:A};return function(G){return G.position=new E(W),R(),G}}function E(W){this.start=W,this.end={line:j,column:A},this.source=C.source}E.prototype.content=k;function F(W){var G=new Error(C.source+":"+j+":"+A+": "+W);if(G.reason=W,G.filename=C.source,G.line=j,G.column=A,G.source=k,!C.silent)throw G}function T(W){var G=W.exec(k);if(G){var B=G[0];return _(B),k=k.slice(B.length),G}}function R(){T(t)}function D(W){var G;for(W=W||[];G=I();)G!==!1&&W.push(G);return W}function I(){var W=M();if(!(h!=k.charAt(0)||m!=k.charAt(1))){for(var G=2;f!=k.charAt(G)&&(m!=k.charAt(G)||h!=k.charAt(G+1));)++G;if(G+=2,f===k.charAt(G-1))return F("End of comment missing");var B=k.slice(2,G-2);return A+=2,_(B),k=k.slice(G),A+=2,W({type:g,comment:B})}}function O(){var W=M(),G=T(n);if(G){if(I(),!T(i))return F("property missing ':'");var B=T(o),q=W({type:b,property:w(G[0].replace(s,f)),value:B?w(B[0].replace(s,f)):f});return T(r),q}}function X(){var W=[];D(W);for(var G;G=O();)G!==!1&&(W.push(G),D(W));return W}return R(),X()}function w(k){return k?k.replace(c,f):f}return qp=v,qp}var b0;function AD(){if(b0)return rr;b0=1;var s=rr&&rr.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(rr,"__esModule",{value:!0}),rr.default=t;const e=s(CD());function t(n,i){let o=null;if(!n||typeof n!="string")return o;const r=(0,e.default)(n),c=typeof i=="function";return r.forEach(u=>{if(u.type!=="declaration")return;const{property:h,value:m}=u;c?i(h,m,u):m&&(o=o||{},o[h]=m)}),o}return rr}var Al={},y0;function ND(){if(y0)return Al;y0=1,Object.defineProperty(Al,"__esModule",{value:!0}),Al.camelCase=void 0;var s=/^--[a-zA-Z0-9_-]+$/,e=/-([a-z])/g,t=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,o=function(h){return!h||t.test(h)||s.test(h)},r=function(h,m){return m.toUpperCase()},c=function(h,m){return"".concat(m,"-")},u=function(h,m){return m===void 0&&(m={}),o(h)?h:(h=h.toLowerCase(),m.reactCompat?h=h.replace(i,c):h=h.replace(n,c),h.replace(e,r))};return Al.camelCase=u,Al}var Nl,x0;function TD(){if(x0)return Nl;x0=1;var s=Nl&&Nl.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},e=s(AD()),t=ND();function n(i,o){var r={};return!i||typeof i!="string"||(0,e.default)(i,function(c,u){c&&u&&(r[(0,t.camelCase)(c,o)]=u)}),r}return n.default=n,Nl=n,Nl}var MD=TD();const ED=sd(MD),XS=YS("end"),Hf=YS("start");function YS(s){return e;function e(t){const n=t&&t.position&&t.position[s]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function _D(s){const e=Hf(s),t=XS(s);if(e&&t)return{start:e,end:t}}function zl(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?v0(s.position):"start"in s||"end"in s?v0(s):"line"in s||"column"in s?Vm(s):""}function Vm(s){return w0(s&&s.line)+":"+w0(s&&s.column)}function v0(s){return Vm(s&&s.start)+"-"+Vm(s&&s.end)}function w0(s){return s&&typeof s=="number"?s:1}class sn extends Error{constructor(e,t,n){super(),typeof t=="string"&&(n=t,t=void 0);let i="",o={},r=!1;if(t&&("line"in t&&"column"in t?o={place:t}:"start"in t&&"end"in t?o={place:t}:"type"in t?o={ancestors:[t],place:t.position}:o={...t}),typeof e=="string"?i=e:!o.cause&&e&&(r=!0,i=e.message,o.cause=e),!o.ruleId&&!o.source&&typeof n=="string"){const u=n.indexOf(":");u===-1?o.ruleId=n:(o.source=n.slice(0,u),o.ruleId=n.slice(u+1))}if(!o.place&&o.ancestors&&o.ancestors){const u=o.ancestors[o.ancestors.length-1];u&&(o.place=u.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=c?c.line:void 0,this.name=zl(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=r&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}sn.prototype.file="";sn.prototype.name="";sn.prototype.reason="";sn.prototype.message="";sn.prototype.stack="";sn.prototype.column=void 0;sn.prototype.line=void 0;sn.prototype.ancestors=void 0;sn.prototype.cause=void 0;sn.prototype.fatal=void 0;sn.prototype.place=void 0;sn.prototype.ruleId=void 0;sn.prototype.source=void 0;const Uf={}.hasOwnProperty,DD=new Map,RD=/[A-Z]/g,LD=new Set(["table","tbody","thead","tfoot","tr"]),BD=new Set(["td","th"]),ZS="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function PD(s,e){if(!e||e.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const t=e.filePath||void 0;let n;if(e.development){if(typeof e.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");n=GD(t,e.jsxDEV)}else{if(typeof e.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof e.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");n=UD(t,e.jsx,e.jsxs)}const i={Fragment:e.Fragment,ancestors:[],components:e.components||{},create:n,elementAttributeNameCase:e.elementAttributeNameCase||"react",evaluater:e.createEvaluater?e.createEvaluater():void 0,filePath:t,ignoreInvalidStyle:e.ignoreInvalidStyle||!1,passKeys:e.passKeys!==!1,passNode:e.passNode||!1,schema:e.space==="svg"?$f:SD,stylePropertyNameCase:e.stylePropertyNameCase||"dom",tableCellAlignToStyle:e.tableCellAlignToStyle!==!1},o=QS(i,s,void 0);return o&&typeof o!="string"?o:i.create(s,i.Fragment,{children:o||void 0},void 0)}function QS(s,e,t){if(e.type==="element")return ID(s,e,t);if(e.type==="mdxFlowExpression"||e.type==="mdxTextExpression")return OD(s,e);if(e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement")return FD(s,e,t);if(e.type==="mdxjsEsm")return zD(s,e);if(e.type==="root")return $D(s,e,t);if(e.type==="text")return HD(s,e)}function ID(s,e,t){const n=s.schema;let i=n;e.tagName.toLowerCase()==="svg"&&n.space==="html"&&(i=$f,s.schema=i),s.ancestors.push(e);const o=ej(s,e.tagName,!1),r=WD(s,e);let c=Wf(s,e);return LD.has(e.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!pD(u):!0})),JS(s,r,o,e),Gf(r,c),s.ancestors.pop(),s.schema=n,s.create(e,o,r,t)}function OD(s,e){if(e.data&&e.data.estree&&s.evaluater){const n=e.data.estree.body[0];return n.type,s.evaluater.evaluateExpression(n.expression)}Yl(s,e.position)}function zD(s,e){if(e.data&&e.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(e.data.estree);Yl(s,e.position)}function FD(s,e,t){const n=s.schema;let i=n;e.name==="svg"&&n.space==="html"&&(i=$f,s.schema=i),s.ancestors.push(e);const o=e.name===null?s.Fragment:ej(s,e.name,!0),r=qD(s,e),c=Wf(s,e);return JS(s,r,o,e),Gf(r,c),s.ancestors.pop(),s.schema=n,s.create(e,o,r,t)}function $D(s,e,t){const n={};return Gf(n,Wf(s,e)),s.create(e,s.Fragment,n,t)}function HD(s,e){return e.value}function JS(s,e,t,n){typeof t!="string"&&t!==s.Fragment&&s.passNode&&(e.node=n)}function Gf(s,e){if(e.length>0){const t=e.length>1?e:e[0];t&&(s.children=t)}}function UD(s,e,t){return n;function n(i,o,r,c){const h=Array.isArray(r.children)?t:e;return c?h(o,r,c):h(o,r)}}function GD(s,e){return t;function t(n,i,o,r){const c=Array.isArray(o.children),u=Hf(n);return e(i,o,r,c,{columnNumber:u?u.column-1:void 0,fileName:s,lineNumber:u?u.line:void 0},void 0)}}function WD(s,e){const t={};let n,i;for(i in e.properties)if(i!=="children"&&Uf.call(e.properties,i)){const o=KD(s,i,e.properties[i]);if(o){const[r,c]=o;s.tableCellAlignToStyle&&r==="align"&&typeof c=="string"&&BD.has(e.tagName)?n=c:t[r]=c}}if(n){const o=t.style||(t.style={});o[s.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return t}function qD(s,e){const t={};for(const n of e.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&s.evaluater){const o=n.data.estree.body[0];o.type;const r=o.expression;r.type;const c=r.properties[0];c.type,Object.assign(t,s.evaluater.evaluateExpression(c.argument))}else Yl(s,e.position);else{const i=n.name;let o;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&s.evaluater){const c=n.value.data.estree.body[0];c.type,o=s.evaluater.evaluateExpression(c.expression)}else Yl(s,e.position);else o=n.value===null?!0:n.value;t[i]=o}return t}function Wf(s,e){const t=[];let n=-1;const i=s.passKeys?new Map:DD;for(;++n<e.children.length;){const o=e.children[n];let r;if(s.passKeys){const u=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(u){const h=i.get(u)||0;r=u+"-"+h,i.set(u,h+1)}}const c=QS(s,o,r);c!==void 0&&t.push(c)}return t}function KD(s,e,t){const n=vD(s.schema,e);if(!(t==null||typeof t=="number"&&Number.isNaN(t))){if(Array.isArray(t)&&(t=n.commaSeparated?lD(t):jD(t)),n.property==="style"){let i=typeof t=="object"?t:VD(s,String(t));return s.stylePropertyNameCase==="css"&&(i=XD(i)),["style",i]}return[s.elementAttributeNameCase==="react"&&n.space?bD[n.property]||n.property:n.attribute,t]}}function VD(s,e){try{return ED(e,{reactCompat:!0})}catch(t){if(s.ignoreInvalidStyle)return{};const n=t,i=new sn("Cannot parse `style` attribute",{ancestors:s.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw i.file=s.filePath||void 0,i.url=ZS+"#cannot-parse-style-attribute",i}}function ej(s,e,t){let n;if(!t)n={type:"Literal",value:e};else if(e.includes(".")){const i=e.split(".");let o=-1,r;for(;++o<i.length;){const c=h0(i[o])?{type:"Identifier",name:i[o]}:{type:"Literal",value:i[o]};r=r?{type:"MemberExpression",object:r,property:c,computed:!!(o&&c.type==="Literal"),optional:!1}:c}n=r}else n=h0(e)&&!/^[a-z]/.test(e)?{type:"Identifier",name:e}:{type:"Literal",value:e};if(n.type==="Literal"){const i=n.value;return Uf.call(s.components,i)?s.components[i]:i}if(s.evaluater)return s.evaluater.evaluateExpression(n);Yl(s)}function Yl(s,e){const t=new sn("Cannot handle MDX estrees without `createEvaluater`",{ancestors:s.ancestors,place:e,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw t.file=s.filePath||void 0,t.url=ZS+"#cannot-handle-mdx-estrees-without-createevaluater",t}function XD(s){const e={};let t;for(t in s)Uf.call(s,t)&&(e[YD(t)]=s[t]);return e}function YD(s){let e=s.replace(RD,ZD);return e.slice(0,3)==="ms-"&&(e="-"+e),e}function ZD(s){return"-"+s.toLowerCase()}const Kp={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},QD={};function qf(s,e){const t=QD,n=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,i=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return tj(s,n,i)}function tj(s,e,t){if(JD(s)){if("value"in s)return s.type==="html"&&!t?"":s.value;if(e&&"alt"in s&&s.alt)return s.alt;if("children"in s)return k0(s.children,e,t)}return Array.isArray(s)?k0(s,e,t):""}function k0(s,e,t){const n=[];let i=-1;for(;++i<s.length;)n[i]=tj(s[i],e,t);return n.join("")}function JD(s){return!!(s&&typeof s=="object")}const S0=document.createElement("i");function Kf(s){const e="&"+s+";";S0.innerHTML=e;const t=S0.textContent;return t.charCodeAt(t.length-1)===59&&s!=="semi"||t===e?!1:t}function Dn(s,e,t,n){const i=s.length;let o=0,r;if(e<0?e=-e>i?0:i+e:e=e>i?i:e,t=t>0?t:0,n.length<1e4)r=Array.from(n),r.unshift(e,t),s.splice(...r);else for(t&&s.splice(e,t);o<n.length;)r=n.slice(o,o+1e4),r.unshift(e,0),s.splice(...r),o+=1e4,e+=1e4}function qn(s,e){return s.length>0?(Dn(s,s.length,0,e),s):e}const j0={}.hasOwnProperty;function sj(s){const e={};let t=-1;for(;++t<s.length;)eR(e,s[t]);return e}function eR(s,e){let t;for(t in e){const i=(j0.call(s,t)?s[t]:void 0)||(s[t]={}),o=e[t];let r;if(o)for(r in o){j0.call(i,r)||(i[r]=[]);const c=o[r];tR(i[r],Array.isArray(c)?c:c?[c]:[])}}}function tR(s,e){let t=-1;const n=[];for(;++t<e.length;)(e[t].add==="after"?s:n).push(e[t]);Dn(s,0,0,n)}function nj(s,e){const t=Number.parseInt(s,e);return t<9||t===11||t>13&&t<32||t>126&&t<160||t>55295&&t<57344||t>64975&&t<65008||(t&65535)===65535||(t&65535)===65534||t>1114111?"�":String.fromCodePoint(t)}function la(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const rn=Ii(/[A-Za-z]/),en=Ii(/[\dA-Za-z]/),sR=Ii(/[#-'*+\--9=?A-Z^-~]/);function Gu(s){return s!==null&&(s<32||s===127)}const Xm=Ii(/\d/),nR=Ii(/[\dA-Fa-f]/),aR=Ii(/[!-/:-@[-`{-~]/);function gt(s){return s!==null&&s<-2}function hs(s){return s!==null&&(s<0||s===32)}function $t(s){return s===-2||s===-1||s===32}const pd=Ii(new RegExp("\\p{P}|\\p{S}","u")),wo=Ii(/\s/);function Ii(s){return e;function e(t){return t!==null&&t>-1&&s.test(String.fromCharCode(t))}}function Nr(s){const e=[];let t=-1,n=0,i=0;for(;++t<s.length;){const o=s.charCodeAt(t);let r="";if(o===37&&en(s.charCodeAt(t+1))&&en(s.charCodeAt(t+2)))i=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(r=String.fromCharCode(o));else if(o>55295&&o<57344){const c=s.charCodeAt(t+1);o<56320&&c>56319&&c<57344?(r=String.fromCharCode(o,c),i=1):r="�"}else r=String.fromCharCode(o);r&&(e.push(s.slice(n,t),encodeURIComponent(r)),n=t+i+1,r=""),i&&(t+=i,i=0)}return e.join("")+s.slice(n)}function Vt(s,e,t,n){const i=n?n-1:Number.POSITIVE_INFINITY;let o=0;return r;function r(u){return $t(u)?(s.enter(t),c(u)):e(u)}function c(u){return $t(u)&&o++<i?(s.consume(u),c):(s.exit(t),e(u))}}const iR={tokenize:oR};function oR(s){const e=s.attempt(this.parser.constructs.contentInitial,n,i);let t;return e;function n(c){if(c===null){s.consume(c);return}return s.enter("lineEnding"),s.consume(c),s.exit("lineEnding"),Vt(s,e,"linePrefix")}function i(c){return s.enter("paragraph"),o(c)}function o(c){const u=s.enter("chunkText",{contentType:"text",previous:t});return t&&(t.next=u),t=u,r(c)}function r(c){if(c===null){s.exit("chunkText"),s.exit("paragraph"),s.consume(c);return}return gt(c)?(s.consume(c),s.exit("chunkText"),o):(s.consume(c),r)}}const rR={tokenize:lR},C0={tokenize:cR};function lR(s){const e=this,t=[];let n=0,i,o,r;return c;function c(A){if(n<t.length){const _=t[n];return e.containerState=_[1],s.attempt(_[0].continuation,u,h)(A)}return h(A)}function u(A){if(n++,e.containerState._closeFlow){e.containerState._closeFlow=void 0,i&&j();const _=e.events.length;let M=_,E;for(;M--;)if(e.events[M][0]==="exit"&&e.events[M][1].type==="chunkFlow"){E=e.events[M][1].end;break}C(n);let F=_;for(;F<e.events.length;)e.events[F][1].end={...E},F++;return Dn(e.events,M+1,0,e.events.slice(_)),e.events.length=F,h(A)}return c(A)}function h(A){if(n===t.length){if(!i)return g(A);if(i.currentConstruct&&i.currentConstruct.concrete)return v(A);e.interrupt=!!(i.currentConstruct&&!i._gfmTableDynamicInterruptHack)}return e.containerState={},s.check(C0,m,f)(A)}function m(A){return i&&j(),C(n),g(A)}function f(A){return e.parser.lazy[e.now().line]=n!==t.length,r=e.now().offset,v(A)}function g(A){return e.containerState={},s.attempt(C0,b,v)(A)}function b(A){return n++,t.push([e.currentConstruct,e.containerState]),g(A)}function v(A){if(A===null){i&&j(),C(0),s.consume(A);return}return i=i||e.parser.flow(e.now()),s.enter("chunkFlow",{_tokenizer:i,contentType:"flow",previous:o}),w(A)}function w(A){if(A===null){k(s.exit("chunkFlow"),!0),C(0),s.consume(A);return}return gt(A)?(s.consume(A),k(s.exit("chunkFlow")),n=0,e.interrupt=void 0,c):(s.consume(A),w)}function k(A,_){const M=e.sliceStream(A);if(_&&M.push(null),A.previous=o,o&&(o.next=A),o=A,i.defineSkip(A.start),i.write(M),e.parser.lazy[A.start.line]){let E=i.events.length;for(;E--;)if(i.events[E][1].start.offset<r&&(!i.events[E][1].end||i.events[E][1].end.offset>r))return;const F=e.events.length;let T=F,R,D;for(;T--;)if(e.events[T][0]==="exit"&&e.events[T][1].type==="chunkFlow"){if(R){D=e.events[T][1].end;break}R=!0}for(C(n),E=F;E<e.events.length;)e.events[E][1].end={...D},E++;Dn(e.events,T+1,0,e.events.slice(F)),e.events.length=E}}function C(A){let _=t.length;for(;_-- >A;){const M=t[_];e.containerState=M[1],M[0].exit.call(e,s)}t.length=A}function j(){i.write([null]),o=void 0,i=void 0,e.containerState._closeFlow=void 0}}function cR(s,e,t){return Vt(s,s.attempt(this.parser.constructs.document,e,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Sr(s){if(s===null||hs(s)||wo(s))return 1;if(pd(s))return 2}function md(s,e,t){const n=[];let i=-1;for(;++i<s.length;){const o=s[i].resolveAll;o&&!n.includes(o)&&(e=o(e,t),n.push(o))}return e}const Ym={name:"attention",resolveAll:uR,tokenize:dR};function uR(s,e){let t=-1,n,i,o,r,c,u,h,m;for(;++t<s.length;)if(s[t][0]==="enter"&&s[t][1].type==="attentionSequence"&&s[t][1]._close){for(n=t;n--;)if(s[n][0]==="exit"&&s[n][1].type==="attentionSequence"&&s[n][1]._open&&e.sliceSerialize(s[n][1]).charCodeAt(0)===e.sliceSerialize(s[t][1]).charCodeAt(0)){if((s[n][1]._close||s[t][1]._open)&&(s[t][1].end.offset-s[t][1].start.offset)%3&&!((s[n][1].end.offset-s[n][1].start.offset+s[t][1].end.offset-s[t][1].start.offset)%3))continue;u=s[n][1].end.offset-s[n][1].start.offset>1&&s[t][1].end.offset-s[t][1].start.offset>1?2:1;const f={...s[n][1].end},g={...s[t][1].start};A0(f,-u),A0(g,u),r={type:u>1?"strongSequence":"emphasisSequence",start:f,end:{...s[n][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...s[t][1].start},end:g},o={type:u>1?"strongText":"emphasisText",start:{...s[n][1].end},end:{...s[t][1].start}},i={type:u>1?"strong":"emphasis",start:{...r.start},end:{...c.end}},s[n][1].end={...r.start},s[t][1].start={...c.end},h=[],s[n][1].end.offset-s[n][1].start.offset&&(h=qn(h,[["enter",s[n][1],e],["exit",s[n][1],e]])),h=qn(h,[["enter",i,e],["enter",r,e],["exit",r,e],["enter",o,e]]),h=qn(h,md(e.parser.constructs.insideSpan.null,s.slice(n+1,t),e)),h=qn(h,[["exit",o,e],["enter",c,e],["exit",c,e],["exit",i,e]]),s[t][1].end.offset-s[t][1].start.offset?(m=2,h=qn(h,[["enter",s[t][1],e],["exit",s[t][1],e]])):m=0,Dn(s,n-1,t-n+3,h),t=n+h.length-m-2;break}}for(t=-1;++t<s.length;)s[t][1].type==="attentionSequence"&&(s[t][1].type="data");return s}function dR(s,e){const t=this.parser.constructs.attentionMarkers.null,n=this.previous,i=Sr(n);let o;return r;function r(u){return o=u,s.enter("attentionSequence"),c(u)}function c(u){if(u===o)return s.consume(u),c;const h=s.exit("attentionSequence"),m=Sr(u),f=!m||m===2&&i||t.includes(u),g=!i||i===2&&m||t.includes(n);return h._open=!!(o===42?f:f&&(i||!g)),h._close=!!(o===42?g:g&&(m||!f)),e(u)}}function A0(s,e){s.column+=e,s.offset+=e,s._bufferIndex+=e}const hR={name:"autolink",tokenize:pR};function pR(s,e,t){let n=0;return i;function i(b){return s.enter("autolink"),s.enter("autolinkMarker"),s.consume(b),s.exit("autolinkMarker"),s.enter("autolinkProtocol"),o}function o(b){return rn(b)?(s.consume(b),r):b===64?t(b):h(b)}function r(b){return b===43||b===45||b===46||en(b)?(n=1,c(b)):h(b)}function c(b){return b===58?(s.consume(b),n=0,u):(b===43||b===45||b===46||en(b))&&n++<32?(s.consume(b),c):(n=0,h(b))}function u(b){return b===62?(s.exit("autolinkProtocol"),s.enter("autolinkMarker"),s.consume(b),s.exit("autolinkMarker"),s.exit("autolink"),e):b===null||b===32||b===60||Gu(b)?t(b):(s.consume(b),u)}function h(b){return b===64?(s.consume(b),m):sR(b)?(s.consume(b),h):t(b)}function m(b){return en(b)?f(b):t(b)}function f(b){return b===46?(s.consume(b),n=0,m):b===62?(s.exit("autolinkProtocol").type="autolinkEmail",s.enter("autolinkMarker"),s.consume(b),s.exit("autolinkMarker"),s.exit("autolink"),e):g(b)}function g(b){if((b===45||en(b))&&n++<63){const v=b===45?g:f;return s.consume(b),v}return t(b)}}const sc={partial:!0,tokenize:mR};function mR(s,e,t){return n;function n(o){return $t(o)?Vt(s,i,"linePrefix")(o):i(o)}function i(o){return o===null||gt(o)?e(o):t(o)}}const aj={continuation:{tokenize:gR},exit:bR,name:"blockQuote",tokenize:fR};function fR(s,e,t){const n=this;return i;function i(r){if(r===62){const c=n.containerState;return c.open||(s.enter("blockQuote",{_container:!0}),c.open=!0),s.enter("blockQuotePrefix"),s.enter("blockQuoteMarker"),s.consume(r),s.exit("blockQuoteMarker"),o}return t(r)}function o(r){return $t(r)?(s.enter("blockQuotePrefixWhitespace"),s.consume(r),s.exit("blockQuotePrefixWhitespace"),s.exit("blockQuotePrefix"),e):(s.exit("blockQuotePrefix"),e(r))}}function gR(s,e,t){const n=this;return i;function i(r){return $t(r)?Vt(s,o,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(r):o(r)}function o(r){return s.attempt(aj,e,t)(r)}}function bR(s){s.exit("blockQuote")}const ij={name:"characterEscape",tokenize:yR};function yR(s,e,t){return n;function n(o){return s.enter("characterEscape"),s.enter("escapeMarker"),s.consume(o),s.exit("escapeMarker"),i}function i(o){return aR(o)?(s.enter("characterEscapeValue"),s.consume(o),s.exit("characterEscapeValue"),s.exit("characterEscape"),e):t(o)}}const oj={name:"characterReference",tokenize:xR};function xR(s,e,t){const n=this;let i=0,o,r;return c;function c(f){return s.enter("characterReference"),s.enter("characterReferenceMarker"),s.consume(f),s.exit("characterReferenceMarker"),u}function u(f){return f===35?(s.enter("characterReferenceMarkerNumeric"),s.consume(f),s.exit("characterReferenceMarkerNumeric"),h):(s.enter("characterReferenceValue"),o=31,r=en,m(f))}function h(f){return f===88||f===120?(s.enter("characterReferenceMarkerHexadecimal"),s.consume(f),s.exit("characterReferenceMarkerHexadecimal"),s.enter("characterReferenceValue"),o=6,r=nR,m):(s.enter("characterReferenceValue"),o=7,r=Xm,m(f))}function m(f){if(f===59&&i){const g=s.exit("characterReferenceValue");return r===en&&!Kf(n.sliceSerialize(g))?t(f):(s.enter("characterReferenceMarker"),s.consume(f),s.exit("characterReferenceMarker"),s.exit("characterReference"),e)}return r(f)&&i++<o?(s.consume(f),m):t(f)}}const N0={partial:!0,tokenize:wR},T0={concrete:!0,name:"codeFenced",tokenize:vR};function vR(s,e,t){const n=this,i={partial:!0,tokenize:M};let o=0,r=0,c;return u;function u(E){return h(E)}function h(E){const F=n.events[n.events.length-1];return o=F&&F[1].type==="linePrefix"?F[2].sliceSerialize(F[1],!0).length:0,c=E,s.enter("codeFenced"),s.enter("codeFencedFence"),s.enter("codeFencedFenceSequence"),m(E)}function m(E){return E===c?(r++,s.consume(E),m):r<3?t(E):(s.exit("codeFencedFenceSequence"),$t(E)?Vt(s,f,"whitespace")(E):f(E))}function f(E){return E===null||gt(E)?(s.exit("codeFencedFence"),n.interrupt?e(E):s.check(N0,w,_)(E)):(s.enter("codeFencedFenceInfo"),s.enter("chunkString",{contentType:"string"}),g(E))}function g(E){return E===null||gt(E)?(s.exit("chunkString"),s.exit("codeFencedFenceInfo"),f(E)):$t(E)?(s.exit("chunkString"),s.exit("codeFencedFenceInfo"),Vt(s,b,"whitespace")(E)):E===96&&E===c?t(E):(s.consume(E),g)}function b(E){return E===null||gt(E)?f(E):(s.enter("codeFencedFenceMeta"),s.enter("chunkString",{contentType:"string"}),v(E))}function v(E){return E===null||gt(E)?(s.exit("chunkString"),s.exit("codeFencedFenceMeta"),f(E)):E===96&&E===c?t(E):(s.consume(E),v)}function w(E){return s.attempt(i,_,k)(E)}function k(E){return s.enter("lineEnding"),s.consume(E),s.exit("lineEnding"),C}function C(E){return o>0&&$t(E)?Vt(s,j,"linePrefix",o+1)(E):j(E)}function j(E){return E===null||gt(E)?s.check(N0,w,_)(E):(s.enter("codeFlowValue"),A(E))}function A(E){return E===null||gt(E)?(s.exit("codeFlowValue"),j(E)):(s.consume(E),A)}function _(E){return s.exit("codeFenced"),e(E)}function M(E,F,T){let R=0;return D;function D(G){return E.enter("lineEnding"),E.consume(G),E.exit("lineEnding"),I}function I(G){return E.enter("codeFencedFence"),$t(G)?Vt(E,O,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(G):O(G)}function O(G){return G===c?(E.enter("codeFencedFenceSequence"),X(G)):T(G)}function X(G){return G===c?(R++,E.consume(G),X):R>=r?(E.exit("codeFencedFenceSequence"),$t(G)?Vt(E,W,"whitespace")(G):W(G)):T(G)}function W(G){return G===null||gt(G)?(E.exit("codeFencedFence"),F(G)):T(G)}}}function wR(s,e,t){const n=this;return i;function i(r){return r===null?t(r):(s.enter("lineEnding"),s.consume(r),s.exit("lineEnding"),o)}function o(r){return n.parser.lazy[n.now().line]?t(r):e(r)}}const Vp={name:"codeIndented",tokenize:SR},kR={partial:!0,tokenize:jR};function SR(s,e,t){const n=this;return i;function i(h){return s.enter("codeIndented"),Vt(s,o,"linePrefix",5)(h)}function o(h){const m=n.events[n.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?r(h):t(h)}function r(h){return h===null?u(h):gt(h)?s.attempt(kR,r,u)(h):(s.enter("codeFlowValue"),c(h))}function c(h){return h===null||gt(h)?(s.exit("codeFlowValue"),r(h)):(s.consume(h),c)}function u(h){return s.exit("codeIndented"),e(h)}}function jR(s,e,t){const n=this;return i;function i(r){return n.parser.lazy[n.now().line]?t(r):gt(r)?(s.enter("lineEnding"),s.consume(r),s.exit("lineEnding"),i):Vt(s,o,"linePrefix",5)(r)}function o(r){const c=n.events[n.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?e(r):gt(r)?i(r):t(r)}}const CR={name:"codeText",previous:NR,resolve:AR,tokenize:TR};function AR(s){let e=s.length-4,t=3,n,i;if((s[t][1].type==="lineEnding"||s[t][1].type==="space")&&(s[e][1].type==="lineEnding"||s[e][1].type==="space")){for(n=t;++n<e;)if(s[n][1].type==="codeTextData"){s[t][1].type="codeTextPadding",s[e][1].type="codeTextPadding",t+=2,e-=2;break}}for(n=t-1,e++;++n<=e;)i===void 0?n!==e&&s[n][1].type!=="lineEnding"&&(i=n):(n===e||s[n][1].type==="lineEnding")&&(s[i][1].type="codeTextData",n!==i+2&&(s[i][1].end=s[n-1][1].end,s.splice(i+2,n-i-2),e-=n-i-2,n=i+2),i=void 0);return s}function NR(s){return s!==96||this.events[this.events.length-1][1].type==="characterEscape"}function TR(s,e,t){let n=0,i,o;return r;function r(f){return s.enter("codeText"),s.enter("codeTextSequence"),c(f)}function c(f){return f===96?(s.consume(f),n++,c):(s.exit("codeTextSequence"),u(f))}function u(f){return f===null?t(f):f===32?(s.enter("space"),s.consume(f),s.exit("space"),u):f===96?(o=s.enter("codeTextSequence"),i=0,m(f)):gt(f)?(s.enter("lineEnding"),s.consume(f),s.exit("lineEnding"),u):(s.enter("codeTextData"),h(f))}function h(f){return f===null||f===32||f===96||gt(f)?(s.exit("codeTextData"),u(f)):(s.consume(f),h)}function m(f){return f===96?(s.consume(f),i++,m):i===n?(s.exit("codeTextSequence"),s.exit("codeText"),e(f)):(o.type="codeTextData",h(f))}}class MR{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,t){const n=t??Number.POSITIVE_INFINITY;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){const i=t||0;this.setCursor(Math.trunc(e));const o=this.right.splice(this.right.length-i,Number.POSITIVE_INFINITY);return n&&Tl(this.left,n),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),Tl(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),Tl(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0))if(e<this.left.length){const t=this.left.splice(e,Number.POSITIVE_INFINITY);Tl(this.right,t.reverse())}else{const t=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);Tl(this.left,t.reverse())}}}function Tl(s,e){let t=0;if(e.length<1e4)s.push(...e);else for(;t<e.length;)s.push(...e.slice(t,t+1e4)),t+=1e4}function rj(s){const e={};let t=-1,n,i,o,r,c,u,h;const m=new MR(s);for(;++t<m.length;){for(;t in e;)t=e[t];if(n=m.get(t),t&&n[1].type==="chunkFlow"&&m.get(t-1)[1].type==="listItemPrefix"&&(u=n[1]._tokenizer.events,o=0,o<u.length&&u[o][1].type==="lineEndingBlank"&&(o+=2),o<u.length&&u[o][1].type==="content"))for(;++o<u.length&&u[o][1].type!=="content";)u[o][1].type==="chunkText"&&(u[o][1]._isInFirstContentOfListItem=!0,o++);if(n[0]==="enter")n[1].contentType&&(Object.assign(e,ER(m,t)),t=e[t],h=!0);else if(n[1]._container){for(o=t,i=void 0;o--;)if(r=m.get(o),r[1].type==="lineEnding"||r[1].type==="lineEndingBlank")r[0]==="enter"&&(i&&(m.get(i)[1].type="lineEndingBlank"),r[1].type="lineEnding",i=o);else if(!(r[1].type==="linePrefix"||r[1].type==="listItemIndent"))break;i&&(n[1].end={...m.get(i)[1].start},c=m.slice(i,t),c.unshift(n),m.splice(i,t-i+1,c))}}return Dn(s,0,Number.POSITIVE_INFINITY,m.slice(0)),!h}function ER(s,e){const t=s.get(e)[1],n=s.get(e)[2];let i=e-1;const o=[];let r=t._tokenizer;r||(r=n.parser[t.contentType](t.start),t._contentTypeTextTrailing&&(r._contentTypeTextTrailing=!0));const c=r.events,u=[],h={};let m,f,g=-1,b=t,v=0,w=0;const k=[w];for(;b;){for(;s.get(++i)[1]!==b;);o.push(i),b._tokenizer||(m=n.sliceStream(b),b.next||m.push(null),f&&r.defineSkip(b.start),b._isInFirstContentOfListItem&&(r._gfmTasklistFirstContentOfListItem=!0),r.write(m),b._isInFirstContentOfListItem&&(r._gfmTasklistFirstContentOfListItem=void 0)),f=b,b=b.next}for(b=t;++g<c.length;)c[g][0]==="exit"&&c[g-1][0]==="enter"&&c[g][1].type===c[g-1][1].type&&c[g][1].start.line!==c[g][1].end.line&&(w=g+1,k.push(w),b._tokenizer=void 0,b.previous=void 0,b=b.next);for(r.events=[],b?(b._tokenizer=void 0,b.previous=void 0):k.pop(),g=k.length;g--;){const C=c.slice(k[g],k[g+1]),j=o.pop();u.push([j,j+C.length-1]),s.splice(j,2,C)}for(u.reverse(),g=-1;++g<u.length;)h[v+u[g][0]]=v+u[g][1],v+=u[g][1]-u[g][0]-1;return h}const _R={resolve:RR,tokenize:LR},DR={partial:!0,tokenize:BR};function RR(s){return rj(s),s}function LR(s,e){let t;return n;function n(c){return s.enter("content"),t=s.enter("chunkContent",{contentType:"content"}),i(c)}function i(c){return c===null?o(c):gt(c)?s.check(DR,r,o)(c):(s.consume(c),i)}function o(c){return s.exit("chunkContent"),s.exit("content"),e(c)}function r(c){return s.consume(c),s.exit("chunkContent"),t.next=s.enter("chunkContent",{contentType:"content",previous:t}),t=t.next,i}}function BR(s,e,t){const n=this;return i;function i(r){return s.exit("chunkContent"),s.enter("lineEnding"),s.consume(r),s.exit("lineEnding"),Vt(s,o,"linePrefix")}function o(r){if(r===null||gt(r))return t(r);const c=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?e(r):s.interrupt(n.parser.constructs.flow,t,e)(r)}}function lj(s,e,t,n,i,o,r,c,u){const h=u||Number.POSITIVE_INFINITY;let m=0;return f;function f(C){return C===60?(s.enter(n),s.enter(i),s.enter(o),s.consume(C),s.exit(o),g):C===null||C===32||C===41||Gu(C)?t(C):(s.enter(n),s.enter(r),s.enter(c),s.enter("chunkString",{contentType:"string"}),w(C))}function g(C){return C===62?(s.enter(o),s.consume(C),s.exit(o),s.exit(i),s.exit(n),e):(s.enter(c),s.enter("chunkString",{contentType:"string"}),b(C))}function b(C){return C===62?(s.exit("chunkString"),s.exit(c),g(C)):C===null||C===60||gt(C)?t(C):(s.consume(C),C===92?v:b)}function v(C){return C===60||C===62||C===92?(s.consume(C),b):b(C)}function w(C){return!m&&(C===null||C===41||hs(C))?(s.exit("chunkString"),s.exit(c),s.exit(r),s.exit(n),e(C)):m<h&&C===40?(s.consume(C),m++,w):C===41?(s.consume(C),m--,w):C===null||C===32||C===40||Gu(C)?t(C):(s.consume(C),C===92?k:w)}function k(C){return C===40||C===41||C===92?(s.consume(C),w):w(C)}}function cj(s,e,t,n,i,o){const r=this;let c=0,u;return h;function h(b){return s.enter(n),s.enter(i),s.consume(b),s.exit(i),s.enter(o),m}function m(b){return c>999||b===null||b===91||b===93&&!u||b===94&&!c&&"_hiddenFootnoteSupport"in r.parser.constructs?t(b):b===93?(s.exit(o),s.enter(i),s.consume(b),s.exit(i),s.exit(n),e):gt(b)?(s.enter("lineEnding"),s.consume(b),s.exit("lineEnding"),m):(s.enter("chunkString",{contentType:"string"}),f(b))}function f(b){return b===null||b===91||b===93||gt(b)||c++>999?(s.exit("chunkString"),m(b)):(s.consume(b),u||(u=!$t(b)),b===92?g:f)}function g(b){return b===91||b===92||b===93?(s.consume(b),c++,f):f(b)}}function uj(s,e,t,n,i,o){let r;return c;function c(g){return g===34||g===39||g===40?(s.enter(n),s.enter(i),s.consume(g),s.exit(i),r=g===40?41:g,u):t(g)}function u(g){return g===r?(s.enter(i),s.consume(g),s.exit(i),s.exit(n),e):(s.enter(o),h(g))}function h(g){return g===r?(s.exit(o),u(r)):g===null?t(g):gt(g)?(s.enter("lineEnding"),s.consume(g),s.exit("lineEnding"),Vt(s,h,"linePrefix")):(s.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===r||g===null||gt(g)?(s.exit("chunkString"),h(g)):(s.consume(g),g===92?f:m)}function f(g){return g===r||g===92?(s.consume(g),m):m(g)}}function Fl(s,e){let t;return n;function n(i){return gt(i)?(s.enter("lineEnding"),s.consume(i),s.exit("lineEnding"),t=!0,n):$t(i)?Vt(s,n,t?"linePrefix":"lineSuffix")(i):e(i)}}const PR={name:"definition",tokenize:OR},IR={partial:!0,tokenize:zR};function OR(s,e,t){const n=this;let i;return o;function o(b){return s.enter("definition"),r(b)}function r(b){return cj.call(n,s,c,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(b)}function c(b){return i=la(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),b===58?(s.enter("definitionMarker"),s.consume(b),s.exit("definitionMarker"),u):t(b)}function u(b){return hs(b)?Fl(s,h)(b):h(b)}function h(b){return lj(s,m,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(b)}function m(b){return s.attempt(IR,f,f)(b)}function f(b){return $t(b)?Vt(s,g,"whitespace")(b):g(b)}function g(b){return b===null||gt(b)?(s.exit("definition"),n.parser.defined.push(i),e(b)):t(b)}}function zR(s,e,t){return n;function n(c){return hs(c)?Fl(s,i)(c):t(c)}function i(c){return uj(s,o,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return $t(c)?Vt(s,r,"whitespace")(c):r(c)}function r(c){return c===null||gt(c)?e(c):t(c)}}const FR={name:"hardBreakEscape",tokenize:$R};function $R(s,e,t){return n;function n(o){return s.enter("hardBreakEscape"),s.consume(o),i}function i(o){return gt(o)?(s.exit("hardBreakEscape"),e(o)):t(o)}}const HR={name:"headingAtx",resolve:UR,tokenize:GR};function UR(s,e){let t=s.length-2,n=3,i,o;return s[n][1].type==="whitespace"&&(n+=2),t-2>n&&s[t][1].type==="whitespace"&&(t-=2),s[t][1].type==="atxHeadingSequence"&&(n===t-1||t-4>n&&s[t-2][1].type==="whitespace")&&(t-=n+1===t?2:4),t>n&&(i={type:"atxHeadingText",start:s[n][1].start,end:s[t][1].end},o={type:"chunkText",start:s[n][1].start,end:s[t][1].end,contentType:"text"},Dn(s,n,t-n+1,[["enter",i,e],["enter",o,e],["exit",o,e],["exit",i,e]])),s}function GR(s,e,t){let n=0;return i;function i(m){return s.enter("atxHeading"),o(m)}function o(m){return s.enter("atxHeadingSequence"),r(m)}function r(m){return m===35&&n++<6?(s.consume(m),r):m===null||hs(m)?(s.exit("atxHeadingSequence"),c(m)):t(m)}function c(m){return m===35?(s.enter("atxHeadingSequence"),u(m)):m===null||gt(m)?(s.exit("atxHeading"),e(m)):$t(m)?Vt(s,c,"whitespace")(m):(s.enter("atxHeadingText"),h(m))}function u(m){return m===35?(s.consume(m),u):(s.exit("atxHeadingSequence"),c(m))}function h(m){return m===null||m===35||hs(m)?(s.exit("atxHeadingText"),c(m)):(s.consume(m),h)}}const WR=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],M0=["pre","script","style","textarea"],qR={concrete:!0,name:"htmlFlow",resolveTo:XR,tokenize:YR},KR={partial:!0,tokenize:QR},VR={partial:!0,tokenize:ZR};function XR(s){let e=s.length;for(;e--&&!(s[e][0]==="enter"&&s[e][1].type==="htmlFlow"););return e>1&&s[e-2][1].type==="linePrefix"&&(s[e][1].start=s[e-2][1].start,s[e+1][1].start=s[e-2][1].start,s.splice(e-2,2)),s}function YR(s,e,t){const n=this;let i,o,r,c,u;return h;function h(U){return m(U)}function m(U){return s.enter("htmlFlow"),s.enter("htmlFlowData"),s.consume(U),f}function f(U){return U===33?(s.consume(U),g):U===47?(s.consume(U),o=!0,w):U===63?(s.consume(U),i=3,n.interrupt?e:L):rn(U)?(s.consume(U),r=String.fromCharCode(U),k):t(U)}function g(U){return U===45?(s.consume(U),i=2,b):U===91?(s.consume(U),i=5,c=0,v):rn(U)?(s.consume(U),i=4,n.interrupt?e:L):t(U)}function b(U){return U===45?(s.consume(U),n.interrupt?e:L):t(U)}function v(U){const H="CDATA[";return U===H.charCodeAt(c++)?(s.consume(U),c===H.length?n.interrupt?e:O:v):t(U)}function w(U){return rn(U)?(s.consume(U),r=String.fromCharCode(U),k):t(U)}function k(U){if(U===null||U===47||U===62||hs(U)){const H=U===47,Q=r.toLowerCase();return!H&&!o&&M0.includes(Q)?(i=1,n.interrupt?e(U):O(U)):WR.includes(r.toLowerCase())?(i=6,H?(s.consume(U),C):n.interrupt?e(U):O(U)):(i=7,n.interrupt&&!n.parser.lazy[n.now().line]?t(U):o?j(U):A(U))}return U===45||en(U)?(s.consume(U),r+=String.fromCharCode(U),k):t(U)}function C(U){return U===62?(s.consume(U),n.interrupt?e:O):t(U)}function j(U){return $t(U)?(s.consume(U),j):D(U)}function A(U){return U===47?(s.consume(U),D):U===58||U===95||rn(U)?(s.consume(U),_):$t(U)?(s.consume(U),A):D(U)}function _(U){return U===45||U===46||U===58||U===95||en(U)?(s.consume(U),_):M(U)}function M(U){return U===61?(s.consume(U),E):$t(U)?(s.consume(U),M):A(U)}function E(U){return U===null||U===60||U===61||U===62||U===96?t(U):U===34||U===39?(s.consume(U),u=U,F):$t(U)?(s.consume(U),E):T(U)}function F(U){return U===u?(s.consume(U),u=null,R):U===null||gt(U)?t(U):(s.consume(U),F)}function T(U){return U===null||U===34||U===39||U===47||U===60||U===61||U===62||U===96||hs(U)?M(U):(s.consume(U),T)}function R(U){return U===47||U===62||$t(U)?A(U):t(U)}function D(U){return U===62?(s.consume(U),I):t(U)}function I(U){return U===null||gt(U)?O(U):$t(U)?(s.consume(U),I):t(U)}function O(U){return U===45&&i===2?(s.consume(U),B):U===60&&i===1?(s.consume(U),q):U===62&&i===4?(s.consume(U),Z):U===63&&i===3?(s.consume(U),L):U===93&&i===5?(s.consume(U),z):gt(U)&&(i===6||i===7)?(s.exit("htmlFlowData"),s.check(KR,V,X)(U)):U===null||gt(U)?(s.exit("htmlFlowData"),X(U)):(s.consume(U),O)}function X(U){return s.check(VR,W,V)(U)}function W(U){return s.enter("lineEnding"),s.consume(U),s.exit("lineEnding"),G}function G(U){return U===null||gt(U)?X(U):(s.enter("htmlFlowData"),O(U))}function B(U){return U===45?(s.consume(U),L):O(U)}function q(U){return U===47?(s.consume(U),r="",Y):O(U)}function Y(U){if(U===62){const H=r.toLowerCase();return M0.includes(H)?(s.consume(U),Z):O(U)}return rn(U)&&r.length<8?(s.consume(U),r+=String.fromCharCode(U),Y):O(U)}function z(U){return U===93?(s.consume(U),L):O(U)}function L(U){return U===62?(s.consume(U),Z):U===45&&i===2?(s.consume(U),L):O(U)}function Z(U){return U===null||gt(U)?(s.exit("htmlFlowData"),V(U)):(s.consume(U),Z)}function V(U){return s.exit("htmlFlow"),e(U)}}function ZR(s,e,t){const n=this;return i;function i(r){return gt(r)?(s.enter("lineEnding"),s.consume(r),s.exit("lineEnding"),o):t(r)}function o(r){return n.parser.lazy[n.now().line]?t(r):e(r)}}function QR(s,e,t){return n;function n(i){return s.enter("lineEnding"),s.consume(i),s.exit("lineEnding"),s.attempt(sc,e,t)}}const JR={name:"htmlText",tokenize:eL};function eL(s,e,t){const n=this;let i,o,r;return c;function c(L){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(L),u}function u(L){return L===33?(s.consume(L),h):L===47?(s.consume(L),M):L===63?(s.consume(L),A):rn(L)?(s.consume(L),T):t(L)}function h(L){return L===45?(s.consume(L),m):L===91?(s.consume(L),o=0,v):rn(L)?(s.consume(L),j):t(L)}function m(L){return L===45?(s.consume(L),b):t(L)}function f(L){return L===null?t(L):L===45?(s.consume(L),g):gt(L)?(r=f,q(L)):(s.consume(L),f)}function g(L){return L===45?(s.consume(L),b):f(L)}function b(L){return L===62?B(L):L===45?g(L):f(L)}function v(L){const Z="CDATA[";return L===Z.charCodeAt(o++)?(s.consume(L),o===Z.length?w:v):t(L)}function w(L){return L===null?t(L):L===93?(s.consume(L),k):gt(L)?(r=w,q(L)):(s.consume(L),w)}function k(L){return L===93?(s.consume(L),C):w(L)}function C(L){return L===62?B(L):L===93?(s.consume(L),C):w(L)}function j(L){return L===null||L===62?B(L):gt(L)?(r=j,q(L)):(s.consume(L),j)}function A(L){return L===null?t(L):L===63?(s.consume(L),_):gt(L)?(r=A,q(L)):(s.consume(L),A)}function _(L){return L===62?B(L):A(L)}function M(L){return rn(L)?(s.consume(L),E):t(L)}function E(L){return L===45||en(L)?(s.consume(L),E):F(L)}function F(L){return gt(L)?(r=F,q(L)):$t(L)?(s.consume(L),F):B(L)}function T(L){return L===45||en(L)?(s.consume(L),T):L===47||L===62||hs(L)?R(L):t(L)}function R(L){return L===47?(s.consume(L),B):L===58||L===95||rn(L)?(s.consume(L),D):gt(L)?(r=R,q(L)):$t(L)?(s.consume(L),R):B(L)}function D(L){return L===45||L===46||L===58||L===95||en(L)?(s.consume(L),D):I(L)}function I(L){return L===61?(s.consume(L),O):gt(L)?(r=I,q(L)):$t(L)?(s.consume(L),I):R(L)}function O(L){return L===null||L===60||L===61||L===62||L===96?t(L):L===34||L===39?(s.consume(L),i=L,X):gt(L)?(r=O,q(L)):$t(L)?(s.consume(L),O):(s.consume(L),W)}function X(L){return L===i?(s.consume(L),i=void 0,G):L===null?t(L):gt(L)?(r=X,q(L)):(s.consume(L),X)}function W(L){return L===null||L===34||L===39||L===60||L===61||L===96?t(L):L===47||L===62||hs(L)?R(L):(s.consume(L),W)}function G(L){return L===47||L===62||hs(L)?R(L):t(L)}function B(L){return L===62?(s.consume(L),s.exit("htmlTextData"),s.exit("htmlText"),e):t(L)}function q(L){return s.exit("htmlTextData"),s.enter("lineEnding"),s.consume(L),s.exit("lineEnding"),Y}function Y(L){return $t(L)?Vt(s,z,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(L):z(L)}function z(L){return s.enter("htmlTextData"),r(L)}}const Vf={name:"labelEnd",resolveAll:aL,resolveTo:iL,tokenize:oL},tL={tokenize:rL},sL={tokenize:lL},nL={tokenize:cL};function aL(s){let e=-1;const t=[];for(;++e<s.length;){const n=s[e][1];if(t.push(s[e]),n.type==="labelImage"||n.type==="labelLink"||n.type==="labelEnd"){const i=n.type==="labelImage"?4:2;n.type="data",e+=i}}return s.length!==t.length&&Dn(s,0,s.length,t),s}function iL(s,e){let t=s.length,n=0,i,o,r,c;for(;t--;)if(i=s[t][1],o){if(i.type==="link"||i.type==="labelLink"&&i._inactive)break;s[t][0]==="enter"&&i.type==="labelLink"&&(i._inactive=!0)}else if(r){if(s[t][0]==="enter"&&(i.type==="labelImage"||i.type==="labelLink")&&!i._balanced&&(o=t,i.type!=="labelLink")){n=2;break}}else i.type==="labelEnd"&&(r=t);const u={type:s[o][1].type==="labelLink"?"link":"image",start:{...s[o][1].start},end:{...s[s.length-1][1].end}},h={type:"label",start:{...s[o][1].start},end:{...s[r][1].end}},m={type:"labelText",start:{...s[o+n+2][1].end},end:{...s[r-2][1].start}};return c=[["enter",u,e],["enter",h,e]],c=qn(c,s.slice(o+1,o+n+3)),c=qn(c,[["enter",m,e]]),c=qn(c,md(e.parser.constructs.insideSpan.null,s.slice(o+n+4,r-3),e)),c=qn(c,[["exit",m,e],s[r-2],s[r-1],["exit",h,e]]),c=qn(c,s.slice(r+1)),c=qn(c,[["exit",u,e]]),Dn(s,o,s.length,c),s}function oL(s,e,t){const n=this;let i=n.events.length,o,r;for(;i--;)if((n.events[i][1].type==="labelImage"||n.events[i][1].type==="labelLink")&&!n.events[i][1]._balanced){o=n.events[i][1];break}return c;function c(g){return o?o._inactive?f(g):(r=n.parser.defined.includes(la(n.sliceSerialize({start:o.end,end:n.now()}))),s.enter("labelEnd"),s.enter("labelMarker"),s.consume(g),s.exit("labelMarker"),s.exit("labelEnd"),u):t(g)}function u(g){return g===40?s.attempt(tL,m,r?m:f)(g):g===91?s.attempt(sL,m,r?h:f)(g):r?m(g):f(g)}function h(g){return s.attempt(nL,m,f)(g)}function m(g){return e(g)}function f(g){return o._balanced=!0,t(g)}}function rL(s,e,t){return n;function n(f){return s.enter("resource"),s.enter("resourceMarker"),s.consume(f),s.exit("resourceMarker"),i}function i(f){return hs(f)?Fl(s,o)(f):o(f)}function o(f){return f===41?m(f):lj(s,r,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(f)}function r(f){return hs(f)?Fl(s,u)(f):m(f)}function c(f){return t(f)}function u(f){return f===34||f===39||f===40?uj(s,h,t,"resourceTitle","resourceTitleMarker","resourceTitleString")(f):m(f)}function h(f){return hs(f)?Fl(s,m)(f):m(f)}function m(f){return f===41?(s.enter("resourceMarker"),s.consume(f),s.exit("resourceMarker"),s.exit("resource"),e):t(f)}}function lL(s,e,t){const n=this;return i;function i(c){return cj.call(n,s,o,r,"reference","referenceMarker","referenceString")(c)}function o(c){return n.parser.defined.includes(la(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?e(c):t(c)}function r(c){return t(c)}}function cL(s,e,t){return n;function n(o){return s.enter("reference"),s.enter("referenceMarker"),s.consume(o),s.exit("referenceMarker"),i}function i(o){return o===93?(s.enter("referenceMarker"),s.consume(o),s.exit("referenceMarker"),s.exit("reference"),e):t(o)}}const uL={name:"labelStartImage",resolveAll:Vf.resolveAll,tokenize:dL};function dL(s,e,t){const n=this;return i;function i(c){return s.enter("labelImage"),s.enter("labelImageMarker"),s.consume(c),s.exit("labelImageMarker"),o}function o(c){return c===91?(s.enter("labelMarker"),s.consume(c),s.exit("labelMarker"),s.exit("labelImage"),r):t(c)}function r(c){return c===94&&"_hiddenFootnoteSupport"in n.parser.constructs?t(c):e(c)}}const hL={name:"labelStartLink",resolveAll:Vf.resolveAll,tokenize:pL};function pL(s,e,t){const n=this;return i;function i(r){return s.enter("labelLink"),s.enter("labelMarker"),s.consume(r),s.exit("labelMarker"),s.exit("labelLink"),o}function o(r){return r===94&&"_hiddenFootnoteSupport"in n.parser.constructs?t(r):e(r)}}const Xp={name:"lineEnding",tokenize:mL};function mL(s,e){return t;function t(n){return s.enter("lineEnding"),s.consume(n),s.exit("lineEnding"),Vt(s,e,"linePrefix")}}const _u={name:"thematicBreak",tokenize:fL};function fL(s,e,t){let n=0,i;return o;function o(h){return s.enter("thematicBreak"),r(h)}function r(h){return i=h,c(h)}function c(h){return h===i?(s.enter("thematicBreakSequence"),u(h)):n>=3&&(h===null||gt(h))?(s.exit("thematicBreak"),e(h)):t(h)}function u(h){return h===i?(s.consume(h),n++,u):(s.exit("thematicBreakSequence"),$t(h)?Vt(s,c,"whitespace")(h):c(h))}}const bn={continuation:{tokenize:xL},exit:wL,name:"list",tokenize:yL},gL={partial:!0,tokenize:kL},bL={partial:!0,tokenize:vL};function yL(s,e,t){const n=this,i=n.events[n.events.length-1];let o=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0,r=0;return c;function c(b){const v=n.containerState.type||(b===42||b===43||b===45?"listUnordered":"listOrdered");if(v==="listUnordered"?!n.containerState.marker||b===n.containerState.marker:Xm(b)){if(n.containerState.type||(n.containerState.type=v,s.enter(v,{_container:!0})),v==="listUnordered")return s.enter("listItemPrefix"),b===42||b===45?s.check(_u,t,h)(b):h(b);if(!n.interrupt||b===49)return s.enter("listItemPrefix"),s.enter("listItemValue"),u(b)}return t(b)}function u(b){return Xm(b)&&++r<10?(s.consume(b),u):(!n.interrupt||r<2)&&(n.containerState.marker?b===n.containerState.marker:b===41||b===46)?(s.exit("listItemValue"),h(b)):t(b)}function h(b){return s.enter("listItemMarker"),s.consume(b),s.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||b,s.check(sc,n.interrupt?t:m,s.attempt(gL,g,f))}function m(b){return n.containerState.initialBlankLine=!0,o++,g(b)}function f(b){return $t(b)?(s.enter("listItemPrefixWhitespace"),s.consume(b),s.exit("listItemPrefixWhitespace"),g):t(b)}function g(b){return n.containerState.size=o+n.sliceSerialize(s.exit("listItemPrefix"),!0).length,e(b)}}function xL(s,e,t){const n=this;return n.containerState._closeFlow=void 0,s.check(sc,i,o);function i(c){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,Vt(s,e,"listItemIndent",n.containerState.size+1)(c)}function o(c){return n.containerState.furtherBlankLines||!$t(c)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,r(c)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,s.attempt(bL,e,r)(c))}function r(c){return n.containerState._closeFlow=!0,n.interrupt=void 0,Vt(s,s.attempt(bn,e,t),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function vL(s,e,t){const n=this;return Vt(s,i,"listItemIndent",n.containerState.size+1);function i(o){const r=n.events[n.events.length-1];return r&&r[1].type==="listItemIndent"&&r[2].sliceSerialize(r[1],!0).length===n.containerState.size?e(o):t(o)}}function wL(s){s.exit(this.containerState.type)}function kL(s,e,t){const n=this;return Vt(s,i,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function i(o){const r=n.events[n.events.length-1];return!$t(o)&&r&&r[1].type==="listItemPrefixWhitespace"?e(o):t(o)}}const E0={name:"setextUnderline",resolveTo:SL,tokenize:jL};function SL(s,e){let t=s.length,n,i,o;for(;t--;)if(s[t][0]==="enter"){if(s[t][1].type==="content"){n=t;break}s[t][1].type==="paragraph"&&(i=t)}else s[t][1].type==="content"&&s.splice(t,1),!o&&s[t][1].type==="definition"&&(o=t);const r={type:"setextHeading",start:{...s[n][1].start},end:{...s[s.length-1][1].end}};return s[i][1].type="setextHeadingText",o?(s.splice(i,0,["enter",r,e]),s.splice(o+1,0,["exit",s[n][1],e]),s[n][1].end={...s[o][1].end}):s[n][1]=r,s.push(["exit",r,e]),s}function jL(s,e,t){const n=this;let i;return o;function o(h){let m=n.events.length,f;for(;m--;)if(n.events[m][1].type!=="lineEnding"&&n.events[m][1].type!=="linePrefix"&&n.events[m][1].type!=="content"){f=n.events[m][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||f)?(s.enter("setextHeadingLine"),i=h,r(h)):t(h)}function r(h){return s.enter("setextHeadingLineSequence"),c(h)}function c(h){return h===i?(s.consume(h),c):(s.exit("setextHeadingLineSequence"),$t(h)?Vt(s,u,"lineSuffix")(h):u(h))}function u(h){return h===null||gt(h)?(s.exit("setextHeadingLine"),e(h)):t(h)}}const CL={tokenize:AL};function AL(s){const e=this,t=s.attempt(sc,n,s.attempt(this.parser.constructs.flowInitial,i,Vt(s,s.attempt(this.parser.constructs.flow,i,s.attempt(_R,i)),"linePrefix")));return t;function n(o){if(o===null){s.consume(o);return}return s.enter("lineEndingBlank"),s.consume(o),s.exit("lineEndingBlank"),e.currentConstruct=void 0,t}function i(o){if(o===null){s.consume(o);return}return s.enter("lineEnding"),s.consume(o),s.exit("lineEnding"),e.currentConstruct=void 0,t}}const NL={resolveAll:hj()},TL=dj("string"),ML=dj("text");function dj(s){return{resolveAll:hj(s==="text"?EL:void 0),tokenize:e};function e(t){const n=this,i=this.parser.constructs[s],o=t.attempt(i,r,c);return r;function r(m){return h(m)?o(m):c(m)}function c(m){if(m===null){t.consume(m);return}return t.enter("data"),t.consume(m),u}function u(m){return h(m)?(t.exit("data"),o(m)):(t.consume(m),u)}function h(m){if(m===null)return!0;const f=i[m];let g=-1;if(f)for(;++g<f.length;){const b=f[g];if(!b.previous||b.previous.call(n,n.previous))return!0}return!1}}}function hj(s){return e;function e(t,n){let i=-1,o;for(;++i<=t.length;)o===void 0?t[i]&&t[i][1].type==="data"&&(o=i,i++):(!t[i]||t[i][1].type!=="data")&&(i!==o+2&&(t[o][1].end=t[i-1][1].end,t.splice(o+2,i-o-2),i=o+2),o=void 0);return s?s(t,n):t}}function EL(s,e){let t=0;for(;++t<=s.length;)if((t===s.length||s[t][1].type==="lineEnding")&&s[t-1][1].type==="data"){const n=s[t-1][1],i=e.sliceStream(n);let o=i.length,r=-1,c=0,u;for(;o--;){const h=i[o];if(typeof h=="string"){for(r=h.length;h.charCodeAt(r-1)===32;)c++,r--;if(r)break;r=-1}else if(h===-2)u=!0,c++;else if(h!==-1){o++;break}}if(e._contentTypeTextTrailing&&t===s.length&&(c=0),c){const h={type:t===s.length||u||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?r:n.start._bufferIndex+r,_index:n.start._index+o,line:n.end.line,column:n.end.column-c,offset:n.end.offset-c},end:{...n.end}};n.end={...h.start},n.start.offset===n.end.offset?Object.assign(n,h):(s.splice(t,0,["enter",h,e],["exit",h,e]),t+=2)}t++}return s}const _L={42:bn,43:bn,45:bn,48:bn,49:bn,50:bn,51:bn,52:bn,53:bn,54:bn,55:bn,56:bn,57:bn,62:aj},DL={91:PR},RL={[-2]:Vp,[-1]:Vp,32:Vp},LL={35:HR,42:_u,45:[E0,_u],60:qR,61:E0,95:_u,96:T0,126:T0},BL={38:oj,92:ij},PL={[-5]:Xp,[-4]:Xp,[-3]:Xp,33:uL,38:oj,42:Ym,60:[hR,JR],91:hL,92:[FR,ij],93:Vf,95:Ym,96:CR},IL={null:[Ym,NL]},OL={null:[42,95]},zL={null:[]},FL=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:OL,contentInitial:DL,disable:zL,document:_L,flow:LL,flowInitial:RL,insideSpan:IL,string:BL,text:PL},Symbol.toStringTag,{value:"Module"}));function $L(s,e,t){let n={_bufferIndex:-1,_index:0,line:t&&t.line||1,column:t&&t.column||1,offset:t&&t.offset||0};const i={},o=[];let r=[],c=[];const u={attempt:F(M),check:F(E),consume:j,enter:A,exit:_,interrupt:F(E,{interrupt:!0})},h={code:null,containerState:{},defineSkip:w,events:[],now:v,parser:s,previous:null,sliceSerialize:g,sliceStream:b,write:f};let m=e.tokenize.call(h,u);return e.resolveAll&&o.push(e),h;function f(I){return r=qn(r,I),k(),r[r.length-1]!==null?[]:(T(e,0),h.events=md(o,h.events,h),h.events)}function g(I,O){return UL(b(I),O)}function b(I){return HL(r,I)}function v(){const{_bufferIndex:I,_index:O,line:X,column:W,offset:G}=n;return{_bufferIndex:I,_index:O,line:X,column:W,offset:G}}function w(I){i[I.line]=I.column,D()}function k(){let I;for(;n._index<r.length;){const O=r[n._index];if(typeof O=="string")for(I=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===I&&n._bufferIndex<O.length;)C(O.charCodeAt(n._bufferIndex));else C(O)}}function C(I){m=m(I)}function j(I){gt(I)?(n.line++,n.column=1,n.offset+=I===-3?2:1,D()):I!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===r[n._index].length&&(n._bufferIndex=-1,n._index++)),h.previous=I}function A(I,O){const X=O||{};return X.type=I,X.start=v(),h.events.push(["enter",X,h]),c.push(X),X}function _(I){const O=c.pop();return O.end=v(),h.events.push(["exit",O,h]),O}function M(I,O){T(I,O.from)}function E(I,O){O.restore()}function F(I,O){return X;function X(W,G,B){let q,Y,z,L;return Array.isArray(W)?V(W):"tokenize"in W?V([W]):Z(W);function Z(te){return ie;function ie(ne){const ce=ne!==null&&te[ne],de=ne!==null&&te.null,oe=[...Array.isArray(ce)?ce:ce?[ce]:[],...Array.isArray(de)?de:de?[de]:[]];return V(oe)(ne)}}function V(te){return q=te,Y=0,te.length===0?B:U(te[Y])}function U(te){return ie;function ie(ne){return L=R(),z=te,te.partial||(h.currentConstruct=te),te.name&&h.parser.constructs.disable.null.includes(te.name)?Q():te.tokenize.call(O?Object.assign(Object.create(h),O):h,u,H,Q)(ne)}}function H(te){return I(z,L),G}function Q(te){return L.restore(),++Y<q.length?U(q[Y]):B}}}function T(I,O){I.resolveAll&&!o.includes(I)&&o.push(I),I.resolve&&Dn(h.events,O,h.events.length-O,I.resolve(h.events.slice(O),h)),I.resolveTo&&(h.events=I.resolveTo(h.events,h))}function R(){const I=v(),O=h.previous,X=h.currentConstruct,W=h.events.length,G=Array.from(c);return{from:W,restore:B};function B(){n=I,h.previous=O,h.currentConstruct=X,h.events.length=W,c=G,D()}}function D(){n.line in i&&n.column<2&&(n.column=i[n.line],n.offset+=i[n.line]-1)}}function HL(s,e){const t=e.start._index,n=e.start._bufferIndex,i=e.end._index,o=e.end._bufferIndex;let r;if(t===i)r=[s[t].slice(n,o)];else{if(r=s.slice(t,i),n>-1){const c=r[0];typeof c=="string"?r[0]=c.slice(n):r.shift()}o>0&&r.push(s[i].slice(0,o))}return r}function UL(s,e){let t=-1;const n=[];let i;for(;++t<s.length;){const o=s[t];let r;if(typeof o=="string")r=o;else switch(o){case-5:{r="\r";break}case-4:{r=`
package/dist/index.html CHANGED
@@ -19,7 +19,7 @@
19
19
  <meta name="apple-mobile-web-app-title" content="Tide CMD" />
20
20
  <link rel="apple-touch-icon" href="/assets/icons/icon-192.png" />
21
21
  <title>Tide Commander</title>
22
- <script type="module" crossorigin src="/assets/main-7Sdu8iJR.js"></script>
22
+ <script type="module" crossorigin src="/assets/main-DxHjwMtl.js"></script>
23
23
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-uS-d4TUT.js">
24
24
  <link rel="modulepreload" crossorigin href="/assets/vendor-three-4iQNXcoo.js">
25
25
  <link rel="stylesheet" crossorigin href="/assets/main-BNzlLSuH.css">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tide-commander",
3
- "version": "0.61.4",
3
+ "version": "0.61.5",
4
4
  "description": "Visual multi-agent orchestrator and manager for Claude Code with 3D/2D interface",
5
5
  "type": "module",
6
6
  "bin": {