tide-commander 0.65.7 → 0.65.8
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.
|
@@ -146,7 +146,7 @@ Error generating stack: `+v.message+`
|
|
|
146
146
|
float h = normalize(vWorldPosition + offset).y;
|
|
147
147
|
gl_FragColor = vec4(mix(bottomColor, topColor, max(pow(max(h, 0.0), exponent), 0.0)), 1.0);
|
|
148
148
|
}
|
|
149
|
-
`,side:VA});a.add(new _e(i,o)),a.add(new Ky(16777215,1));const l=n.fromScene(a,.04).texture;t.environment=l,n.dispose(),i.dispose(),o.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?H.openFileExplorerForAreaFolder(e,t):H.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)=>H.updateBuildingPosition(e,t),onContextMenu:(e,t,n)=>this.callbackManager.triggerContextMenu(e,t,n),onActivity:()=>this.renderLoop.markActivity(),onToggleTerminal:()=>H.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 a=n.group.getObjectByName("characterBody");a&&this.proceduralBodiesCache.set(t,a)}this.proceduralBodiesDirty=!1}this.proceduralBodiesCache.size>0&&this.proceduralAnimator.update(e,this.proceduralBodiesCache)}updateIndicatorScales(e,t,n){for(const[,a]of t){const i=e.position.distanceTo(a.group.position),o=Math.max(.5,Math.min(2.5,i/15))*n,l=a.group.userData.isBoss===!0,c=a.group.getObjectByName("statusBar"),d=a.group.getObjectByName("nameLabelSprite");if(c){const p=typeof c.userData.baseIndicatorScale=="number"?c.userData.baseIndicatorScale:l?2:1.6,g=typeof c.userData.aspectRatio=="number"?c.userData.aspectRatio:2560/4096;c.scale.set(p*o,p*g*o,1)}if(d){const p=typeof d.userData.baseIndicatorScale=="number"?d.userData.baseIndicatorScale:l?1.5:1.25,y=Math.max(l?1.35:1.1,Math.min(l?1.65:1.35,p)),w=typeof d.userData.aspectRatio=="number"?d.userData.aspectRatio:1024/4096;d.scale.set(y*o,y*w*o,1)}const f=a.group.getObjectByName("combinedUI");if(f){const p=typeof f.userData.baseIndicatorScale=="number"?f.userData.baseIndicatorScale:l?3:2.4,g=typeof f.userData.aspectRatio=="number"?f.userData.aspectRatio:1024/2048;f.scale.set(p*o,p*g*o,1)}if(!c&&!f){const p=a.group.getObjectByName("nameLabel");if(p){const y=.3*o;p.scale.set(y*(p.userData.aspectRatio||2),y,1)}const g=a.group.getObjectByName("manaBar");g&&g.scale.set(.9,.14,1);const b=a.group.getObjectByName("idleTimer");b&&b.scale.set(.9*o,.14*o,1)}}for(const[,a]of this.buildingManager.getBuildingMeshData()){const i=e.position.distanceTo(a.group.position),o=Math.max(.5,Math.min(2.5,i/15))*n,l=a.group.getObjectByName("buildingLabel");if(l){const c=.3*o;l.scale.set(c*(l.userData.aspectRatio||2),c,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,a){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.addSubagentEffect(e,t,n,a)}completeSubagentEffect(e){this.effectsManager.completeSubagentEffect(e)}removeSubagentEffect(e){this.effectsManager.removeSubagentEffect(e)}focusAgent(e){this.cameraManager.focusAgent(e)}callSubordinates(e){var o;const n=H.getState().agents.get(e);if(!n||!(n.isBoss||n.class==="boss")||!((o=n.subordinateIds)!=null&&o.length))return;const a=new bt(n.position.x,n.position.y,n.position.z),i=this.inputHandler.calculateFormationPositions(a,n.subordinateIds.length);this.effectsManager.createMoveOrderEffect(a.clone()),n.subordinateIds.forEach((l,c)=>{const d=this.agentManager.getAgentMeshes().get(l);H.moveAgent(l,i[c]),d&&this.movementAnimator.startMovement(l,d,i[c])})}setDrawingTool(e){this.drawingManager.setTool(e),H.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 i,o;console.log("[SceneManager] Reattaching to new canvas (HMR)"),this.isReattaching=!0,this.renderLoop.stop(),(i=this.resizeObserver)==null||i.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&&((o=this.resizeObserver)==null||o.observe(e.parentElement)),this.onWindowResize();const a=(l=0)=>{this.isReattaching=!1,e.isConnected&&this.sceneCore.getRenderer()?(console.log("[SceneManager] Restarting animation loop after HMR reattach"),this.renderLoop.start()):l<10?(console.log(`[SceneManager] Canvas not connected, retrying... (attempt ${l+1})`),this.isReattaching=!0,requestAnimationFrame(()=>a(l+1))):console.warn("[SceneManager] Failed to restart animation loop - canvas never connected")};requestAnimationFrame(()=>a())}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:ql.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 vp="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 Jp(){return typeof window<"u"?window.__tidePersistedScene??null:null}function ON(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function TI(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function ed(s){typeof window<"u"&&(window.__tidePersistedScene=s)}function wp(s){typeof window<"u"&&(window.__tidePersistedCanvas=s)}function IN(s){typeof window<"u"&&(window.__tideWsConnected=s)}function EI(s){typeof window<"u"&&(window.__tideIsPageUnloading=s)}function _I(){sessionStorage.setItem(vp,"true")}function Ph(s){EI(!0),sessionStorage.removeItem(vp),jN(),jP(),window.__tideScene&&(window.__tideScene=null);const e=Jp();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),ed(null)):console.log("[App] No persistedScene to dispose"),wp(null),IN(!1);const t=document.getElementById("battlefield");t&&t.remove();const n=document.getElementById("app");n&&(n.innerHTML="")}function DI(){var a,i;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(vp)==="true"&&console.log("[App] Detected unclean shutdown from previous session - forcing cleanup"),window.__tideScene){console.log("[App] Cleaning up stale __tideScene reference");try{(i=(a=window.__tideScene).dispose)==null||i.call(a)}catch{}window.__tideScene=null}const e=Jp();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}ed(null)}const t=document.getElementById("battlefield"),n=ON();t&&t!==n&&t.remove(),sessionStorage.removeItem(vp)}function RI(){typeof window>"u"||(DI(),window.addEventListener("pageshow",s=>{s.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),Ph(),window.location.reload())}),window.onunload=()=>Ph(),window.onbeforeunload=s=>{Ph()},window.addEventListener("pagehide",s=>{Ph(`pagehide (persisted=${s.persisted})`)}))}RI();const oj={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"concrete",brightness:1,skyColor:null},lj={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},cj={idleAnimation:"sit",workingAnimation:"sprint"},PI=0;function BN(){const s={characterScale:2,indicatorScale:1,gridVisible:!0,timeMode:"day",terrain:oj,modelStyle:lj,animations:cj,fpsLimit:PI},e=xi(xt.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:{...oj,...e.terrain},modelStyle:{...lj,...e.modelStyle},animations:{...cj,...e.animations},fpsLimit:e.fpsLimit??s.fpsLimit}:s}function LI(s){Qi(xt.CONFIG,s)}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function zN(){console.log("[Tide HMR] Manual scene refresh triggered");const s=Jp();if(s){try{s.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}ed(null)}wp(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=zN);function OI({canvasRef:s,selectionBoxRef:e,showToast:t,showAgentNotification:n,toolboxModal:a,contextMenu:i,setHoveredAgentPopup:o,setBuildingPopup:l,getBuildingPopup:c,openBuildingModal:d,openPM2LogsModal:f,openBossLogsModal:p,openDatabasePanel:g}){const b=x.useRef(null),y=x.useRef(null),w=x.useRef(null);return x.useEffect(()=>{if(!s.current||!e.current)return;let k=!1;const S=Jp(),C=ON()===s.current;function N(){var D,E,$,M,R,_,P,O;(D=b.current)==null||D.setOnToast(t),(E=b.current)==null||E.setOnBuildingClick((F,B)=>{H.selectBuilding(F);const I=H.getState().buildings.get(F);(I==null?void 0:I.type)==="folder"&&I.folderPath?H.openFileExplorer(I.folderPath):(I==null?void 0:I.type)==="server"||(I==null?void 0:I.type)==="boss"||(I==null?void 0:I.type)==="database"?(y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{l({buildingId:F,screenPos:B,fromClick:!0}),y.current=null},150)):d(F)}),($=b.current)==null||$.setOnContextMenu((F,B,I)=>{i.open(F,B,I)}),(M=b.current)==null||M.setOnAgentHover(()=>{}),(R=b.current)==null||R.setOnBuildingHover((F,B)=>{const I=c();if(F&&B){const U=H.getState().buildings.get(F);((U==null?void 0:U.type)==="server"||(U==null?void 0:U.type)==="boss"||(U==null?void 0:U.type)==="database")&&!(I!=null&&I.fromClick)&&l({buildingId:F,screenPos:B,fromClick:!1})}else I!=null&&I.fromClick||l(null)}),(_=b.current)==null||_.setOnGroundClick(()=>{l(null)}),(P=b.current)==null||P.setOnAreaDoubleClick(F=>{H.selectArea(F),a.open()}),(O=b.current)==null||O.setOnBuildingDoubleClick(F=>{var I;y.current&&(clearTimeout(y.current),y.current=null),l(null);const B=H.getState().buildings.get(F);(B==null?void 0:B.type)==="server"&&((I=B.pm2)!=null&&I.enabled)?f==null||f(F):(B==null?void 0:B.type)==="boss"?p==null||p(F):(B==null?void 0:B.type)==="database"?g==null||g(F):(B==null?void 0:B.type)==="folder"&&B.folderPath?H.openFileExplorer(B.folderPath):d(F)})}if(S&&C){b.current=S,console.log("[Tide] Reusing existing scene (StrictMode remount)");const D=H.getState();S.syncAreas(),S.syncBuildings(),D.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",D.agents.size),S.syncAgents(Array.from(D.agents.values()))),N()}else{const D=s.current,E=e.current,$=()=>{if(k){console.log("[Tide] Effect cleaned up before scene init, skipping");return}if(!D.isConnected||!E.isConnected){console.warn("[Tide] Canvas disconnected before initialization");return}(!D.clientWidth||!D.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),D.style.width="100%",D.style.height="100%",D.offsetHeight),(!D.clientWidth||!D.clientHeight)&&(D.width=window.innerWidth,D.height=window.innerHeight),_I();try{const M=new MI(D,E);b.current=M,ed(M),wp(D);const R=BN();M.setCharacterScale(R.characterScale),M.setIndicatorScale(R.indicatorScale),M.setGridVisible(R.gridVisible),M.setTimeMode(R.timeMode),M.setTerrainConfig(R.terrain),M.setFloorStyle(R.terrain.floorStyle,!0),M.setAgentModelStyle(R.modelStyle),M.setIdleAnimation(R.animations.idleAnimation),M.setWorkingAnimation(R.animations.workingAnimation),M.setFpsLimit(R.fpsLimit),M.syncAreas(),M.syncBuildings(),M.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const _=H.getState();_.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",_.customAgentClasses.size),M.setCustomAgentClasses(_.customAgentClasses)),_.agents.size>0&&(console.log("[Tide] Syncing agents from store:",_.agents.size),M.syncAgents(Array.from(_.agents.values()))),M.upgradeAgentModels()}).catch(_=>{console.warn("[Tide] Some models failed to load, using fallback:",_)}),N()}catch(M){console.error("[Tide] Failed to initialize 3D scene:",M)}};w.current=requestAnimationFrame($)}return wN({onAgentCreated:D=>{var E,$;(E=b.current)==null||E.addAgent(D),($=window.__spawnModalSuccess)==null||$.call(window)},onAgentUpdated:(D,E)=>{var $;($=b.current)==null||$.updateAgent(D,E)},onAgentDeleted:D=>{var E;(E=b.current)==null||E.removeAgent(D)},onAgentsSync:D=>{var E;(E=b.current)==null||E.syncAgents(D)},onAreasSync:()=>{var E,$;(E=b.current)==null||E.syncAreas();const D=Array.from(H.getState().agents.values());($=b.current)==null||$.syncAgents(D)},onSpawnError:()=>{var D;(D=window.__spawnModalError)==null||D.call(window)},onSpawnSuccess:()=>{var D;(D=window.__spawnModalSuccess)==null||D.call(window)},onDirectoryNotFound:D=>{var E;(E=window.__spawnModalDirNotFound)==null||E.call(window,D)},onToolUse:(D,E,$)=>{var M;(M=b.current)==null||M.showToolBubble(D,E,$)},onDelegation:(D,E)=>{var $;($=b.current)==null||$.showDelegationEffect(D,E)},onCustomClassesSync:D=>{var E,$;(E=b.current)==null||E.setCustomAgentClasses(D),($=b.current)==null||$.upgradeAgentModels()},onBuildingUpdated:D=>{var E;(E=b.current)==null||E.updateBuilding(D)},onSubagentStarted:D=>{var E;(E=b.current)==null||E.addSubagentEffect(D.id,D.parentAgentId,D.name,D.subagentType)},onSubagentCompleted:D=>{var M;const E=H.getSubagent(D)||H.getSubagentByToolUseId(D),$=(E==null?void 0:E.id)||D;(M=b.current)==null||M.completeSubagentEffect($),setTimeout(()=>{var R;(R=b.current)==null||R.removeSubagentEffect($)},3e4)}}),()=>{var D;k=!0,w.current!==null&&(cancelAnimationFrame(w.current),w.current=null),!((D=s.current)!=null&&D.isConnected)&&b.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),CP(),b.current.dispose(),b.current=null,ed(null),wp(null))}},[s.current,e.current]),b}let td,Yl;try{td=require("@capacitor/local-notifications").LocalNotifications,Yl=require("@capacitor/core").Capacitor}catch{}let II=1;const BI="agent_alerts",FN="tide-notification-tap";function zI(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function $N(s){if(zI()){H.openTerminalOnMobile(s);return}H.selectAgent(s),H.setTerminalOpen(!0)}function ix(){var s;return((s=Yl==null?void 0:Yl.isNativePlatform)==null?void 0:s.call(Yl))??!1}async function FI(){return ix()?(await td.requestPermissions()).display==="granted":"Notification"in window?await Notification.requestPermission()==="granted":!1}async function $I(s){const{title:e,body:t,icon:n,data:a}=s;if(ix())await td.schedule({notifications:[{id:II++,title:e,body:t,schedule:{at:new Date(Date.now()+100)},extra:a,channelId:BI,smallIcon:"ic_launcher",autoCancel:!0}]});else if("Notification"in window&&Notification.permission==="granted"){const i=new Notification(e,{body:t,icon:n,data:a});i.onclick=()=>{window.focus(),a&&window.dispatchEvent(new CustomEvent(FN,{detail:a}))}}}async function HI(s){s&&window.addEventListener(FN,e=>{const t=e;t.detail&&s(t.detail)}),ix()&&td&&await td.addListener("localNotificationActionPerformed",e=>{s&&e.notification.extra&&s(e.notification.extra)})}function UI({showToast:s,showAgentNotification:e}){const t=x.useRef(!1);x.useEffect(()=>{if(t.current||TI())return;t.current=!0,wN({onToast:s,onReconnect:()=>{H.triggerReconnect()},onAgentNotification:a=>{e(a)}}),Ju(),IN(!0),FI(),HI(a=>{a.type==="agent_notification"&&typeof a.agentId=="string"&&$N(a.agentId)});const n=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>Ju(),100)};return window.addEventListener("tideAppResume",n),()=>{window.removeEventListener("tideAppResume",n)}},[s,e])}function GI(s){x.useEffect(()=>{let e="",t="",n=new Map;const a=i=>{var c;let o=!1;const l=new Map;for(const[d,f]of i){const g=`${f.position.x.toFixed(2)},${f.position.z.toFixed(2)},${f.status},${f.class},${f.isBoss},${((c=f.subordinateIds)==null?void 0:c.length)??0}`.split("").reduce((b,y)=>(b<<5)-b+y.charCodeAt(0),0);l.set(d,g),n.get(d)!==g&&(o=!0)}return l.size!==n.size&&(o=!0),{newVersion:l,changed:o}};return H.subscribe(()=>{var g;const i=H.getState(),o=Array.from(i.selectedAgentIds).sort().join(","),l=Array.from(i.selectedBuildingIds).sort().join(","),c=o!==e,d=l!==t,{newVersion:f,changed:p}=a(i.agents);(c||d||p)&&(e=o,t=l,n=f,(g=s.current)==null||g.refreshSelectionVisuals())})},[s])}function WI(s){x.useEffect(()=>{var n;(n=s.current)==null||n.syncAreas();let e=0,t=0;return H.subscribe(()=>{var l,c;const i=H.getState().areas;if(i.size!==e){e=i.size,t=Date.now(),(l=s.current)==null||l.syncAreas();return}let o=0;for(const[d,f]of i){let p=d.charCodeAt(0);p+=(f.width??0)+(f.height??0)+(f.radius??0),p+=Math.floor(f.center.x*100)+Math.floor(f.center.z*100),p+=(f.zIndex??0)*1e3;for(let g=0;g<f.name.length;g++)p+=f.name.charCodeAt(g);for(let g=0;g<f.color.length;g++)p+=f.color.charCodeAt(g);if(f.directoryGitCounts)for(const g of f.directoryGitCounts)p+=(g+1)*7;o^=p|0}o!==t&&(t=o,(c=s.current)==null||c.syncAreas())})},[s])}function qI(s){x.useEffect(()=>{var n;(n=s.current)==null||n.syncBuildings();let e=0,t=0;return H.subscribe(()=>{var l,c;const i=H.getState().buildings;if(i.size!==e){e=i.size,t=Date.now(),(l=s.current)==null||l.syncBuildings();return}let o=0;for(const[d,f]of i){o^=f.position.x*1e3+f.position.z|0,o^=(f.scale||1)*1e4|0;const p=`${f.style||""}${f.name}${f.status}${f.gitChangesCount||0}`;for(let g=0;g<p.length;g++)o=(o<<5)-o+p.charCodeAt(g)|0}o!==t&&(t=o,(c=s.current)==null||c.syncBuildings())})},[s])}function YI(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.highlightArea(e)},[s,e])}function VI(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.setPowerSaving(e)},[s,e])}function KI({sceneRef:s,spawnModal:e,commanderModal:t,explorerModal:n,spotlightModal:a,deleteConfirmModal:i,onRequestBuildingDelete:o,onOpenDatabasePanel:l,onCloseDatabasePanel:c,databasePanelOpen:d}){x.useEffect(()=>{const f=p=>{var _,P,O,F;const g=H.getShortcuts(),b=p.target,y=b.tagName==="INPUT"||b.tagName==="TEXTAREA",w=g.find(B=>B.id==="deselect-all");if(vt(p,w)){if(ey()){p.preventDefault();return}const B=H.getState();if(B.activeTool==="rectangle"||B.activeTool==="circle"){(_=s.current)==null||_.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():B.terminalOpen?(H.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(H.deselectAll(),(P=s.current)==null||P.refreshSelectionVisuals())}for(let B=1;B<=9;B++){const I=g.find(U=>U.id===`select-agent-${B}`);if(vt(p,I)){p.preventDefault();const U=H.getState(),q=B-1,K=Array.from(U.agents.keys());q<K.length&&(H.selectAgent(K[q]),(O=s.current)==null||O.refreshSelectionVisuals());return}}const k=g.find(B=>B.id==="spawn-agent");if(vt(p,k)){p.preventDefault(),e.open();return}const S=g.find(B=>B.id==="toggle-commander-tab");if(vt(p,S)&&!y){p.preventDefault(),t.toggle();return}const j=g.find(B=>B.id==="toggle-commander");if(vt(p,j)){p.preventDefault(),t.toggle();return}const C=g.find(B=>B.id==="toggle-file-explorer");if(vt(p,C)){p.preventDefault();const B=H.getState();if(n.isOpen||B.explorerFolderPath!==null||B.explorerAreaId!==null)n.close(),H.closeFileExplorer();else{const U=H.getLastExplorerState();if((U==null?void 0:U.type)==="folder")H.openFileExplorer(U.path);else if((U==null?void 0:U.type)==="area")if(B.areas.has(U.areaId))n.open(U.areaId);else{const q=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);q.length>0&&n.open(q[0].id)}else{const q=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);q.length>0&&n.open(q[0].id)}}return}if(p.altKey&&!p.ctrlKey&&!p.shiftKey&&!p.metaKey&&p.code==="KeyD"){if(p.preventDefault(),p.stopPropagation(),d){c();return}const B=localStorage.getItem("tide-commander-last-database-building"),I=H.getState();if(B){const U=I.buildings.get(B);if((U==null?void 0:U.type)==="database"){l(B);return}}for(const[U,q]of I.buildings)if(q.type==="database"){l(U);return}return}const N=g.find(B=>B.id==="toggle-spotlight");if(vt(p,N)||p.altKey&&!p.ctrlKey&&!p.metaKey&&p.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:N,altKey:p.altKey,code:p.code}),p.preventDefault(),a.toggle();return}const D=g.find(B=>B.id==="toggle-2d-view");if(vt(p,D)){p.preventDefault();const B=H.getState().viewMode,I=B==="3d"?"2d":B==="2d"?"dashboard":"3d";H.setViewMode(I);return}const E=g.find(B=>B.id==="next-working-agent"),$=g.find(B=>B.id==="prev-working-agent");if((vt(p,E)||vt(p,$))&&!y){const B=H.getState();if(B.terminalOpen)return;const U=Array.from(B.agents.values()).filter(L=>L.status==="working");if(U.length===0)return;p.preventDefault();const q=B.selectedAgentIds.size===1?Array.from(B.selectedAgentIds)[0]:null,K=q?U.findIndex(L=>L.id===q):-1;let X;vt(p,E)?X=K===-1?0:(K+1)%U.length:X=K===-1?U.length-1:(K-1+U.length)%U.length,H.selectAgent(U[X].id),(F=s.current)==null||F.refreshSelectionVisuals();return}const M=g.find(B=>B.id==="delete-selected"),R=g.find(B=>B.id==="delete-selected-backspace");if((vt(p,M)||vt(p,R))&&!y){const B=H.getState();if(B.selectedAgentIds.size>0){p.preventDefault(),i.open();return}if(B.selectedBuildingIds.size>0){p.preventDefault(),o();return}return}};return document.addEventListener("keydown",f,!0),()=>document.removeEventListener("keydown",f,!0)},[s,e,t,n,a,i,o,l,c,d])}function XI(){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 a=()=>{var o;window.innerWidth>768||window.location.hash.includes("app")||(window.location.hash="#app",ey()||(o=window.__tideSetBackNavModal)==null||o.call(window,!0))},i=()=>{var o;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),ey()||(o=window.__tideSetBackNavModal)==null||o.call(window,!0))};window.history.pushState(null,"","#app1"),window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"),window.addEventListener("hashchange",a),window.addEventListener("popstate",i)},[]),{showBackNavModal:s,setShowBackNavModal:e,handleLeave:()=>{e(!1);const n=window.__tideHistoryDepth??2;window.history.go(-(n+1))}}}const Kg="agent-order-change";function HN(s){const e=x.useMemo(()=>new Set(s.map(c=>c.id)),[s]),[t,n]=x.useState(()=>xi(xt.AGENT_ORDER,[]));x.useEffect(()=>{const c=d=>{n(d.detail)};return window.addEventListener(Kg,c),()=>{window.removeEventListener(Kg,c)}},[]);const a=x.useMemo(()=>{const c=t.filter(g=>e.has(g)),d=s.filter(g=>!c.includes(g.id)).map(g=>g.id),f=[...c,...d],p=new Map(s.map(g=>[g.id,g]));return f.map(g=>p.get(g)).filter(g=>g!==void 0)},[s,t,e]),i=x.useCallback(c=>{n(c),Qi(xt.AGENT_ORDER,c),window.dispatchEvent(new CustomEvent(Kg,{detail:c}))},[]),o=x.useCallback((c,d)=>{const f=a.map(g=>g.id),[p]=f.splice(c,1);f.splice(d,0,p),i(f)},[a,i]),l=x.useCallback(()=>{n([]),Qi(xt.AGENT_ORDER,[])},[]);return x.useEffect(()=>{if(e.size===0)return;const c=t.filter(d=>e.has(d));c.length!==t.length&&i(c)},[e,t,i]),{orderedAgents:a,moveAgent:o,resetOrder:l}}let li,py;try{li=require("@capacitor/core").Capacitor,py=require("@capacitor/core").CapacitorHttp}catch{}const rx="deivid11/tide-commander",ZI=`https://api.github.com/repos/${rx}/releases/latest`,QI=`https://api.github.com/repos/${rx}/releases?per_page=3`,JI=3600*1e3,uj="app_update_dismissed_version",dj="0.65.7";function eB(){var f;const[s,e]=x.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:dj}),t=((f=li==null?void 0:li.getPlatform)==null?void 0:f.call(li))==="android"||!1,n=p=>p.replace(/^v/,"").split(".").map(b=>parseInt(b,10)||0),a=(p,g)=>{const b=n(p),y=n(g),w=Math.max(b.length,y.length);for(let k=0;k<w;k++){const S=b[k]||0,j=y[k]||0;if(S>j)return 1;if(S<j)return-1}return 0},i=async p=>{var b;if(li&&py&&((b=li.isNativePlatform)==null?void 0:b.call(li))===!0){const y=await py.get({url:p,headers:{Accept:"application/vnd.github.v3+json"}});return{data:y.data,status:y.status}}else{const y=await fetch(p,{headers:{Accept:"application/vnd.github.v3+json"}});return y.ok?{data:await y.json(),status:y.status}:{data:null,status:y.status}}},o=x.useCallback(async(p=!1)=>{e(g=>({...g,isChecking:!0,error:null}));try{const[g,b]=await Promise.all([i(ZI),i(QI)]);if(g.status!==200)throw new Error(`GitHub API error: ${g.status}`);const y=g.data,w=y.tag_name;let k=[];b.status===200&&b.data&&(k=b.data.map(D=>({version:D.tag_name,name:D.name,publishedAt:D.published_at,releaseUrl:D.html_url})));const S=localStorage.getItem(uj);if(!p&&S===w)return e(D=>({...D,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;if(!(a(w,dj)>0))return e(D=>({...D,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;const C=y.assets.find(D=>D.name.endsWith(".apk")&&D.content_type==="application/vnd.android.package-archive"),N={version:w,name:y.name,changelog:y.body,releaseUrl:y.html_url,apkUrl:(C==null?void 0:C.browser_download_url)||null,apkSize:(C==null?void 0:C.size)||null,publishedAt:y.published_at};return e(D=>({...D,isChecking:!1,updateAvailable:!0,updateInfo:N,recentReleases:k})),N}catch(g){const b=g instanceof Error?g.message:"Failed to check for updates";return e(y=>({...y,isChecking:!1,error:b})),null}},[]),l=x.useCallback(async()=>{var p,g,b;if(!((p=s.updateInfo)!=null&&p.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(y=>({...y,error:null}))}catch(y){const w=y instanceof Error?y.message:"Failed to open download";e(k=>({...k,error:w}))}},[s.updateInfo,t]),c=x.useCallback(()=>{s.updateInfo&&localStorage.setItem(uj,s.updateInfo.version),e(p=>({...p,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),d=x.useCallback(()=>{var p;(p=s.updateInfo)!=null&&p.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${rx}/releases`,"_blank")},[s.updateInfo]);return x.useEffect(()=>{if(!t)return;const p=setTimeout(()=>{o()},5e3),g=setInterval(()=>{o()},JI);return()=>{clearTimeout(p),clearInterval(g)}},[t,o]),{...s,isAndroid:t,checkForUpdate:o,downloadAndInstall:l,dismissUpdate:c,openReleasePage:d}}function js(s){const e=x.useRef(null),t=x.useCallback(a=>{e.current=a.target,a.target===a.currentTarget&&a.stopPropagation()},[]),n=x.useCallback(a=>{a.target===a.currentTarget&&e.current===a.currentTarget&&(a.stopPropagation(),s()),e.current=null},[s]);return{handleMouseDown:t,handleClick:n}}const tB=3e4;function nB(){const s=x.useRef(null);x.useEffect(()=>{const e=async()=>{var o,l;const t=H.getState(),n=new Map,a=new Map;for(const[c,d]of t.buildings){const f=d.folderPath||d.cwd;f&&(a.has(f)||a.set(f,[]),a.get(f).push(c))}for(const[c,d]of a)try{const f=await ft(st(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!f.ok)continue;const g=((o=(await f.json()).files)==null?void 0:o.length)||0;n.set(c,g);for(const b of d){const y=H.getState().buildings.get(b);y&&y.gitChangesCount!==g&&H.updateBuildingLocal(b,{gitChangesCount:g})}}catch{}const i=new Map;for(const[c,d]of t.areas)d.archived||!d.directories||d.directories.forEach((f,p)=>{f&&(i.has(f)||i.set(f,[]),i.get(f).push({areaId:c,dirIndex:p}))});if(i.size!==0)for(const[c,d]of i)try{let f;if(n.has(c))f=n.get(c);else{const g=await ft(st(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!g.ok)continue;f=((l=(await g.json()).files)==null?void 0:l.length)||0,n.set(c,f)}const p=new Map;for(const g of d)p.has(g.areaId)||p.set(g.areaId,[]),p.get(g.areaId).push({dirIndex:g.dirIndex,count:f});for(const[g,b]of p){const y=H.getState().areas.get(g);if(!y)continue;const w=y.directoryGitCounts?[...y.directoryGitCounts]:new Array(y.directories.length).fill(0);let k=!1;for(const{dirIndex:S,count:j}of b)w[S]!==j&&(w[S]=j,k=!0);k&&H.updateAreaLocal(g,{directoryGitCounts:w})}}catch{}};return e(),s.current=setInterval(e,tB),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[])}const hj={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,externalEditorCommand:""};function sB(s,e,t,n){return{setAgents(a){const i=new Map;for(const l of a)i.set(l.id,l),(l.class==="boss"||l.isBoss)&&console.log("[Store.setAgents] Boss agent:",l.name,"subordinateIds:",l.subordinateIds);const o=a.find(l=>l.status==="working");e(l=>{l.agents=i,o&&l.selectedAgentIds.size===0&&(l.selectedAgentIds.add(o.id),l.terminalOpen=!0)}),t()},addAgent(a){e(i=>{const o=new Map(i.agents);o.set(a.id,a),i.agents=o}),t()},updateAgent(a){var c;const o=s().agents.get(a.id),l=(o==null?void 0:o.status)!==a.status;l&&console.log(`[Store] Agent ${a.name} status update: ${o==null?void 0:o.status} → ${a.status}`),e(d=>{const f=new Map(d.agents);f.set(a.id,a),d.agents=f}),t(),l&&console.log(`[Store] Agent ${a.name} status now in store: ${(c=s().agents.get(a.id))==null?void 0:c.status}`)},updateAgentContextStats(a,i){const l=s().agents.get(a);l&&(e(c=>{const d=new Map(c.agents);d.set(a,{...l,contextStats:i,contextUsed:i.totalTokens,contextLimit:i.contextWindow}),c.agents=d}),t())},removeAgent(a){e(i=>{const o=new Map(i.agents);o.delete(a),i.agents=o,i.selectedAgentIds.delete(a),i.agentOutputs.delete(a)}),t()},selectAgent(a){e(i=>{i.selectedAgentIds.clear(),a&&(i.selectedAgentIds.add(a),i.lastSelectedAgentId=a),i.currentSnapshot=null}),t()},addToSelection(a){e(i=>{i.selectedAgentIds.has(a)?i.selectedAgentIds.delete(a):i.selectedAgentIds.add(a)}),t()},selectMultiple(a){e(i=>{i.selectedAgentIds.clear();for(const o of a)i.selectedAgentIds.add(o)}),t()},deselectAll(){e(a=>{a.selectedAgentIds.clear()}),t()},spawnAgent(a,i,o,l,c,d,f,p,g,b,y,w,k){console.log("[Store] spawnAgent called with:",{name:a,agentClass:i,cwd:o,position:l,sessionId:c,useChrome:d,permissionMode:f,initialSkillIds:p,provider:g,codexConfig:b,codexModel:y,model:w,customInstructions:k?`${k.length} chars`:void 0});const S=l?{x:l.x,y:0,z:l.z}:void 0,j={type:"spawn_agent",payload:{name:a,class:i,cwd:o,position:S,sessionId:c,useChrome:d,permissionMode:f,initialSkillIds:p,provider:g,codexConfig:b,codexModel:y,model:w,customInstructions:k}},C=n();if(!C){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}C(j),console.log("[Store] Message sent to WebSocket")},createDirectoryAndSpawn(a,i,o){var l;(l=n())==null||l({type:"create_directory",payload:{path:a,name:i,class:o}})},sendCommand(a,i){var o;e(l=>{l.lastPrompts.set(a,{text:i,timestamp:Date.now()})}),t(),(o=n())==null||o({type:"send_command",payload:{agentId:a,command:i}})},refreshAgentContext(a){var i;(i=n())==null||i({type:"request_context_stats",payload:{agentId:a}})},moveAgentLocal(a,i){const l=s().agents.get(a);l&&(e(c=>{const d={...l,position:i},f=new Map(c.agents);f.set(a,d),c.agents=f}),t())},moveAgent(a,i){var c;const l=s().agents.get(a);l&&(e(d=>{const f={...l,position:i},p=new Map(d.agents);p.set(a,f),d.agents=p}),t()),(c=n())==null||c({type:"move_agent",payload:{agentId:a,position:i}})},killAgent(a){var i;(i=n())==null||i({type:"kill_agent",payload:{agentId:a}})},stopAgent(a){var i;(i=n())==null||i({type:"stop_agent",payload:{agentId:a}})},clearContext(a){var i;(i=n())==null||i({type:"clear_context",payload:{agentId:a}}),e(o=>{const l=new Map(o.agentOutputs);l.delete(a),o.agentOutputs=l}),t()},collapseContext(a){var i;(i=n())==null||i({type:"collapse_context",payload:{agentId:a}})},removeAgentFromServer(a){var i;(i=n())==null||i({type:"remove_agent",payload:{agentId:a}})},renameAgent(a,i){var c;const l=s().agents.get(a);l&&(e(d=>{const f={...l,name:i},p=new Map(d.agents);p.set(a,f),d.agents=p}),t()),(c=n())==null||c({type:"rename_agent",payload:{agentId:a,name:i}})},updateAgentProperties(a,i){var c;const l=s().agents.get(a);l&&(e(d=>{const f={...l};i.class!==void 0&&(f.class=i.class),i.permissionMode!==void 0&&(f.permissionMode=i.permissionMode),i.model!==void 0&&(f.model=i.model),i.provider!==void 0&&(f.provider=i.provider),i.codexConfig!==void 0&&(f.codexConfig=i.codexConfig),i.codexModel!==void 0&&(f.codexModel=i.codexModel),i.useChrome!==void 0&&(f.useChrome=i.useChrome),i.cwd!==void 0&&(f.cwd=i.cwd);const p=new Map(d.agents);p.set(a,f),d.agents=p}),t()),(c=n())==null||c({type:"update_agent_properties",payload:{agentId:a,updates:i}})},getTotalTokens(){let a=0;for(const i of s().agents.values())a+=i.tokensUsed;return a},getSelectedAgents(){const a=s(),i=[];for(const o of a.selectedAgentIds){const l=a.agents.get(o);l&&i.push(l)}return i},addActivity(a){e(i=>{i.activities.unshift(a),i.activities.length>100&&i.activities.pop()}),t()},addToolExecution(a,i,o){const c=s().agents.get(a);e(d=>{d.toolExecutions.unshift({agentId:a,agentName:(c==null?void 0:c.name)||"Unknown",toolName:i,toolInput:o,timestamp:Date.now()}),d.toolExecutions.length>200&&d.toolExecutions.pop()}),t()},addFileChange(a,i,o){const c=s().agents.get(a);e(d=>{d.fileChanges.unshift({agentId:a,agentName:(c==null?void 0:c.name)||"Unknown",action:i,filePath:o,timestamp:Date.now()}),d.fileChanges.length>200&&d.fileChanges.pop()}),t()},async loadToolHistory(){try{const i=await(await ft(st("/api/agents/tool-history?limit=100"))).json();e(o=>{i.toolExecutions&&(o.toolExecutions=i.toolExecutions),i.fileChanges&&(o.fileChanges=i.fileChanges)}),t()}catch(a){console.error("[Store] Failed to load tool history:",a)}}}}function aB(s,e,t,n){return{addOutput(a,i){const o=n();e(l=>{const c=l.agentOutputs.get(a)||[];if(i.uuid&&c.some(g=>g.uuid===i.uuid))return;let d=[...c,i];d.length>200&&(d=d.slice(-200)),Qu.info(`Store: ${c.length} -> ${d.length}`,{agentId:a,text:i.text.slice(0,60),isStreaming:i.isStreaming,listeners:o},"store:addOutput");const f=new Map(l.agentOutputs);f.set(a,d),l.agentOutputs=f}),t()},clearOutputs(a){e(i=>{const o=new Map(i.agentOutputs);o.delete(a),i.agentOutputs=o}),t()},getOutputs(a){return s().agentOutputs.get(a)||[]},addUserPromptToOutput(a,i){this.addOutput(a,{text:i,isStreaming:!1,timestamp:Date.now(),isUserPrompt:!0})},getLastPrompt(a){return s().lastPrompts.get(a)},setLastPrompt(a,i){e(o=>{o.lastPrompts.set(a,{text:i,timestamp:Date.now()})}),t()},preserveOutputs(){const a=s(),i=new Map;for(const[o,l]of a.agentOutputs)i.set(o,l.map(c=>({...c})));return i},mergeOutputsWithHistory(a,i,o){const l=[...i,...o];return l.sort((c,d)=>c.timestamp-d.timestamp),e(c=>{const d=new Map(c.agentOutputs);d.set(a,l),c.agentOutputs=d}),t(),l}}}function iB(s,e,t,n){return{setSupervisorReport(a){e(i=>{i.supervisor.lastReport=a,i.supervisor.lastReportTime=a.timestamp;const o=new Map(i.supervisor.agentHistories);for(const l of a.agentSummaries){const c=o.get(l.agentId)||[],d={id:`${a.id}-${l.agentId}`,timestamp:a.timestamp,reportId:a.id,analysis:l};if(!c.some(f=>f.reportId===a.id)){const f=[d,...c];f.length>50&&f.pop(),o.set(l.agentId,f)}}i.supervisor.agentHistories=o,i.supervisor.generatingReport=!1}),t()},addNarrative(a,i){e(o=>{const l=o.supervisor.narratives.get(a)||[];l.unshift(i),l.length>50&&l.pop();const c=new Map(o.supervisor.narratives);c.set(a,l),o.supervisor.narratives=c}),t()},getNarratives(a){return s().supervisor.narratives.get(a)||[]},setSupervisorStatus(a){e(i=>{i.supervisor.enabled=a.enabled,a.autoReportOnComplete!==void 0&&(i.supervisor.autoReportOnComplete=a.autoReportOnComplete),i.supervisor.lastReportTime=a.lastReportTime,i.supervisor.nextReportTime=a.nextReportTime}),t()},setSupervisorConfig(a){var i;(i=n())==null||i({type:"set_supervisor_config",payload:a})},requestSupervisorReport(){var a;e(i=>{i.supervisor.generatingReport=!0}),t(),(a=n())==null||a({type:"request_supervisor_report",payload:{}})},requestAgentSupervisorHistory(a){var i;e(o=>{o.supervisor.loadingHistoryForAgent=a}),t(),(i=n())==null||i({type:"request_agent_supervisor_history",payload:{agentId:a}})},setAgentSupervisorHistory(a){e(i=>{const o=new Map(i.supervisor.agentHistories);o.set(a.agentId,a.entries),i.supervisor.agentHistories=o,i.supervisor.historyFetchedForAgents.add(a.agentId),i.supervisor.loadingHistoryForAgent===a.agentId&&(i.supervisor.loadingHistoryForAgent=null)}),t()},getAgentSupervisorHistory(a){return s().supervisor.agentHistories.get(a)||[]},addAgentAnalysis(a,i){e(o=>{const l=new Map(o.supervisor.agentHistories),c=l.get(a)||[],d={id:`single-${Date.now()}-${a}`,timestamp:Date.now(),reportId:`single-${Date.now()}`,analysis:i};if(!c.some(p=>Math.abs(p.timestamp-d.timestamp)<5e3&&p.analysis.statusDescription===i.statusDescription)){const p=[d,...c];p.length>50&&p.pop(),l.set(a,p),o.supervisor.agentHistories=l}}),t()},isLoadingHistoryForAgent(a){return s().supervisor.loadingHistoryForAgent===a},hasHistoryBeenFetched(a){return s().supervisor.historyFetchedForAgents.has(a)},setGlobalUsage(a){console.log("[Supervisor] setGlobalUsage called with:",a),e(i=>{i.supervisor.globalUsage=a,i.supervisor.refreshingUsage=!1}),t()},requestGlobalUsage(){console.log("[Supervisor] requestGlobalUsage called"),e(i=>{i.supervisor.refreshingUsage=!0}),t();const a=n();console.log("[Supervisor] sendMessage function:",a?"available":"null"),a?(console.log("[Supervisor] Sending request_global_usage message"),a({type:"request_global_usage",payload:{}})):console.warn("[Supervisor] Cannot send request_global_usage - no sendMessage function")},getGlobalUsage(){return s().supervisor.globalUsage}}}function rB(s,e,t,n){const a=()=>{var o;const i=Array.from(s().areas.values());(o=n())==null||o({type:"sync_areas",payload:i})};return{setActiveTool(i){e(o=>{o.activeTool=i,i!=="select"&&(o.selectedAreaId=null)}),t()},selectArea(i){e(o=>{o.selectedAreaId=i}),t()},addArea(i){if(i.zIndex===void 0||i.zIndex===null){const o=Array.from(s().areas.values()),l=o.length===0?-1:Math.max(...o.map(c=>c.zIndex??0));i.zIndex=l+1}e(o=>{o.areas.set(i.id,i)}),a(),t()},updateArea(i,o){s().areas.get(i)&&(e(d=>{Object.assign(d.areas.get(i),o)}),a(),t())},updateAreaLocal(i,o){s().areas.get(i)&&(e(d=>{Object.assign(d.areas.get(i),o)}),t())},deleteArea(i){e(o=>{o.areas.delete(i),o.selectedAreaId===i&&(o.selectedAreaId=null)}),a(),t()},assignAgentToArea(i,o){const c=s().areas.get(o);c&&!c.assignedAgentIds.includes(i)&&(e(d=>{for(const f of d.areas.values()){const p=f.assignedAgentIds.indexOf(i);p!==-1&&f.assignedAgentIds.splice(p,1)}d.areas.get(o).assignedAgentIds.push(i)}),a(),t())},unassignAgentFromArea(i,o){const c=s().areas.get(o);if(c){const d=c.assignedAgentIds.indexOf(i);d!==-1&&(e(f=>{f.areas.get(o).assignedAgentIds.splice(d,1)}),a(),t())}},addDirectoryToArea(i,o){const c=s().areas.get(i);c&&!c.directories.includes(o)&&(e(d=>{d.areas.get(i).directories.push(o)}),a(),t())},removeDirectoryFromArea(i,o){const c=s().areas.get(i);if(c){const d=c.directories.indexOf(o);d!==-1&&(e(f=>{f.areas.get(i).directories.splice(d,1)}),a(),t())}},getAreaDirectories(i){const o=s().areas.get(i);return(o==null?void 0:o.directories)||[]},isPositionInArea(i,o){if(o.type==="rectangle"&&o.width&&o.height){const l=o.width/2,c=o.height/2;return i.x>=o.center.x-l&&i.x<=o.center.x+l&&i.z>=o.center.z-c&&i.z<=o.center.z+c}else if(o.type==="circle"&&o.radius){const l=i.x-o.center.x,c=i.z-o.center.z;return l*l+c*c<=o.radius*o.radius}return!1},getAreaForAgent(i){const o=s(),l=o.agents.get(i);if(!l)return null;for(const c of o.areas.values())if(this.isPositionInArea({x:l.position.x,z:l.position.z},c))return c;return null},setAreasFromServer(i){e(o=>{const l=new Map;for(let c=0;c<i.length;c++){const d=i[c];d.directories||(d.directories=[]),(d.zIndex===void 0||d.zIndex===null)&&(d.zIndex=c),d.archived===void 0&&(d.archived=!1),l.set(d.id,d)}o.areas=l}),t()},getAreasInZOrder(){return Array.from(s().areas.values()).sort((o,l)=>(o.zIndex??0)-(l.zIndex??0))},getNextZIndex(){const i=Array.from(s().areas.values());return i.length===0?0:Math.max(...i.map(l=>l.zIndex??0))+1},bringAreaToFront(i){const o=s(),l=o.areas.get(i);if(!l)return;const c=Array.from(o.areas.values()),d=c.length===0?-1:Math.max(...c.map(b=>b.zIndex??0)),f=d+1,p=l.zIndex??0,g=c.filter(b=>(b.zIndex??0)===d);p===d&&g.length===1||(e(b=>{b.areas.get(i).zIndex=f}),a(),t())},sendAreaToBack(i){const o=s(),l=o.areas.get(i);if(!l)return;const c=Array.from(o.areas.values()),d=Math.min(...c.map(g=>g.zIndex??0)),f=l.zIndex??0,p=c.filter(g=>(g.zIndex??0)===d);f===d&&p.length===1||(e(g=>{for(const b of g.areas.values())b.id!==i&&(b.zIndex=(b.zIndex??0)+1);g.areas.get(i).zIndex=0}),a(),t())},setAreaZIndex(i,o){s().areas.get(i)&&(e(d=>{d.areas.get(i).zIndex=o}),a(),t())},archiveArea(i,o){const c=s().areas.get(i);if(!(!c||c.archived)){if(o)for(const d of c.assignedAgentIds)o(d);e(d=>{const f=d.areas.get(i);f.archived=!0,f.archivedAt=Date.now(),f.originalCenter={...f.center},d.selectedAreaId===i&&(d.selectedAreaId=null)}),a(),t()}},restoreArchivedArea(i,o){const l=s(),c=l.areas.get(i);if(!c||!c.archived)return;const d=c.center,f=o||c.originalCenter||c.center,p=f.x-d.x,g=f.z-d.z,b=Array.from(l.areas.values()),w=(b.length===0?-1:Math.max(...b.map(k=>k.zIndex??0)))+1;e(k=>{const S=k.areas.get(i);if(S.archived=!1,S.archivedAt=void 0,S.center=f,S.zIndex=w,p!==0||g!==0)for(const j of S.assignedAgentIds){const C=k.agents.get(j);C&&(C.position={x:C.position.x+p,y:C.position.y,z:C.position.z+g})}}),a(),t()},getArchivedAreas(){return Array.from(s().areas.values()).filter(i=>i.archived===!0)},getVisibleAreas(){return Array.from(s().areas.values()).filter(i=>!i.archived)},isAgentInArchivedArea(i){const o=s();for(const l of o.areas.values())if(l.archived&&l.assignedAgentIds.includes(i))return!0;return!1}}}function oB(s,e,t,n){const a=()=>{var l;const o=Array.from(s().buildings.values());(l=n())==null||l({type:"sync_buildings",payload:o})},i={selectBuilding(o){e(l=>{l.selectedBuildingIds.clear(),o&&l.selectedBuildingIds.add(o)}),t()},selectMultipleBuildings(o){e(l=>{l.selectedBuildingIds.clear();for(const c of o)l.selectedBuildingIds.add(c)}),t()},toggleBuildingSelection(o){e(l=>{l.selectedBuildingIds.has(o)?l.selectedBuildingIds.delete(o):l.selectedBuildingIds.add(o)}),t()},isBuildingSelected(o){return s().selectedBuildingIds.has(o)},getSelectedBuildingIds(){return Array.from(s().selectedBuildingIds)},deleteSelectedBuildings(){var l,c,d;const o=s();for(const f of o.selectedBuildingIds){const p=o.buildings.get(f);((l=p==null?void 0:p.pm2)!=null&&l.enabled||(c=p==null?void 0:p.docker)!=null&&c.enabled)&&((d=n())==null||d({type:"building_command",payload:{buildingId:f,command:"delete"}}))}e(f=>{const p=new Map(f.buildings);for(const g of f.selectedBuildingIds)p.delete(g);f.buildings=p,f.selectedBuildingIds.clear()}),a(),t()},addBuilding(o){e(l=>{const c=new Map(l.buildings);c.set(o.id,o),l.buildings=c}),a(),t()},updateBuilding(o,l){const d=s().buildings.get(o);d&&(e(f=>{const p=new Map(f.buildings);p.set(o,{...d,...l}),f.buildings=p}),a(),t())},updateBuildingLocal(o,l){const d=s().buildings.get(o);d&&(e(f=>{const p=new Map(f.buildings);p.set(o,{...d,...l}),f.buildings=p}),t())},deleteBuilding(o){var d,f,p;const c=s().buildings.get(o);((d=c==null?void 0:c.pm2)!=null&&d.enabled||(f=c==null?void 0:c.docker)!=null&&f.enabled)&&((p=n())==null||p({type:"building_command",payload:{buildingId:o,command:"delete"}})),e(g=>{const b=new Map(g.buildings);b.delete(o),g.buildings=b,g.selectedBuildingIds.delete(o)}),a(),t()},moveBuilding(o,l){const d=s().buildings.get(o);d&&(e(f=>{const p=new Map(f.buildings);p.set(o,{...d,position:l}),f.buildings=p}),a(),t())},updateBuildingPosition(o,l){i.moveBuilding(o,l)},createBuilding(o){const l={...o,id:`building_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,status:"stopped",createdAt:Date.now()};i.addBuilding(l)},sendBuildingCommand(o,l){var c;(c=n())==null||c({type:"building_command",payload:{buildingId:o,command:l}})},addBuildingLogs(o,l){e(c=>{const f=[...c.buildingLogs.get(o)||[],l];f.length>500&&f.splice(0,f.length-500);const p=new Map(c.buildingLogs);p.set(o,f),c.buildingLogs=p}),t()},getBuildingLogs(o){return s().buildingLogs.get(o)||[]},clearBuildingLogs(o){e(l=>{const c=new Map(l.buildingLogs);c.delete(o),l.buildingLogs=c}),t()},setBuildingsFromServer(o){e(l=>{const c=new Map;for(const d of o)c.set(d.id,d);l.buildings=c}),t()},updateBuildingFromServer(o){e(l=>{const c=new Map(l.buildings);c.set(o.id,o),l.buildings=c}),t()},removeBuildingFromServer(o){e(l=>{const c=new Map(l.buildings);c.delete(o),l.buildings=c,l.selectedBuildingIds.delete(o)}),t()},startLogStreaming(o,l=100){var d,f,p;const c=s().buildings.get(o);e(g=>{const b=new Map(g.streamingBuildingLogs);b.set(o,""),g.streamingBuildingLogs=b}),(d=c==null?void 0:c.docker)!=null&&d.enabled?(f=n())==null||f({type:"docker_logs_start",payload:{buildingId:o,lines:l}}):(p=n())==null||p({type:"pm2_logs_start",payload:{buildingId:o,lines:l}})},stopLogStreaming(o){var c,d,f;const l=s().buildings.get(o);(c=l==null?void 0:l.docker)!=null&&c.enabled?(d=n())==null||d({type:"docker_logs_stop",payload:{buildingId:o}}):(f=n())==null||f({type:"pm2_logs_stop",payload:{buildingId:o}})},appendStreamingLogChunk(o,l){e(c=>{const d=c.streamingBuildingLogs.get(o)||"",f=500*1024;let p=d+l;if(p.length>f){const b=p.indexOf(`
|
|
149
|
+
`,side:VA});a.add(new _e(i,o)),a.add(new Ky(16777215,1));const l=n.fromScene(a,.04).texture;t.environment=l,n.dispose(),i.dispose(),o.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?H.openFileExplorerForAreaFolder(e,t):H.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)=>H.updateBuildingPosition(e,t),onContextMenu:(e,t,n)=>this.callbackManager.triggerContextMenu(e,t,n),onActivity:()=>this.renderLoop.markActivity(),onToggleTerminal:()=>H.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 a=n.group.getObjectByName("characterBody");a&&this.proceduralBodiesCache.set(t,a)}this.proceduralBodiesDirty=!1}this.proceduralBodiesCache.size>0&&this.proceduralAnimator.update(e,this.proceduralBodiesCache)}updateIndicatorScales(e,t,n){for(const[,a]of t){const i=e.position.distanceTo(a.group.position),o=Math.max(.5,Math.min(2.5,i/15))*n,l=a.group.userData.isBoss===!0,c=a.group.getObjectByName("statusBar"),d=a.group.getObjectByName("nameLabelSprite");if(c){const p=typeof c.userData.baseIndicatorScale=="number"?c.userData.baseIndicatorScale:l?2:1.6,g=typeof c.userData.aspectRatio=="number"?c.userData.aspectRatio:2560/4096;c.scale.set(p*o,p*g*o,1)}if(d){const p=typeof d.userData.baseIndicatorScale=="number"?d.userData.baseIndicatorScale:l?1.5:1.25,y=Math.max(l?1.35:1.1,Math.min(l?1.65:1.35,p)),w=typeof d.userData.aspectRatio=="number"?d.userData.aspectRatio:1024/4096;d.scale.set(y*o,y*w*o,1)}const f=a.group.getObjectByName("combinedUI");if(f){const p=typeof f.userData.baseIndicatorScale=="number"?f.userData.baseIndicatorScale:l?3:2.4,g=typeof f.userData.aspectRatio=="number"?f.userData.aspectRatio:1024/2048;f.scale.set(p*o,p*g*o,1)}if(!c&&!f){const p=a.group.getObjectByName("nameLabel");if(p){const y=.3*o;p.scale.set(y*(p.userData.aspectRatio||2),y,1)}const g=a.group.getObjectByName("manaBar");g&&g.scale.set(.9,.14,1);const b=a.group.getObjectByName("idleTimer");b&&b.scale.set(.9*o,.14*o,1)}}for(const[,a]of this.buildingManager.getBuildingMeshData()){const i=e.position.distanceTo(a.group.position),o=Math.max(.5,Math.min(2.5,i/15))*n,l=a.group.getObjectByName("buildingLabel");if(l){const c=.3*o;l.scale.set(c*(l.userData.aspectRatio||2),c,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,a){this.effectsManager.setAgentMeshes(this.agentManager.getAgentMeshes()),this.effectsManager.addSubagentEffect(e,t,n,a)}completeSubagentEffect(e){this.effectsManager.completeSubagentEffect(e)}removeSubagentEffect(e){this.effectsManager.removeSubagentEffect(e)}focusAgent(e){this.cameraManager.focusAgent(e)}callSubordinates(e){var o;const n=H.getState().agents.get(e);if(!n||!(n.isBoss||n.class==="boss")||!((o=n.subordinateIds)!=null&&o.length))return;const a=new bt(n.position.x,n.position.y,n.position.z),i=this.inputHandler.calculateFormationPositions(a,n.subordinateIds.length);this.effectsManager.createMoveOrderEffect(a.clone()),n.subordinateIds.forEach((l,c)=>{const d=this.agentManager.getAgentMeshes().get(l);H.moveAgent(l,i[c]),d&&this.movementAnimator.startMovement(l,d,i[c])})}setDrawingTool(e){this.drawingManager.setTool(e),H.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 i,o;console.log("[SceneManager] Reattaching to new canvas (HMR)"),this.isReattaching=!0,this.renderLoop.stop(),(i=this.resizeObserver)==null||i.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&&((o=this.resizeObserver)==null||o.observe(e.parentElement)),this.onWindowResize();const a=(l=0)=>{this.isReattaching=!1,e.isConnected&&this.sceneCore.getRenderer()?(console.log("[SceneManager] Restarting animation loop after HMR reattach"),this.renderLoop.start()):l<10?(console.log(`[SceneManager] Canvas not connected, retrying... (attempt ${l+1})`),this.isReattaching=!0,requestAnimationFrame(()=>a(l+1))):console.warn("[SceneManager] Failed to restart animation loop - canvas never connected")};requestAnimationFrame(()=>a())}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:ql.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 vp="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 Jp(){return typeof window<"u"?window.__tidePersistedScene??null:null}function ON(){return typeof window<"u"?window.__tidePersistedCanvas??null:null}function TI(){return typeof window<"u"?window.__tideWsConnected??!1:!1}function ed(s){typeof window<"u"&&(window.__tidePersistedScene=s)}function wp(s){typeof window<"u"&&(window.__tidePersistedCanvas=s)}function IN(s){typeof window<"u"&&(window.__tideWsConnected=s)}function EI(s){typeof window<"u"&&(window.__tideIsPageUnloading=s)}function _I(){sessionStorage.setItem(vp,"true")}function Ph(s){EI(!0),sessionStorage.removeItem(vp),jN(),jP(),window.__tideScene&&(window.__tideScene=null);const e=Jp();e?(console.log("[App] Calling persistedScene.dispose()"),e.dispose(),ed(null)):console.log("[App] No persistedScene to dispose"),wp(null),IN(!1);const t=document.getElementById("battlefield");t&&t.remove();const n=document.getElementById("app");n&&(n.innerHTML="")}function DI(){var a,i;if(window.__tideAppInitialized)return;if(window.__tideAppInitialized=!0,sessionStorage.getItem(vp)==="true"&&console.log("[App] Detected unclean shutdown from previous session - forcing cleanup"),window.__tideScene){console.log("[App] Cleaning up stale __tideScene reference");try{(i=(a=window.__tideScene).dispose)==null||i.call(a)}catch{}window.__tideScene=null}const e=Jp();if(e){console.log("[App] Cleaning up stale persistedScene");try{e.dispose()}catch{}ed(null)}const t=document.getElementById("battlefield"),n=ON();t&&t!==n&&t.remove(),sessionStorage.removeItem(vp)}function RI(){typeof window>"u"||(DI(),window.addEventListener("pageshow",s=>{s.persisted&&(console.log("[App] Page restored from bfcache - cleaning up"),Ph(),window.location.reload())}),window.onunload=()=>Ph(),window.onbeforeunload=s=>{Ph()},window.addEventListener("pagehide",s=>{Ph(`pagehide (persisted=${s.persisted})`)}))}RI();const oj={showTrees:!0,showBushes:!0,showHouse:!0,showLamps:!0,showGrass:!0,showClouds:!0,fogDensity:1,floorStyle:"concrete",brightness:1,skyColor:null},lj={saturation:2,roughness:.5,metalness:-1,emissiveBoost:0,envMapIntensity:1,wireframe:!1,colorMode:"normal"},cj={idleAnimation:"sit",workingAnimation:"sprint"},PI=0;function BN(){const s={characterScale:2,indicatorScale:1,gridVisible:!0,timeMode:"day",terrain:oj,modelStyle:lj,animations:cj,fpsLimit:PI},e=xi(xt.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:{...oj,...e.terrain},modelStyle:{...lj,...e.modelStyle},animations:{...cj,...e.animations},fpsLimit:e.fpsLimit??s.fpsLimit}:s}function LI(s){Qi(xt.CONFIG,s)}typeof window<"u"&&!window.__tideHmrRefreshListeners&&(window.__tideHmrRefreshListeners=new Set);function zN(){console.log("[Tide HMR] Manual scene refresh triggered");const s=Jp();if(s){try{s.dispose()}catch(t){console.warn("[Tide HMR] Error disposing scene:",t)}ed(null)}wp(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=zN);function OI({canvasRef:s,selectionBoxRef:e,showToast:t,showAgentNotification:n,toolboxModal:a,contextMenu:i,setHoveredAgentPopup:o,setBuildingPopup:l,getBuildingPopup:c,openBuildingModal:d,openPM2LogsModal:f,openBossLogsModal:p,openDatabasePanel:g}){const b=x.useRef(null),y=x.useRef(null),w=x.useRef(null);return x.useEffect(()=>{if(!s.current||!e.current)return;let k=!1;const S=Jp(),C=ON()===s.current;function N(){var D,E,$,M,R,_,P,O;(D=b.current)==null||D.setOnToast(t),(E=b.current)==null||E.setOnBuildingClick((F,B)=>{H.selectBuilding(F);const I=H.getState().buildings.get(F);(I==null?void 0:I.type)==="folder"&&I.folderPath?H.openFileExplorer(I.folderPath):(I==null?void 0:I.type)==="server"||(I==null?void 0:I.type)==="boss"||(I==null?void 0:I.type)==="database"?(y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{l({buildingId:F,screenPos:B,fromClick:!0}),y.current=null},150)):d(F)}),($=b.current)==null||$.setOnContextMenu((F,B,I)=>{i.open(F,B,I)}),(M=b.current)==null||M.setOnAgentHover(()=>{}),(R=b.current)==null||R.setOnBuildingHover((F,B)=>{const I=c();if(F&&B){const U=H.getState().buildings.get(F);((U==null?void 0:U.type)==="server"||(U==null?void 0:U.type)==="boss"||(U==null?void 0:U.type)==="database")&&!(I!=null&&I.fromClick)&&l({buildingId:F,screenPos:B,fromClick:!1})}else I!=null&&I.fromClick||l(null)}),(_=b.current)==null||_.setOnGroundClick(()=>{l(null)}),(P=b.current)==null||P.setOnAreaDoubleClick(F=>{H.selectArea(F),a.open()}),(O=b.current)==null||O.setOnBuildingDoubleClick(F=>{var I;y.current&&(clearTimeout(y.current),y.current=null),l(null);const B=H.getState().buildings.get(F);(B==null?void 0:B.type)==="server"&&((I=B.pm2)!=null&&I.enabled)?f==null||f(F):(B==null?void 0:B.type)==="boss"?p==null||p(F):(B==null?void 0:B.type)==="database"?g==null||g(F):(B==null?void 0:B.type)==="folder"&&B.folderPath?H.openFileExplorer(B.folderPath):d(F)})}if(S&&C){b.current=S,console.log("[Tide] Reusing existing scene (StrictMode remount)");const D=H.getState();S.syncAreas(),S.syncBuildings(),D.agents.size>0&&(console.log("[Tide] Re-syncing agents from store after remount:",D.agents.size),S.syncAgents(Array.from(D.agents.values()))),N()}else{const D=s.current,E=e.current,$=()=>{if(k){console.log("[Tide] Effect cleaned up before scene init, skipping");return}if(!D.isConnected||!E.isConnected){console.warn("[Tide] Canvas disconnected before initialization");return}(!D.clientWidth||!D.clientHeight)&&(console.log("[Tide] Canvas has no CSS dimensions, using window fallback"),D.style.width="100%",D.style.height="100%",D.offsetHeight),(!D.clientWidth||!D.clientHeight)&&(D.width=window.innerWidth,D.height=window.innerHeight),_I();try{const M=new MI(D,E);b.current=M,ed(M),wp(D);const R=BN();M.setCharacterScale(R.characterScale),M.setIndicatorScale(R.indicatorScale),M.setGridVisible(R.gridVisible),M.setTimeMode(R.timeMode),M.setTerrainConfig(R.terrain),M.setFloorStyle(R.terrain.floorStyle,!0),M.setAgentModelStyle(R.modelStyle),M.setIdleAnimation(R.animations.idleAnimation),M.setWorkingAnimation(R.animations.workingAnimation),M.setFpsLimit(R.fpsLimit),M.syncAreas(),M.syncBuildings(),M.loadCharacterModels().then(()=>{console.log("[Tide] Character models ready");const _=H.getState();_.customAgentClasses.size>0&&(console.log("[Tide] Applying custom classes from store:",_.customAgentClasses.size),M.setCustomAgentClasses(_.customAgentClasses)),_.agents.size>0&&(console.log("[Tide] Syncing agents from store:",_.agents.size),M.syncAgents(Array.from(_.agents.values()))),M.upgradeAgentModels()}).catch(_=>{console.warn("[Tide] Some models failed to load, using fallback:",_)}),N()}catch(M){console.error("[Tide] Failed to initialize 3D scene:",M)}};w.current=requestAnimationFrame($)}return wN({onAgentCreated:D=>{var E,$;(E=b.current)==null||E.addAgent(D),($=window.__spawnModalSuccess)==null||$.call(window)},onAgentUpdated:(D,E)=>{var $;($=b.current)==null||$.updateAgent(D,E)},onAgentDeleted:D=>{var E;(E=b.current)==null||E.removeAgent(D)},onAgentsSync:D=>{var E;(E=b.current)==null||E.syncAgents(D)},onAreasSync:()=>{var E,$;(E=b.current)==null||E.syncAreas();const D=Array.from(H.getState().agents.values());($=b.current)==null||$.syncAgents(D)},onSpawnError:()=>{var D;(D=window.__spawnModalError)==null||D.call(window)},onSpawnSuccess:()=>{var D;(D=window.__spawnModalSuccess)==null||D.call(window)},onDirectoryNotFound:D=>{var E;(E=window.__spawnModalDirNotFound)==null||E.call(window,D)},onToolUse:(D,E,$)=>{var M;(M=b.current)==null||M.showToolBubble(D,E,$)},onDelegation:(D,E)=>{var $;($=b.current)==null||$.showDelegationEffect(D,E)},onCustomClassesSync:D=>{var E,$;(E=b.current)==null||E.setCustomAgentClasses(D),($=b.current)==null||$.upgradeAgentModels()},onBuildingUpdated:D=>{var E;(E=b.current)==null||E.updateBuilding(D)},onSubagentStarted:D=>{var E;(E=b.current)==null||E.addSubagentEffect(D.id,D.parentAgentId,D.name,D.subagentType)},onSubagentCompleted:D=>{var M;const E=H.getSubagent(D)||H.getSubagentByToolUseId(D),$=(E==null?void 0:E.id)||D;(M=b.current)==null||M.completeSubagentEffect($),setTimeout(()=>{var R;(R=b.current)==null||R.removeSubagentEffect($)},3e4)}}),()=>{var D;k=!0,w.current!==null&&(cancelAnimationFrame(w.current),w.current=null),!((D=s.current)!=null&&D.isConnected)&&b.current&&(console.log("[Tide] 3D canvas unmounted - disposing scene to free memory"),CP(),b.current.dispose(),b.current=null,ed(null),wp(null))}},[s.current,e.current]),b}let td,Yl;try{td=require("@capacitor/local-notifications").LocalNotifications,Yl=require("@capacitor/core").Capacitor}catch{}let II=1;const BI="agent_alerts",FN="tide-notification-tap";function zI(){return typeof window<"u"&&window.innerWidth<=768&&"ontouchstart"in window}function $N(s){if(zI()){H.openTerminalOnMobile(s);return}H.selectAgent(s),H.setTerminalOpen(!0)}function ix(){var s;return((s=Yl==null?void 0:Yl.isNativePlatform)==null?void 0:s.call(Yl))??!1}async function FI(){return ix()?(await td.requestPermissions()).display==="granted":"Notification"in window?await Notification.requestPermission()==="granted":!1}async function $I(s){const{title:e,body:t,icon:n,data:a}=s;if(ix())await td.schedule({notifications:[{id:II++,title:e,body:t,schedule:{at:new Date(Date.now()+100)},extra:a,channelId:BI,smallIcon:"ic_launcher",autoCancel:!0}]});else if("Notification"in window&&Notification.permission==="granted"){const i=new Notification(e,{body:t,icon:n,data:a});i.onclick=()=>{window.focus(),a&&window.dispatchEvent(new CustomEvent(FN,{detail:a}))}}}async function HI(s){s&&window.addEventListener(FN,e=>{const t=e;t.detail&&s(t.detail)}),ix()&&td&&await td.addListener("localNotificationActionPerformed",e=>{s&&e.notification.extra&&s(e.notification.extra)})}function UI({showToast:s,showAgentNotification:e}){const t=x.useRef(!1);x.useEffect(()=>{if(t.current||TI())return;t.current=!0,wN({onToast:s,onReconnect:()=>{H.triggerReconnect()},onAgentNotification:a=>{e(a)}}),Ju(),IN(!0),FI(),HI(a=>{a.type==="agent_notification"&&typeof a.agentId=="string"&&$N(a.agentId)});const n=()=>{console.log("[Tide] App resumed from background, reconnecting..."),setTimeout(()=>Ju(),100)};return window.addEventListener("tideAppResume",n),()=>{window.removeEventListener("tideAppResume",n)}},[s,e])}function GI(s){x.useEffect(()=>{let e="",t="",n=new Map;const a=i=>{var c;let o=!1;const l=new Map;for(const[d,f]of i){const g=`${f.position.x.toFixed(2)},${f.position.z.toFixed(2)},${f.status},${f.class},${f.isBoss},${((c=f.subordinateIds)==null?void 0:c.length)??0}`.split("").reduce((b,y)=>(b<<5)-b+y.charCodeAt(0),0);l.set(d,g),n.get(d)!==g&&(o=!0)}return l.size!==n.size&&(o=!0),{newVersion:l,changed:o}};return H.subscribe(()=>{var g;const i=H.getState(),o=Array.from(i.selectedAgentIds).sort().join(","),l=Array.from(i.selectedBuildingIds).sort().join(","),c=o!==e,d=l!==t,{newVersion:f,changed:p}=a(i.agents);(c||d||p)&&(e=o,t=l,n=f,(g=s.current)==null||g.refreshSelectionVisuals())})},[s])}function WI(s){x.useEffect(()=>{var n;(n=s.current)==null||n.syncAreas();let e=0,t=0;return H.subscribe(()=>{var l,c;const i=H.getState().areas;if(i.size!==e){e=i.size,t=Date.now(),(l=s.current)==null||l.syncAreas();return}let o=0;for(const[d,f]of i){let p=d.charCodeAt(0);p+=(f.width??0)+(f.height??0)+(f.radius??0),p+=Math.floor(f.center.x*100)+Math.floor(f.center.z*100),p+=(f.zIndex??0)*1e3;for(let g=0;g<f.name.length;g++)p+=f.name.charCodeAt(g);for(let g=0;g<f.color.length;g++)p+=f.color.charCodeAt(g);if(f.directoryGitCounts)for(const g of f.directoryGitCounts)p+=(g+1)*7;o^=p|0}o!==t&&(t=o,(c=s.current)==null||c.syncAreas())})},[s])}function qI(s){x.useEffect(()=>{var n;(n=s.current)==null||n.syncBuildings();let e=0,t=0;return H.subscribe(()=>{var l,c;const i=H.getState().buildings;if(i.size!==e){e=i.size,t=Date.now(),(l=s.current)==null||l.syncBuildings();return}let o=0;for(const[d,f]of i){o^=f.position.x*1e3+f.position.z|0,o^=(f.scale||1)*1e4|0;const p=`${f.style||""}${f.name}${f.status}${f.gitChangesCount||0}`;for(let g=0;g<p.length;g++)o=(o<<5)-o+p.charCodeAt(g)|0}o!==t&&(t=o,(c=s.current)==null||c.syncBuildings())})},[s])}function YI(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.highlightArea(e)},[s,e])}function VI(s,e){x.useEffect(()=>{var t;(t=s.current)==null||t.setPowerSaving(e)},[s,e])}function KI({sceneRef:s,spawnModal:e,commanderModal:t,explorerModal:n,spotlightModal:a,deleteConfirmModal:i,onRequestBuildingDelete:o,onOpenDatabasePanel:l,onCloseDatabasePanel:c,databasePanelOpen:d}){x.useEffect(()=>{const f=p=>{var _,P,O,F;const g=H.getShortcuts(),b=p.target,y=b.tagName==="INPUT"||b.tagName==="TEXTAREA",w=g.find(B=>B.id==="deselect-all");if(vt(p,w)){if(ey()){p.preventDefault();return}const B=H.getState();if(B.activeTool==="rectangle"||B.activeTool==="circle"){(_=s.current)==null||_.setDrawingTool(null),typeof window<"u"&&window.__tideScene2D_setDrawingTool&&window.__tideScene2D_setDrawingTool(null);return}e.isOpen?e.close():B.terminalOpen?(H.setTerminalOpen(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):(H.deselectAll(),(P=s.current)==null||P.refreshSelectionVisuals())}for(let B=1;B<=9;B++){const I=g.find(U=>U.id===`select-agent-${B}`);if(vt(p,I)){p.preventDefault();const U=H.getState(),q=B-1,K=Array.from(U.agents.keys());q<K.length&&(H.selectAgent(K[q]),(O=s.current)==null||O.refreshSelectionVisuals());return}}const k=g.find(B=>B.id==="spawn-agent");if(vt(p,k)){p.preventDefault(),e.open();return}const S=g.find(B=>B.id==="toggle-commander-tab");if(vt(p,S)&&!y){p.preventDefault(),t.toggle();return}const j=g.find(B=>B.id==="toggle-commander");if(vt(p,j)){p.preventDefault(),t.toggle();return}const C=g.find(B=>B.id==="toggle-file-explorer");if(vt(p,C)){p.preventDefault();const B=H.getState();if(n.isOpen||B.explorerFolderPath!==null||B.explorerAreaId!==null)n.close(),H.closeFileExplorer();else{const U=H.getLastExplorerState();if((U==null?void 0:U.type)==="folder")H.openFileExplorer(U.path);else if((U==null?void 0:U.type)==="area")if(B.areas.has(U.areaId))n.open(U.areaId);else{const q=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);q.length>0&&n.open(q[0].id)}else{const q=Array.from(B.areas.values()).filter(K=>K.directories&&K.directories.length>0);q.length>0&&n.open(q[0].id)}}return}if(p.altKey&&!p.ctrlKey&&!p.shiftKey&&!p.metaKey&&p.code==="KeyD"){if(p.preventDefault(),p.stopPropagation(),d){c();return}const B=localStorage.getItem("tide-commander-last-database-building"),I=H.getState();if(B){const U=I.buildings.get(B);if((U==null?void 0:U.type)==="database"){l(B);return}}for(const[U,q]of I.buildings)if(q.type==="database"){l(U);return}return}const N=g.find(B=>B.id==="toggle-spotlight");if(vt(p,N)||p.altKey&&!p.ctrlKey&&!p.metaKey&&p.code==="KeyP"){console.log("[useKeyboardShortcuts] Spotlight shortcut matched!",{spotlightShortcut:N,altKey:p.altKey,code:p.code}),p.preventDefault(),a.toggle();return}const D=g.find(B=>B.id==="toggle-2d-view");if(vt(p,D)){p.preventDefault();const B=H.getState().viewMode,I=B==="3d"?"2d":B==="2d"?"dashboard":"3d";H.setViewMode(I);return}const E=g.find(B=>B.id==="next-working-agent"),$=g.find(B=>B.id==="prev-working-agent");if((vt(p,E)||vt(p,$))&&!y){const B=H.getState();if(B.terminalOpen)return;const U=Array.from(B.agents.values()).filter(L=>L.status==="working");if(U.length===0)return;p.preventDefault();const q=B.selectedAgentIds.size===1?Array.from(B.selectedAgentIds)[0]:null,K=q?U.findIndex(L=>L.id===q):-1;let X;vt(p,E)?X=K===-1?0:(K+1)%U.length:X=K===-1?U.length-1:(K-1+U.length)%U.length,H.selectAgent(U[X].id),(F=s.current)==null||F.refreshSelectionVisuals();return}const M=g.find(B=>B.id==="delete-selected"),R=g.find(B=>B.id==="delete-selected-backspace");if((vt(p,M)||vt(p,R))&&!y){const B=H.getState();if(B.selectedAgentIds.size>0){p.preventDefault(),i.open();return}if(B.selectedBuildingIds.size>0){p.preventDefault(),o();return}return}};return document.addEventListener("keydown",f,!0),()=>document.removeEventListener("keydown",f,!0)},[s,e,t,n,a,i,o,l,c,d])}function XI(){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 a=()=>{var o;window.innerWidth>768||window.location.hash.includes("app")||(window.location.hash="#app",ey()||(o=window.__tideSetBackNavModal)==null||o.call(window,!0))},i=()=>{var o;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),ey()||(o=window.__tideSetBackNavModal)==null||o.call(window,!0))};window.history.pushState(null,"","#app1"),window.history.pushState(null,"","#app2"),window.history.pushState(null,"","#app"),window.addEventListener("hashchange",a),window.addEventListener("popstate",i)},[]),{showBackNavModal:s,setShowBackNavModal:e,handleLeave:()=>{e(!1);const n=window.__tideHistoryDepth??2;window.history.go(-(n+1))}}}const Kg="agent-order-change";function HN(s){const e=x.useMemo(()=>new Set(s.map(c=>c.id)),[s]),[t,n]=x.useState(()=>xi(xt.AGENT_ORDER,[]));x.useEffect(()=>{const c=d=>{n(d.detail)};return window.addEventListener(Kg,c),()=>{window.removeEventListener(Kg,c)}},[]);const a=x.useMemo(()=>{const c=t.filter(g=>e.has(g)),d=s.filter(g=>!c.includes(g.id)).map(g=>g.id),f=[...c,...d],p=new Map(s.map(g=>[g.id,g]));return f.map(g=>p.get(g)).filter(g=>g!==void 0)},[s,t,e]),i=x.useCallback(c=>{n(c),Qi(xt.AGENT_ORDER,c),window.dispatchEvent(new CustomEvent(Kg,{detail:c}))},[]),o=x.useCallback((c,d)=>{const f=a.map(g=>g.id),[p]=f.splice(c,1);f.splice(d,0,p),i(f)},[a,i]),l=x.useCallback(()=>{n([]),Qi(xt.AGENT_ORDER,[])},[]);return x.useEffect(()=>{if(e.size===0)return;const c=t.filter(d=>e.has(d));c.length!==t.length&&i(c)},[e,t,i]),{orderedAgents:a,moveAgent:o,resetOrder:l}}let li,py;try{li=require("@capacitor/core").Capacitor,py=require("@capacitor/core").CapacitorHttp}catch{}const rx="deivid11/tide-commander",ZI=`https://api.github.com/repos/${rx}/releases/latest`,QI=`https://api.github.com/repos/${rx}/releases?per_page=3`,JI=3600*1e3,uj="app_update_dismissed_version",dj="0.65.8";function eB(){var f;const[s,e]=x.useState({isChecking:!1,updateAvailable:!1,updateInfo:null,recentReleases:[],error:null,currentVersion:dj}),t=((f=li==null?void 0:li.getPlatform)==null?void 0:f.call(li))==="android"||!1,n=p=>p.replace(/^v/,"").split(".").map(b=>parseInt(b,10)||0),a=(p,g)=>{const b=n(p),y=n(g),w=Math.max(b.length,y.length);for(let k=0;k<w;k++){const S=b[k]||0,j=y[k]||0;if(S>j)return 1;if(S<j)return-1}return 0},i=async p=>{var b;if(li&&py&&((b=li.isNativePlatform)==null?void 0:b.call(li))===!0){const y=await py.get({url:p,headers:{Accept:"application/vnd.github.v3+json"}});return{data:y.data,status:y.status}}else{const y=await fetch(p,{headers:{Accept:"application/vnd.github.v3+json"}});return y.ok?{data:await y.json(),status:y.status}:{data:null,status:y.status}}},o=x.useCallback(async(p=!1)=>{e(g=>({...g,isChecking:!0,error:null}));try{const[g,b]=await Promise.all([i(ZI),i(QI)]);if(g.status!==200)throw new Error(`GitHub API error: ${g.status}`);const y=g.data,w=y.tag_name;let k=[];b.status===200&&b.data&&(k=b.data.map(D=>({version:D.tag_name,name:D.name,publishedAt:D.published_at,releaseUrl:D.html_url})));const S=localStorage.getItem(uj);if(!p&&S===w)return e(D=>({...D,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;if(!(a(w,dj)>0))return e(D=>({...D,isChecking:!1,updateAvailable:!1,recentReleases:k})),null;const C=y.assets.find(D=>D.name.endsWith(".apk")&&D.content_type==="application/vnd.android.package-archive"),N={version:w,name:y.name,changelog:y.body,releaseUrl:y.html_url,apkUrl:(C==null?void 0:C.browser_download_url)||null,apkSize:(C==null?void 0:C.size)||null,publishedAt:y.published_at};return e(D=>({...D,isChecking:!1,updateAvailable:!0,updateInfo:N,recentReleases:k})),N}catch(g){const b=g instanceof Error?g.message:"Failed to check for updates";return e(y=>({...y,isChecking:!1,error:b})),null}},[]),l=x.useCallback(async()=>{var p,g,b;if(!((p=s.updateInfo)!=null&&p.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(y=>({...y,error:null}))}catch(y){const w=y instanceof Error?y.message:"Failed to open download";e(k=>({...k,error:w}))}},[s.updateInfo,t]),c=x.useCallback(()=>{s.updateInfo&&localStorage.setItem(uj,s.updateInfo.version),e(p=>({...p,updateAvailable:!1,updateInfo:null}))},[s.updateInfo]),d=x.useCallback(()=>{var p;(p=s.updateInfo)!=null&&p.releaseUrl?window.open(s.updateInfo.releaseUrl,"_blank"):window.open(`https://github.com/${rx}/releases`,"_blank")},[s.updateInfo]);return x.useEffect(()=>{if(!t)return;const p=setTimeout(()=>{o()},5e3),g=setInterval(()=>{o()},JI);return()=>{clearTimeout(p),clearInterval(g)}},[t,o]),{...s,isAndroid:t,checkForUpdate:o,downloadAndInstall:l,dismissUpdate:c,openReleasePage:d}}function js(s){const e=x.useRef(null),t=x.useCallback(a=>{e.current=a.target,a.target===a.currentTarget&&a.stopPropagation()},[]),n=x.useCallback(a=>{a.target===a.currentTarget&&e.current===a.currentTarget&&(a.stopPropagation(),s()),e.current=null},[s]);return{handleMouseDown:t,handleClick:n}}const tB=3e4;function nB(){const s=x.useRef(null);x.useEffect(()=>{const e=async()=>{var o,l;const t=H.getState(),n=new Map,a=new Map;for(const[c,d]of t.buildings){const f=d.folderPath||d.cwd;f&&(a.has(f)||a.set(f,[]),a.get(f).push(c))}for(const[c,d]of a)try{const f=await ft(st(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!f.ok)continue;const g=((o=(await f.json()).files)==null?void 0:o.length)||0;n.set(c,g);for(const b of d){const y=H.getState().buildings.get(b);y&&y.gitChangesCount!==g&&H.updateBuildingLocal(b,{gitChangesCount:g})}}catch{}const i=new Map;for(const[c,d]of t.areas)d.archived||!d.directories||d.directories.forEach((f,p)=>{f&&(i.has(f)||i.set(f,[]),i.get(f).push({areaId:c,dirIndex:p}))});if(i.size!==0)for(const[c,d]of i)try{let f;if(n.has(c))f=n.get(c);else{const g=await ft(st(`/api/files/git-status?path=${encodeURIComponent(c)}`));if(!g.ok)continue;f=((l=(await g.json()).files)==null?void 0:l.length)||0,n.set(c,f)}const p=new Map;for(const g of d)p.has(g.areaId)||p.set(g.areaId,[]),p.get(g.areaId).push({dirIndex:g.dirIndex,count:f});for(const[g,b]of p){const y=H.getState().areas.get(g);if(!y)continue;const w=y.directoryGitCounts?[...y.directoryGitCounts]:new Array(y.directories.length).fill(0);let k=!1;for(const{dirIndex:S,count:j}of b)w[S]!==j&&(w[S]=j,k=!0);k&&H.updateAreaLocal(g,{directoryGitCounts:w})}}catch{}};return e(),s.current=setInterval(e,tB),()=>{s.current&&(clearInterval(s.current),s.current=null)}},[])}const hj={historyLimit:500,hideCost:!0,showFPS:!1,powerSaving:!1,customAgentNames:[],experimental2DView:!1,experimentalVoiceAssistant:!1,experimentalTTS:!1,externalEditorCommand:""};function sB(s,e,t,n){return{setAgents(a){const i=new Map;for(const l of a)i.set(l.id,l),(l.class==="boss"||l.isBoss)&&console.log("[Store.setAgents] Boss agent:",l.name,"subordinateIds:",l.subordinateIds);const o=a.find(l=>l.status==="working");e(l=>{l.agents=i,o&&l.selectedAgentIds.size===0&&(l.selectedAgentIds.add(o.id),l.terminalOpen=!0)}),t()},addAgent(a){e(i=>{const o=new Map(i.agents);o.set(a.id,a),i.agents=o}),t()},updateAgent(a){var c;const o=s().agents.get(a.id),l=(o==null?void 0:o.status)!==a.status;l&&console.log(`[Store] Agent ${a.name} status update: ${o==null?void 0:o.status} → ${a.status}`),e(d=>{const f=new Map(d.agents);f.set(a.id,a),d.agents=f}),t(),l&&console.log(`[Store] Agent ${a.name} status now in store: ${(c=s().agents.get(a.id))==null?void 0:c.status}`)},updateAgentContextStats(a,i){const l=s().agents.get(a);l&&(e(c=>{const d=new Map(c.agents);d.set(a,{...l,contextStats:i,contextUsed:i.totalTokens,contextLimit:i.contextWindow}),c.agents=d}),t())},removeAgent(a){e(i=>{const o=new Map(i.agents);o.delete(a),i.agents=o,i.selectedAgentIds.delete(a),i.agentOutputs.delete(a)}),t()},selectAgent(a){e(i=>{i.selectedAgentIds.clear(),a&&(i.selectedAgentIds.add(a),i.lastSelectedAgentId=a),i.currentSnapshot=null}),t()},addToSelection(a){e(i=>{i.selectedAgentIds.has(a)?i.selectedAgentIds.delete(a):i.selectedAgentIds.add(a)}),t()},selectMultiple(a){e(i=>{i.selectedAgentIds.clear();for(const o of a)i.selectedAgentIds.add(o)}),t()},deselectAll(){e(a=>{a.selectedAgentIds.clear()}),t()},spawnAgent(a,i,o,l,c,d,f,p,g,b,y,w,k){console.log("[Store] spawnAgent called with:",{name:a,agentClass:i,cwd:o,position:l,sessionId:c,useChrome:d,permissionMode:f,initialSkillIds:p,provider:g,codexConfig:b,codexModel:y,model:w,customInstructions:k?`${k.length} chars`:void 0});const S=l?{x:l.x,y:0,z:l.z}:void 0,j={type:"spawn_agent",payload:{name:a,class:i,cwd:o,position:S,sessionId:c,useChrome:d,permissionMode:f,initialSkillIds:p,provider:g,codexConfig:b,codexModel:y,model:w,customInstructions:k}},C=n();if(!C){console.error("[Store] sendMessage is not defined! WebSocket may not be connected");return}C(j),console.log("[Store] Message sent to WebSocket")},createDirectoryAndSpawn(a,i,o){var l;(l=n())==null||l({type:"create_directory",payload:{path:a,name:i,class:o}})},sendCommand(a,i){var o;e(l=>{l.lastPrompts.set(a,{text:i,timestamp:Date.now()})}),t(),(o=n())==null||o({type:"send_command",payload:{agentId:a,command:i}})},refreshAgentContext(a){var i;(i=n())==null||i({type:"request_context_stats",payload:{agentId:a}})},moveAgentLocal(a,i){const l=s().agents.get(a);l&&(e(c=>{const d={...l,position:i},f=new Map(c.agents);f.set(a,d),c.agents=f}),t())},moveAgent(a,i){var c;const l=s().agents.get(a);l&&(e(d=>{const f={...l,position:i},p=new Map(d.agents);p.set(a,f),d.agents=p}),t()),(c=n())==null||c({type:"move_agent",payload:{agentId:a,position:i}})},killAgent(a){var i;(i=n())==null||i({type:"kill_agent",payload:{agentId:a}})},stopAgent(a){var i;(i=n())==null||i({type:"stop_agent",payload:{agentId:a}})},clearContext(a){var i;(i=n())==null||i({type:"clear_context",payload:{agentId:a}}),e(o=>{const l=new Map(o.agentOutputs);l.delete(a),o.agentOutputs=l}),t()},collapseContext(a){var i;(i=n())==null||i({type:"collapse_context",payload:{agentId:a}})},removeAgentFromServer(a){var i;(i=n())==null||i({type:"remove_agent",payload:{agentId:a}})},renameAgent(a,i){var c;const l=s().agents.get(a);l&&(e(d=>{const f={...l,name:i},p=new Map(d.agents);p.set(a,f),d.agents=p}),t()),(c=n())==null||c({type:"rename_agent",payload:{agentId:a,name:i}})},updateAgentProperties(a,i){var c;const l=s().agents.get(a);l&&(e(d=>{const f={...l};i.class!==void 0&&(f.class=i.class),i.permissionMode!==void 0&&(f.permissionMode=i.permissionMode),i.model!==void 0&&(f.model=i.model),i.provider!==void 0&&(f.provider=i.provider),i.codexConfig!==void 0&&(f.codexConfig=i.codexConfig),i.codexModel!==void 0&&(f.codexModel=i.codexModel),i.useChrome!==void 0&&(f.useChrome=i.useChrome),i.cwd!==void 0&&(f.cwd=i.cwd);const p=new Map(d.agents);p.set(a,f),d.agents=p}),t()),(c=n())==null||c({type:"update_agent_properties",payload:{agentId:a,updates:i}})},getTotalTokens(){let a=0;for(const i of s().agents.values())a+=i.tokensUsed;return a},getSelectedAgents(){const a=s(),i=[];for(const o of a.selectedAgentIds){const l=a.agents.get(o);l&&i.push(l)}return i},addActivity(a){e(i=>{i.activities.unshift(a),i.activities.length>100&&i.activities.pop()}),t()},addToolExecution(a,i,o){const c=s().agents.get(a);e(d=>{d.toolExecutions.unshift({agentId:a,agentName:(c==null?void 0:c.name)||"Unknown",toolName:i,toolInput:o,timestamp:Date.now()}),d.toolExecutions.length>200&&d.toolExecutions.pop()}),t()},addFileChange(a,i,o){const c=s().agents.get(a);e(d=>{d.fileChanges.unshift({agentId:a,agentName:(c==null?void 0:c.name)||"Unknown",action:i,filePath:o,timestamp:Date.now()}),d.fileChanges.length>200&&d.fileChanges.pop()}),t()},async loadToolHistory(){try{const i=await(await ft(st("/api/agents/tool-history?limit=100"))).json();e(o=>{i.toolExecutions&&(o.toolExecutions=i.toolExecutions),i.fileChanges&&(o.fileChanges=i.fileChanges)}),t()}catch(a){console.error("[Store] Failed to load tool history:",a)}}}}function aB(s,e,t,n){return{addOutput(a,i){const o=n();e(l=>{const c=l.agentOutputs.get(a)||[];if(i.uuid&&c.some(g=>g.uuid===i.uuid))return;let d=[...c,i];d.length>200&&(d=d.slice(-200)),Qu.info(`Store: ${c.length} -> ${d.length}`,{agentId:a,text:i.text.slice(0,60),isStreaming:i.isStreaming,listeners:o},"store:addOutput");const f=new Map(l.agentOutputs);f.set(a,d),l.agentOutputs=f}),t()},clearOutputs(a){e(i=>{const o=new Map(i.agentOutputs);o.delete(a),i.agentOutputs=o}),t()},getOutputs(a){return s().agentOutputs.get(a)||[]},addUserPromptToOutput(a,i){this.addOutput(a,{text:i,isStreaming:!1,timestamp:Date.now(),isUserPrompt:!0})},getLastPrompt(a){return s().lastPrompts.get(a)},setLastPrompt(a,i){e(o=>{o.lastPrompts.set(a,{text:i,timestamp:Date.now()})}),t()},preserveOutputs(){const a=s(),i=new Map;for(const[o,l]of a.agentOutputs)i.set(o,l.map(c=>({...c})));return i},mergeOutputsWithHistory(a,i,o){const l=[...i,...o];return l.sort((c,d)=>c.timestamp-d.timestamp),e(c=>{const d=new Map(c.agentOutputs);d.set(a,l),c.agentOutputs=d}),t(),l}}}function iB(s,e,t,n){return{setSupervisorReport(a){e(i=>{i.supervisor.lastReport=a,i.supervisor.lastReportTime=a.timestamp;const o=new Map(i.supervisor.agentHistories);for(const l of a.agentSummaries){const c=o.get(l.agentId)||[],d={id:`${a.id}-${l.agentId}`,timestamp:a.timestamp,reportId:a.id,analysis:l};if(!c.some(f=>f.reportId===a.id)){const f=[d,...c];f.length>50&&f.pop(),o.set(l.agentId,f)}}i.supervisor.agentHistories=o,i.supervisor.generatingReport=!1}),t()},addNarrative(a,i){e(o=>{const l=o.supervisor.narratives.get(a)||[];l.unshift(i),l.length>50&&l.pop();const c=new Map(o.supervisor.narratives);c.set(a,l),o.supervisor.narratives=c}),t()},getNarratives(a){return s().supervisor.narratives.get(a)||[]},setSupervisorStatus(a){e(i=>{i.supervisor.enabled=a.enabled,a.autoReportOnComplete!==void 0&&(i.supervisor.autoReportOnComplete=a.autoReportOnComplete),i.supervisor.lastReportTime=a.lastReportTime,i.supervisor.nextReportTime=a.nextReportTime}),t()},setSupervisorConfig(a){var i;(i=n())==null||i({type:"set_supervisor_config",payload:a})},requestSupervisorReport(){var a;e(i=>{i.supervisor.generatingReport=!0}),t(),(a=n())==null||a({type:"request_supervisor_report",payload:{}})},requestAgentSupervisorHistory(a){var i;e(o=>{o.supervisor.loadingHistoryForAgent=a}),t(),(i=n())==null||i({type:"request_agent_supervisor_history",payload:{agentId:a}})},setAgentSupervisorHistory(a){e(i=>{const o=new Map(i.supervisor.agentHistories);o.set(a.agentId,a.entries),i.supervisor.agentHistories=o,i.supervisor.historyFetchedForAgents.add(a.agentId),i.supervisor.loadingHistoryForAgent===a.agentId&&(i.supervisor.loadingHistoryForAgent=null)}),t()},getAgentSupervisorHistory(a){return s().supervisor.agentHistories.get(a)||[]},addAgentAnalysis(a,i){e(o=>{const l=new Map(o.supervisor.agentHistories),c=l.get(a)||[],d={id:`single-${Date.now()}-${a}`,timestamp:Date.now(),reportId:`single-${Date.now()}`,analysis:i};if(!c.some(p=>Math.abs(p.timestamp-d.timestamp)<5e3&&p.analysis.statusDescription===i.statusDescription)){const p=[d,...c];p.length>50&&p.pop(),l.set(a,p),o.supervisor.agentHistories=l}}),t()},isLoadingHistoryForAgent(a){return s().supervisor.loadingHistoryForAgent===a},hasHistoryBeenFetched(a){return s().supervisor.historyFetchedForAgents.has(a)},setGlobalUsage(a){console.log("[Supervisor] setGlobalUsage called with:",a),e(i=>{i.supervisor.globalUsage=a,i.supervisor.refreshingUsage=!1}),t()},requestGlobalUsage(){console.log("[Supervisor] requestGlobalUsage called"),e(i=>{i.supervisor.refreshingUsage=!0}),t();const a=n();console.log("[Supervisor] sendMessage function:",a?"available":"null"),a?(console.log("[Supervisor] Sending request_global_usage message"),a({type:"request_global_usage",payload:{}})):console.warn("[Supervisor] Cannot send request_global_usage - no sendMessage function")},getGlobalUsage(){return s().supervisor.globalUsage}}}function rB(s,e,t,n){const a=()=>{var o;const i=Array.from(s().areas.values());(o=n())==null||o({type:"sync_areas",payload:i})};return{setActiveTool(i){e(o=>{o.activeTool=i,i!=="select"&&(o.selectedAreaId=null)}),t()},selectArea(i){e(o=>{o.selectedAreaId=i}),t()},addArea(i){if(i.zIndex===void 0||i.zIndex===null){const o=Array.from(s().areas.values()),l=o.length===0?-1:Math.max(...o.map(c=>c.zIndex??0));i.zIndex=l+1}e(o=>{o.areas.set(i.id,i)}),a(),t()},updateArea(i,o){s().areas.get(i)&&(e(d=>{Object.assign(d.areas.get(i),o)}),a(),t())},updateAreaLocal(i,o){s().areas.get(i)&&(e(d=>{Object.assign(d.areas.get(i),o)}),t())},deleteArea(i){e(o=>{o.areas.delete(i),o.selectedAreaId===i&&(o.selectedAreaId=null)}),a(),t()},assignAgentToArea(i,o){const c=s().areas.get(o);c&&!c.assignedAgentIds.includes(i)&&(e(d=>{for(const f of d.areas.values()){const p=f.assignedAgentIds.indexOf(i);p!==-1&&f.assignedAgentIds.splice(p,1)}d.areas.get(o).assignedAgentIds.push(i)}),a(),t())},unassignAgentFromArea(i,o){const c=s().areas.get(o);if(c){const d=c.assignedAgentIds.indexOf(i);d!==-1&&(e(f=>{f.areas.get(o).assignedAgentIds.splice(d,1)}),a(),t())}},addDirectoryToArea(i,o){const c=s().areas.get(i);c&&!c.directories.includes(o)&&(e(d=>{d.areas.get(i).directories.push(o)}),a(),t())},removeDirectoryFromArea(i,o){const c=s().areas.get(i);if(c){const d=c.directories.indexOf(o);d!==-1&&(e(f=>{f.areas.get(i).directories.splice(d,1)}),a(),t())}},getAreaDirectories(i){const o=s().areas.get(i);return(o==null?void 0:o.directories)||[]},isPositionInArea(i,o){if(o.type==="rectangle"&&o.width&&o.height){const l=o.width/2,c=o.height/2;return i.x>=o.center.x-l&&i.x<=o.center.x+l&&i.z>=o.center.z-c&&i.z<=o.center.z+c}else if(o.type==="circle"&&o.radius){const l=i.x-o.center.x,c=i.z-o.center.z;return l*l+c*c<=o.radius*o.radius}return!1},getAreaForAgent(i){const o=s(),l=o.agents.get(i);if(!l)return null;for(const c of o.areas.values())if(this.isPositionInArea({x:l.position.x,z:l.position.z},c))return c;return null},setAreasFromServer(i){e(o=>{const l=new Map;for(let c=0;c<i.length;c++){const d=i[c];d.directories||(d.directories=[]),(d.zIndex===void 0||d.zIndex===null)&&(d.zIndex=c),d.archived===void 0&&(d.archived=!1),l.set(d.id,d)}o.areas=l}),t()},getAreasInZOrder(){return Array.from(s().areas.values()).sort((o,l)=>(o.zIndex??0)-(l.zIndex??0))},getNextZIndex(){const i=Array.from(s().areas.values());return i.length===0?0:Math.max(...i.map(l=>l.zIndex??0))+1},bringAreaToFront(i){const o=s(),l=o.areas.get(i);if(!l)return;const c=Array.from(o.areas.values()),d=c.length===0?-1:Math.max(...c.map(b=>b.zIndex??0)),f=d+1,p=l.zIndex??0,g=c.filter(b=>(b.zIndex??0)===d);p===d&&g.length===1||(e(b=>{b.areas.get(i).zIndex=f}),a(),t())},sendAreaToBack(i){const o=s(),l=o.areas.get(i);if(!l)return;const c=Array.from(o.areas.values()),d=Math.min(...c.map(g=>g.zIndex??0)),f=l.zIndex??0,p=c.filter(g=>(g.zIndex??0)===d);f===d&&p.length===1||(e(g=>{for(const b of g.areas.values())b.id!==i&&(b.zIndex=(b.zIndex??0)+1);g.areas.get(i).zIndex=0}),a(),t())},setAreaZIndex(i,o){s().areas.get(i)&&(e(d=>{d.areas.get(i).zIndex=o}),a(),t())},archiveArea(i,o){const c=s().areas.get(i);if(!(!c||c.archived)){if(o)for(const d of c.assignedAgentIds)o(d);e(d=>{const f=d.areas.get(i);f.archived=!0,f.archivedAt=Date.now(),f.originalCenter={...f.center},d.selectedAreaId===i&&(d.selectedAreaId=null)}),a(),t()}},restoreArchivedArea(i,o){const l=s(),c=l.areas.get(i);if(!c||!c.archived)return;const d=c.center,f=o||c.originalCenter||c.center,p=f.x-d.x,g=f.z-d.z,b=Array.from(l.areas.values()),w=(b.length===0?-1:Math.max(...b.map(k=>k.zIndex??0)))+1;e(k=>{const S=k.areas.get(i);if(S.archived=!1,S.archivedAt=void 0,S.center=f,S.zIndex=w,p!==0||g!==0)for(const j of S.assignedAgentIds){const C=k.agents.get(j);C&&(C.position={x:C.position.x+p,y:C.position.y,z:C.position.z+g})}}),a(),t()},getArchivedAreas(){return Array.from(s().areas.values()).filter(i=>i.archived===!0)},getVisibleAreas(){return Array.from(s().areas.values()).filter(i=>!i.archived)},isAgentInArchivedArea(i){const o=s();for(const l of o.areas.values())if(l.archived&&l.assignedAgentIds.includes(i))return!0;return!1}}}function oB(s,e,t,n){const a=()=>{var l;const o=Array.from(s().buildings.values());(l=n())==null||l({type:"sync_buildings",payload:o})},i={selectBuilding(o){e(l=>{l.selectedBuildingIds.clear(),o&&l.selectedBuildingIds.add(o)}),t()},selectMultipleBuildings(o){e(l=>{l.selectedBuildingIds.clear();for(const c of o)l.selectedBuildingIds.add(c)}),t()},toggleBuildingSelection(o){e(l=>{l.selectedBuildingIds.has(o)?l.selectedBuildingIds.delete(o):l.selectedBuildingIds.add(o)}),t()},isBuildingSelected(o){return s().selectedBuildingIds.has(o)},getSelectedBuildingIds(){return Array.from(s().selectedBuildingIds)},deleteSelectedBuildings(){var l,c,d;const o=s();for(const f of o.selectedBuildingIds){const p=o.buildings.get(f);((l=p==null?void 0:p.pm2)!=null&&l.enabled||(c=p==null?void 0:p.docker)!=null&&c.enabled)&&((d=n())==null||d({type:"building_command",payload:{buildingId:f,command:"delete"}}))}e(f=>{const p=new Map(f.buildings);for(const g of f.selectedBuildingIds)p.delete(g);f.buildings=p,f.selectedBuildingIds.clear()}),a(),t()},addBuilding(o){e(l=>{const c=new Map(l.buildings);c.set(o.id,o),l.buildings=c}),a(),t()},updateBuilding(o,l){const d=s().buildings.get(o);d&&(e(f=>{const p=new Map(f.buildings);p.set(o,{...d,...l}),f.buildings=p}),a(),t())},updateBuildingLocal(o,l){const d=s().buildings.get(o);d&&(e(f=>{const p=new Map(f.buildings);p.set(o,{...d,...l}),f.buildings=p}),t())},deleteBuilding(o){var d,f,p;const c=s().buildings.get(o);((d=c==null?void 0:c.pm2)!=null&&d.enabled||(f=c==null?void 0:c.docker)!=null&&f.enabled)&&((p=n())==null||p({type:"building_command",payload:{buildingId:o,command:"delete"}})),e(g=>{const b=new Map(g.buildings);b.delete(o),g.buildings=b,g.selectedBuildingIds.delete(o)}),a(),t()},moveBuilding(o,l){const d=s().buildings.get(o);d&&(e(f=>{const p=new Map(f.buildings);p.set(o,{...d,position:l}),f.buildings=p}),a(),t())},updateBuildingPosition(o,l){i.moveBuilding(o,l)},createBuilding(o){const l={...o,id:`building_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,status:"stopped",createdAt:Date.now()};i.addBuilding(l)},sendBuildingCommand(o,l){var c;(c=n())==null||c({type:"building_command",payload:{buildingId:o,command:l}})},addBuildingLogs(o,l){e(c=>{const f=[...c.buildingLogs.get(o)||[],l];f.length>500&&f.splice(0,f.length-500);const p=new Map(c.buildingLogs);p.set(o,f),c.buildingLogs=p}),t()},getBuildingLogs(o){return s().buildingLogs.get(o)||[]},clearBuildingLogs(o){e(l=>{const c=new Map(l.buildingLogs);c.delete(o),l.buildingLogs=c}),t()},setBuildingsFromServer(o){e(l=>{const c=new Map;for(const d of o)c.set(d.id,d);l.buildings=c}),t()},updateBuildingFromServer(o){e(l=>{const c=new Map(l.buildings);c.set(o.id,o),l.buildings=c}),t()},removeBuildingFromServer(o){e(l=>{const c=new Map(l.buildings);c.delete(o),l.buildings=c,l.selectedBuildingIds.delete(o)}),t()},startLogStreaming(o,l=100){var d,f,p;const c=s().buildings.get(o);e(g=>{const b=new Map(g.streamingBuildingLogs);b.set(o,""),g.streamingBuildingLogs=b}),(d=c==null?void 0:c.docker)!=null&&d.enabled?(f=n())==null||f({type:"docker_logs_start",payload:{buildingId:o,lines:l}}):(p=n())==null||p({type:"pm2_logs_start",payload:{buildingId:o,lines:l}})},stopLogStreaming(o){var c,d,f;const l=s().buildings.get(o);(c=l==null?void 0:l.docker)!=null&&c.enabled?(d=n())==null||d({type:"docker_logs_stop",payload:{buildingId:o}}):(f=n())==null||f({type:"pm2_logs_stop",payload:{buildingId:o}})},appendStreamingLogChunk(o,l){e(c=>{const d=c.streamingBuildingLogs.get(o)||"",f=500*1024;let p=d+l;if(p.length>f){const b=p.indexOf(`
|
|
150
150
|
`,p.length-f);b>0?p=p.slice(b+1):p=p.slice(-f)}const g=new Map(c.streamingBuildingLogs);g.set(o,p),c.streamingBuildingLogs=g}),t()},setStreamingStatus(o,l){e(c=>{const d=new Set(c.streamingBuildingIds);l?d.add(o):d.delete(o),c.streamingBuildingIds=d}),t()},getStreamingLogs(o){return s().streamingBuildingLogs.get(o)||""},clearStreamingLogs(o){e(l=>{const c=new Map(l.streamingBuildingLogs);c.delete(o),l.streamingBuildingLogs=c}),t()},isLogStreaming(o){return s().streamingBuildingIds.has(o)},sendBossBuildingCommand(o,l){var c;(c=n())==null||c({type:"boss_building_command",payload:{buildingId:o,command:l}})},assignBuildingsToBoSS(o,l){var f;const d=s().buildings.get(o);d&&(e(p=>{const g=new Map(p.buildings);g.set(o,{...d,subordinateBuildingIds:l}),p.buildings=g}),a(),t()),(f=n())==null||f({type:"assign_buildings",payload:{bossBuildingId:o,subordinateBuildingIds:l}})},startBossLogStreaming(o,l=50){var c;e(d=>{const f=new Map(d.bossStreamingLogs);f.set(o,[]),d.bossStreamingLogs=f}),(c=n())==null||c({type:"boss_building_logs_start",payload:{buildingId:o,lines:l}})},stopBossLogStreaming(o){var l;(l=n())==null||l({type:"boss_building_logs_stop",payload:{buildingId:o}})},appendBossStreamingLogChunk(o,l,c,d,f){e(p=>{const g=p.bossStreamingLogs.get(o)||[],b={subordinateId:l,subordinateName:c,chunk:d,timestamp:Date.now(),isError:f},y=[...g,b];y.length>1e3&&y.splice(0,y.length-1e3);const w=new Map(p.bossStreamingLogs);w.set(o,y),p.bossStreamingLogs=w}),t()},getBossStreamingLogs(o){return s().bossStreamingLogs.get(o)||[]},clearBossStreamingLogs(o){e(l=>{const c=new Map(l.bossStreamingLogs);c.delete(o),l.bossStreamingLogs=c}),t()},requestDockerContainersList(){var o;(o=n())==null||o({type:"docker_list_containers",payload:{}})},setDockerContainersList(o,l){e(c=>{c.dockerContainersList=o,c.dockerComposeProjectsList=l}),t()},getDockerContainersList(){return s().dockerContainersList},getDockerComposeProjectsList(){return s().dockerComposeProjectsList}};return i}function lB(s,e,t,n){return{addPermissionRequest(a){e(i=>{const o=new Map(i.permissionRequests);o.set(a.id,a),i.permissionRequests=o}),t()},resolvePermissionRequest(a,i){const l=s().permissionRequests.get(a);l&&(e(c=>{const d=new Map(c.permissionRequests);d.set(a,{...l,status:i?"approved":"denied"}),c.permissionRequests=d}),t(),setTimeout(()=>{e(c=>{const d=new Map(c.permissionRequests);d.delete(a),c.permissionRequests=d}),t()},2e3))},respondToPermissionRequest(a,i,o,l){var c;(c=n())==null||c({type:"permission_response",payload:{requestId:a,approved:i,reason:o,remember:l}})},getPendingPermissionsForAgent(a){return Array.from(s().permissionRequests.values()).filter(i=>i.agentId===a&&i.status==="pending")},clearAllPermissions(){e(a=>{a.permissionRequests=new Map}),t()}}}function cB(s,e,t,n){return{spawnBossAgent(a,i,o,l,c,d,f,p,g,b,y,w,k){var j;const S=l?{x:l.x,y:0,z:l.z}:void 0;(j=n())==null||j({type:"spawn_boss_agent",payload:{name:a,class:i,cwd:o,position:S,subordinateIds:c,useChrome:d,permissionMode:f,provider:p,codexConfig:g,codexModel:b,model:y,customInstructions:w,initialSkillIds:k}})},assignSubordinates(a,i){var o;(o=n())==null||o({type:"assign_subordinates",payload:{bossId:a,subordinateIds:i}})},removeSubordinate(a,i){var o;(o=n())==null||o({type:"remove_subordinate",payload:{bossId:a,subordinateId:i}})},sendBossCommand(a,i){var o;e(l=>{l.pendingDelegation={bossId:a,command:i}}),t(),(o=n())==null||o({type:"send_boss_command",payload:{bossId:a,command:i}})},requestDelegationHistory(a){var i;(i=n())==null||i({type:"request_delegation_history",payload:{bossId:a}})},handleDelegationDecision(a){e(i=>{var d;const o=new Map(i.delegationHistories),l=o.get(a.bossId)||[],c=l.findIndex(f=>f.id===a.id);if(c!==-1?l[c]=a:(l.unshift(a),l.length>100&&l.pop()),o.set(a.bossId,l),i.delegationHistories=o,a.status==="sent"&&a.selectedAgentId){const f=i.agents.get(a.bossId),p=new Map(i.lastDelegationReceived);p.set(a.selectedAgentId,{bossName:(f==null?void 0:f.name)||"Boss",taskCommand:a.userCommand,timestamp:Date.now()}),i.lastDelegationReceived=p}((d=i.pendingDelegation)==null?void 0:d.bossId)===a.bossId&&a.status!=="pending"&&(i.pendingDelegation=null)}),t()},setDelegationHistory(a,i){e(o=>{const l=new Map(o.delegationHistories);l.set(a,i),o.delegationHistories=l}),t()},getDelegationHistory(a){return s().delegationHistories.get(a)||[]},getLastDelegationReceived(a){return s().lastDelegationReceived.get(a)||null},clearLastDelegationReceived(a){s().lastDelegationReceived.has(a)&&(e(o=>{const l=new Map(o.lastDelegationReceived);l.delete(a),o.lastDelegationReceived=l}),t())},updateBossSubordinates(a,i){const l=s().agents.get(a);l&&(e(c=>{const d={...l,subordinateIds:i},f=new Map(c.agents);f.set(a,d),c.agents=f}),t())},getSubordinates(a){const i=s(),o=i.agents.get(a),l=(o==null?void 0:o.isBoss)===!0||(o==null?void 0:o.class)==="boss";return!o||!l||!o.subordinateIds?[]:o.subordinateIds.map(c=>i.agents.get(c)).filter(c=>c!==void 0)},isBossAgent(a){const i=s().agents.get(a);return(i==null?void 0:i.isBoss)===!0||(i==null?void 0:i.class)==="boss"},getBossForAgent(a){const i=s(),o=i.agents.get(a);return o!=null&&o.bossId&&i.agents.get(o.bossId)||null},getAvailableSubordinates(){return Array.from(s().agents.values()).filter(a=>a.class!=="boss")},handleAgentTaskStarted(a,i,o,l){e(c=>{const d=new Map(c.agentTaskProgress);let f=d.get(a);f||(f=new Map,d.set(a,f)),f.set(i,{agentId:i,agentName:o,taskDescription:l,status:"working",output:[],startedAt:Date.now()}),c.agentTaskProgress=d}),t()},handleAgentTaskOutput(a,i,o){e(l=>{const c=l.agentTaskProgress.get(a);if(!c)return;const d=c.get(i);if(!d)return;const f=new Map(l.agentTaskProgress),p=new Map(c);p.set(i,{...d,output:[...d.output,o]}),f.set(a,p),l.agentTaskProgress=f}),t()},handleAgentTaskCompleted(a,i,o){e(l=>{const c=l.agentTaskProgress.get(a);if(!c)return;const d=c.get(i);if(!d)return;const f=new Map(l.agentTaskProgress),p=new Map(c);p.set(i,{...d,status:o?"completed":"failed",completedAt:Date.now()}),f.set(a,p),l.agentTaskProgress=f}),t()},getAgentTaskProgress(a){return s().agentTaskProgress.get(a)||new Map},clearAgentTaskProgress(a,i){e(o=>{if(i){const l=o.agentTaskProgress.get(a);if(l){const c=new Map(o.agentTaskProgress),d=new Map(l);d.delete(i),c.set(a,d),o.agentTaskProgress=c}}else{const l=new Map(o.agentTaskProgress);l.delete(a),o.agentTaskProgress=l}}),t()},clearAllSubordinatesContext(a){const o=s().agents.get(a),l=(o==null?void 0:o.isBoss)===!0||(o==null?void 0:o.class)==="boss";if(console.log("[Store] clearAllSubordinatesContext called:",{bossId:a,bossName:o==null?void 0:o.name,isBoss:l,subordinateIds:o==null?void 0:o.subordinateIds}),!o||!l||!o.subordinateIds||o.subordinateIds.length===0){console.log("[Store] clearAllSubordinatesContext: No boss or subordinates found, returning early");return}const c=n();console.log("[Store] clearAllSubordinatesContext: sendMessage available:",!!c);for(const d of o.subordinateIds)console.log("[Store] clearAllSubordinatesContext: Sending clear_context for subordinate:",d),c==null||c({type:"clear_context",payload:{agentId:d}});e(d=>{const f=new Map(d.agentOutputs);for(const p of o.subordinateIds||[])f.delete(p);d.agentOutputs=f}),t(),console.log("[Store] clearAllSubordinatesContext: Completed")}}}function uB(s,e,t,n){return{setSkillsFromServer(a){e(i=>{const o=new Map;for(const l of a)o.set(l.id,l);i.skills=o}),t()},addSkillFromServer(a){e(i=>{const o=new Map(i.skills);o.set(a.id,a),i.skills=o}),t()},updateSkillFromServer(a){e(i=>{const o=new Map(i.skills);o.set(a.id,a),i.skills=o}),t()},removeSkillFromServer(a){e(i=>{const o=new Map(i.skills);o.delete(a),i.skills=o}),t()},getSkill(a){return s().skills.get(a)},getAllSkills(){return Array.from(s().skills.values())},getSkillsForAgent(a){const i=s(),o=i.agents.get(a);return o?Array.from(i.skills.values()).filter(l=>l.enabled?!!(l.assignedAgentIds.includes(a)||l.assignedAgentClasses.includes(o.class)):!1):[]},createSkill(a){var i;(i=n())==null||i({type:"create_skill",payload:a})},updateSkill(a,i){var o;(o=n())==null||o({type:"update_skill",payload:{id:a,updates:i}})},deleteSkill(a){var i;(i=n())==null||i({type:"delete_skill",payload:{id:a}})},assignSkillToAgent(a,i){var o;(o=n())==null||o({type:"assign_skill",payload:{skillId:a,agentId:i}})},unassignSkillFromAgent(a,i){var o;(o=n())==null||o({type:"unassign_skill",payload:{skillId:a,agentId:i}})},requestAgentSkills(a){var i;(i=n())==null||i({type:"request_agent_skills",payload:{agentId:a}})},setCustomAgentClassesFromServer(a){e(i=>{const o=new Map;for(const l of a)o.set(l.id,l);i.customAgentClasses=o}),t()},addCustomAgentClassFromServer(a){e(i=>{const o=new Map(i.customAgentClasses);o.set(a.id,a),i.customAgentClasses=o}),t()},updateCustomAgentClassFromServer(a){e(i=>{const o=new Map(i.customAgentClasses);o.set(a.id,a),i.customAgentClasses=o}),t()},removeCustomAgentClassFromServer(a){e(i=>{const o=new Map(i.customAgentClasses);o.delete(a),i.customAgentClasses=o}),t()},getCustomAgentClass(a){return s().customAgentClasses.get(a)},getAllCustomAgentClasses(){return Array.from(s().customAgentClasses.values())},createCustomAgentClass(a){var i;(i=n())==null||i({type:"create_custom_agent_class",payload:a})},updateCustomAgentClass(a,i){var o;(o=n())==null||o({type:"update_custom_agent_class",payload:{id:a,updates:i}})},deleteCustomAgentClass(a){var i;(i=n())==null||i({type:"delete_custom_agent_class",payload:{id:a}})}}}function dB(s,e,t){return{handleExecTaskStarted(n,a,i,o,l){e(c=>{const d={taskId:n,agentId:a,agentName:i,command:o,cwd:l,status:"running",output:[],startedAt:Date.now()};c.execTasks||(c.execTasks=new Map),c.execTasks.set(n,d)}),t()},handleExecTaskOutput(n,a,i,o){e(l=>{var d;const c=(d=l.execTasks)==null?void 0:d.get(n);if(c){const f=i.split(`
|
|
151
151
|
`);for(const p of f)p.length>0&&c.output.push(o?`[stderr] ${p}`:p);c.output.length>500&&(c.output=c.output.slice(-500))}}),t()},handleExecTaskCompleted(n,a,i,o){e(l=>{var d;const c=(d=l.execTasks)==null?void 0:d.get(n);c&&(c.status=o?"completed":"failed",c.exitCode=i,c.completedAt=Date.now())}),t()},async stopExecTask(n){try{return(await fetch(`/api/exec/tasks/${n}`,{method:"DELETE"})).ok?(e(i=>{var l;const o=(l=i.execTasks)==null?void 0:l.get(n);o&&o.status==="running"&&(o.status="failed",o.exitCode=-15,o.completedAt=Date.now(),o.output.push("[Task stopped by user]"))}),t(),!0):!1}catch(a){return console.error("Failed to stop exec task:",a),!1}},getExecTasks(n){const a=s();return a.execTasks?Array.from(a.execTasks.values()).filter(i=>i.agentId===n):[]},getAllExecTasks(){const n=s();return n.execTasks?Array.from(n.execTasks.values()):[]},getExecTask(n){var i;return(i=s().execTasks)==null?void 0:i.get(n)},clearCompletedExecTasks(n){e(a=>{if(a.execTasks)for(const[i,o]of a.execTasks.entries())o.agentId===n&&o.status!=="running"&&a.execTasks.delete(i)}),t()},clearAllExecTasks(n){e(a=>{if(a.execTasks)for(const[i,o]of a.execTasks.entries())o.agentId===n&&a.execTasks.delete(i)}),t()},removeExecTask(n){e(a=>{a.execTasks&&a.execTasks.delete(n)}),t()}}}function hB(s,e,t,n){return{setSecretsFromServer(a){e(i=>{const o=new Map;for(const l of a)o.set(l.id,l);i.secrets=o}),t()},addSecretFromServer(a){e(i=>{const o=new Map(i.secrets);o.set(a.id,a),i.secrets=o}),t()},updateSecretFromServer(a){e(i=>{const o=new Map(i.secrets);o.set(a.id,a),i.secrets=o}),t()},removeSecretFromServer(a){e(i=>{const o=new Map(i.secrets);o.delete(a),i.secrets=o}),t()},getSecret(a){return s().secrets.get(a)},getSecretByKey(a){return Array.from(s().secrets.values()).find(i=>i.key===a)},getAllSecrets(){return Array.from(s().secrets.values())},createSecret(a){var i;(i=n())==null||i({type:"create_secret",payload:a})},updateSecret(a,i){var o;(o=n())==null||o({type:"update_secret",payload:{id:a,updates:i}})},deleteSecret(a){var i;(i=n())==null||i({type:"delete_secret",payload:{id:a}})}}}function pj(){return{connectionStatus:new Map,databases:new Map,tables:new Map,tableSchemas:new Map,queryResults:[],queryHistory:[],executingQuery:!1,activeConnectionId:null,activeDatabase:null,lastSilentQueryResult:null}}function pB(s,e,t,n){const a=o=>{s().databaseState.has(o)||e(c=>{const d=new Map(c.databaseState);d.set(o,pj()),c.databaseState=d})};return{testDatabaseConnection(o,l){var c;(c=n())==null||c({type:"test_database_connection",payload:{buildingId:o,connectionId:l}})},setConnectionStatus(o,l,c){a(o),e(d=>{const f=d.databaseState.get(o);if(f){const p=new Map(f.connectionStatus);p.set(l,c);const g={...f,connectionStatus:p},b=new Map(d.databaseState);b.set(o,g),d.databaseState=b}}),t()},listDatabases(o,l){var c;(c=n())==null||c({type:"list_databases",payload:{buildingId:o,connectionId:l}})},setDatabases(o,l,c){a(o),e(d=>{const f=d.databaseState.get(o);if(f){const p=new Map(f.databases);p.set(l,c);const g={...f,databases:p},b=new Map(d.databaseState);b.set(o,g),d.databaseState=b}}),t()},listTables(o,l,c){var d;(d=n())==null||d({type:"list_tables",payload:{buildingId:o,connectionId:l,database:c}})},setTables(o,l,c,d){a(o);const f=`${l}:${c}`;e(p=>{const g=p.databaseState.get(o);if(g){const b=new Map(g.tables);b.set(f,d);const y={...g,tables:b},w=new Map(p.databaseState);w.set(o,y),p.databaseState=w}}),t()},getTableSchema(o,l,c,d){var f;(f=n())==null||f({type:"get_table_schema",payload:{buildingId:o,connectionId:l,database:c,table:d}})},setTableSchema(o,l,c,d,f){a(o);const p=`${l}:${c}:${d}`;e(g=>{const b=g.databaseState.get(o);if(b){const y=new Map(b.tableSchemas);y.set(p,f);const w={...b,tableSchemas:y},k=new Map(g.databaseState);k.set(o,w),g.databaseState=k}}),t()},executeQuery(o,l,c,d,f=1e3){var p;a(o),e(g=>{const b=g.databaseState.get(o);if(b){const y={...b,executingQuery:!0},w=new Map(g.databaseState);w.set(o,y),g.databaseState=w}}),t(),(p=n())==null||p({type:"execute_query",payload:{buildingId:o,connectionId:l,database:c,query:d,limit:f}})},executeSilentQuery(o,l,c,d,f){var p;(p=n())==null||p({type:"execute_query",payload:{buildingId:o,connectionId:l,database:c,query:d,limit:0,silent:!0,requestId:f}})},setSilentQueryResult(o,l){a(o),e(c=>{const d=c.databaseState.get(o);if(d){const f={...d,lastSilentQueryResult:{...l,timestamp:Date.now()}},p=new Map(c.databaseState);p.set(o,f),c.databaseState=p}}),t()},setQueryResult(o,l){a(o),e(c=>{const d=c.databaseState.get(o);if(d){const f=[l,...d.queryResults].slice(0,20),p={...d,queryResults:f,executingQuery:!1},g=new Map(c.databaseState);g.set(o,p),c.databaseState=g}}),t()},setExecutingQuery(o,l){a(o),e(c=>{const d=c.databaseState.get(o);if(d){const f={...d,executingQuery:l},p=new Map(c.databaseState);p.set(o,f),c.databaseState=p}}),t()},requestQueryHistory(o,l=100){var c;(c=n())==null||c({type:"request_query_history",payload:{buildingId:o,limit:l}})},setQueryHistory(o,l){a(o),e(c=>{const d=c.databaseState.get(o);if(d){const f={...d,queryHistory:l},p=new Map(c.databaseState);p.set(o,f),c.databaseState=p}}),t()},toggleQueryFavorite(o,l){var c;(c=n())==null||c({type:"toggle_query_favorite",payload:{buildingId:o,queryId:l}})},deleteQueryFromHistory(o,l){var c;(c=n())==null||c({type:"delete_query_history",payload:{buildingId:o,queryId:l}})},clearQueryHistory(o){var l;(l=n())==null||l({type:"clear_query_history",payload:{buildingId:o}})},setActiveConnection(o,l){a(o),e(c=>{const d=c.databaseState.get(o);if(d){const f={...d,activeConnectionId:l,activeDatabase:null},p=new Map(c.databaseState);p.set(o,f),c.databaseState=p}}),t()},setActiveDatabase(o,l){a(o),e(c=>{const d=c.databaseState.get(o);if(d){const f={...d,activeDatabase:l},p=new Map(c.databaseState);p.set(o,f),c.databaseState=p}}),t()},getDatabaseState(o){return s().databaseState.get(o)||pj()},clearDatabaseState(o){e(l=>{const c=new Map(l.databaseState);c.delete(o),l.databaseState=c}),t()}}}function fB(s,e,t){return{async fetchSnapshots(){e(n=>{n.snapshotsLoading=!0,n.snapshotsError=null}),t();try{const n=await ft(st("/api/snapshots"));if(!n.ok)throw new Error(`Failed to fetch snapshots: ${n.statusText}`);const a=await n.json(),i=Array.isArray(a)?a:a.snapshots||[];this.setSnapshots(i)}catch(n){const a=n instanceof Error?n.message:"Failed to fetch snapshots";this.setError(a),console.error("Snapshot fetch error:",n)}finally{e(n=>{n.snapshotsLoading=!1}),t()}},setSnapshots(n){e(a=>{const i=new Map;n.forEach(o=>{i.set(o.id,o)}),a.snapshots=i}),t()},async createSnapshot(n,a,i,o,l,c){e(d=>{d.snapshotsLoading=!0,d.snapshotsError=null}),t();try{const d={agentId:n,agentName:a,title:i,description:o,outputs:l||[],files:c||[]},f=await ft(st("/api/snapshots"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!f.ok)throw new Error(`Failed to create snapshot: ${f.statusText}`);const p=await f.json();return await this.fetchSnapshots(),p}catch(d){const f=d instanceof Error?d.message:"Failed to create snapshot";throw this.setError(f),console.error("Snapshot creation error:",d),d}finally{e(d=>{d.snapshotsLoading=!1}),t()}},async loadSnapshot(n){e(a=>{a.snapshotsLoading=!0,a.snapshotsError=null}),t();try{const a=await ft(st(`/api/snapshots/${n}`));if(!a.ok)throw new Error(`Failed to load snapshot: ${a.statusText}`);const i=await a.json();this.setCurrentSnapshot(i)}catch(a){const i=a instanceof Error?a.message:"Failed to load snapshot";this.setError(i),console.error("Snapshot load error:",a)}finally{e(a=>{a.snapshotsLoading=!1}),t()}},setCurrentSnapshot(n){e(a=>{a.currentSnapshot=n}),t()},async deleteSnapshot(n){var a;e(i=>{i.snapshotsLoading=!0,i.snapshotsError=null}),t();try{const i=await ft(st(`/api/snapshots/${n}`),{method:"DELETE"});if(!i.ok)throw new Error(`Failed to delete snapshot: ${i.statusText}`);await this.fetchSnapshots(),((a=s().currentSnapshot)==null?void 0:a.id)===n&&this.setCurrentSnapshot(null)}catch(i){const o=i instanceof Error?i.message:"Failed to delete snapshot";throw this.setError(o),console.error("Snapshot deletion error:",i),i}finally{e(i=>{i.snapshotsLoading=!1}),t()}},async restoreFiles(n,a){e(i=>{i.snapshotsLoading=!0,i.snapshotsError=null}),t();try{const i=a?{filePaths:a}:{},o=await ft(st(`/api/snapshots/${n}/restore`),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!o.ok)throw new Error(`Failed to restore files: ${o.statusText}`)}catch(i){const o=i instanceof Error?i.message:"Failed to restore files";throw this.setError(o),console.error("File restoration error:",i),i}finally{e(i=>{i.snapshotsLoading=!1}),t()}},setLoading(n){e(a=>{a.snapshotsLoading=n}),t()},setError(n){e(a=>{a.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 mB(s,e,t){return{addSubagent(n){e(a=>{const i=new Map(a.subagents);i.set(n.id,n),a.subagents=i}),t(),console.log(`[Subagent] Added: ${n.name} (${n.id}) for agent ${n.parentAgentId}`)},completeSubagent(n,a,i){e(o=>{let l=o.subagents.get(n);if(!l){for(const[,c]of o.subagents)if(c.toolUseId===n&&c.parentAgentId===a){l=c;break}}if(l){const c=new Map(o.subagents);c.set(l.id,{...l,status:i?"completed":"failed",completedAt:Date.now()}),o.subagents=c,console.log(`[Subagent] Completed: ${l.name} (${l.id}) success=${i}`),setTimeout(()=>{e(d=>{const f=d.subagents.get(l.id);if(f&&(f.status==="completed"||f.status==="failed")){const p=new Map(d.subagents);p.delete(l.id),d.subagents=p}}),t()},3e4)}}),t()},getSubagentsForAgent(n){const a=s();return Array.from(a.subagents.values()).filter(i=>i.parentAgentId===n)},getSubagent(n){return s().subagents.get(n)},removeSubagent(n){e(a=>{const i=new Map(a.subagents);i.delete(n),a.subagents=i}),t()},getSubagentByToolUseId(n){const a=s();for(const[,i]of a.subagents)if(i.toolUseId===n)return i}}}function ea(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 ar(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 gB(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 Pt(s,e=Object.is){const[t,n]=x.useState(()=>s(H.getState())),a=x.useRef(t);return x.useEffect(()=>{a.current=t},[t]),x.useEffect(()=>{const i=()=>{const o=s(H.getState());e(a.current,o)||(a.current=o,n(o))};return i(),H.subscribe(i)},[s,e]),t}function An(){const[,s]=x.useState({});return x.useEffect(()=>H.subscribe(()=>s({})),[]),H.getState()}function ir(){return Pt(x.useCallback(s=>s.agents,[]),ar)}function ef(){const s=ir(),e=x.useRef([]),t=Array.from(s.values());return ea(e.current,t)||(e.current=t),e.current}function ox(s){return Pt(x.useCallback(e=>s?e.agents.get(s):void 0,[s]))}function UN(){return Pt(x.useCallback(s=>s.selectedAgentIds,[]),gB)}function lx(s){const e=x.useRef([]),t=x.useRef(0),n=Pt(x.useCallback(a=>s&&a.agentOutputs.get(s)||e.current,[s]),ea);return n.length!==t.current&&(Qu.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 cx(){return Pt(x.useCallback(s=>s.lastPrompts,[]),ar)}function tf(){return Pt(x.useCallback(s=>s.areas,[]),ar)}function bB(){return Pt(x.useCallback(s=>s.buildings,[]),ar)}function GN(){return Pt(x.useCallback(s=>s.supervisor,[]))}function tl(){return Pt(x.useCallback(s=>s.settings,[]))}function WN(){return Pt(x.useCallback(s=>s.settings.hideCost,[]))}function yB(){return Pt(x.useCallback(s=>s.settings.customAgentNames,[]),ea)}function xB(){return Pt(x.useCallback(s=>s.shortcuts,[]),ea)}function qN(){return Pt(x.useCallback(s=>s.mouseControls,[]))}function vB(){return Pt(x.useCallback(s=>s.mouseControls.trackpad,[]))}function YN(){return Pt(x.useCallback(s=>s.terminalOpen,[]))}function VN(){return Pt(x.useCallback(s=>s.mobileView,[]))}function ux(){return Pt(x.useCallback(s=>s.fileViewerPath,[]))}function wB(){return Pt(x.useCallback(s=>s.fileViewerEditData,[]))}function kB(){return Pt(x.useCallback(s=>s.fileViewerSearchRoot,[]))}function SB(){return Pt(x.useCallback(s=>s.explorerFolderPath,[]))}function dx(){return Pt(x.useCallback(s=>s.contextModalAgentId,[]))}function KN(){return Pt(x.useCallback(s=>s.toolExecutions,[]),ea)}function jB(){return Pt(x.useCallback(s=>s.fileChanges,[]),ea)}function XN(){return Pt(x.useCallback(s=>s.skills,[]),ar)}function nf(){const s=XN(),e=x.useRef([]),t=Array.from(s.values());return ea(e.current,t)||(e.current=t),e.current}function CB(s){return Pt(x.useCallback(e=>s?e.skills.get(s):void 0,[s]))}function AB(s){const e=x.useRef([]),t=ir(),n=XN();if(!s)return e.current;const a=t.get(s);return a?Array.from(n.values()).filter(o=>o.enabled?!!(o.assignedAgentIds.includes(s)||o.assignedAgentClasses.includes(a.class)):!1):e.current}function NB(){return Pt(x.useCallback(s=>s.customAgentClasses,[]),ar)}function ei(){const s=NB(),e=x.useRef([]),t=Array.from(s.values());return ea(e.current,t)||(e.current=t),e.current}function ZN(s){return Pt(x.useCallback(e=>s?e.customAgentClasses.get(s):void 0,[s]))}function hx(){return Pt(x.useCallback(s=>s.reconnectCount,[]))}function MB(){return Pt(x.useCallback(s=>s.supervisor.globalUsage,[]))}function TB(){return Pt(x.useCallback(s=>s.supervisor.refreshingUsage,[]))}function EB(s){const e=x.useRef(new Map);return Pt(x.useCallback(t=>s&&t.agentTaskProgress.get(s)||e.current,[s]),ar)}function _B(s){return Pt(x.useCallback(e=>!s||!e.execTasks?[]:Array.from(e.execTasks.values()).filter(t=>t.agentId===s),[s]),ea)}function DB(){return Pt(x.useCallback(s=>s.secrets,[]),ar)}function RB(){const s=DB(),e=x.useRef([]),t=Array.from(s.values());return ea(e.current,t)||(e.current=t),e.current}const PB={connectionStatus:new Map,databases:new Map,tables:new Map,tableSchemas:new Map,queryResults:[],queryHistory:[],executingQuery:!1,activeConnectionId:null,activeDatabase:null,lastSilentQueryResult:null};function sf(s){return Pt(x.useCallback(e=>(s?e.databaseState.get(s):void 0)??PB,[s]))}function LB(s){return Pt(x.useCallback(e=>{if(!s)return[];const t=e.databaseState.get(s);return(t==null?void 0:t.queryResults)??[]},[s]),ea)}function OB(s){return Pt(x.useCallback(e=>{if(!s)return[];const t=e.databaseState.get(s);return(t==null?void 0:t.queryHistory)??[]},[s]),ea)}function IB(s){return Pt(x.useCallback(e=>{if(!s)return!1;const t=e.databaseState.get(s);return(t==null?void 0:t.executingQuery)??!1},[s]))}function BB(){return Pt(s=>s.dockerContainersList,ea)}function zB(){return Pt(s=>s.currentSnapshot)}function FB(){return Pt(s=>s.subagents,ar)}function $B(s){return Pt(x.useCallback(e=>s?Array.from(e.subagents.values()).filter(t=>t.parentAgentId===s):[],[s]),ea)}function HB(){return Pt(s=>s.viewMode)}function UB(){return Pt(x.useCallback(s=>s.overviewPanelOpen,[]))}class fj{constructor(){G(this,"state");G(this,"listeners",new Set);G(this,"sendMessage",null);G(this,"agentActions");G(this,"outputActions");G(this,"supervisorActions");G(this,"areaActions");G(this,"buildingActions");G(this,"permissionActions");G(this,"delegationActions");G(this,"skillActions");G(this,"execTaskActions");G(this,"secretActions");G(this,"databaseActions");G(this,"snapshotActions");G(this,"subagentActions");G(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,fileViewerSearchRoot: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 o=Ds(xt.SCENE_VIEW_MODE,"3d");return o==="2d"||o==="3d"||o==="dashboard"?o:"3d"})(),overviewPanelOpen:!1};const e=()=>this.state,t=o=>{o(this.state)},n=()=>this.notify(),a=()=>this.sendMessage,i=()=>this.listeners.size;this.agentActions=sB(e,t,n,a),this.outputActions=aB(e,t,n,i),this.supervisorActions=iB(e,t,n,a),this.areaActions=rB(e,t,n,a),this.buildingActions=oB(e,t,n,a),this.permissionActions=lB(e,t,n,a),this.delegationActions=cB(e,t,n,a),this.skillActions=uB(e,t,n,a),this.execTaskActions=dB(e,t,n),this.secretActions=hB(e,t,n,a),this.databaseActions=pB(e,t,n,a),this.snapshotActions=fB(e,t,n),this.subagentActions=mB(e,t,n)}loadSettings(){const e=xi(xt.SETTINGS,null);return e?{...hj,...e}:{...hj}}loadShortcuts(){const e=xi(xt.SHORTCUTS,null);return e?Wg.map(n=>{const a=e.find(i=>i.id===n.id);return a?{...n,...a}:n}):[...Wg]}loadMouseControls(){var t;const e=xi(xt.MOUSE_CONTROLS,null);return e?{bindings:Yg.map(a=>{var o;const i=(o=e.bindings)==null?void 0:o.find(l=>l.id===a.id);return i?{...a,...i}:a}),sensitivity:{...qg,...e.sensitivity},trackpad:{...Dh,...e.trackpad,sensitivity:{...Dh.sensitivity,...(t=e.trackpad)==null?void 0:t.sensitivity}}}:{bindings:[...Yg],sensitivity:{...qg},trackpad:{...Dh}}}loadMobileView(){const e=Ds(xt.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,La(xt.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,La(xt.SCENE_VIEW_MODE,e),this.state.settings.experimental2DView=e==="2d",this.notify()}openTerminalOnMobile(e){console.log("[Store] openTerminalOnMobile called for agent:",e),fP("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,n){this.state.fileViewerPath=e,this.state.fileViewerEditData=t||null,this.state.fileViewerSearchRoot=n||null,this.notify()}clearFileViewerPath(){this.state.fileViewerPath=null,this.state.fileViewerEditData=null,this.state.fileViewerSearchRoot=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},Qi(xt.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(a=>a.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=[...Wg],this.saveShortcuts(),this.notify()}saveShortcuts(){Qi(xt.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(a=>a.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:[...Yg],sensitivity:{...qg},trackpad:{...Dh}},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(){Qi(xt.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)}moveAgentLocal(...e){return this.agentActions.moveAgentLocal(...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)}executeSilentQuery(...e){return this.databaseActions.executeSilentQuery(...e)}setSilentQueryResult(...e){return this.databaseActions.setSilentQueryResult(...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 mj=1;function GB(){return typeof window<"u"?(window.__tideStore&&window.__tideStoreVersion===mj||(window.__tideStore=new fj,window.__tideStoreVersion=mj),window.__tideStore):new fj}const H=GB(),QN=x.createContext(null),WB={error:"❌",success:"✅",warning:"⚠️",info:"ℹ️"};let qB=0;function YB({children:s}){const[e,t]=x.useState(null),n=x.useRef([]),a=x.useRef(null),i=x.useCallback(()=>{if(n.current.length>0&&!e){const c=n.current.shift();t(c)}},[e]);x.useEffect(()=>{e||i()},[e,i]),x.useEffect(()=>{if(e&&e.duration>0)return a.current=window.setTimeout(()=>{t(null)},e.duration),()=>{a.current&&clearTimeout(a.current)}},[e]);const o=x.useCallback((c,d,f,p=5e3)=>{const b={id:++qB,type:c,title:d,message:f,duration:p};if(n.current.push(b),!e){const y=n.current.shift();t(y)}},[e]),l=x.useCallback(()=>{a.current&&clearTimeout(a.current),t(null)},[]);return r.jsxs(QN.Provider,{value:{showToast:o},children:[s,r.jsx("div",{id:"toast-container",children:e&&r.jsxs("div",{className:`toast ${e.type}`,children:[r.jsx("span",{className:"toast-icon",children:WB[e.type]}),r.jsxs("div",{className:"toast-content",children:[r.jsx("div",{className:"toast-title",children:e.title}),r.jsx("div",{className:"toast-message",children:e.message})]}),r.jsx("button",{className:"toast-close",onClick:l,children:"×"})]},e.id)})]})}function px(){const s=x.useContext(QN);if(!s)throw new Error("useToast must be used within ToastProvider");return s}const tr={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"}},vi=tr,Va={bypass:{label:"Permissionless",description:"Skip all permission prompts (less safe, faster)"},interactive:{label:"Interactive",description:"Ask for approval before sensitive operations"}},Ra={"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:"🧩"}},Pa={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:"🚀"}},fy="<<<BOSS_CONTEXT_START>>>",gj="<<<BOSS_CONTEXT_END>>>",sc={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"}},Jh={"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"}},bj={"":{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)"}},yj={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"}},xj={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"}},vu={mysql:{label:"MySQL",icon:"🐬",defaultPort:3306},postgresql:{label:"PostgreSQL",icon:"🐘",defaultPort:5432},oracle:{label:"Oracle",icon:"🔶",defaultPort:1521}},JN=x.createContext(null);function VB(s){const e=tr[s];if(e)return e.icon;const n=H.getState().customAgentClasses.get(s);return n?n.icon:"🤖"}function KB(s){const e=tr[s];if(e)return e.color;const n=H.getState().customAgentClasses.get(s);return n?n.color:"#888888"}const XB=3;function ZB({children:s}){const{t:e}=He(["notifications"]),[t,n]=x.useState([]),a=x.useRef(new Map);x.useEffect(()=>()=>{a.current.forEach(c=>clearTimeout(c))},[]);const i=x.useCallback(c=>{n(f=>f.filter(p=>p.id!==c));const d=a.current.get(c);d&&(clearTimeout(d),a.current.delete(c))},[]),o=x.useCallback(c=>{n(f=>{const p=[...f,c];if(p.length>XB){const g=p.shift();if(g){const b=a.current.get(g.id);b&&(clearTimeout(b),a.current.delete(g.id))}}return p});const d=window.setTimeout(()=>{i(c.id)},8e3);a.current.set(c.id,d),$I({title:`${c.agentName}: ${c.title}`,body:c.message,data:{type:"agent_notification",agentId:c.agentId,notificationId:c.id}})},[i]),l=x.useCallback(c=>{$N(c.agentId),i(c.id)},[i]);return r.jsxs(JN.Provider,{value:{showAgentNotification:o},children:[s,r.jsx("div",{id:"agent-notification-container",children:t.map(c=>{const d=VB(c.agentClass),f=KB(c.agentClass);return r.jsxs("div",{className:"agent-notification",onClick:()=>l(c),style:{"--agent-color":f},children:[r.jsx("div",{className:"agent-notification-avatar",children:r.jsx("span",{className:"agent-notification-icon",children:d})}),r.jsxs("div",{className:"agent-notification-content",children:[r.jsxs("div",{className:"agent-notification-header",children:[r.jsx("span",{className:"agent-notification-name",children:c.agentName}),r.jsx("span",{className:"agent-notification-hint",children:e("notifications:agent.clickToFocus")})]}),r.jsx("div",{className:"agent-notification-title",children:c.title}),r.jsx("div",{className:"agent-notification-message",children:c.message})]}),r.jsx("button",{className:"agent-notification-close",onClick:p=>{p.stopPropagation(),i(c.id)},children:"×"})]},c.id)})})]})}function QB(){const s=x.useContext(JN);if(!s)throw new Error("useAgentNotification must be used within AgentNotificationProvider");return s}function JB(s){return typeof s=="string"?s:"#"+s.toString(16).padStart(6,"0")}function Zr(s,e){const t=Oa[s];if(t)return{icon:t.icon,color:JB(t.color),description:t.description};const n=e.find(a=>a.id===s);return n?{icon:n.icon,color:n.color,description:n.description}:{icon:"🤖",color:"#888888"}}function e5(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 kp(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 eM(s){const e=s.contextStats;if(e){const i=e.usedPercent,o=100-i,l=e.contextWindow-e.totalTokens;return{remainingPercent:o,usedPercent:i,hasData:!0,totalTokens:e.totalTokens,contextWindow:e.contextWindow,freeTokens:l}}const t=s.contextUsed||0,n=s.contextLimit||2e5,a=Math.max(0,n-t);return{remainingPercent:a/n*100,usedPercent:t/n*100,hasData:!1,totalTokens:t,contextWindow:n,freeTokens:a}}function t5(s){return s<20?"#c85858":s<50?"#c89858":"#6a9a78"}function n5(s,e){const t=new Map;for(const n of s){const a=e(n.id),i=(a==null?void 0:a.id)||null;t.has(i)||t.set(i,[]),t.get(i).push(n)}return t}function s5(s,e){return[...s].sort((t,n)=>{if(t===null)return 1;if(n===null)return-1;const a=t?e(t):void 0,i=n?e(n):void 0;return((a==null?void 0:a.name)||"").localeCompare((i==null?void 0:i.name)||"")})}function vj({onOpenAreaExplorer:s}){const{t:e}=He(["common"]),t=An(),n=Array.from(t.agents.values()),a=Array.from(t.areas.values()),i=x.useMemo(()=>n.map(d=>d.id).sort().join(","),[n]),o=x.useRef(new Set);x.useEffect(()=>{for(const d of n){if(o.current.has(d.id))continue;H.getAgentSupervisorHistory(d.id).length===0&&!H.isLoadingHistoryForAgent(d.id)&&(o.current.add(d.id),H.requestAgentSupervisorHistory(d.id))}},[i]);const l=n5(n,d=>H.getAreaForAgent(d));for(const d of a)l.has(d.id)||l.set(d.id,[]);const c=s5(Array.from(l.keys()),d=>t.areas.get(d));return n.length===0&&a.length===0?r.jsxs("div",{className:"empty-state",children:[r.jsx("div",{className:"empty-state-icon",children:"⚔️"}),r.jsx("div",{className:"empty-state-title",children:e("agentsList.noAgentsDeployed")}),r.jsx("div",{className:"empty-state-desc",children:e("agentsList.clickNewAgent")})]}):r.jsxs("div",{className:"agents-list",children:[r.jsx("div",{className:"agents-list-header",children:e("agentsList.areasAndAgents")}),c.map(d=>{const f=l.get(d),p=d?t.areas.get(d):null;return r.jsxs("div",{className:"agents-group",children:[r.jsxs("div",{className:"agents-group-header",style:p?{borderLeftColor:p.color,background:`${p.color}15`}:void 0,children:[p?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"agents-group-dot",style:{background:p.color}}),r.jsx("span",{className:"agents-group-name",children:p.name}),p.directories.length>0&&r.jsx("button",{className:"area-browse-btn",onClick:()=>s==null?void 0:s(p.id),title:e("agentsList.browseFiles"),children:"📂"})]}):r.jsx("span",{className:"agents-group-name unassigned",children:e("agentsList.unassigned")}),r.jsx("span",{className:"agents-group-count",children:f.length})]}),f.length>0&&r.jsx("div",{className:"agents-group-items",style:p?{background:`${p.color}08`}:void 0,children:f.map(g=>r.jsx(a5,{agent:g,area:p},g.id))})]},d||"unassigned")}),n.length>0&&r.jsx(i5,{agents:n})]})}const a5=x.memo(function({agent:e,area:t}){const n=An(),a=ei(),i=Zr(e.class,a),o=n.selectedAgentIds.has(e.id),[,l]=x.useState(0);x.useEffect(()=>{if(e.status==="idle"){const p=setInterval(()=>{l(g=>g+1)},15e3);return()=>clearInterval(p)}},[e.status]);const c=()=>{H.selectAgent(e.id)},d=e.status==="idle"&&e.lastActivity>0,f=e.lastActivity>0?Kp(e.lastActivity):void 0;return r.jsxs("div",{className:`agent-item ${o?"selected":""}`,onClick:c,children:[r.jsx("div",{className:"agent-item-icon",style:{background:`${i.color}20`},children:i.icon}),r.jsxs("div",{className:"agent-item-info",children:[r.jsx("div",{className:"agent-item-name",children:e.name}),r.jsxs("div",{className:"agent-item-status",children:[e.status,e.currentTool?` • ${e.currentTool}`:"",d&&r.jsxs("span",{className:"agent-item-idle",style:{color:f},title:Xp(e.lastActivity),children:[" ","⏱ ",e5(e.lastActivity)]})]})]}),r.jsx("div",{className:`agent-status-dot ${e.status}`})]})}),i5=x.memo(function({agents:e}){const{t}=He(["common"]),n=An(),a=ei(),i=n.settings.hideCost,[o,l]=x.useState(()=>Qb(xt.GLOBAL_SUPERVISOR_COLLAPSED)),c=()=>{const p=!o;l(p),Jb(xt.GLOBAL_SUPERVISOR_COLLAPSED,p)},d=x.useMemo(()=>e.map(p=>{const g=H.getAgentSupervisorHistory(p.id),b=g.length>0?g[0]:null;return{agent:p,entry:b,timestamp:(b==null?void 0:b.timestamp)||p.lastActivity||0}}).filter(p=>p.entry!==null).sort((p,g)=>g.timestamp-p.timestamp),[e,n.supervisor.agentHistories]),f=d.length>0?d[0].timestamp:Date.now();return d.length===0?null:r.jsxs("div",{className:"global-supervisor-status",children:[r.jsxs("div",{className:"global-supervisor-header",onClick:c,children:[r.jsx("span",{className:"global-supervisor-toggle",children:o?"▶":"▼"}),r.jsx("span",{className:"global-supervisor-title",children:t("agentsList.supervisorStatus")}),r.jsx("span",{className:"global-supervisor-time",children:kp(f)})]}),!o&&r.jsx("div",{className:"global-supervisor-list",children:d.map(({agent:p,entry:g})=>{const b=Zr(p.class,a),y=g.analysis;return r.jsxs("div",{className:"global-supervisor-item",onClick:()=>H.selectAgent(p.id),children:[r.jsxs("div",{className:"global-supervisor-item-header",children:[r.jsx("span",{className:"global-supervisor-progress-dot",style:{background:dN[y.progress]||"#888"}}),r.jsx("span",{className:"global-supervisor-agent-icon",children:b.icon}),r.jsx("span",{className:"global-supervisor-agent-name",children:p.name}),r.jsx("span",{className:"global-supervisor-item-time",children:kp(g.timestamp)})]}),r.jsx("div",{className:"global-supervisor-status-line",children:Ur(y.statusDescription,i)}),r.jsx("div",{className:"global-supervisor-summary-text",children:Ur(y.recentWorkSummary,i)})]},p.id)})})]})}),r5={idle:"idle",working:"walk",waiting:"sit",waiting_permission:"idle",error:"emote-no",offline:"static",orphaned:"idle"},wj={idle:4915102,working:4890367,waiting:16752202,waiting_permission:16763904,error:16730698,offline:8947848,orphaned:16752202};function cc({agentClass:s,modelFile:e,customModelFile:t,customModelUrl:n,modelScale:a=1,modelOffset:i,idleAnimation:o,status:l="idle",width:c=150,height:d=200}){const f=x.useRef(null),p=x.useRef(null),g=x.useRef(null),b=x.useRef(null),y=x.useRef(null),w=x.useRef(null),k=x.useRef(new Map),S=x.useRef(null),j=x.useRef(null),C=x.useRef(0),N=x.useRef(new KA),[D,E]=x.useState(!1),[$,M]=x.useState(!1),R=x.useRef(!1),_=x.useRef(0),P=x.useRef(new bt),O=x.useRef(!1),F=x.useRef({x:0,y:0}),B=x.useRef({x:0,y:0});x.useEffect(()=>{const U=f.current;if(!U)return;M(!1);const q=new Xy;q.background=new zt(1710628),g.current=q;const K=new Vy(45,c/d,.1,100);K.position.set(0,1.2,1.4),K.lookAt(0,.4,0),b.current=K;let X;try{X=new XA({antialias:!0,alpha:!0})}catch{console.warn("[ModelPreview] WebGL context creation failed — too many active contexts"),M(!0);return}X.setSize(c,d),X.setPixelRatio(Math.min(window.devicePixelRatio,2)),X.setClearColor(1710628,1),U.appendChild(X.domElement),p.current=X;const L=new Ky(16777215,1);q.add(L);const ee=new ec(16777215,1.5);ee.position.set(2,3,2),q.add(ee);const Z=new ec(4890367,.6);Z.position.set(-2,1,-1),q.add(Z);const z=new Hb(1,32),V=new it({color:2763322,roughness:.8}),Q=new _e(z,V);Q.rotation.x=-Math.PI/2,Q.position.y=0,q.add(Q);const J=new Yo(.35,.42,32),Y=new We({color:wj.idle,side:Ss,transparent:!0,opacity:.8}),se=new _e(J,Y);se.rotation.x=-Math.PI/2,se.position.y=.01,q.add(se),j.current=se,E(!0);const ae=he=>{O.current=!0,F.current={x:he.clientX,y:he.clientY},U.style.cursor="grabbing"},le=he=>{if(!O.current||!y.current)return;const we=he.clientX-F.current.x,Me=he.clientY-F.current.y;B.current.y+=we*.01,B.current.x+=Me*.01,B.current.x=Math.max(-Math.PI/4,Math.min(Math.PI/4,B.current.x)),y.current.rotation.y=B.current.y,y.current.rotation.x=B.current.x,F.current={x:he.clientX,y:he.clientY}},pe=()=>{O.current=!1,U.style.cursor="grab"},be=()=>{O.current=!1,U.style.cursor="grab"};U.addEventListener("mousedown",ae),window.addEventListener("mousemove",le),window.addEventListener("mouseup",pe),U.addEventListener("mouseleave",be),U.style.cursor="grab";const ce=()=>{C.current=requestAnimationFrame(ce);const he=N.current.getDelta();if(w.current)w.current.update(he);else if(y.current&&!R.current){_.current+=he;const we=_.current,ne=Math.sin(we*1.5)*.02,ye=Math.sin(we*.8)*.01;y.current.position.set(P.current.x+ye,P.current.y+ne,P.current.z)}p.current&&g.current&&b.current&&p.current.render(g.current,b.current)};return ce(),()=>{if(cancelAnimationFrame(C.current),U.removeEventListener("mousedown",ae),window.removeEventListener("mousemove",le),window.removeEventListener("mouseup",pe),U.removeEventListener("mouseleave",be),y.current&&g.current&&(g.current.remove(y.current),y.current.traverse(he=>{var we,Me;he instanceof _e&&((we=he.geometry)==null||we.dispose(),Array.isArray(he.material)?he.material.forEach(re=>{re.map&&re.map.dispose(),re.dispose()}):he.material&&(he.material.map&&((Me=he.material.map)==null||Me.dispose()),he.material.dispose()))}),y.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(he=>{var we;he instanceof _e&&((we=he.geometry)==null||we.dispose(),he.material instanceof Hr&&he.material.dispose())}),g.current.clear()),w.current=null,S.current=null,k.current.clear(),p.current){try{const we=p.current.getContext().getExtension("WEBGL_lose_context");we&&we.loseContext()}catch{}p.current.dispose(),U.contains(p.current.domElement)&&U.removeChild(p.current.domElement),p.current=null}g.current=null,b.current=null,E(!1)}},[c,d]),x.useEffect(()=>{if(!D||!g.current)return;const U=new ex,q=new tx;q.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.7/"),U.setDRACOLoader(q),U.setMeshoptDecoder(nx);let K=null;const X=L=>{y.current&&g.current&&(g.current.remove(y.current),y.current=null,w.current=null,S.current=null);const ee=L.scene;ee.scale.setScalar(a);const Z=(i==null?void 0:i.x)??0,z=(i==null?void 0:i.y)??0,V=(i==null?void 0:i.z)??0;if(ee.position.set(Z,V,z),ee.visible=!0,B.current={x:0,y:0},ee.rotation.set(0,0,0),ee.traverse(Q=>{if(Q instanceof _e&&(Q.castShadow=!0,Q.receiveShadow=!0,Q.material)){const J=Q.material;J.map&&(J.map.colorSpace=qa)}}),g.current)if(g.current.add(ee),y.current=ee,P.current.copy(ee.position),L.animations.length>0){R.current=!0;const Q=new Fu(ee);w.current=Q,k.current.clear();for(const J of L.animations)k.current.set(J.name.toLowerCase(),J);if(o!==""){const J=o?k.current.get(o.toLowerCase())||L.animations[0]:k.current.get("idle")||L.animations[0];if(J){const Y=Q.clipAction(J);Y.reset().play(),S.current=Y}}}else R.current=!1,w.current=null,k.current.clear()};if(t)K=URL.createObjectURL(t),console.log("[ModelPreview] Loading custom model from file:",t.name,"blob URL:",K),U.load(K,L=>{console.log("[ModelPreview] Successfully loaded custom model file, animations:",L.animations.length),X(L)},void 0,L=>{console.error("[ModelPreview] Failed to load custom model file:",L)});else if(n){const L=bN(n);console.log("[ModelPreview] Loading custom model from URL:",n),U.load(L,ee=>{console.log("[ModelPreview] Successfully loaded custom model URL, animations:",ee.animations.length),X(ee)},void 0,ee=>{console.error("[ModelPreview] Failed to load custom model URL:",n,ee)})}else{const L=e||(s?Ql[s]:void 0)||"character-male-a.glb";U.load(`/assets/characters/${L}`,X,void 0,ee=>{console.error("[ModelPreview] Failed to load model:",L,ee)})}return()=>{K&&URL.revokeObjectURL(K),q.dispose()}},[s,e,t,n,a,i,D]);const I=U=>{if(!w.current)return;const q=r5[U],K=k.current.get(q);if(!K){const L=k.current.get("idle");if(L){const ee=w.current.clipAction(L);ee.reset().play(),S.current=ee}return}const X=w.current.clipAction(K);U==="working"?X.timeScale=1.5:U==="error"&&(X.setLoop(WA,1),X.clampWhenFinished=!0),S.current&&S.current!==X?(S.current.fadeOut(.3),X.reset().fadeIn(.3).play()):X.reset().play(),S.current=X};return x.useEffect(()=>{if(D){if(j.current){const U=j.current.material;U.color.setHex(wj[l]),l==="working"?U.opacity=.6+Math.sin(Date.now()*.005)*.4:U.opacity=.8}I(l)}},[l,D]),x.useEffect(()=>{if(!D||!w.current||l!=="idle")return;if(o===""){S.current&&(S.current.stop(),S.current=null);return}const U=o?o.toLowerCase():"idle",q=k.current.get(U);if(q){const K=w.current.clipAction(q);S.current&&S.current!==K?(S.current.fadeOut(.3),K.reset().fadeIn(.3).play()):K.reset().play(),S.current=K}else S.current&&(S.current.stop(),S.current=null)},[o,D,l]),$?r.jsx("div",{className:"model-preview",style:{width:c,height:d,borderRadius:8,overflow:"hidden",background:"#1a1a24",display:"flex",alignItems:"center",justifyContent:"center",color:"#666",fontSize:12,textAlign:"center",padding:8},children:"3D preview unavailable"}):r.jsx("div",{ref:f,className:"model-preview",style:{width:c,height:d,borderRadius:8,overflow:"hidden",background:"#1a1a24"}})}function Qr({value:s,onChange:e,onSubmit:t,placeholder:n="/path/to/folder",className:a="",directoriesOnly:i=!0,autoFocus:o=!1,hasError:l=!1,disabled:c=!1}){const[d,f]=x.useState([]),[p,g]=x.useState(-1),[b,y]=x.useState(!1),[w,k]=x.useState(!1),S=x.useRef(null),j=x.useRef(null),C=x.useRef(null),N=x.useCallback(async P=>{if(!P){f([]);return}k(!0);try{const O=new URLSearchParams({path:P,dirs:i?"true":"false",limit:"15"}),F=await ft(st(`/api/files/autocomplete?${O}`));if(F.ok){const B=await F.json();f(B.suggestions||[]),g(-1)}}catch(O){console.error("Failed to fetch path suggestions:",O)}finally{k(!1)}},[i]);x.useEffect(()=>(C.current&&clearTimeout(C.current),s&&b?C.current=setTimeout(()=>{N(s)},150):f([]),()=>{C.current&&clearTimeout(C.current)}),[s,b,N]);const D=P=>{e(P.target.value),y(!0)},E=x.useCallback(P=>{var F;const O=P.isDirectory?P.path+"/":P.path;e(O),y(P.isDirectory),g(-1),(F=S.current)==null||F.focus(),P.isDirectory&&N(O)},[e,N]),$=P=>{if(!b||d.length===0){P.key==="Enter"&&t&&(P.preventDefault(),t()),P.key==="Escape"&&y(!1);return}switch(P.key){case"ArrowDown":P.preventDefault(),g(O=>O<d.length-1?O+1:O);break;case"ArrowUp":P.preventDefault(),g(O=>O>0?O-1:-1);break;case"Tab":if(P.preventDefault(),d.length>0){const O=p>=0?p:0;E(d[O])}break;case"Enter":P.preventDefault(),p>=0&&d[p]?E(d[p]):t&&(y(!1),t());break;case"Escape":P.preventDefault(),y(!1),g(-1);break}},M=()=>{y(!0),s&&N(s)},R=()=>{setTimeout(()=>{y(!1),g(-1)},200)};x.useEffect(()=>{if(p>=0&&j.current){const O=j.current.querySelectorAll(".folder-input-suggestion")[p];O&&O.scrollIntoView({block:"nearest"})}},[p]);const _=["folder-input",a,l?"error":""].filter(Boolean).join(" ");return r.jsxs("div",{className:"folder-input-container",children:[r.jsx("input",{ref:S,type:"text",className:_,value:s,onChange:D,onKeyDown:$,onFocus:M,onBlur:R,placeholder:n,autoFocus:o,disabled:c,autoComplete:"off",spellCheck:!1}),b&&(d.length>0||w)&&r.jsx("div",{ref:j,className:"folder-input-suggestions",children:w&&d.length===0?r.jsx("div",{className:"folder-input-loading",children:"Loading..."}):d.map((P,O)=>r.jsxs("div",{className:`folder-input-suggestion ${O===p?"selected":""}`,onClick:()=>E(P),onMouseEnter:()=>g(O),children:[r.jsx("span",{className:"folder-input-suggestion-icon",children:P.isDirectory?"📁":"📄"}),r.jsx("span",{className:"folder-input-suggestion-name",children:P.name}),P.isDirectory&&r.jsx("span",{className:"folder-input-suggestion-hint",children:"/"})]},P.path))})]})}function tM({agent:s,isOpen:e,onClose:t}){const{t:n}=He(["terminal","common","tools"]),a=nf(),i=ei(),[o,l]=x.useState(s.name),[c,d]=x.useState(s.class),[f,p]=x.useState(s.permissionMode),[g,b]=x.useState(s.provider||"claude"),[y,w]=x.useState(s.codexConfig||{fullAuto:!0,sandbox:"workspace-write",approvalMode:"on-request",search:!1}),[k,S]=x.useState(s.model||"sonnet"),[j,C]=x.useState(s.codexModel||"gpt-5.3-codex"),[N,D]=x.useState(s.useChrome||!1),[E,$]=x.useState(s.cwd),[M,R]=x.useState(new Set),[_,P]=x.useState("");x.useMemo(()=>a.filter(Q=>Q.enabled&&(Q.assignedAgentIds.includes(s.id)||Q.assignedAgentClasses.includes(s.class))),[a,s.id,s.class]),x.useEffect(()=>{const Q=a.filter(J=>J.assignedAgentIds.includes(s.id)).map(J=>J.id);R(new Set(Q))},[a,s.id]),x.useEffect(()=>{if(e){l(s.name),d(s.class),p(s.permissionMode),b(s.provider||"claude"),w(s.codexConfig||{fullAuto:!0,sandbox:"workspace-write",approvalMode:"on-request",search:!1}),S(s.model||"sonnet"),C(s.codexModel||"gpt-5.3-codex"),D(s.useChrome||!1),$(s.cwd);const Q=a.filter(J=>J.assignedAgentIds.includes(s.id)).map(J=>J.id);R(new Set(Q))}},[e,s,a]);const O=x.useMemo(()=>a.filter(Q=>Q.enabled),[a]),F=x.useMemo(()=>{if(!_.trim())return O;const Q=_.toLowerCase();return O.filter(J=>J.name.toLowerCase().includes(Q)||J.description.toLowerCase().includes(Q)||J.slug.toLowerCase().includes(Q))},[O,_]),B=x.useMemo(()=>O.filter(Q=>Q.assignedAgentClasses.includes(c)),[O,c]),I=x.useCallback(Q=>{R(J=>{const Y=new Set(J);return Y.has(Q)?Y.delete(Q):Y.add(Q),Y})},[]),U=x.useMemo(()=>{const Q=i.find(J=>J.id===c);if(Q!=null&&Q.model)return Q.model},[i,c]),q=x.useMemo(()=>{const Q=i.find(J=>J.id===c);if(Q!=null&&Q.customModelPath)return st(`/api/custom-models/${Q.id}`)},[i,c]),K=x.useMemo(()=>{const Q=i.find(J=>J.id===c);return Q==null?void 0:Q.modelScale},[i,c]),X=x.useMemo(()=>i.find(Q=>Q.id===c),[i,c]),L=x.useMemo(()=>i.find(J=>J.id===c)?"scout":c,[i,c]),ee=x.useMemo(()=>{const Q=o.trim();if(Q&&Q!==s.name||c!==s.class||f!==s.permissionMode||g!==(s.provider||"claude")||g==="claude"&&k!==(s.model||"sonnet")||g==="codex"&&j!==(s.codexModel||"gpt-5.3-codex")||g==="codex"&&JSON.stringify(y||{})!==JSON.stringify(s.codexConfig||{})||N!==(s.useChrome||!1)||E!==s.cwd)return!0;const J=a.filter(se=>se.assignedAgentIds.includes(s.id)).map(se=>se.id).sort().join(","),Y=Array.from(M).sort().join(",");return J!==Y},[o,c,f,g,k,j,y,N,E,M,s,a]),Z=()=>{const Q=o.trim(),J={};Q&&Q!==s.name&&H.renameAgent(s.id,Q),c!==s.class&&(J.class=c),f!==s.permissionMode&&(J.permissionMode=f),g!==(s.provider||"claude")&&(J.provider=g),g==="codex"&&JSON.stringify(y||{})!==JSON.stringify(s.codexConfig||{})&&(J.codexConfig=y),g==="codex"&&j!==(s.codexModel||"gpt-5.3-codex")&&(J.codexModel=j),g==="claude"&&k!==(s.model||"sonnet")&&(J.model=k),N!==(s.useChrome||!1)&&(J.useChrome=N),E!==s.cwd&&(J.cwd=E);const Y=a.filter(ae=>ae.assignedAgentIds.includes(s.id)).map(ae=>ae.id).sort().join(","),se=Array.from(M).sort().join(",");Y!==se&&(J.skillIds=Array.from(M)),Object.keys(J).length>0&&H.updateAgentProperties(s.id,J),t()},{handleMouseDown:z,handleClick:V}=js(t);return e?r.jsx("div",{className:"modal-overlay visible",onMouseDown:z,onClick:V,children:r.jsxs("div",{className:"modal agent-edit-modal",children:[r.jsxs("div",{className:"modal-header",children:[n("terminal:spawn.editAgentTitle"),": ",o.trim()||s.name]}),r.jsxs("div",{className:"modal-body spawn-modal-body",children:[r.jsxs("div",{className:"spawn-top-section",children:[r.jsx("div",{className:"spawn-preview-compact",children:r.jsx(cc,{agentClass:L,modelFile:U,customModelUrl:q,modelScale:K,width:100,height:120})}),r.jsxs("div",{className:"spawn-class-section",children:[r.jsx("div",{className:"spawn-class-label",children:n("terminal:spawn.agentClass")}),r.jsxs("div",{className:"class-selector-inline",children:[i.map(Q=>r.jsxs("button",{className:`class-chip ${c===Q.id?"selected":""}`,onClick:()=>d(Q.id),title:Q.description,children:[r.jsx("span",{className:"class-chip-icon",children:Q.icon}),r.jsx("span",{className:"class-chip-name",children:Q.name})]},Q.id)),Object.entries(tr).filter(([Q])=>Q!=="boss").map(([Q,J])=>r.jsxs("button",{className:`class-chip ${c===Q?"selected":""}`,onClick:()=>d(Q),title:J.description,children:[r.jsx("span",{className:"class-chip-icon",children:J.icon}),r.jsx("span",{className:"class-chip-name",children:Q.charAt(0).toUpperCase()+Q.slice(1)})]},Q))]})]})]}),(X==null?void 0:X.instructions)&&r.jsxs("div",{className:"custom-class-notice",children:[r.jsxs("div",{className:"custom-class-notice-header",children:[r.jsx("span",{children:"📋"}),r.jsx("span",{children:n("terminal:spawn.hasCustomInstructions")})]}),r.jsx("div",{className:"custom-class-notice-info",children:n("terminal:spawn.instructionsInjected",{count:X.instructions.length})})]}),r.jsxs("div",{className:"spawn-form-section",children:[r.jsx("div",{className:"spawn-form-row",children:r.jsxs("div",{className:"spawn-field",children:[r.jsx("label",{className:"spawn-label",children:n("common:labels.name")}),r.jsx("input",{type:"text",className:"spawn-input",value:o,onChange:Q=>l(Q.target.value),placeholder:n("terminal:spawn.agentNamePlaceholder")})]})}),r.jsxs("div",{className:"spawn-form-row",children:[r.jsxs("div",{className:"spawn-field",children:[r.jsx("label",{className:"spawn-label",children:n("common:labels.runtime")}),r.jsxs("div",{className:"spawn-select-row",children:[r.jsxs("button",{className:`spawn-select-btn ${g==="claude"?"selected":""}`,onClick:()=>b("claude"),children:[r.jsx("span",{children:"🧠"}),r.jsx("span",{children:"Claude"})]}),r.jsxs("button",{className:`spawn-select-btn ${g==="codex"?"selected":""}`,onClick:()=>b("codex"),children:[r.jsx("span",{children:"⚙️"}),r.jsx("span",{children:"Codex"})]})]})]}),r.jsxs("div",{className:"spawn-field",children:[r.jsx("label",{className:"spawn-label",children:n("common:labels.permissions")}),r.jsx("div",{className:"spawn-select-row",children:Object.keys(Va).map(Q=>r.jsxs("button",{className:`spawn-select-btn ${f===Q?"selected":""}`,onClick:()=>p(Q),title:Va[Q].description,children:[r.jsx("span",{children:Q==="bypass"?"⚡":"🔐"}),r.jsx("span",{children:Va[Q].label})]},Q))})]})]}),r.jsx("div",{className:"spawn-form-row",children:r.jsxs("div",{className:"spawn-field",children:[r.jsx("label",{className:"spawn-label",children:n("common:labels.model")}),g==="claude"?r.jsx("div",{className:"spawn-select-row",children:Object.keys(Pa).map(Q=>r.jsxs("button",{className:`spawn-select-btn ${k===Q?"selected":""}`,onClick:()=>S(Q),title:Pa[Q].description,children:[r.jsx("span",{children:Pa[Q].icon}),r.jsx("span",{children:Pa[Q].label})]},Q))}):g==="codex"?r.jsx("div",{className:"spawn-select-row spawn-select-row--codex-models",children:Object.keys(Ra).map(Q=>r.jsxs("button",{className:`spawn-select-btn ${j===Q?"selected":""}`,onClick:()=>C(Q),title:Ra[Q].description,children:[r.jsx("span",{children:Ra[Q].icon}),r.jsx("span",{children:Ra[Q].label})]},Q))}):r.jsx("div",{className:"spawn-inline-hint",children:n("terminal:spawn.codex.configuration")})]})}),g==="codex"&&r.jsx("div",{className:"spawn-form-row",children:r.jsxs("div",{className:"spawn-field",children:[r.jsx("label",{className:"spawn-label",children:n("terminal:spawn.codex.config")}),r.jsxs("div",{className:"spawn-options-row",style:{display:"flex",flexDirection:"column",gap:8},children:[r.jsxs("label",{className:"spawn-checkbox",children:[r.jsx("input",{type:"checkbox",checked:y.fullAuto!==!1,onChange:Q=>w(J=>({...J,fullAuto:Q.target.checked}))}),r.jsx("span",{children:n("terminal:spawn.codex.useFullAuto")})]}),r.jsxs("label",{className:"spawn-checkbox",children:[r.jsx("input",{type:"checkbox",checked:!!y.search,onChange:Q=>w(J=>({...J,search:Q.target.checked}))}),r.jsx("span",{children:n("terminal:spawn.codex.enableSearch")})]}),y.fullAuto===!1&&r.jsxs(r.Fragment,{children:[r.jsxs("select",{className:"spawn-input",value:y.sandbox||"workspace-write",onChange:Q=>w(J=>({...J,sandbox:Q.target.value})),children:[r.jsx("option",{value:"read-only",children:n("terminal:spawn.codex.sandboxReadOnly")}),r.jsx("option",{value:"workspace-write",children:n("terminal:spawn.codex.sandboxWorkspaceWrite")}),r.jsx("option",{value:"danger-full-access",children:n("terminal:spawn.codex.sandboxDangerFullAccess")})]}),r.jsxs("select",{className:"spawn-input",value:y.approvalMode||"on-request",onChange:Q=>w(J=>({...J,approvalMode:Q.target.value})),children:[r.jsx("option",{value:"untrusted",children:n("terminal:spawn.codex.approvalsUntrusted")}),r.jsx("option",{value:"on-failure",children:n("terminal:spawn.codex.approvalsOnFailure")}),r.jsx("option",{value:"on-request",children:n("terminal:spawn.codex.approvalsOnRequest")}),r.jsx("option",{value:"never",children:n("terminal:spawn.codex.approvalsNever")})]})]}),r.jsx("input",{type:"text",className:"spawn-input",placeholder:n("terminal:spawn.codex.profileOptional"),value:y.profile||"",onChange:Q=>w(J=>({...J,profile:Q.target.value||void 0}))})]})]})}),g==="claude"&&k!==(s.model||"sonnet")&&r.jsx("div",{className:"model-change-notice",children:n("terminal:spawn.contextPreserved")}),r.jsx("div",{className:"spawn-form-row spawn-options-row",children:r.jsxs("label",{className:"spawn-checkbox",children:[r.jsx("input",{type:"checkbox",checked:N,onChange:Q=>D(Q.target.checked),disabled:g!=="claude"}),r.jsx("span",{children:n("terminal:spawn.chromeBrowser")})]})}),r.jsx("div",{className:"spawn-form-row",children:r.jsxs("div",{className:"spawn-field",children:[r.jsx("label",{className:"spawn-label",children:n("terminal:spawn.workingDir")}),r.jsx(Qr,{value:E,onChange:$,placeholder:n("terminal:spawn.workingDirPlaceholder"),className:"spawn-input",directoriesOnly:!0})]})}),E!==s.cwd&&r.jsx("div",{className:"model-change-notice warning",children:n("terminal:spawn.newSessionWarning")}),r.jsxs("div",{className:"spawn-skills-section",children:[r.jsxs("label",{className:"spawn-label",children:[n("terminal:spawn.skills")," ",r.jsxs("span",{className:"spawn-label-hint",children:["(",n("terminal:spawn.clickToToggle"),")"]})]}),O.length>6&&r.jsx("input",{type:"text",className:"spawn-input skill-search-input",placeholder:n("terminal:spawn.filterSkills"),value:_,onChange:Q=>P(Q.target.value)}),r.jsx("div",{className:"skills-chips-compact",children:O.length===0?r.jsx("div",{className:"skills-empty",children:n("terminal:spawn.noEnabledSkills")}):F.length===0?r.jsx("div",{className:"skills-empty",children:n("terminal:spawn.noSkillsMatch",{query:_})}):F.map(Q=>{const J=B.includes(Q),se=M.has(Q.id)||J;return r.jsxs("button",{className:`skill-chip ${se?"selected":""} ${J?"class-based":""}`,onClick:()=>!J&&I(Q.id),title:J?n("terminal:spawn.assignedViaClass"):Q.name,children:[se&&r.jsx("span",{className:"skill-check",children:"✓"}),r.jsx("span",{className:"skill-chip-name",children:Q.name}),Q.builtin&&r.jsx("span",{className:"skill-chip-badge builtin",children:"TC"}),J&&r.jsx("span",{className:"skill-chip-badge",children:"class"})]},Q.id)})})]})]})]}),r.jsxs("div",{className:"modal-footer",children:[r.jsx("button",{className:"btn btn-secondary",onClick:t,children:n("common:buttons.cancel")}),r.jsx("button",{className:"btn btn-primary",onClick:Z,disabled:!ee,children:n("common:buttons2.saveChanges")})]})]})}):null}var vc=PA();const o5=ld(vc);function nl({children:s}){return typeof document>"u"?null:vc.createPortal(s,document.body)}function wu(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}function kj(s){return`${s.toFixed(1)}%`}function l5(s){return s>=80?"#ff4a4a":s>=60?"#ff9e4a":s>=40?"#ffd700":"#4aff9e"}const c5={systemPrompt:"#4a9eff",systemTools:"#9e4aff",messages:"#4aff9e",freeSpace:"rgba(255,255,255,0.1)",autocompactBuffer:"#ff9e4a"},u5={systemPrompt:"terminal:context.systemPrompt",systemTools:"terminal:context.systemTools",messages:"terminal:context.messagesCategory",freeSpace:"terminal:context.freeSpace",autocompactBuffer:"terminal:context.autocompactBuffer"},d5={systemPrompt:"terminal:context.systemPromptDesc",systemTools:"terminal:context.systemToolsDesc",messages:"terminal:context.messagesDesc",freeSpace:"terminal:context.freeSpaceDesc",autocompactBuffer:"terminal:context.autocompactBufferDesc"};function nM({agent:s,isOpen:e,onClose:t,onRefresh:n}){const{t:a}=He(["terminal","common"]),i=s.contextStats,[o,l]=x.useState(!1),c=()=>{n&&!o&&(l(!0),n(),setTimeout(()=>l(!1),3e3))},d=["systemPrompt","systemTools","messages","autocompactBuffer","freeSpace"],f=x.useMemo(()=>i?d.map(y=>({key:y,...i.categories[y],label:a(u5[y]),description:a(d5[y]),color:c5[y]})):[],[i]),p=x.useMemo(()=>f.filter(y=>y.key!=="freeSpace"),[f]),{handleMouseDown:g,handleClick:b}=js(t);return e?r.jsx(nl,{children:r.jsx("div",{className:"modal-overlay visible",onMouseDown:g,onClick:b,children:r.jsxs("div",{className:"modal context-view-modal",style:{maxWidth:"520px"},children:[r.jsxs("div",{className:"modal-header",style:{display:"flex",alignItems:"center",gap:"12px"},children:[r.jsx("span",{style:{flex:1},children:a("terminal:context.contextWindow",{name:s.name})}),n&&r.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"?a("terminal:context.agentMustBeIdle"):a("terminal:context.fetchContextStats"),children:[r.jsx("span",{style:{display:"inline-block",animation:o?"spin 1s linear infinite":"none"},children:o?"⟳":"↻"}),a(o?"common:status.loading":"common:buttons.refresh")]})]}),r.jsx("div",{className:"modal-body",style:{padding:"16px"},children:i?r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px",padding:"8px 12px",background:"var(--bg-secondary)",borderRadius:"6px"},children:[r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:"11px",color:"var(--text-secondary)"},children:a("terminal:context.model")}),r.jsx("div",{style:{fontSize:"13px",fontWeight:500},children:i.model})]}),r.jsxs("div",{style:{textAlign:"right"},children:[r.jsx("div",{style:{fontSize:"11px",color:"var(--text-secondary)"},children:a("terminal:context.contextWindowLabel")}),r.jsx("div",{style:{fontSize:"13px",fontWeight:500},children:wu(i.contextWindow)})]})]}),r.jsxs("div",{style:{marginBottom:"24px"},children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:"8px",fontSize:"13px"},children:[r.jsx("span",{children:a("terminal:context.contextUsage")}),r.jsxs("span",{style:{color:l5(i.usedPercent)},children:[wu(i.totalTokens)," / ",wu(i.contextWindow)," (",i.usedPercent,"%)"]})]}),r.jsx("div",{style:{height:"28px",background:"var(--bg-tertiary)",borderRadius:"6px",overflow:"hidden",display:"flex"},children:p.map(y=>y.percent>0&&r.jsx("div",{style:{width:`${y.percent}%`,background:y.color,height:"100%",minWidth:y.percent>.5?"2px":"0",transition:"width 0.3s ease"},title:`${y.label}: ${wu(y.tokens)} (${kj(y.percent)})`},y.key))})]}),r.jsxs("div",{style:{marginBottom:"16px"},children:[r.jsx("div",{style:{fontSize:"12px",color:"var(--text-secondary)",marginBottom:"8px",textTransform:"uppercase",letterSpacing:"0.5px"},children:a("terminal:context.tokenBreakdown")}),r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"6px"},children:f.map(y=>r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px",padding:"10px 12px",background:y.key==="freeSpace"?"transparent":"var(--bg-secondary)",borderRadius:"6px",borderLeft:y.key==="freeSpace"?"3px dashed rgba(255,255,255,0.2)":`3px solid ${y.color}`,opacity:y.key==="freeSpace"?.7:1},children:[r.jsx("div",{style:{width:"12px",height:"12px",borderRadius:"3px",background:y.color,flexShrink:0,border:y.key==="freeSpace"?"1px dashed rgba(255,255,255,0.3)":"none"}}),r.jsxs("div",{style:{flex:1},children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500},children:y.label}),r.jsx("div",{style:{fontSize:"11px",color:"var(--text-secondary)"},children:y.description})]}),r.jsxs("div",{style:{textAlign:"right"},children:[r.jsx("div",{style:{fontSize:"13px",fontWeight:500},children:wu(y.tokens)}),r.jsx("div",{style:{fontSize:"11px",color:"var(--text-secondary)"},children:kj(y.percent)})]})]},y.key))})]}),r.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",textAlign:"center"},children:a("terminal:context.lastUpdated",{time:new Date(i.lastUpdated).toLocaleTimeString()})})]}):r.jsxs("div",{style:{textAlign:"center",color:"var(--text-secondary)",padding:"32px"},children:[r.jsx("div",{style:{fontSize:"48px",marginBottom:"16px",opacity:.5},children:"📊"}),r.jsx("div",{style:{fontSize:"14px",marginBottom:"8px"},children:a("terminal:context.noContextData")}),r.jsx("div",{style:{fontSize:"12px",marginBottom:"20px",opacity:.7},children:a("terminal:context.clickRefresh")}),n&&r.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:[r.jsx("span",{style:{display:"inline-block",animation:o?"spin 1s linear infinite":"none"},children:o?"⟳":"↻"}),a(o?"terminal:context.fetchingStats":"terminal:context.fetchContextStats")]}),s.status!=="idle"&&r.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"12px"},children:a("terminal:context.agentMustBeIdle")})]})}),r.jsx("div",{className:"modal-footer",style:{display:"flex",justifyContent:"flex-end",padding:"12px 16px",borderTop:"1px solid var(--border-color)"},children:r.jsx("button",{className:"btn btn-secondary",onClick:t,children:a("common:buttons.close")})})]})})}):null}const h5=x.memo(function({tokensUsed:e,createdAt:t}){const{t:n}=He(["common"]);return r.jsxs("div",{className:"unit-stats",children:[r.jsxs("div",{className:"unit-stat",children:[r.jsx("div",{className:"unit-stat-label",children:n("labels.tokens")}),r.jsx("div",{className:"unit-stat-value",children:Zb(e)})]}),r.jsxs("div",{className:"unit-stat",children:[r.jsx("div",{className:"unit-stat-label",children:n("labels.uptime")}),r.jsx("div",{className:"unit-stat-value",children:pN(t)})]})]})}),sM=x.memo(function({contextInfo:e,onClick:t}){const{t:n}=He(["common"]),{remainingPercent:a,hasData:i}=e;return r.jsxs("div",{className:"unit-context unit-context-clickable",onClick:t,title:n(i?"unitPanel.remainingContext":"unitPanel.notRetrievedYet"),style:{cursor:"pointer"},children:[r.jsxs("div",{className:"unit-stat-label",style:{display:"flex",alignItems:"center",gap:"4px"},children:[r.jsx("span",{children:n("unitPanel.remainingContext")}),i?r.jsx("span",{style:{fontSize:"10px",opacity:.6},children:"📊"}):r.jsx("span",{style:{fontSize:"9px",color:"#ff9e4a",opacity:.8},title:n("unitPanel.notRetrievedYet"),children:"⚠️"})]}),i?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"unit-context-bar",children:r.jsx("div",{className:"unit-context-fill",style:{width:`${a}%`,background:t5(a)}})}),r.jsxs("span",{className:"unit-context-value",children:[Math.round(a),"%"]})]}):r.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",fontStyle:"italic"},children:n("unitPanel.notRetrievedYet")})]})}),p5=x.memo(function({lastActivity:e}){const{t}=He(["common"]);return r.jsxs("div",{className:"unit-idle-timer",title:t("unitPanel.timeSinceActivity"),style:{color:Kp(e)},children:["⏱ ",Xp(e)]})}),f5=x.memo(function({toolName:e}){const{t}=He(["common"]);return r.jsxs("div",{className:"unit-current-tool",children:[r.jsx("span",{className:"unit-stat-label",children:t("unitPanel.using")}),r.jsx("span",{className:"unit-tool-name",children:e})]})}),m5=x.memo(function({task:e}){const{t}=He(["common"]);return r.jsxs("div",{className:"unit-task",children:[r.jsx("div",{className:"unit-stat-label",children:t("labels.task")}),r.jsx("div",{className:"unit-task-text",children:e})]})}),g5=x.memo(function({cwd:e}){const{t}=He(["common"]);return r.jsxs("div",{className:"unit-cwd",children:[r.jsx("div",{className:"unit-stat-label",children:t("labels.cwd")}),r.jsx("div",{className:"unit-cwd-path",title:e,children:e})]})}),b5=x.memo(function({text:e,maxLength:t=150}){const{t:n}=He(["common"]);return r.jsxs("div",{className:"unit-last-prompt",children:[r.jsx("div",{className:"unit-stat-label",children:n("unitPanel.lastPrompt")}),r.jsx("div",{className:"unit-last-prompt-text",children:e.length>t?e.slice(0,t)+"...":e})]})}),y5=x.memo(function({text:e,maxLength:t=200}){const{t:n}=He(["common"]);return r.jsxs("div",{className:"unit-last-message",children:[r.jsx("div",{className:"unit-stat-label",children:n("unitPanel.lastResponse")}),r.jsx("div",{className:"unit-last-message-text",children:e.length>t?e.slice(0,t)+"...":e})]})});function x5({agent:s,onFocusAgent:e,onKillAgent:t,onCallSubordinates:n,onOpenAreaExplorer:a}){var ae,le;const{t:i}=He(["common"]),o=An(),l=ei(),{showToast:c}=px(),d=o.agents.get(s.id)||s,f=Zr(d.class,l),p=l.find(pe=>pe.id===d.class),g=p==null?void 0:p.model,b=p!=null&&p.customModelPath?st(`/api/custom-models/${p.id}`):void 0,y=p==null?void 0:p.modelScale,[w,k]=x.useState(!1),[S,j]=x.useState(d.name),C=x.useRef(null),[,N]=x.useState(0),[D,E]=x.useState(!0),[$,M]=x.useState(!1),[R,_]=x.useState([]),[P,O]=x.useState(null),[F,B]=x.useState(!1),[I,U]=x.useState(!1),q=H.getAgentSupervisorHistory(d.id),K=H.isLoadingHistoryForAgent(d.id);x.useEffect(()=>{!H.hasHistoryBeenFetched(d.id)&&!K&&H.requestAgentSupervisorHistory(d.id)},[d.id,K]),x.useEffect(()=>{j(d.name)},[d.name]),x.useEffect(()=>{w&&C.current&&(C.current.focus(),C.current.select())},[w]),x.useEffect(()=>{if(d.status==="idle"){const pe=setInterval(()=>{N(be=>be+1)},15e3);return()=>clearInterval(pe)}},[d.status]),x.useEffect(()=>{d.permissionMode==="interactive"&&ft(st("/api/remembered-patterns")).then(pe=>pe.json()).then(_).catch(pe=>console.error("Failed to fetch remembered patterns:",pe))},[d.permissionMode]);const X=x.useMemo(()=>eM(d),[d.contextStats,d.contextUsed,d.contextLimit]),L=H.getAreaForAgent(d.id),ee=o.agentOutputs.get(d.id)||[],Z=ee.length>0?ee[ee.length-1]:null,z=o.lastPrompts.get(d.id),V=async(pe,be)=>{try{(await ft(st(`/api/remembered-patterns/${pe}/${encodeURIComponent(be)}`),{method:"DELETE"})).ok&&_(he=>he.filter(we=>!(we.tool===pe&&we.pattern===be)))}catch(ce){console.error("Failed to remove pattern:",ce)}},Q=async()=>{if(confirm(i("confirm.clearPatterns")))try{(await ft(st("/api/remembered-patterns"),{method:"DELETE"})).ok&&_([])}catch(pe){console.error("Failed to clear patterns:",pe)}},J=()=>{confirm(i("confirm.terminateAgent"))&&t(d.id)},Y=()=>{const pe=S.trim();pe&&pe!==d.name?H.renameAgent(d.id,pe):j(d.name),k(!1)},se=pe=>{pe.key==="Enter"?Y():pe.key==="Escape"&&(j(d.name),k(!1))};return r.jsxs("div",{className:"unit-panel",children:[r.jsx("div",{className:"unit-model-preview",children:r.jsx(cc,{agentClass:d.class,modelFile:g,customModelUrl:b,modelScale:y,status:d.status,width:80,height:80})}),r.jsxs("div",{className:"unit-panel-header",children:[r.jsx("div",{className:"unit-class-icon",style:{background:`${f.color}20`},children:f.icon}),r.jsxs("div",{className:"unit-header-info",children:[w?r.jsx("input",{ref:C,type:"text",className:"unit-name-input",value:S,onChange:pe=>j(pe.target.value),onBlur:Y,onKeyDown:se}):r.jsx("div",{className:"unit-name unit-name-editable",onClick:()=>k(!0),title:i("unitPanel.clickToRename"),children:d.name}),r.jsxs("div",{className:"unit-status",children:[r.jsx("span",{style:{color:mp[d.status]||mp.default},children:d.status}),r.jsxs("span",{children:[" • ",d.class," • ",d.provider]})]}),d.status==="idle"&&d.lastActivity>0&&r.jsx(p5,{lastActivity:d.lastActivity})]}),r.jsxs("div",{className:"unit-header-actions",children:[r.jsx("button",{className:"unit-action-icon",onClick:()=>e(d.id),title:i("unitPanel.focusOnAgent"),children:"🎯"}),r.jsx("button",{className:"unit-action-icon",onClick:()=>B(!0),title:i("unitPanel.editProperties"),children:"✏️"}),(d.isBoss||d.class==="boss")&&d.subordinateIds&&d.subordinateIds.length>0&&r.jsx("button",{className:"unit-action-icon",onClick:()=>n==null?void 0:n(d.id),title:i("unitPanel.callSubordinates"),children:"📢"}),r.jsx("button",{className:"unit-action-icon",onClick:()=>O("collapse"),title:i("unitPanel.collapseContext"),disabled:d.status!=="idle",children:"📦"}),r.jsx("button",{className:"unit-action-icon warning",onClick:()=>O("clear"),title:i("unitPanel.clearContext"),children:"🗑️"}),r.jsx("button",{className:"unit-action-icon danger",onClick:J,title:i("unitPanel.killAgent"),children:"☠️"})]})]}),L&&r.jsxs("div",{className:"unit-area",children:[r.jsx("span",{className:"unit-area-dot",style:{background:L.color}}),r.jsx("span",{className:"unit-area-name",children:L.name})]}),z&&r.jsx(b5,{text:z.text}),Z&&r.jsx(y5,{text:Z.text}),r.jsx(h5,{tokensUsed:d.tokensUsed,createdAt:d.createdAt}),r.jsx(sM,{contextInfo:X,onClick:()=>U(!0)}),d.currentTool&&r.jsx(f5,{toolName:d.currentTool}),d.currentTask&&r.jsx(m5,{task:d.currentTask}),r.jsx(g5,{cwd:d.cwd}),r.jsxs("div",{className:"unit-permission-mode",children:[r.jsx("div",{className:"unit-stat-label",children:i("unitPanel.permissions")}),r.jsxs("div",{className:"unit-permission-mode-value",title:(ae=Va[d.permissionMode])==null?void 0:ae.description,children:[r.jsx("span",{className:"unit-permission-mode-icon",children:d.permissionMode==="bypass"?"⚡":"🔐"}),r.jsx("span",{className:"unit-permission-mode-label",children:((le=Va[d.permissionMode])==null?void 0:le.label)||d.permissionMode})]})]}),d.permissionMode==="interactive"&&r.jsx(v5,{patterns:R,showPatterns:$,onToggle:()=>M(!$),onRemovePattern:V,onClearAll:Q}),d.sessionId?r.jsxs("div",{className:"unit-resume-cmd",children:[r.jsx("div",{className:"unit-stat-label",children:i("unitPanel.resumeSession")}),r.jsxs("div",{className:"unit-resume-cmd-text",title:i("unitPanel.clickToCopy"),onClick:async()=>{try{await navigator.clipboard.writeText(`codex resume ${d.sessionId}`),c("success",i("toast.copied"),i("toast.resumeCommandCopied"),2e3)}catch{c("error",i("toast.errorTitle"),i("toast.failedToCopy"),3e3)}},children:["codex resume ",d.sessionId]})]}):r.jsxs("div",{className:"unit-resume-cmd",children:[r.jsx("div",{className:"unit-stat-label",children:i("unitPanel.session")}),r.jsx("div",{className:"unit-new-session-indicator",children:i("unitPanel.newSession")})]}),r.jsxs("div",{className:"unit-supervisor-history",children:[r.jsxs("div",{className:"unit-supervisor-history-header",onClick:()=>E(!D),children:[r.jsx("div",{className:"unit-stat-label",children:i("unitPanel.supervisorHistory")}),r.jsxs("span",{className:"unit-supervisor-history-toggle",children:[q.length>0&&r.jsx("span",{className:"unit-supervisor-history-count",children:q.length}),D?"▼":"▶"]})]}),D&&r.jsx("div",{className:"unit-supervisor-history-list",children:K?r.jsx("div",{className:"unit-supervisor-history-loading",children:i("status.loading")}):q.length===0?r.jsx("div",{className:"unit-supervisor-history-empty",children:i("unitPanel.noSupervisorReports")}):q.slice(0,10).map((pe,be)=>r.jsx(k5,{entry:pe,defaultExpanded:be===0},pe.id))})]}),(d.isBoss||d.class==="boss")&&r.jsx(S5,{agent:d}),d.bossId&&r.jsx(C5,{agentId:d.id,bossId:d.bossId}),d.class!=="boss"&&!d.isBoss&&!d.bossId&&r.jsx(A5,{agentId:d.id}),P&&r.jsx(w5,{action:P,agentName:d.name,onClose:()=>O(null),onConfirm:()=>{P==="collapse"?H.collapseContext(d.id):H.clearContext(d.id),O(null)}}),r.jsx(tM,{agent:d,isOpen:F,onClose:()=>B(!1)}),r.jsx(nM,{agent:d,isOpen:I,onClose:()=>U(!1),onRefresh:()=>{H.refreshAgentContext(d.id)}})]})}const v5=x.memo(function({patterns:e,showPatterns:t,onToggle:n,onRemovePattern:a,onClearAll:i}){const{t:o}=He(["common"]);return r.jsxs("div",{className:"unit-remembered-patterns",children:[r.jsxs("div",{className:"unit-remembered-patterns-header",onClick:n,children:[r.jsx("div",{className:"unit-stat-label",children:o("unitPanel.allowedPatterns")}),r.jsxs("span",{className:"unit-remembered-patterns-toggle",children:[e.length>0&&r.jsx("span",{className:"unit-remembered-patterns-count",children:e.length}),t?"▼":"▶"]})]}),t&&r.jsx("div",{className:"unit-remembered-patterns-list",children:e.length===0?r.jsx("div",{className:"unit-remembered-patterns-empty",children:o("unitPanel.noPatterns")}):r.jsxs(r.Fragment,{children:[e.map((l,c)=>r.jsxs("div",{className:"unit-remembered-pattern-item",children:[r.jsx("span",{className:"unit-pattern-tool",children:l.tool}),r.jsx("span",{className:"unit-pattern-desc",title:l.pattern,children:l.description}),r.jsx("button",{className:"unit-pattern-remove",onClick:()=>a(l.tool,l.pattern),title:o("unitPanel.removePattern"),children:"×"})]},c)),r.jsx("button",{className:"unit-patterns-clear-all",onClick:i,children:o("buttons.clearAll")})]})})]})}),w5=x.memo(function({action:e,agentName:t,onClose:n,onConfirm:a}){const{t:i}=He(["common"]),{handleMouseDown:o,handleClick:l}=js(n);return r.jsx("div",{className:"modal-overlay visible",onMouseDown:o,onClick:l,children:r.jsxs("div",{className:"modal confirm-modal",children:[r.jsx("div",{className:"modal-header",children:i(e==="collapse"?"unitPanel.collapseContextTitle":"unitPanel.clearContextTitle")}),r.jsx("div",{className:"modal-body confirm-modal-body",children:e==="collapse"?r.jsxs(r.Fragment,{children:[r.jsx("p",{dangerouslySetInnerHTML:{__html:i("unitPanel.collapseContextMsg",{name:t})}}),r.jsx("p",{className:"confirm-modal-note",children:i("unitPanel.collapseContextNote")})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{dangerouslySetInnerHTML:{__html:i("unitPanel.clearContextMsg",{name:t})}}),r.jsx("p",{className:"confirm-modal-note",children:i("unitPanel.clearContextNote")})]})}),r.jsxs("div",{className:"modal-footer",children:[r.jsx("button",{className:"btn btn-secondary",onClick:n,children:i("buttons.cancel")}),r.jsx("button",{className:`btn ${e==="clear"?"btn-danger":"btn-primary"}`,onClick:a,autoFocus:!0,children:i(e==="collapse"?"unitPanel.collapseBtn":"unitPanel.clearContextBtn")})]})]})})}),k5=x.memo(function({entry:e,defaultExpanded:t=!1}){var g;const{t:n}=He(["common"]),[a,i]=x.useState(t),o=An(),{analysis:l}=e,c=o.settings.hideCost,d=Ur(l.statusDescription,c),f=Ur(l.recentWorkSummary,c),p=(g=l.concerns)==null?void 0:g.map(b=>Ur(b,c)).filter(b=>b.length>0);return r.jsxs("div",{className:"supervisor-history-item",children:[r.jsxs("div",{className:"supervisor-history-item-header",onClick:()=>i(!a),children:[r.jsx("span",{className:"supervisor-history-progress-dot",style:{background:dN[l.progress]||"#888"},title:l.progress}),r.jsx("span",{className:"supervisor-history-status",children:d}),r.jsx("span",{className:"supervisor-history-time",children:kp(e.timestamp)})]}),a&&r.jsxs("div",{className:"supervisor-history-item-details",children:[r.jsxs("div",{className:"supervisor-history-summary",children:[r.jsxs("strong",{children:[n("labels.summary"),":"]})," ",f]}),p&&p.length>0&&r.jsxs("div",{className:"supervisor-history-concerns",children:[r.jsxs("strong",{children:[n("labels.concerns"),":"]}),r.jsx("ul",{children:p.map((b,y)=>r.jsx("li",{children:b},y))})]})]})]})}),S5=x.memo(function({agent:e}){const{t}=He(["common"]),n=An(),a=ei(),[i,o]=x.useState(!0),[l,c]=x.useState(!0),d=x.useMemo(()=>{const y=n.agents.get(e.id);return!y||!y.isBoss&&y.class!=="boss"||!y.subordinateIds?[]:y.subordinateIds.map(w=>n.agents.get(w)).filter(w=>w!==void 0)},[n.agents,e.id]),f=H.getDelegationHistory(e.id),p=n.pendingDelegation,g=(p==null?void 0:p.bossId)===e.id;x.useEffect(()=>{H.requestDelegationHistory(e.id)},[e.id]);const b=vi.boss;return r.jsxs("div",{className:"boss-section",children:[r.jsxs("div",{className:"boss-header",children:[r.jsx("span",{className:"boss-crown-icon",style:{color:b.color},children:b.icon}),r.jsx("span",{className:"boss-title",children:t("unitPanel.bossAgent")})]}),r.jsxs("div",{className:"boss-subordinates",children:[r.jsxs("div",{className:"boss-subordinates-header",onClick:()=>o(!i),children:[r.jsxs("div",{className:"unit-stat-label",children:[t("labels.team")," (",d.length,")"]}),r.jsx("span",{className:"boss-toggle",children:i?"▼":"▶"})]}),i&&r.jsx("div",{className:"boss-subordinates-list",children:d.length===0?r.jsx("div",{className:"boss-subordinates-empty",children:t("unitPanel.noSubordinates")}):d.map(y=>{const w=Zr(y.class,a);return r.jsxs("div",{className:"boss-subordinate-item",onClick:()=>H.selectAgent(y.id),children:[r.jsx("span",{className:"boss-subordinate-icon",style:{color:w.color},children:w.icon}),r.jsx("span",{className:"boss-subordinate-name",children:y.name}),r.jsx("span",{className:`boss-subordinate-status status-${y.status}`,children:y.status}),r.jsx("button",{className:"boss-subordinate-unlink",onClick:k=>{k.stopPropagation(),H.removeSubordinate(e.id,y.id)},title:t("unitPanel.unlinkSubordinate"),children:"✕"})]},y.id)})})]}),r.jsxs("div",{className:"boss-delegation-history",children:[r.jsxs("div",{className:"boss-delegation-history-header",onClick:()=>c(!l),children:[r.jsxs("div",{className:"unit-stat-label",children:[t("unitPanel.delegationHistory")," (",f.length,")"]}),r.jsx("span",{className:"boss-toggle",children:l?"▼":"▶"})]}),l&&r.jsxs("div",{className:"boss-delegation-history-list",children:[g&&r.jsxs("div",{className:"boss-delegation-pending",children:[r.jsx("span",{className:"delegation-spinner",children:"⏳"}),t("unitPanel.analyzingRequest")]}),f.length===0&&!g?r.jsx("div",{className:"boss-delegation-empty",children:t("unitPanel.noDelegationHistory")}):f.slice(0,10).map(y=>r.jsx(j5,{decision:y},y.id))]})]})]})}),j5=x.memo(function({decision:e}){const{t}=He(["common"]),[n,a]=x.useState(!1),o=An().agents.get(e.selectedAgentId),l=o?vi[o.class]:null,c={high:"#4aff9e",medium:"#ff9e4a",low:"#ff4a4a"};return r.jsxs("div",{className:"delegation-decision-item",children:[r.jsxs("div",{className:"delegation-decision-header",onClick:()=>a(!n),children:[r.jsx("span",{className:"delegation-decision-arrow",children:n?"▼":"▶"}),l&&r.jsx("span",{className:"delegation-decision-icon",style:{color:l.color},children:l.icon}),r.jsxs("span",{className:"delegation-decision-agent",children:["→ ",e.selectedAgentName]}),r.jsx("span",{className:"delegation-decision-confidence",style:{color:c[e.confidence]},title:t("unitPanel.confidence",{level:e.confidence}),children:e.confidence==="high"?"●●●":e.confidence==="medium"?"●●○":"●○○"}),r.jsx("span",{className:"delegation-decision-time",children:kp(e.timestamp)})]}),n&&r.jsxs("div",{className:"delegation-decision-details",children:[r.jsxs("div",{className:"delegation-decision-command",children:[r.jsxs("strong",{children:[t("labels.command"),":"]}),r.jsx("div",{className:"delegation-command-text",children:e.userCommand.length>200?e.userCommand.slice(0,200)+"...":e.userCommand})]}),r.jsxs("div",{className:"delegation-decision-reasoning",children:[r.jsxs("strong",{children:[t("labels.reasoning"),":"]})," ",e.reasoning]}),e.alternativeAgents.length>0&&r.jsxs("div",{className:"delegation-decision-alternatives",children:[r.jsxs("strong",{children:[t("labels.alternatives"),":"]})," ",e.alternativeAgents.join(", ")]})]})]})}),C5=x.memo(function({agentId:e,bossId:t}){const{t:n}=He(["common"]),i=An().agents.get(t);if(!i)return null;const o=vi.boss,l=c=>{c.stopPropagation(),H.removeSubordinate(t,e)};return r.jsxs("div",{className:"subordinate-badge",children:[r.jsx("span",{className:"subordinate-badge-icon",style:{color:o.color},children:o.icon}),r.jsxs("span",{className:"subordinate-badge-text",children:[n("labels.reportsTo"),": ",r.jsx("strong",{children:i.name})]}),r.jsx("button",{className:"subordinate-badge-goto",onClick:()=>H.selectAgent(t),title:n("unitPanel.goToBoss"),children:"→"}),r.jsx("button",{className:"subordinate-badge-unlink",onClick:l,title:n("unitPanel.unlinkFromBoss"),children:"✕"})]})}),A5=x.memo(function({agentId:e}){const{t}=He(["common"]),n=An(),[a,i]=x.useState(!1),o=Array.from(n.agents.values()).filter(d=>d.isBoss===!0||d.class==="boss");if(o.length===0)return null;const l=vi.boss,c=d=>{const f=n.agents.get(d);if(!f)return;const p=f.subordinateIds||[];H.assignSubordinates(d,[...p,e]),i(!1)};return r.jsx("div",{className:"link-to-boss-section",children:a?r.jsxs("div",{className:"link-to-boss-dropdown",children:[r.jsxs("div",{className:"link-to-boss-header",children:[r.jsx("span",{children:t("unitPanel.selectBoss")}),r.jsx("button",{className:"link-to-boss-close",onClick:()=>i(!1),children:"✕"})]}),r.jsx("div",{className:"link-to-boss-list",children:o.map(d=>{var f;return r.jsxs("div",{className:"link-to-boss-item",onClick:()=>c(d.id),children:[r.jsx("span",{className:"link-to-boss-item-icon",style:{color:l.color},children:l.icon}),r.jsx("span",{className:"link-to-boss-item-name",children:d.name}),r.jsx("span",{className:"link-to-boss-item-count",children:t("unitPanel.agentsCount",{count:((f=d.subordinateIds)==null?void 0:f.length)||0})})]},d.id)})})]}):r.jsxs("button",{className:"link-to-boss-btn",onClick:()=>i(!0),children:[r.jsx("span",{className:"link-to-boss-icon",style:{color:l.color},children:l.icon}),r.jsx("span",{children:t("unitPanel.linkToBoss")})]})})}),N5=x.memo(function({agents:e}){const{t}=He(["common"]),n=ei(),a=e.reduce((o,l)=>o+l.tokensUsed,0),i=e.filter(o=>o.status==="working").length;return r.jsxs("div",{className:"unit-panel",children:[r.jsxs("div",{className:"unit-panel-header",children:[r.jsx("div",{className:"unit-class-icon",style:{background:"#4a9eff20"},children:"👥"}),r.jsxs("div",{children:[r.jsx("div",{className:"unit-name",children:t("multiAgent.agentsSelected",{count:e.length})}),r.jsx("div",{className:"unit-status",children:t("multiAgent.groupSelection")})]})]}),r.jsxs("div",{className:"unit-stats",children:[r.jsxs("div",{className:"unit-stat",children:[r.jsx("div",{className:"unit-stat-label",children:t("multiAgent.totalTokens")}),r.jsx("div",{className:"unit-stat-value",children:cP(a)})]}),r.jsxs("div",{className:"unit-stat",children:[r.jsx("div",{className:"unit-stat-label",children:t("multiAgent.working")}),r.jsx("div",{className:"unit-stat-value",children:i})]})]}),r.jsx("div",{style:{padding:"8px 0",maxHeight:100,overflowY:"auto"},children:e.map(o=>r.jsx(M5,{agent:o,customClasses:n},o.id))}),r.jsx("div",{className:"unit-actions",children:r.jsx("button",{className:"unit-action-btn",onClick:()=>H.deselectAll(),children:t("buttons.deselectAll")})})]})}),M5=x.memo(function({agent:e,customClasses:t}){const n=Zr(e.class,t);return r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 0",fontSize:12},children:[r.jsx("span",{children:n.icon}),r.jsx("span",{style:{flex:1},children:e.name}),r.jsx("span",{style:{color:"var(--text-secondary)"},children:e.status})]})});function Sj({onFocusAgent:s,onKillAgent:e,onCallSubordinates:t,onOpenAreaExplorer:n}){const a=An(),i=H.getSelectedAgents();if(a.selectedAgentIds.size===0)return r.jsx(vj,{onOpenAreaExplorer:n});if(a.selectedAgentIds.size===1){const o=i[0];return o?r.jsx(x5,{agent:o,onFocusAgent:s,onKillAgent:e,onCallSubordinates:t,onOpenAreaExplorer:n}):r.jsx(vj,{onOpenAreaExplorer:n})}return r.jsx(N5,{agents:i})}function T5(s,e){const t={};return(s[s.length-1]===""?[...s,""]:s).join((t.padRight?" ":"")+","+(t.padLeft===!1?"":" ")).trim()}const E5=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,_5=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,D5={};function jj(s,e){return(D5.jsx?_5:E5).test(s)}const R5=/[ \t\n\f\r]/g;function P5(s){return typeof s=="object"?s.type==="text"?Cj(s.value):!1:Cj(s)}function Cj(s){return s.replace(R5,"")===""}class dd{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}}dd.prototype.normal={};dd.prototype.property={};dd.prototype.space=void 0;function aM(s,e){const t={},n={};for(const a of s)Object.assign(t,a.property),Object.assign(n,a.normal);return new dd(t,n,e)}function my(s){return s.toLowerCase()}class ta{constructor(e,t){this.attribute=t,this.property=e}}ta.prototype.attribute="";ta.prototype.booleanish=!1;ta.prototype.boolean=!1;ta.prototype.commaOrSpaceSeparated=!1;ta.prototype.commaSeparated=!1;ta.prototype.defined=!1;ta.prototype.mustUseProperty=!1;ta.prototype.number=!1;ta.prototype.overloadedBoolean=!1;ta.prototype.property="";ta.prototype.spaceSeparated=!1;ta.prototype.space=void 0;let L5=0;const Bt=sl(),ls=sl(),gy=sl(),Ze=sl(),En=sl(),ac=sl(),da=sl();function sl(){return 2**++L5}const by=Object.freeze(Object.defineProperty({__proto__:null,boolean:Bt,booleanish:ls,commaOrSpaceSeparated:da,commaSeparated:ac,number:Ze,overloadedBoolean:gy,spaceSeparated:En},Symbol.toStringTag,{value:"Module"})),Xg=Object.keys(by);class fx extends ta{constructor(e,t,n,a){let i=-1;if(super(e,t),Aj(this,"space",a),typeof n=="number")for(;++i<Xg.length;){const o=Xg[i];Aj(this,Xg[i],(n&by[o])===by[o])}}}fx.prototype.defined=!0;function Aj(s,e,t){t&&(s[e]=t)}function wc(s){const e={},t={};for(const[n,a]of Object.entries(s.properties)){const i=new fx(n,s.transform(s.attributes||{},n),a,s.space);s.mustUseProperty&&s.mustUseProperty.includes(n)&&(i.mustUseProperty=!0),e[n]=i,t[my(n)]=n,t[my(i.attribute)]=n}return new dd(e,t,s.space)}const iM=wc({properties:{ariaActiveDescendant:null,ariaAtomic:ls,ariaAutoComplete:null,ariaBusy:ls,ariaChecked:ls,ariaColCount:Ze,ariaColIndex:Ze,ariaColSpan:Ze,ariaControls:En,ariaCurrent:null,ariaDescribedBy:En,ariaDetails:null,ariaDisabled:ls,ariaDropEffect:En,ariaErrorMessage:null,ariaExpanded:ls,ariaFlowTo:En,ariaGrabbed:ls,ariaHasPopup:null,ariaHidden:ls,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:En,ariaLevel:Ze,ariaLive:null,ariaModal:ls,ariaMultiLine:ls,ariaMultiSelectable:ls,ariaOrientation:null,ariaOwns:En,ariaPlaceholder:null,ariaPosInSet:Ze,ariaPressed:ls,ariaReadOnly:ls,ariaRelevant:null,ariaRequired:ls,ariaRoleDescription:En,ariaRowCount:Ze,ariaRowIndex:Ze,ariaRowSpan:Ze,ariaSelected:ls,ariaSetSize:Ze,ariaSort:null,ariaValueMax:Ze,ariaValueMin:Ze,ariaValueNow:Ze,ariaValueText:null,role:null},transform(s,e){return e==="role"?e:"aria-"+e.slice(4).toLowerCase()}});function rM(s,e){return e in s?s[e]:e}function oM(s,e){return rM(s,e.toLowerCase())}const O5=wc({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:ac,acceptCharset:En,accessKey:En,action:null,allow:null,allowFullScreen:Bt,allowPaymentRequest:Bt,allowUserMedia:Bt,alt:null,as:null,async:Bt,autoCapitalize:null,autoComplete:En,autoFocus:Bt,autoPlay:Bt,blocking:En,capture:null,charSet:null,checked:Bt,cite:null,className:En,cols:Ze,colSpan:null,content:null,contentEditable:ls,controls:Bt,controlsList:En,coords:Ze|ac,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Bt,defer:Bt,dir:null,dirName:null,disabled:Bt,download:gy,draggable:ls,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Bt,formTarget:null,headers:En,height:Ze,hidden:gy,high:Ze,href:null,hrefLang:null,htmlFor:En,httpEquiv:En,id:null,imageSizes:null,imageSrcSet:null,inert:Bt,inputMode:null,integrity:null,is:null,isMap:Bt,itemId:null,itemProp:En,itemRef:En,itemScope:Bt,itemType:En,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Bt,low:Ze,manifest:null,max:null,maxLength:Ze,media:null,method:null,min:null,minLength:Ze,multiple:Bt,muted:Bt,name:null,nonce:null,noModule:Bt,noValidate:Bt,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:Bt,optimum:Ze,pattern:null,ping:En,placeholder:null,playsInline:Bt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Bt,referrerPolicy:null,rel:En,required:Bt,reversed:Bt,rows:Ze,rowSpan:Ze,sandbox:En,scope:null,scoped:Bt,seamless:Bt,selected:Bt,shadowRootClonable:Bt,shadowRootDelegatesFocus:Bt,shadowRootMode:null,shape:null,size:Ze,sizes:null,slot:null,span:Ze,spellCheck:ls,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Ze,step:null,style:null,tabIndex:Ze,target:null,title:null,translate:null,type:null,typeMustMatch:Bt,useMap:null,value:ls,width:Ze,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:En,axis:null,background:null,bgColor:null,border:Ze,borderColor:null,bottomMargin:Ze,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Bt,declare:Bt,event:null,face:null,frame:null,frameBorder:null,hSpace:Ze,leftMargin:Ze,link:null,longDesc:null,lowSrc:null,marginHeight:Ze,marginWidth:Ze,noResize:Bt,noHref:Bt,noShade:Bt,noWrap:Bt,object:null,profile:null,prompt:null,rev:null,rightMargin:Ze,rules:null,scheme:null,scrolling:ls,standby:null,summary:null,text:null,topMargin:Ze,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Ze,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Bt,disableRemotePlayback:Bt,prefix:null,property:null,results:Ze,security:null,unselectable:null},space:"html",transform:oM}),I5=wc({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:da,accentHeight:Ze,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Ze,amplitude:Ze,arabicForm:null,ascent:Ze,attributeName:null,attributeType:null,azimuth:Ze,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Ze,by:null,calcMode:null,capHeight:Ze,className:En,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:Ze,diffuseConstant:Ze,direction:null,display:null,dur:null,divisor:Ze,dominantBaseline:null,download:Bt,dx:null,dy:null,edgeMode:null,editable:null,elevation:Ze,enableBackground:null,end:null,event:null,exponent:Ze,externalResourcesRequired:null,fill:null,fillOpacity:Ze,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:ac,g2:ac,glyphName:ac,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Ze,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Ze,horizOriginX:Ze,horizOriginY:Ze,id:null,ideographic:Ze,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Ze,k:Ze,k1:Ze,k2:Ze,k3:Ze,k4:Ze,kernelMatrix:da,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Ze,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:Ze,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:Ze,overlineThickness:Ze,paintOrder:null,panose1:null,path:null,pathLength:Ze,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:En,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Ze,pointsAtY:Ze,pointsAtZ:Ze,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:da,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:da,rev:da,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:da,requiredFeatures:da,requiredFonts:da,requiredFormats:da,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:Ze,specularExponent:Ze,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Ze,strikethroughThickness:Ze,string:null,stroke:null,strokeDashArray:da,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Ze,strokeOpacity:Ze,strokeWidth:null,style:null,surfaceScale:Ze,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:da,tabIndex:Ze,tableValues:null,target:null,targetX:Ze,targetY:Ze,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:da,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Ze,underlineThickness:Ze,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Ze,values:null,vAlphabetic:Ze,vMathematical:Ze,vectorEffect:null,vHanging:Ze,vIdeographic:Ze,version:null,vertAdvY:Ze,vertOriginX:Ze,vertOriginY:Ze,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Ze,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:rM}),lM=wc({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()}}),cM=wc({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:oM}),uM=wc({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(s,e){return"xml:"+e.slice(3).toLowerCase()}}),B5={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"},z5=/[A-Z]/g,Nj=/-[a-z]/g,F5=/^data[-\w.:]+$/i;function $5(s,e){const t=my(e);let n=e,a=ta;if(t in s.normal)return s.property[s.normal[t]];if(t.length>4&&t.slice(0,4)==="data"&&F5.test(e)){if(e.charAt(4)==="-"){const i=e.slice(5).replace(Nj,U5);n="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=e.slice(4);if(!Nj.test(i)){let o=i.replace(z5,H5);o.charAt(0)!=="-"&&(o="-"+o),e="data"+o}}a=fx}return new a(n,e)}function H5(s){return"-"+s.toLowerCase()}function U5(s){return s.charAt(1).toUpperCase()}const G5=aM([iM,O5,lM,cM,uM],"html"),mx=aM([iM,I5,lM,cM,uM],"svg");function W5(s){return s.join(" ").trim()}var zl={},Zg,Mj;function q5(){if(Mj)return Zg;Mj=1;var s=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,e=/\n/g,t=/^\s*/,n=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,l=/^\s+|\s+$/g,c=`
|
|
152
152
|
`,d="/",f="*",p="",g="comment",b="declaration";function y(k,S){if(typeof k!="string")throw new TypeError("First argument must be a string");if(!k)return[];S=S||{};var j=1,C=1;function N(B){var I=B.match(e);I&&(j+=I.length);var U=B.lastIndexOf(c);C=~U?B.length-U:C+B.length}function D(){var B={line:j,column:C};return function(I){return I.position=new E(B),R(),I}}function E(B){this.start=B,this.end={line:j,column:C},this.source=S.source}E.prototype.content=k;function $(B){var I=new Error(S.source+":"+j+":"+C+": "+B);if(I.reason=B,I.filename=S.source,I.line=j,I.column=C,I.source=k,!S.silent)throw I}function M(B){var I=B.exec(k);if(I){var U=I[0];return N(U),k=k.slice(U.length),I}}function R(){M(t)}function _(B){var I;for(B=B||[];I=P();)I!==!1&&B.push(I);return B}function P(){var B=D();if(!(d!=k.charAt(0)||f!=k.charAt(1))){for(var I=2;p!=k.charAt(I)&&(f!=k.charAt(I)||d!=k.charAt(I+1));)++I;if(I+=2,p===k.charAt(I-1))return $("End of comment missing");var U=k.slice(2,I-2);return C+=2,N(U),k=k.slice(I),C+=2,B({type:g,comment:U})}}function O(){var B=D(),I=M(n);if(I){if(P(),!M(a))return $("property missing ':'");var U=M(i),q=B({type:b,property:w(I[0].replace(s,p)),value:U?w(U[0].replace(s,p)):p});return M(o),q}}function F(){var B=[];_(B);for(var I;I=O();)I!==!1&&(B.push(I),_(B));return B}return R(),F()}function w(k){return k?k.replace(l,p):p}return Zg=y,Zg}var Tj;function Y5(){if(Tj)return zl;Tj=1;var s=zl&&zl.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(zl,"__esModule",{value:!0}),zl.default=t;const e=s(q5());function t(n,a){let i=null;if(!n||typeof n!="string")return i;const o=(0,e.default)(n),l=typeof a=="function";return o.forEach(c=>{if(c.type!=="declaration")return;const{property:d,value:f}=c;l?a(d,f,c):f&&(i=i||{},i[d]=f)}),i}return zl}var ku={},Ej;function V5(){if(Ej)return ku;Ej=1,Object.defineProperty(ku,"__esModule",{value:!0}),ku.camelCase=void 0;var s=/^--[a-zA-Z0-9_-]+$/,e=/-([a-z])/g,t=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,i=function(d){return!d||t.test(d)||s.test(d)},o=function(d,f){return f.toUpperCase()},l=function(d,f){return"".concat(f,"-")},c=function(d,f){return f===void 0&&(f={}),i(d)?d:(d=d.toLowerCase(),f.reactCompat?d=d.replace(a,l):d=d.replace(n,l),d.replace(e,o))};return ku.camelCase=c,ku}var Su,_j;function K5(){if(_j)return Su;_j=1;var s=Su&&Su.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},e=s(Y5()),t=V5();function n(a,i){var o={};return!a||typeof a!="string"||(0,e.default)(a,function(l,c){l&&c&&(o[(0,t.camelCase)(l,i)]=c)}),o}return n.default=n,Su=n,Su}var X5=K5();const Z5=ld(X5),dM=hM("end"),gx=hM("start");function hM(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 Q5(s){const e=gx(s),t=dM(s);if(e&&t)return{start:e,end:t}}function Uu(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?Dj(s.position):"start"in s||"end"in s?Dj(s):"line"in s||"column"in s?yy(s):""}function yy(s){return Rj(s&&s.line)+":"+Rj(s&&s.column)}function Dj(s){return yy(s&&s.start)+"-"+yy(s&&s.end)}function Rj(s){return s&&typeof s=="number"?s:1}class Rs extends Error{constructor(e,t,n){super(),typeof t=="string"&&(n=t,t=void 0);let a="",i={},o=!1;if(t&&("line"in t&&"column"in t?i={place:t}:"start"in t&&"end"in t?i={place:t}:"type"in t?i={ancestors:[t],place:t.position}:i={...t}),typeof e=="string"?a=e:!i.cause&&e&&(o=!0,a=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof n=="string"){const c=n.indexOf(":");c===-1?i.ruleId=n:(i.source=n.slice(0,c),i.ruleId=n.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const l=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=l?l.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=l?l.line:void 0,this.name=Uu(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=o&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Rs.prototype.file="";Rs.prototype.name="";Rs.prototype.reason="";Rs.prototype.message="";Rs.prototype.stack="";Rs.prototype.column=void 0;Rs.prototype.line=void 0;Rs.prototype.ancestors=void 0;Rs.prototype.cause=void 0;Rs.prototype.fatal=void 0;Rs.prototype.place=void 0;Rs.prototype.ruleId=void 0;Rs.prototype.source=void 0;const bx={}.hasOwnProperty,J5=new Map,ez=/[A-Z]/g,tz=new Set(["table","tbody","thead","tfoot","tr"]),nz=new Set(["td","th"]),pM="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function sz(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=dz(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=uz(t,e.jsx,e.jsxs)}const a={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"?mx:G5,stylePropertyNameCase:e.stylePropertyNameCase||"dom",tableCellAlignToStyle:e.tableCellAlignToStyle!==!1},i=fM(a,s,void 0);return i&&typeof i!="string"?i:a.create(s,a.Fragment,{children:i||void 0},void 0)}function fM(s,e,t){if(e.type==="element")return az(s,e,t);if(e.type==="mdxFlowExpression"||e.type==="mdxTextExpression")return iz(s,e);if(e.type==="mdxJsxFlowElement"||e.type==="mdxJsxTextElement")return oz(s,e,t);if(e.type==="mdxjsEsm")return rz(s,e);if(e.type==="root")return lz(s,e,t);if(e.type==="text")return cz(s,e)}function az(s,e,t){const n=s.schema;let a=n;e.tagName.toLowerCase()==="svg"&&n.space==="html"&&(a=mx,s.schema=a),s.ancestors.push(e);const i=gM(s,e.tagName,!1),o=hz(s,e);let l=xx(s,e);return tz.has(e.tagName)&&(l=l.filter(function(c){return typeof c=="string"?!P5(c):!0})),mM(s,o,i,e),yx(o,l),s.ancestors.pop(),s.schema=n,s.create(e,i,o,t)}function iz(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)}nd(s,e.position)}function rz(s,e){if(e.data&&e.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(e.data.estree);nd(s,e.position)}function oz(s,e,t){const n=s.schema;let a=n;e.name==="svg"&&n.space==="html"&&(a=mx,s.schema=a),s.ancestors.push(e);const i=e.name===null?s.Fragment:gM(s,e.name,!0),o=pz(s,e),l=xx(s,e);return mM(s,o,i,e),yx(o,l),s.ancestors.pop(),s.schema=n,s.create(e,i,o,t)}function lz(s,e,t){const n={};return yx(n,xx(s,e)),s.create(e,s.Fragment,n,t)}function cz(s,e){return e.value}function mM(s,e,t,n){typeof t!="string"&&t!==s.Fragment&&s.passNode&&(e.node=n)}function yx(s,e){if(e.length>0){const t=e.length>1?e:e[0];t&&(s.children=t)}}function uz(s,e,t){return n;function n(a,i,o,l){const d=Array.isArray(o.children)?t:e;return l?d(i,o,l):d(i,o)}}function dz(s,e){return t;function t(n,a,i,o){const l=Array.isArray(i.children),c=gx(n);return e(a,i,o,l,{columnNumber:c?c.column-1:void 0,fileName:s,lineNumber:c?c.line:void 0},void 0)}}function hz(s,e){const t={};let n,a;for(a in e.properties)if(a!=="children"&&bx.call(e.properties,a)){const i=fz(s,a,e.properties[a]);if(i){const[o,l]=i;s.tableCellAlignToStyle&&o==="align"&&typeof l=="string"&&nz.has(e.tagName)?n=l:t[o]=l}}if(n){const i=t.style||(t.style={});i[s.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return t}function pz(s,e){const t={};for(const n of e.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&s.evaluater){const i=n.data.estree.body[0];i.type;const o=i.expression;o.type;const l=o.properties[0];l.type,Object.assign(t,s.evaluater.evaluateExpression(l.argument))}else nd(s,e.position);else{const a=n.name;let i;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&s.evaluater){const l=n.value.data.estree.body[0];l.type,i=s.evaluater.evaluateExpression(l.expression)}else nd(s,e.position);else i=n.value===null?!0:n.value;t[a]=i}return t}function xx(s,e){const t=[];let n=-1;const a=s.passKeys?new Map:J5;for(;++n<e.children.length;){const i=e.children[n];let o;if(s.passKeys){const c=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(c){const d=a.get(c)||0;o=c+"-"+d,a.set(c,d+1)}}const l=fM(s,i,o);l!==void 0&&t.push(l)}return t}function fz(s,e,t){const n=$5(s.schema,e);if(!(t==null||typeof t=="number"&&Number.isNaN(t))){if(Array.isArray(t)&&(t=n.commaSeparated?T5(t):W5(t)),n.property==="style"){let a=typeof t=="object"?t:mz(s,String(t));return s.stylePropertyNameCase==="css"&&(a=gz(a)),["style",a]}return[s.elementAttributeNameCase==="react"&&n.space?B5[n.property]||n.property:n.attribute,t]}}function mz(s,e){try{return Z5(e,{reactCompat:!0})}catch(t){if(s.ignoreInvalidStyle)return{};const n=t,a=new Rs("Cannot parse `style` attribute",{ancestors:s.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=s.filePath||void 0,a.url=pM+"#cannot-parse-style-attribute",a}}function gM(s,e,t){let n;if(!t)n={type:"Literal",value:e};else if(e.includes(".")){const a=e.split(".");let i=-1,o;for(;++i<a.length;){const l=jj(a[i])?{type:"Identifier",name:a[i]}:{type:"Literal",value:a[i]};o=o?{type:"MemberExpression",object:o,property:l,computed:!!(i&&l.type==="Literal"),optional:!1}:l}n=o}else n=jj(e)&&!/^[a-z]/.test(e)?{type:"Identifier",name:e}:{type:"Literal",value:e};if(n.type==="Literal"){const a=n.value;return bx.call(s.components,a)?s.components[a]:a}if(s.evaluater)return s.evaluater.evaluateExpression(n);nd(s)}function nd(s,e){const t=new Rs("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=pM+"#cannot-handle-mdx-estrees-without-createevaluater",t}function gz(s){const e={};let t;for(t in s)bx.call(s,t)&&(e[bz(t)]=s[t]);return e}function bz(s){let e=s.replace(ez,yz);return e.slice(0,3)==="ms-"&&(e="-"+e),e}function yz(s){return"-"+s.toLowerCase()}const Qg={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"]},xz={};function vx(s,e){const t=xz,n=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,a=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return bM(s,n,a)}function bM(s,e,t){if(vz(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 Pj(s.children,e,t)}return Array.isArray(s)?Pj(s,e,t):""}function Pj(s,e,t){const n=[];let a=-1;for(;++a<s.length;)n[a]=bM(s[a],e,t);return n.join("")}function vz(s){return!!(s&&typeof s=="object")}const Lj=document.createElement("i");function wx(s){const e="&"+s+";";Lj.innerHTML=e;const t=Lj.textContent;return t.charCodeAt(t.length-1)===59&&s!=="semi"||t===e?!1:t}function ma(s,e,t,n){const a=s.length;let i=0,o;if(e<0?e=-e>a?0:a+e:e=e>a?a:e,t=t>0?t:0,n.length<1e4)o=Array.from(n),o.unshift(e,t),s.splice(...o);else for(t&&s.splice(e,t);i<n.length;)o=n.slice(i,i+1e4),o.unshift(e,0),s.splice(...o),i+=1e4,e+=1e4}function Ea(s,e){return s.length>0?(ma(s,s.length,0,e),s):e}const Oj={}.hasOwnProperty;function yM(s){const e={};let t=-1;for(;++t<s.length;)wz(e,s[t]);return e}function wz(s,e){let t;for(t in e){const a=(Oj.call(s,t)?s[t]:void 0)||(s[t]={}),i=e[t];let o;if(i)for(o in i){Oj.call(a,o)||(a[o]=[]);const l=i[o];kz(a[o],Array.isArray(l)?l:l?[l]:[])}}}function kz(s,e){let t=-1;const n=[];for(;++t<e.length;)(e[t].add==="after"?s:n).push(e[t]);ma(s,0,0,n)}function xM(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 Ka(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const zs=to(/[A-Za-z]/),_s=to(/[\dA-Za-z]/),Sz=to(/[#-'*+\--9=?A-Z^-~]/);function Sp(s){return s!==null&&(s<32||s===127)}const xy=to(/\d/),jz=to(/[\dA-Fa-f]/),Cz=to(/[!-/:-@[-`{-~]/);function jt(s){return s!==null&&s<-2}function Tn(s){return s!==null&&(s<0||s===32)}function Xt(s){return s===-2||s===-1||s===32}const af=to(new RegExp("\\p{P}|\\p{S}","u")),Zo=to(/\s/);function to(s){return e;function e(t){return t!==null&&t>-1&&s.test(String.fromCharCode(t))}}function kc(s){const e=[];let t=-1,n=0,a=0;for(;++t<s.length;){const i=s.charCodeAt(t);let o="";if(i===37&&_s(s.charCodeAt(t+1))&&_s(s.charCodeAt(t+2)))a=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(o=String.fromCharCode(i));else if(i>55295&&i<57344){const l=s.charCodeAt(t+1);i<56320&&l>56319&&l<57344?(o=String.fromCharCode(i,l),a=1):o="�"}else o=String.fromCharCode(i);o&&(e.push(s.slice(n,t),encodeURIComponent(o)),n=t+a+1,o=""),a&&(t+=a,a=0)}return e.join("")+s.slice(n)}function an(s,e,t,n){const a=n?n-1:Number.POSITIVE_INFINITY;let i=0;return o;function o(c){return Xt(c)?(s.enter(t),l(c)):e(c)}function l(c){return Xt(c)&&i++<a?(s.consume(c),l):(s.exit(t),e(c))}}const Az={tokenize:Nz};function Nz(s){const e=s.attempt(this.parser.constructs.contentInitial,n,a);let t;return e;function n(l){if(l===null){s.consume(l);return}return s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),an(s,e,"linePrefix")}function a(l){return s.enter("paragraph"),i(l)}function i(l){const c=s.enter("chunkText",{contentType:"text",previous:t});return t&&(t.next=c),t=c,o(l)}function o(l){if(l===null){s.exit("chunkText"),s.exit("paragraph"),s.consume(l);return}return jt(l)?(s.consume(l),s.exit("chunkText"),i):(s.consume(l),o)}}const Mz={tokenize:Tz},Ij={tokenize:Ez};function Tz(s){const e=this,t=[];let n=0,a,i,o;return l;function l(C){if(n<t.length){const N=t[n];return e.containerState=N[1],s.attempt(N[0].continuation,c,d)(C)}return d(C)}function c(C){if(n++,e.containerState._closeFlow){e.containerState._closeFlow=void 0,a&&j();const N=e.events.length;let D=N,E;for(;D--;)if(e.events[D][0]==="exit"&&e.events[D][1].type==="chunkFlow"){E=e.events[D][1].end;break}S(n);let $=N;for(;$<e.events.length;)e.events[$][1].end={...E},$++;return ma(e.events,D+1,0,e.events.slice(N)),e.events.length=$,d(C)}return l(C)}function d(C){if(n===t.length){if(!a)return g(C);if(a.currentConstruct&&a.currentConstruct.concrete)return y(C);e.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return e.containerState={},s.check(Ij,f,p)(C)}function f(C){return a&&j(),S(n),g(C)}function p(C){return e.parser.lazy[e.now().line]=n!==t.length,o=e.now().offset,y(C)}function g(C){return e.containerState={},s.attempt(Ij,b,y)(C)}function b(C){return n++,t.push([e.currentConstruct,e.containerState]),g(C)}function y(C){if(C===null){a&&j(),S(0),s.consume(C);return}return a=a||e.parser.flow(e.now()),s.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:i}),w(C)}function w(C){if(C===null){k(s.exit("chunkFlow"),!0),S(0),s.consume(C);return}return jt(C)?(s.consume(C),k(s.exit("chunkFlow")),n=0,e.interrupt=void 0,l):(s.consume(C),w)}function k(C,N){const D=e.sliceStream(C);if(N&&D.push(null),C.previous=i,i&&(i.next=C),i=C,a.defineSkip(C.start),a.write(D),e.parser.lazy[C.start.line]){let E=a.events.length;for(;E--;)if(a.events[E][1].start.offset<o&&(!a.events[E][1].end||a.events[E][1].end.offset>o))return;const $=e.events.length;let M=$,R,_;for(;M--;)if(e.events[M][0]==="exit"&&e.events[M][1].type==="chunkFlow"){if(R){_=e.events[M][1].end;break}R=!0}for(S(n),E=$;E<e.events.length;)e.events[E][1].end={..._},E++;ma(e.events,M+1,0,e.events.slice($)),e.events.length=E}}function S(C){let N=t.length;for(;N-- >C;){const D=t[N];e.containerState=D[1],D[0].exit.call(e,s)}t.length=C}function j(){a.write([null]),i=void 0,a=void 0,e.containerState._closeFlow=void 0}}function Ez(s,e,t){return an(s,s.attempt(this.parser.constructs.document,e,t),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function uc(s){if(s===null||Tn(s)||Zo(s))return 1;if(af(s))return 2}function rf(s,e,t){const n=[];let a=-1;for(;++a<s.length;){const i=s[a].resolveAll;i&&!n.includes(i)&&(e=i(e,t),n.push(i))}return e}const vy={name:"attention",resolveAll:_z,tokenize:Dz};function _z(s,e){let t=-1,n,a,i,o,l,c,d,f;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;c=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 p={...s[n][1].end},g={...s[t][1].start};Bj(p,-c),Bj(g,c),o={type:c>1?"strongSequence":"emphasisSequence",start:p,end:{...s[n][1].end}},l={type:c>1?"strongSequence":"emphasisSequence",start:{...s[t][1].start},end:g},i={type:c>1?"strongText":"emphasisText",start:{...s[n][1].end},end:{...s[t][1].start}},a={type:c>1?"strong":"emphasis",start:{...o.start},end:{...l.end}},s[n][1].end={...o.start},s[t][1].start={...l.end},d=[],s[n][1].end.offset-s[n][1].start.offset&&(d=Ea(d,[["enter",s[n][1],e],["exit",s[n][1],e]])),d=Ea(d,[["enter",a,e],["enter",o,e],["exit",o,e],["enter",i,e]]),d=Ea(d,rf(e.parser.constructs.insideSpan.null,s.slice(n+1,t),e)),d=Ea(d,[["exit",i,e],["enter",l,e],["exit",l,e],["exit",a,e]]),s[t][1].end.offset-s[t][1].start.offset?(f=2,d=Ea(d,[["enter",s[t][1],e],["exit",s[t][1],e]])):f=0,ma(s,n-1,t-n+3,d),t=n+d.length-f-2;break}}for(t=-1;++t<s.length;)s[t][1].type==="attentionSequence"&&(s[t][1].type="data");return s}function Dz(s,e){const t=this.parser.constructs.attentionMarkers.null,n=this.previous,a=uc(n);let i;return o;function o(c){return i=c,s.enter("attentionSequence"),l(c)}function l(c){if(c===i)return s.consume(c),l;const d=s.exit("attentionSequence"),f=uc(c),p=!f||f===2&&a||t.includes(c),g=!a||a===2&&f||t.includes(n);return d._open=!!(i===42?p:p&&(a||!g)),d._close=!!(i===42?g:g&&(f||!p)),e(c)}}function Bj(s,e){s.column+=e,s.offset+=e,s._bufferIndex+=e}const Rz={name:"autolink",tokenize:Pz};function Pz(s,e,t){let n=0;return a;function a(b){return s.enter("autolink"),s.enter("autolinkMarker"),s.consume(b),s.exit("autolinkMarker"),s.enter("autolinkProtocol"),i}function i(b){return zs(b)?(s.consume(b),o):b===64?t(b):d(b)}function o(b){return b===43||b===45||b===46||_s(b)?(n=1,l(b)):d(b)}function l(b){return b===58?(s.consume(b),n=0,c):(b===43||b===45||b===46||_s(b))&&n++<32?(s.consume(b),l):(n=0,d(b))}function c(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||Sp(b)?t(b):(s.consume(b),c)}function d(b){return b===64?(s.consume(b),f):Sz(b)?(s.consume(b),d):t(b)}function f(b){return _s(b)?p(b):t(b)}function p(b){return b===46?(s.consume(b),n=0,f):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||_s(b))&&n++<63){const y=b===45?g:p;return s.consume(b),y}return t(b)}}const hd={partial:!0,tokenize:Lz};function Lz(s,e,t){return n;function n(i){return Xt(i)?an(s,a,"linePrefix")(i):a(i)}function a(i){return i===null||jt(i)?e(i):t(i)}}const vM={continuation:{tokenize:Iz},exit:Bz,name:"blockQuote",tokenize:Oz};function Oz(s,e,t){const n=this;return a;function a(o){if(o===62){const l=n.containerState;return l.open||(s.enter("blockQuote",{_container:!0}),l.open=!0),s.enter("blockQuotePrefix"),s.enter("blockQuoteMarker"),s.consume(o),s.exit("blockQuoteMarker"),i}return t(o)}function i(o){return Xt(o)?(s.enter("blockQuotePrefixWhitespace"),s.consume(o),s.exit("blockQuotePrefixWhitespace"),s.exit("blockQuotePrefix"),e):(s.exit("blockQuotePrefix"),e(o))}}function Iz(s,e,t){const n=this;return a;function a(o){return Xt(o)?an(s,i,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):i(o)}function i(o){return s.attempt(vM,e,t)(o)}}function Bz(s){s.exit("blockQuote")}const wM={name:"characterEscape",tokenize:zz};function zz(s,e,t){return n;function n(i){return s.enter("characterEscape"),s.enter("escapeMarker"),s.consume(i),s.exit("escapeMarker"),a}function a(i){return Cz(i)?(s.enter("characterEscapeValue"),s.consume(i),s.exit("characterEscapeValue"),s.exit("characterEscape"),e):t(i)}}const kM={name:"characterReference",tokenize:Fz};function Fz(s,e,t){const n=this;let a=0,i,o;return l;function l(p){return s.enter("characterReference"),s.enter("characterReferenceMarker"),s.consume(p),s.exit("characterReferenceMarker"),c}function c(p){return p===35?(s.enter("characterReferenceMarkerNumeric"),s.consume(p),s.exit("characterReferenceMarkerNumeric"),d):(s.enter("characterReferenceValue"),i=31,o=_s,f(p))}function d(p){return p===88||p===120?(s.enter("characterReferenceMarkerHexadecimal"),s.consume(p),s.exit("characterReferenceMarkerHexadecimal"),s.enter("characterReferenceValue"),i=6,o=jz,f):(s.enter("characterReferenceValue"),i=7,o=xy,f(p))}function f(p){if(p===59&&a){const g=s.exit("characterReferenceValue");return o===_s&&!wx(n.sliceSerialize(g))?t(p):(s.enter("characterReferenceMarker"),s.consume(p),s.exit("characterReferenceMarker"),s.exit("characterReference"),e)}return o(p)&&a++<i?(s.consume(p),f):t(p)}}const zj={partial:!0,tokenize:Hz},Fj={concrete:!0,name:"codeFenced",tokenize:$z};function $z(s,e,t){const n=this,a={partial:!0,tokenize:D};let i=0,o=0,l;return c;function c(E){return d(E)}function d(E){const $=n.events[n.events.length-1];return i=$&&$[1].type==="linePrefix"?$[2].sliceSerialize($[1],!0).length:0,l=E,s.enter("codeFenced"),s.enter("codeFencedFence"),s.enter("codeFencedFenceSequence"),f(E)}function f(E){return E===l?(o++,s.consume(E),f):o<3?t(E):(s.exit("codeFencedFenceSequence"),Xt(E)?an(s,p,"whitespace")(E):p(E))}function p(E){return E===null||jt(E)?(s.exit("codeFencedFence"),n.interrupt?e(E):s.check(zj,w,N)(E)):(s.enter("codeFencedFenceInfo"),s.enter("chunkString",{contentType:"string"}),g(E))}function g(E){return E===null||jt(E)?(s.exit("chunkString"),s.exit("codeFencedFenceInfo"),p(E)):Xt(E)?(s.exit("chunkString"),s.exit("codeFencedFenceInfo"),an(s,b,"whitespace")(E)):E===96&&E===l?t(E):(s.consume(E),g)}function b(E){return E===null||jt(E)?p(E):(s.enter("codeFencedFenceMeta"),s.enter("chunkString",{contentType:"string"}),y(E))}function y(E){return E===null||jt(E)?(s.exit("chunkString"),s.exit("codeFencedFenceMeta"),p(E)):E===96&&E===l?t(E):(s.consume(E),y)}function w(E){return s.attempt(a,N,k)(E)}function k(E){return s.enter("lineEnding"),s.consume(E),s.exit("lineEnding"),S}function S(E){return i>0&&Xt(E)?an(s,j,"linePrefix",i+1)(E):j(E)}function j(E){return E===null||jt(E)?s.check(zj,w,N)(E):(s.enter("codeFlowValue"),C(E))}function C(E){return E===null||jt(E)?(s.exit("codeFlowValue"),j(E)):(s.consume(E),C)}function N(E){return s.exit("codeFenced"),e(E)}function D(E,$,M){let R=0;return _;function _(I){return E.enter("lineEnding"),E.consume(I),E.exit("lineEnding"),P}function P(I){return E.enter("codeFencedFence"),Xt(I)?an(E,O,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):O(I)}function O(I){return I===l?(E.enter("codeFencedFenceSequence"),F(I)):M(I)}function F(I){return I===l?(R++,E.consume(I),F):R>=o?(E.exit("codeFencedFenceSequence"),Xt(I)?an(E,B,"whitespace")(I):B(I)):M(I)}function B(I){return I===null||jt(I)?(E.exit("codeFencedFence"),$(I)):M(I)}}}function Hz(s,e,t){const n=this;return a;function a(o){return o===null?t(o):(s.enter("lineEnding"),s.consume(o),s.exit("lineEnding"),i)}function i(o){return n.parser.lazy[n.now().line]?t(o):e(o)}}const Jg={name:"codeIndented",tokenize:Gz},Uz={partial:!0,tokenize:Wz};function Gz(s,e,t){const n=this;return a;function a(d){return s.enter("codeIndented"),an(s,i,"linePrefix",5)(d)}function i(d){const f=n.events[n.events.length-1];return f&&f[1].type==="linePrefix"&&f[2].sliceSerialize(f[1],!0).length>=4?o(d):t(d)}function o(d){return d===null?c(d):jt(d)?s.attempt(Uz,o,c)(d):(s.enter("codeFlowValue"),l(d))}function l(d){return d===null||jt(d)?(s.exit("codeFlowValue"),o(d)):(s.consume(d),l)}function c(d){return s.exit("codeIndented"),e(d)}}function Wz(s,e,t){const n=this;return a;function a(o){return n.parser.lazy[n.now().line]?t(o):jt(o)?(s.enter("lineEnding"),s.consume(o),s.exit("lineEnding"),a):an(s,i,"linePrefix",5)(o)}function i(o){const l=n.events[n.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?e(o):jt(o)?a(o):t(o)}}const qz={name:"codeText",previous:Vz,resolve:Yz,tokenize:Kz};function Yz(s){let e=s.length-4,t=3,n,a;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;)a===void 0?n!==e&&s[n][1].type!=="lineEnding"&&(a=n):(n===e||s[n][1].type==="lineEnding")&&(s[a][1].type="codeTextData",n!==a+2&&(s[a][1].end=s[n-1][1].end,s.splice(a+2,n-a-2),e-=n-a-2,n=a+2),a=void 0);return s}function Vz(s){return s!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Kz(s,e,t){let n=0,a,i;return o;function o(p){return s.enter("codeText"),s.enter("codeTextSequence"),l(p)}function l(p){return p===96?(s.consume(p),n++,l):(s.exit("codeTextSequence"),c(p))}function c(p){return p===null?t(p):p===32?(s.enter("space"),s.consume(p),s.exit("space"),c):p===96?(i=s.enter("codeTextSequence"),a=0,f(p)):jt(p)?(s.enter("lineEnding"),s.consume(p),s.exit("lineEnding"),c):(s.enter("codeTextData"),d(p))}function d(p){return p===null||p===32||p===96||jt(p)?(s.exit("codeTextData"),c(p)):(s.consume(p),d)}function f(p){return p===96?(s.consume(p),a++,f):a===n?(s.exit("codeTextSequence"),s.exit("codeText"),e(p)):(i.type="codeTextData",d(p))}}class Xz{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 a=t||0;this.setCursor(Math.trunc(e));const i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return n&&ju(this.left,n),i.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),ju(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),ju(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);ju(this.right,t.reverse())}else{const t=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);ju(this.left,t.reverse())}}}function ju(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 SM(s){const e={};let t=-1,n,a,i,o,l,c,d;const f=new Xz(s);for(;++t<f.length;){for(;t in e;)t=e[t];if(n=f.get(t),t&&n[1].type==="chunkFlow"&&f.get(t-1)[1].type==="listItemPrefix"&&(c=n[1]._tokenizer.events,i=0,i<c.length&&c[i][1].type==="lineEndingBlank"&&(i+=2),i<c.length&&c[i][1].type==="content"))for(;++i<c.length&&c[i][1].type!=="content";)c[i][1].type==="chunkText"&&(c[i][1]._isInFirstContentOfListItem=!0,i++);if(n[0]==="enter")n[1].contentType&&(Object.assign(e,Zz(f,t)),t=e[t],d=!0);else if(n[1]._container){for(i=t,a=void 0;i--;)if(o=f.get(i),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(a&&(f.get(a)[1].type="lineEndingBlank"),o[1].type="lineEnding",a=i);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;a&&(n[1].end={...f.get(a)[1].start},l=f.slice(a,t),l.unshift(n),f.splice(a,t-a+1,l))}}return ma(s,0,Number.POSITIVE_INFINITY,f.slice(0)),!d}function Zz(s,e){const t=s.get(e)[1],n=s.get(e)[2];let a=e-1;const i=[];let o=t._tokenizer;o||(o=n.parser[t.contentType](t.start),t._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const l=o.events,c=[],d={};let f,p,g=-1,b=t,y=0,w=0;const k=[w];for(;b;){for(;s.get(++a)[1]!==b;);i.push(a),b._tokenizer||(f=n.sliceStream(b),b.next||f.push(null),p&&o.defineSkip(b.start),b._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(f),b._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),p=b,b=b.next}for(b=t;++g<l.length;)l[g][0]==="exit"&&l[g-1][0]==="enter"&&l[g][1].type===l[g-1][1].type&&l[g][1].start.line!==l[g][1].end.line&&(w=g+1,k.push(w),b._tokenizer=void 0,b.previous=void 0,b=b.next);for(o.events=[],b?(b._tokenizer=void 0,b.previous=void 0):k.pop(),g=k.length;g--;){const S=l.slice(k[g],k[g+1]),j=i.pop();c.push([j,j+S.length-1]),s.splice(j,2,S)}for(c.reverse(),g=-1;++g<c.length;)d[y+c[g][0]]=y+c[g][1],y+=c[g][1]-c[g][0]-1;return d}const Qz={resolve:eF,tokenize:tF},Jz={partial:!0,tokenize:nF};function eF(s){return SM(s),s}function tF(s,e){let t;return n;function n(l){return s.enter("content"),t=s.enter("chunkContent",{contentType:"content"}),a(l)}function a(l){return l===null?i(l):jt(l)?s.check(Jz,o,i)(l):(s.consume(l),a)}function i(l){return s.exit("chunkContent"),s.exit("content"),e(l)}function o(l){return s.consume(l),s.exit("chunkContent"),t.next=s.enter("chunkContent",{contentType:"content",previous:t}),t=t.next,a}}function nF(s,e,t){const n=this;return a;function a(o){return s.exit("chunkContent"),s.enter("lineEnding"),s.consume(o),s.exit("lineEnding"),an(s,i,"linePrefix")}function i(o){if(o===null||jt(o))return t(o);const l=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?e(o):s.interrupt(n.parser.constructs.flow,t,e)(o)}}function jM(s,e,t,n,a,i,o,l,c){const d=c||Number.POSITIVE_INFINITY;let f=0;return p;function p(S){return S===60?(s.enter(n),s.enter(a),s.enter(i),s.consume(S),s.exit(i),g):S===null||S===32||S===41||Sp(S)?t(S):(s.enter(n),s.enter(o),s.enter(l),s.enter("chunkString",{contentType:"string"}),w(S))}function g(S){return S===62?(s.enter(i),s.consume(S),s.exit(i),s.exit(a),s.exit(n),e):(s.enter(l),s.enter("chunkString",{contentType:"string"}),b(S))}function b(S){return S===62?(s.exit("chunkString"),s.exit(l),g(S)):S===null||S===60||jt(S)?t(S):(s.consume(S),S===92?y:b)}function y(S){return S===60||S===62||S===92?(s.consume(S),b):b(S)}function w(S){return!f&&(S===null||S===41||Tn(S))?(s.exit("chunkString"),s.exit(l),s.exit(o),s.exit(n),e(S)):f<d&&S===40?(s.consume(S),f++,w):S===41?(s.consume(S),f--,w):S===null||S===32||S===40||Sp(S)?t(S):(s.consume(S),S===92?k:w)}function k(S){return S===40||S===41||S===92?(s.consume(S),w):w(S)}}function CM(s,e,t,n,a,i){const o=this;let l=0,c;return d;function d(b){return s.enter(n),s.enter(a),s.consume(b),s.exit(a),s.enter(i),f}function f(b){return l>999||b===null||b===91||b===93&&!c||b===94&&!l&&"_hiddenFootnoteSupport"in o.parser.constructs?t(b):b===93?(s.exit(i),s.enter(a),s.consume(b),s.exit(a),s.exit(n),e):jt(b)?(s.enter("lineEnding"),s.consume(b),s.exit("lineEnding"),f):(s.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===null||b===91||b===93||jt(b)||l++>999?(s.exit("chunkString"),f(b)):(s.consume(b),c||(c=!Xt(b)),b===92?g:p)}function g(b){return b===91||b===92||b===93?(s.consume(b),l++,p):p(b)}}function AM(s,e,t,n,a,i){let o;return l;function l(g){return g===34||g===39||g===40?(s.enter(n),s.enter(a),s.consume(g),s.exit(a),o=g===40?41:g,c):t(g)}function c(g){return g===o?(s.enter(a),s.consume(g),s.exit(a),s.exit(n),e):(s.enter(i),d(g))}function d(g){return g===o?(s.exit(i),c(o)):g===null?t(g):jt(g)?(s.enter("lineEnding"),s.consume(g),s.exit("lineEnding"),an(s,d,"linePrefix")):(s.enter("chunkString",{contentType:"string"}),f(g))}function f(g){return g===o||g===null||jt(g)?(s.exit("chunkString"),d(g)):(s.consume(g),g===92?p:f)}function p(g){return g===o||g===92?(s.consume(g),f):f(g)}}function Gu(s,e){let t;return n;function n(a){return jt(a)?(s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),t=!0,n):Xt(a)?an(s,n,t?"linePrefix":"lineSuffix")(a):e(a)}}const sF={name:"definition",tokenize:iF},aF={partial:!0,tokenize:rF};function iF(s,e,t){const n=this;let a;return i;function i(b){return s.enter("definition"),o(b)}function o(b){return CM.call(n,s,l,t,"definitionLabel","definitionLabelMarker","definitionLabelString")(b)}function l(b){return a=Ka(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),b===58?(s.enter("definitionMarker"),s.consume(b),s.exit("definitionMarker"),c):t(b)}function c(b){return Tn(b)?Gu(s,d)(b):d(b)}function d(b){return jM(s,f,t,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(b)}function f(b){return s.attempt(aF,p,p)(b)}function p(b){return Xt(b)?an(s,g,"whitespace")(b):g(b)}function g(b){return b===null||jt(b)?(s.exit("definition"),n.parser.defined.push(a),e(b)):t(b)}}function rF(s,e,t){return n;function n(l){return Tn(l)?Gu(s,a)(l):t(l)}function a(l){return AM(s,i,t,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function i(l){return Xt(l)?an(s,o,"whitespace")(l):o(l)}function o(l){return l===null||jt(l)?e(l):t(l)}}const oF={name:"hardBreakEscape",tokenize:lF};function lF(s,e,t){return n;function n(i){return s.enter("hardBreakEscape"),s.consume(i),a}function a(i){return jt(i)?(s.exit("hardBreakEscape"),e(i)):t(i)}}const cF={name:"headingAtx",resolve:uF,tokenize:dF};function uF(s,e){let t=s.length-2,n=3,a,i;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&&(a={type:"atxHeadingText",start:s[n][1].start,end:s[t][1].end},i={type:"chunkText",start:s[n][1].start,end:s[t][1].end,contentType:"text"},ma(s,n,t-n+1,[["enter",a,e],["enter",i,e],["exit",i,e],["exit",a,e]])),s}function dF(s,e,t){let n=0;return a;function a(f){return s.enter("atxHeading"),i(f)}function i(f){return s.enter("atxHeadingSequence"),o(f)}function o(f){return f===35&&n++<6?(s.consume(f),o):f===null||Tn(f)?(s.exit("atxHeadingSequence"),l(f)):t(f)}function l(f){return f===35?(s.enter("atxHeadingSequence"),c(f)):f===null||jt(f)?(s.exit("atxHeading"),e(f)):Xt(f)?an(s,l,"whitespace")(f):(s.enter("atxHeadingText"),d(f))}function c(f){return f===35?(s.consume(f),c):(s.exit("atxHeadingSequence"),l(f))}function d(f){return f===null||f===35||Tn(f)?(s.exit("atxHeadingText"),l(f)):(s.consume(f),d)}}const hF=["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"],$j=["pre","script","style","textarea"],pF={concrete:!0,name:"htmlFlow",resolveTo:gF,tokenize:bF},fF={partial:!0,tokenize:xF},mF={partial:!0,tokenize:yF};function gF(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 bF(s,e,t){const n=this;let a,i,o,l,c;return d;function d(z){return f(z)}function f(z){return s.enter("htmlFlow"),s.enter("htmlFlowData"),s.consume(z),p}function p(z){return z===33?(s.consume(z),g):z===47?(s.consume(z),i=!0,w):z===63?(s.consume(z),a=3,n.interrupt?e:L):zs(z)?(s.consume(z),o=String.fromCharCode(z),k):t(z)}function g(z){return z===45?(s.consume(z),a=2,b):z===91?(s.consume(z),a=5,l=0,y):zs(z)?(s.consume(z),a=4,n.interrupt?e:L):t(z)}function b(z){return z===45?(s.consume(z),n.interrupt?e:L):t(z)}function y(z){const V="CDATA[";return z===V.charCodeAt(l++)?(s.consume(z),l===V.length?n.interrupt?e:O:y):t(z)}function w(z){return zs(z)?(s.consume(z),o=String.fromCharCode(z),k):t(z)}function k(z){if(z===null||z===47||z===62||Tn(z)){const V=z===47,Q=o.toLowerCase();return!V&&!i&&$j.includes(Q)?(a=1,n.interrupt?e(z):O(z)):hF.includes(o.toLowerCase())?(a=6,V?(s.consume(z),S):n.interrupt?e(z):O(z)):(a=7,n.interrupt&&!n.parser.lazy[n.now().line]?t(z):i?j(z):C(z))}return z===45||_s(z)?(s.consume(z),o+=String.fromCharCode(z),k):t(z)}function S(z){return z===62?(s.consume(z),n.interrupt?e:O):t(z)}function j(z){return Xt(z)?(s.consume(z),j):_(z)}function C(z){return z===47?(s.consume(z),_):z===58||z===95||zs(z)?(s.consume(z),N):Xt(z)?(s.consume(z),C):_(z)}function N(z){return z===45||z===46||z===58||z===95||_s(z)?(s.consume(z),N):D(z)}function D(z){return z===61?(s.consume(z),E):Xt(z)?(s.consume(z),D):C(z)}function E(z){return z===null||z===60||z===61||z===62||z===96?t(z):z===34||z===39?(s.consume(z),c=z,$):Xt(z)?(s.consume(z),E):M(z)}function $(z){return z===c?(s.consume(z),c=null,R):z===null||jt(z)?t(z):(s.consume(z),$)}function M(z){return z===null||z===34||z===39||z===47||z===60||z===61||z===62||z===96||Tn(z)?D(z):(s.consume(z),M)}function R(z){return z===47||z===62||Xt(z)?C(z):t(z)}function _(z){return z===62?(s.consume(z),P):t(z)}function P(z){return z===null||jt(z)?O(z):Xt(z)?(s.consume(z),P):t(z)}function O(z){return z===45&&a===2?(s.consume(z),U):z===60&&a===1?(s.consume(z),q):z===62&&a===4?(s.consume(z),ee):z===63&&a===3?(s.consume(z),L):z===93&&a===5?(s.consume(z),X):jt(z)&&(a===6||a===7)?(s.exit("htmlFlowData"),s.check(fF,Z,F)(z)):z===null||jt(z)?(s.exit("htmlFlowData"),F(z)):(s.consume(z),O)}function F(z){return s.check(mF,B,Z)(z)}function B(z){return s.enter("lineEnding"),s.consume(z),s.exit("lineEnding"),I}function I(z){return z===null||jt(z)?F(z):(s.enter("htmlFlowData"),O(z))}function U(z){return z===45?(s.consume(z),L):O(z)}function q(z){return z===47?(s.consume(z),o="",K):O(z)}function K(z){if(z===62){const V=o.toLowerCase();return $j.includes(V)?(s.consume(z),ee):O(z)}return zs(z)&&o.length<8?(s.consume(z),o+=String.fromCharCode(z),K):O(z)}function X(z){return z===93?(s.consume(z),L):O(z)}function L(z){return z===62?(s.consume(z),ee):z===45&&a===2?(s.consume(z),L):O(z)}function ee(z){return z===null||jt(z)?(s.exit("htmlFlowData"),Z(z)):(s.consume(z),ee)}function Z(z){return s.exit("htmlFlow"),e(z)}}function yF(s,e,t){const n=this;return a;function a(o){return jt(o)?(s.enter("lineEnding"),s.consume(o),s.exit("lineEnding"),i):t(o)}function i(o){return n.parser.lazy[n.now().line]?t(o):e(o)}}function xF(s,e,t){return n;function n(a){return s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),s.attempt(hd,e,t)}}const vF={name:"htmlText",tokenize:wF};function wF(s,e,t){const n=this;let a,i,o;return l;function l(L){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(L),c}function c(L){return L===33?(s.consume(L),d):L===47?(s.consume(L),D):L===63?(s.consume(L),C):zs(L)?(s.consume(L),M):t(L)}function d(L){return L===45?(s.consume(L),f):L===91?(s.consume(L),i=0,y):zs(L)?(s.consume(L),j):t(L)}function f(L){return L===45?(s.consume(L),b):t(L)}function p(L){return L===null?t(L):L===45?(s.consume(L),g):jt(L)?(o=p,q(L)):(s.consume(L),p)}function g(L){return L===45?(s.consume(L),b):p(L)}function b(L){return L===62?U(L):L===45?g(L):p(L)}function y(L){const ee="CDATA[";return L===ee.charCodeAt(i++)?(s.consume(L),i===ee.length?w:y):t(L)}function w(L){return L===null?t(L):L===93?(s.consume(L),k):jt(L)?(o=w,q(L)):(s.consume(L),w)}function k(L){return L===93?(s.consume(L),S):w(L)}function S(L){return L===62?U(L):L===93?(s.consume(L),S):w(L)}function j(L){return L===null||L===62?U(L):jt(L)?(o=j,q(L)):(s.consume(L),j)}function C(L){return L===null?t(L):L===63?(s.consume(L),N):jt(L)?(o=C,q(L)):(s.consume(L),C)}function N(L){return L===62?U(L):C(L)}function D(L){return zs(L)?(s.consume(L),E):t(L)}function E(L){return L===45||_s(L)?(s.consume(L),E):$(L)}function $(L){return jt(L)?(o=$,q(L)):Xt(L)?(s.consume(L),$):U(L)}function M(L){return L===45||_s(L)?(s.consume(L),M):L===47||L===62||Tn(L)?R(L):t(L)}function R(L){return L===47?(s.consume(L),U):L===58||L===95||zs(L)?(s.consume(L),_):jt(L)?(o=R,q(L)):Xt(L)?(s.consume(L),R):U(L)}function _(L){return L===45||L===46||L===58||L===95||_s(L)?(s.consume(L),_):P(L)}function P(L){return L===61?(s.consume(L),O):jt(L)?(o=P,q(L)):Xt(L)?(s.consume(L),P):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),a=L,F):jt(L)?(o=O,q(L)):Xt(L)?(s.consume(L),O):(s.consume(L),B)}function F(L){return L===a?(s.consume(L),a=void 0,I):L===null?t(L):jt(L)?(o=F,q(L)):(s.consume(L),F)}function B(L){return L===null||L===34||L===39||L===60||L===61||L===96?t(L):L===47||L===62||Tn(L)?R(L):(s.consume(L),B)}function I(L){return L===47||L===62||Tn(L)?R(L):t(L)}function U(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"),K}function K(L){return Xt(L)?an(s,X,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(L):X(L)}function X(L){return s.enter("htmlTextData"),o(L)}}const kx={name:"labelEnd",resolveAll:CF,resolveTo:AF,tokenize:NF},kF={tokenize:MF},SF={tokenize:TF},jF={tokenize:EF};function CF(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 a=n.type==="labelImage"?4:2;n.type="data",e+=a}}return s.length!==t.length&&ma(s,0,s.length,t),s}function AF(s,e){let t=s.length,n=0,a,i,o,l;for(;t--;)if(a=s[t][1],i){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;s[t][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(o){if(s[t][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(i=t,a.type!=="labelLink")){n=2;break}}else a.type==="labelEnd"&&(o=t);const c={type:s[i][1].type==="labelLink"?"link":"image",start:{...s[i][1].start},end:{...s[s.length-1][1].end}},d={type:"label",start:{...s[i][1].start},end:{...s[o][1].end}},f={type:"labelText",start:{...s[i+n+2][1].end},end:{...s[o-2][1].start}};return l=[["enter",c,e],["enter",d,e]],l=Ea(l,s.slice(i+1,i+n+3)),l=Ea(l,[["enter",f,e]]),l=Ea(l,rf(e.parser.constructs.insideSpan.null,s.slice(i+n+4,o-3),e)),l=Ea(l,[["exit",f,e],s[o-2],s[o-1],["exit",d,e]]),l=Ea(l,s.slice(o+1)),l=Ea(l,[["exit",c,e]]),ma(s,i,s.length,l),s}function NF(s,e,t){const n=this;let a=n.events.length,i,o;for(;a--;)if((n.events[a][1].type==="labelImage"||n.events[a][1].type==="labelLink")&&!n.events[a][1]._balanced){i=n.events[a][1];break}return l;function l(g){return i?i._inactive?p(g):(o=n.parser.defined.includes(Ka(n.sliceSerialize({start:i.end,end:n.now()}))),s.enter("labelEnd"),s.enter("labelMarker"),s.consume(g),s.exit("labelMarker"),s.exit("labelEnd"),c):t(g)}function c(g){return g===40?s.attempt(kF,f,o?f:p)(g):g===91?s.attempt(SF,f,o?d:p)(g):o?f(g):p(g)}function d(g){return s.attempt(jF,f,p)(g)}function f(g){return e(g)}function p(g){return i._balanced=!0,t(g)}}function MF(s,e,t){return n;function n(p){return s.enter("resource"),s.enter("resourceMarker"),s.consume(p),s.exit("resourceMarker"),a}function a(p){return Tn(p)?Gu(s,i)(p):i(p)}function i(p){return p===41?f(p):jM(s,o,l,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(p)}function o(p){return Tn(p)?Gu(s,c)(p):f(p)}function l(p){return t(p)}function c(p){return p===34||p===39||p===40?AM(s,d,t,"resourceTitle","resourceTitleMarker","resourceTitleString")(p):f(p)}function d(p){return Tn(p)?Gu(s,f)(p):f(p)}function f(p){return p===41?(s.enter("resourceMarker"),s.consume(p),s.exit("resourceMarker"),s.exit("resource"),e):t(p)}}function TF(s,e,t){const n=this;return a;function a(l){return CM.call(n,s,i,o,"reference","referenceMarker","referenceString")(l)}function i(l){return n.parser.defined.includes(Ka(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?e(l):t(l)}function o(l){return t(l)}}function EF(s,e,t){return n;function n(i){return s.enter("reference"),s.enter("referenceMarker"),s.consume(i),s.exit("referenceMarker"),a}function a(i){return i===93?(s.enter("referenceMarker"),s.consume(i),s.exit("referenceMarker"),s.exit("reference"),e):t(i)}}const _F={name:"labelStartImage",resolveAll:kx.resolveAll,tokenize:DF};function DF(s,e,t){const n=this;return a;function a(l){return s.enter("labelImage"),s.enter("labelImageMarker"),s.consume(l),s.exit("labelImageMarker"),i}function i(l){return l===91?(s.enter("labelMarker"),s.consume(l),s.exit("labelMarker"),s.exit("labelImage"),o):t(l)}function o(l){return l===94&&"_hiddenFootnoteSupport"in n.parser.constructs?t(l):e(l)}}const RF={name:"labelStartLink",resolveAll:kx.resolveAll,tokenize:PF};function PF(s,e,t){const n=this;return a;function a(o){return s.enter("labelLink"),s.enter("labelMarker"),s.consume(o),s.exit("labelMarker"),s.exit("labelLink"),i}function i(o){return o===94&&"_hiddenFootnoteSupport"in n.parser.constructs?t(o):e(o)}}const eb={name:"lineEnding",tokenize:LF};function LF(s,e){return t;function t(n){return s.enter("lineEnding"),s.consume(n),s.exit("lineEnding"),an(s,e,"linePrefix")}}const ep={name:"thematicBreak",tokenize:OF};function OF(s,e,t){let n=0,a;return i;function i(d){return s.enter("thematicBreak"),o(d)}function o(d){return a=d,l(d)}function l(d){return d===a?(s.enter("thematicBreakSequence"),c(d)):n>=3&&(d===null||jt(d))?(s.exit("thematicBreak"),e(d)):t(d)}function c(d){return d===a?(s.consume(d),n++,c):(s.exit("thematicBreakSequence"),Xt(d)?an(s,l,"whitespace")(d):l(d))}}const Ks={continuation:{tokenize:FF},exit:HF,name:"list",tokenize:zF},IF={partial:!0,tokenize:UF},BF={partial:!0,tokenize:$F};function zF(s,e,t){const n=this,a=n.events[n.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,o=0;return l;function l(b){const y=n.containerState.type||(b===42||b===43||b===45?"listUnordered":"listOrdered");if(y==="listUnordered"?!n.containerState.marker||b===n.containerState.marker:xy(b)){if(n.containerState.type||(n.containerState.type=y,s.enter(y,{_container:!0})),y==="listUnordered")return s.enter("listItemPrefix"),b===42||b===45?s.check(ep,t,d)(b):d(b);if(!n.interrupt||b===49)return s.enter("listItemPrefix"),s.enter("listItemValue"),c(b)}return t(b)}function c(b){return xy(b)&&++o<10?(s.consume(b),c):(!n.interrupt||o<2)&&(n.containerState.marker?b===n.containerState.marker:b===41||b===46)?(s.exit("listItemValue"),d(b)):t(b)}function d(b){return s.enter("listItemMarker"),s.consume(b),s.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||b,s.check(hd,n.interrupt?t:f,s.attempt(IF,g,p))}function f(b){return n.containerState.initialBlankLine=!0,i++,g(b)}function p(b){return Xt(b)?(s.enter("listItemPrefixWhitespace"),s.consume(b),s.exit("listItemPrefixWhitespace"),g):t(b)}function g(b){return n.containerState.size=i+n.sliceSerialize(s.exit("listItemPrefix"),!0).length,e(b)}}function FF(s,e,t){const n=this;return n.containerState._closeFlow=void 0,s.check(hd,a,i);function a(l){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,an(s,e,"listItemIndent",n.containerState.size+1)(l)}function i(l){return n.containerState.furtherBlankLines||!Xt(l)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,o(l)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,s.attempt(BF,e,o)(l))}function o(l){return n.containerState._closeFlow=!0,n.interrupt=void 0,an(s,s.attempt(Ks,e,t),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function $F(s,e,t){const n=this;return an(s,a,"listItemIndent",n.containerState.size+1);function a(i){const o=n.events[n.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===n.containerState.size?e(i):t(i)}}function HF(s){s.exit(this.containerState.type)}function UF(s,e,t){const n=this;return an(s,a,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const o=n.events[n.events.length-1];return!Xt(i)&&o&&o[1].type==="listItemPrefixWhitespace"?e(i):t(i)}}const Hj={name:"setextUnderline",resolveTo:GF,tokenize:WF};function GF(s,e){let t=s.length,n,a,i;for(;t--;)if(s[t][0]==="enter"){if(s[t][1].type==="content"){n=t;break}s[t][1].type==="paragraph"&&(a=t)}else s[t][1].type==="content"&&s.splice(t,1),!i&&s[t][1].type==="definition"&&(i=t);const o={type:"setextHeading",start:{...s[n][1].start},end:{...s[s.length-1][1].end}};return s[a][1].type="setextHeadingText",i?(s.splice(a,0,["enter",o,e]),s.splice(i+1,0,["exit",s[n][1],e]),s[n][1].end={...s[i][1].end}):s[n][1]=o,s.push(["exit",o,e]),s}function WF(s,e,t){const n=this;let a;return i;function i(d){let f=n.events.length,p;for(;f--;)if(n.events[f][1].type!=="lineEnding"&&n.events[f][1].type!=="linePrefix"&&n.events[f][1].type!=="content"){p=n.events[f][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||p)?(s.enter("setextHeadingLine"),a=d,o(d)):t(d)}function o(d){return s.enter("setextHeadingLineSequence"),l(d)}function l(d){return d===a?(s.consume(d),l):(s.exit("setextHeadingLineSequence"),Xt(d)?an(s,c,"lineSuffix")(d):c(d))}function c(d){return d===null||jt(d)?(s.exit("setextHeadingLine"),e(d)):t(d)}}const qF={tokenize:YF};function YF(s){const e=this,t=s.attempt(hd,n,s.attempt(this.parser.constructs.flowInitial,a,an(s,s.attempt(this.parser.constructs.flow,a,s.attempt(Qz,a)),"linePrefix")));return t;function n(i){if(i===null){s.consume(i);return}return s.enter("lineEndingBlank"),s.consume(i),s.exit("lineEndingBlank"),e.currentConstruct=void 0,t}function a(i){if(i===null){s.consume(i);return}return s.enter("lineEnding"),s.consume(i),s.exit("lineEnding"),e.currentConstruct=void 0,t}}const VF={resolveAll:MM()},KF=NM("string"),XF=NM("text");function NM(s){return{resolveAll:MM(s==="text"?ZF:void 0),tokenize:e};function e(t){const n=this,a=this.parser.constructs[s],i=t.attempt(a,o,l);return o;function o(f){return d(f)?i(f):l(f)}function l(f){if(f===null){t.consume(f);return}return t.enter("data"),t.consume(f),c}function c(f){return d(f)?(t.exit("data"),i(f)):(t.consume(f),c)}function d(f){if(f===null)return!0;const p=a[f];let g=-1;if(p)for(;++g<p.length;){const b=p[g];if(!b.previous||b.previous.call(n,n.previous))return!0}return!1}}}function MM(s){return e;function e(t,n){let a=-1,i;for(;++a<=t.length;)i===void 0?t[a]&&t[a][1].type==="data"&&(i=a,a++):(!t[a]||t[a][1].type!=="data")&&(a!==i+2&&(t[i][1].end=t[a-1][1].end,t.splice(i+2,a-i-2),a=i+2),i=void 0);return s?s(t,n):t}}function ZF(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],a=e.sliceStream(n);let i=a.length,o=-1,l=0,c;for(;i--;){const d=a[i];if(typeof d=="string"){for(o=d.length;d.charCodeAt(o-1)===32;)l++,o--;if(o)break;o=-1}else if(d===-2)c=!0,l++;else if(d!==-1){i++;break}}if(e._contentTypeTextTrailing&&t===s.length&&(l=0),l){const d={type:t===s.length||c||l<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?o:n.start._bufferIndex+o,_index:n.start._index+i,line:n.end.line,column:n.end.column-l,offset:n.end.offset-l},end:{...n.end}};n.end={...d.start},n.start.offset===n.end.offset?Object.assign(n,d):(s.splice(t,0,["enter",d,e],["exit",d,e]),t+=2)}t++}return s}const QF={42:Ks,43:Ks,45:Ks,48:Ks,49:Ks,50:Ks,51:Ks,52:Ks,53:Ks,54:Ks,55:Ks,56:Ks,57:Ks,62:vM},JF={91:sF},e3={[-2]:Jg,[-1]:Jg,32:Jg},t3={35:cF,42:ep,45:[Hj,ep],60:pF,61:Hj,95:ep,96:Fj,126:Fj},n3={38:kM,92:wM},s3={[-5]:eb,[-4]:eb,[-3]:eb,33:_F,38:kM,42:vy,60:[Rz,vF],91:RF,92:[oF,wM],93:kx,95:vy,96:qz},a3={null:[vy,VF]},i3={null:[42,95]},r3={null:[]},o3=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:i3,contentInitial:JF,disable:r3,document:QF,flow:t3,flowInitial:e3,insideSpan:a3,string:n3,text:s3},Symbol.toStringTag,{value:"Module"}));function l3(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 a={},i=[];let o=[],l=[];const c={attempt:$(D),check:$(E),consume:j,enter:C,exit:N,interrupt:$(E,{interrupt:!0})},d={code:null,containerState:{},defineSkip:w,events:[],now:y,parser:s,previous:null,sliceSerialize:g,sliceStream:b,write:p};let f=e.tokenize.call(d,c);return e.resolveAll&&i.push(e),d;function p(P){return o=Ea(o,P),k(),o[o.length-1]!==null?[]:(M(e,0),d.events=rf(i,d.events,d),d.events)}function g(P,O){return u3(b(P),O)}function b(P){return c3(o,P)}function y(){const{_bufferIndex:P,_index:O,line:F,column:B,offset:I}=n;return{_bufferIndex:P,_index:O,line:F,column:B,offset:I}}function w(P){a[P.line]=P.column,_()}function k(){let P;for(;n._index<o.length;){const O=o[n._index];if(typeof O=="string")for(P=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===P&&n._bufferIndex<O.length;)S(O.charCodeAt(n._bufferIndex));else S(O)}}function S(P){f=f(P)}function j(P){jt(P)?(n.line++,n.column=1,n.offset+=P===-3?2:1,_()):P!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===o[n._index].length&&(n._bufferIndex=-1,n._index++)),d.previous=P}function C(P,O){const F=O||{};return F.type=P,F.start=y(),d.events.push(["enter",F,d]),l.push(F),F}function N(P){const O=l.pop();return O.end=y(),d.events.push(["exit",O,d]),O}function D(P,O){M(P,O.from)}function E(P,O){O.restore()}function $(P,O){return F;function F(B,I,U){let q,K,X,L;return Array.isArray(B)?Z(B):"tokenize"in B?Z([B]):ee(B);function ee(J){return Y;function Y(se){const ae=se!==null&&J[se],le=se!==null&&J.null,pe=[...Array.isArray(ae)?ae:ae?[ae]:[],...Array.isArray(le)?le:le?[le]:[]];return Z(pe)(se)}}function Z(J){return q=J,K=0,J.length===0?U:z(J[K])}function z(J){return Y;function Y(se){return L=R(),X=J,J.partial||(d.currentConstruct=J),J.name&&d.parser.constructs.disable.null.includes(J.name)?Q():J.tokenize.call(O?Object.assign(Object.create(d),O):d,c,V,Q)(se)}}function V(J){return P(X,L),I}function Q(J){return L.restore(),++K<q.length?z(q[K]):U}}}function M(P,O){P.resolveAll&&!i.includes(P)&&i.push(P),P.resolve&&ma(d.events,O,d.events.length-O,P.resolve(d.events.slice(O),d)),P.resolveTo&&(d.events=P.resolveTo(d.events,d))}function R(){const P=y(),O=d.previous,F=d.currentConstruct,B=d.events.length,I=Array.from(l);return{from:B,restore:U};function U(){n=P,d.previous=O,d.currentConstruct=F,d.events.length=B,l=I,_()}}function _(){n.line in a&&n.column<2&&(n.column=a[n.line],n.offset+=a[n.line]-1)}}function c3(s,e){const t=e.start._index,n=e.start._bufferIndex,a=e.end._index,i=e.end._bufferIndex;let o;if(t===a)o=[s[t].slice(n,i)];else{if(o=s.slice(t,a),n>-1){const l=o[0];typeof l=="string"?o[0]=l.slice(n):o.shift()}i>0&&o.push(s[a].slice(0,i))}return o}function u3(s,e){let t=-1;const n=[];let a;for(;++t<s.length;){const i=s[t];let o;if(typeof i=="string")o=i;else switch(i){case-5:{o="\r";break}case-4:{o=`
|
|
@@ -229,7 +229,7 @@ ${re}`:ce=re}H.sendCommand(e,ce),a(""),o(!1),w(new Map),d([]),k(),window.innerWi
|
|
|
229
229
|
`),children:["⑂",w.length]}),y.length>0&&w.length===0&&r.jsxs("span",{className:"aop-subagent-count",title:c("terminal:overview.subagentsCompleted",{count:y.length}),style:{opacity:.5},children:["⑂",y.length]})]}),g&&r.jsxs("div",{className:`aop-last-message ${g.isUserPrompt?"user":"assistant"}`,title:g.text.split(`
|
|
230
230
|
`)[0],children:[r.jsx("span",{className:"lm-prefix",children:g.isUserPrompt?"▶":"◀"}),r.jsx("span",{className:"lm-text",children:VC(g.text,80)}),r.jsx("span",{className:"lm-time",children:bp(g.timestamp)})]}),t&&r.jsxs("div",{className:"aop-agent-body",children:[y.length>0&&r.jsxs("div",{className:"aop-subagents",children:[r.jsx("div",{className:"aop-section-label",children:c("terminal:overview.subagents",{count:y.length})}),y.map(k=>r.jsxs("div",{className:`aop-subagent-item ${k.status}`,children:[r.jsx("span",{className:"sub-icon",children:k.status==="completed"?"✅":k.status==="failed"?"❌":k.status==="unknown"?"⬜":"⑂"}),r.jsx("span",{className:"sub-name",children:k.name}),r.jsx("span",{className:"sub-type",children:k.type}),k.description&&r.jsx("span",{className:"sub-desc",title:k.description,children:VC(k.description,50)})]},k.id))]}),p.length>0&&r.jsxs("div",{className:"aop-tool-timeline",children:[r.jsx("div",{className:"aop-section-label",children:c("terminal:overview.recentActivity")}),p.map((k,S)=>{var C,N;const j=k.toolInput&&(k.toolInput.file_path||((C=k.toolInput.command)==null?void 0:C.slice(0,40))||k.toolInput.pattern||k.toolInput.description||((N=k.toolInput.prompt)==null?void 0:N.slice(0,50)))||"";return r.jsxs("div",{className:"aop-timeline-entry",children:[r.jsx("span",{className:"tl-time",children:bp(k.timestamp)}),r.jsx("span",{className:"tl-icon",children:hs[k.toolName]||hs.default}),r.jsx("span",{className:"tl-tool",children:k.toolName}),j&&r.jsx("span",{className:"tl-param",children:j})]},`${k.timestamp}-${S}`)})]}),n.length===0&&a.length===0&&r.jsx("div",{className:"aop-no-activity",children:c("terminal:overview.noToolActivity")})]})]})}function y9({progress:s,defaultExpanded:e=!1,onAgentClick:t}){const[n,a]=x.useState(null),i=x.useRef(s.status),o=n!==null?!n:s.status==="working"||s.status==="completed"||s.status==="failed";x.useEffect(()=>{i.current!==s.status&&(i.current==="working"&&(s.status==="completed"||s.status==="failed")&&a(!1),i.current=s.status)},[s.status]);const l={working:"#4a9eff",completed:"#22c55e",failed:"#ef4444"},c={working:"⚙️",completed:"✅",failed:"❌"},{t:d}=He(["tools"]),f={working:d("tools:progress.workingOn"),completed:d("tools:progress.taskFinished"),failed:d("tools:progress.taskFailed")},p=s.taskDescription.length>80?s.taskDescription.slice(0,80)+"...":s.taskDescription,g=()=>{const y=s.completedAt||Date.now(),w=Math.floor((y-s.startedAt)/1e3);if(w<60)return`${w}s`;const k=Math.floor(w/60),S=w%60;return`${k}m ${S}s`},b=()=>{a(o)};return r.jsxs("div",{className:`agent-progress-indicator status-${s.status} ${o?"expanded":"collapsed"}`,children:[r.jsxs("div",{className:"agent-progress-header",onClick:b,children:[r.jsx("span",{className:"agent-progress-status-icon",style:{color:l[s.status]},children:c[s.status]}),r.jsx("span",{className:"agent-progress-agent-name",onClick:y=>{t&&(y.stopPropagation(),t(s.agentId))},children:s.agentName}),r.jsx("span",{className:"agent-progress-status-text",style:{color:l[s.status]},children:f[s.status]}),r.jsx("span",{className:"agent-progress-elapsed",children:g()}),r.jsx("span",{className:"agent-progress-toggle",children:o?"▼":"▶"})]}),!o&&r.jsx("div",{className:"agent-progress-task-preview",children:p}),o&&r.jsxs("div",{className:"agent-progress-expanded",children:[r.jsx("div",{className:"agent-progress-task-full",children:s.taskDescription}),s.output.length>0&&r.jsx("div",{className:"agent-progress-output-section",children:r.jsx(x9,{output:s.output,agentId:s.agentId,maxHeight:200})})]})]})}function x9({output:s,agentId:e,maxHeight:t=200}){const n=x.useRef(null),a=x.useMemo(()=>s.map((o,l)=>({text:o,isStreaming:!1,timestamp:Date.now()-(s.length-l)*100})),[s]),i=Rx({outputs:a,viewMode:"simple"});return x.useEffect(()=>{n.current&&(n.current.scrollTop=n.current.scrollHeight)},[i]),i.length===0?null:r.jsx("div",{ref:n,className:"agent-progress-output",style:{maxHeight:`${t}px`},children:i.map((o,l)=>r.jsx(pf,{output:o,agentId:e},`progress-${l}`))})}const v9={id:"dracula",name:"Dracula",description:"Vampire purple with fangs pink",colors:{bgPrimary:"#282a36",bgSecondary:"#21222c",bgTertiary:"#343746",borderColor:"#44475a",textPrimary:"#f8f8f2",textSecondary:"#bfbfbf",textMuted:"#6272a4",accentBlue:"#8be9fd",accentGreen:"#50fa7b",accentOrange:"#ffb86c",accentRed:"#ff5555",accentPurple:"#bd93f9",accentCyan:"#8be9fd",accentClaude:"#50fa7b",accentClaudeLight:"#69ff94",accentPink:"#ff79c6",accentYellow:"#f1fa8c",msgUserBg:"rgba(189, 147, 249, 0.12)",msgUserBorder:"#bd93f9",msgUserText:"#bd93f9",msgAssistantBg:"rgba(255, 121, 198, 0.12)",msgAssistantBorder:"#ff79c6",msgAssistantText:"#ff79c6",toolUseBg:"rgba(255, 184, 108, 0.08)",toolUseBorder:"#ffb86c",toolUseText:"#ffb86c",toolUseName:"#8be9fd",toolResultBg:"rgba(80, 250, 123, 0.08)",toolResultBorder:"#50fa7b",toolResultText:"#50fa7b",outputLineBg:"rgba(189, 147, 249, 0.04)",contextBarBg:"rgba(189, 147, 249, 0.25)",contextBarFill:"#bd93f9"}},DT={id:"muted",name:"Muted",description:"Foggy dawn through frosted glass",colors:{bgPrimary:"#16181c",bgSecondary:"#1c1f24",bgTertiary:"#24282e",borderColor:"#33393f",textPrimary:"#c8ccd4",textSecondary:"#9099a4",textMuted:"#5c6670",accentBlue:"#7aa8c8",accentGreen:"#8ab898",accentOrange:"#c8a878",accentRed:"#c88888",accentPurple:"#a898b8",accentCyan:"#88b8c0",accentClaude:"#8ab898",accentClaudeLight:"#9ac8a8",accentPink:"#b898a8",accentYellow:"#c8c098",msgUserBg:"rgba(138, 184, 152, 0.06)",msgUserBorder:"rgba(138, 184, 152, 0.3)",msgUserText:"#8ab898",msgAssistantBg:"rgba(168, 152, 184, 0.06)",msgAssistantBorder:"rgba(168, 152, 184, 0.3)",msgAssistantText:"#a898b8",toolUseBg:"rgba(200, 168, 120, 0.05)",toolUseBorder:"rgba(200, 168, 120, 0.3)",toolUseText:"#c8a878",toolUseName:"#88b8c0",toolResultBg:"rgba(136, 184, 192, 0.05)",toolResultBorder:"rgba(136, 184, 192, 0.3)",toolResultText:"#88b8c0",outputLineBg:"rgba(144, 153, 164, 0.03)",contextBarBg:"rgba(168, 152, 184, 0.2)",contextBarFill:"#a898b8"}},w9={id:"muted-red",name:"Rosewood",description:"Aged wine by candlelight",colors:{bgPrimary:"#1a1014",bgSecondary:"#221418",bgTertiary:"#2c1c20",borderColor:"#482830",textPrimary:"#f0e4e8",textSecondary:"#c8b0b8",textMuted:"#8c6878",accentBlue:"#8898c8",accentGreen:"#78a890",accentOrange:"#d8a068",accentRed:"#c85868",accentPurple:"#a878a0",accentCyan:"#88a8b0",accentClaude:"#78a890",accentClaudeLight:"#88b8a0",accentPink:"#d88898",accentYellow:"#d8c088",msgUserBg:"rgba(216, 136, 152, 0.10)",msgUserBorder:"#d88898",msgUserText:"#d88898",msgAssistantBg:"rgba(200, 88, 104, 0.10)",msgAssistantBorder:"#c85868",msgAssistantText:"#c85868",toolUseBg:"rgba(216, 160, 104, 0.08)",toolUseBorder:"#d8a068",toolUseText:"#d8a068",toolUseName:"#d8c088",toolResultBg:"rgba(168, 120, 160, 0.08)",toolResultBorder:"#a878a0",toolResultText:"#a878a0",outputLineBg:"rgba(200, 88, 104, 0.03)",contextBarBg:"rgba(216, 136, 152, 0.25)",contextBarFill:"#d88898"}},k9={id:"nord",name:"Nord",description:"Polar night with aurora",colors:{bgPrimary:"#2e3440",bgSecondary:"#3b4252",bgTertiary:"#434c5e",borderColor:"#4c566a",textPrimary:"#eceff4",textSecondary:"#d8dee9",textMuted:"#7b88a1",accentBlue:"#81a1c1",accentGreen:"#a3be8c",accentOrange:"#d08770",accentRed:"#bf616a",accentPurple:"#b48ead",accentCyan:"#88c0d0",accentClaude:"#a3be8c",accentClaudeLight:"#b3ce9c",accentPink:"#b48ead",accentYellow:"#ebcb8b",msgUserBg:"rgba(136, 192, 208, 0.10)",msgUserBorder:"#88c0d0",msgUserText:"#88c0d0",msgAssistantBg:"rgba(163, 190, 140, 0.10)",msgAssistantBorder:"#a3be8c",msgAssistantText:"#a3be8c",toolUseBg:"rgba(208, 135, 112, 0.08)",toolUseBorder:"#d08770",toolUseText:"#d08770",toolUseName:"#ebcb8b",toolResultBg:"rgba(180, 142, 173, 0.08)",toolResultBorder:"#b48ead",toolResultText:"#b48ead",outputLineBg:"rgba(67, 76, 94, 0.3)",contextBarBg:"rgba(129, 161, 193, 0.25)",contextBarFill:"#81a1c1"}},S9={id:"solarized-dark",name:"Solarized",description:"Precision-engineered contrast",colors:{bgPrimary:"#002b36",bgSecondary:"#073642",bgTertiary:"#094652",borderColor:"#586e75",textPrimary:"#93a1a1",textSecondary:"#839496",textMuted:"#657b83",accentBlue:"#268bd2",accentGreen:"#859900",accentOrange:"#cb4b16",accentRed:"#dc322f",accentPurple:"#6c71c4",accentCyan:"#2aa198",accentClaude:"#859900",accentClaudeLight:"#95a910",accentPink:"#d33682",accentYellow:"#b58900",msgUserBg:"rgba(42, 161, 152, 0.12)",msgUserBorder:"#2aa198",msgUserText:"#2aa198",msgAssistantBg:"rgba(133, 153, 0, 0.12)",msgAssistantBorder:"#859900",msgAssistantText:"#859900",toolUseBg:"rgba(203, 75, 22, 0.10)",toolUseBorder:"#cb4b16",toolUseText:"#cb4b16",toolUseName:"#b58900",toolResultBg:"rgba(108, 113, 196, 0.10)",toolResultBorder:"#6c71c4",toolResultText:"#6c71c4",outputLineBg:"rgba(7, 54, 66, 0.5)",contextBarBg:"rgba(38, 139, 210, 0.25)",contextBarFill:"#268bd2"}},j9={id:"monokai",name:"Monokai",description:"Neon jungle on warm charcoal",colors:{bgPrimary:"#272822",bgSecondary:"#1e1f1a",bgTertiary:"#3e3d32",borderColor:"#49483e",textPrimary:"#f8f8f2",textSecondary:"#cfcfc2",textMuted:"#75715e",accentBlue:"#66d9ef",accentGreen:"#a6e22e",accentOrange:"#fd971f",accentRed:"#f92672",accentPurple:"#ae81ff",accentCyan:"#66d9ef",accentClaude:"#a6e22e",accentClaudeLight:"#b6f23e",accentPink:"#f92672",accentYellow:"#e6db74",msgUserBg:"rgba(249, 38, 114, 0.10)",msgUserBorder:"#f92672",msgUserText:"#f92672",msgAssistantBg:"rgba(166, 226, 46, 0.10)",msgAssistantBorder:"#a6e22e",msgAssistantText:"#a6e22e",toolUseBg:"rgba(253, 151, 31, 0.08)",toolUseBorder:"#fd971f",toolUseText:"#fd971f",toolUseName:"#66d9ef",toolResultBg:"rgba(174, 129, 255, 0.08)",toolResultBorder:"#ae81ff",toolResultText:"#ae81ff",outputLineBg:"rgba(62, 61, 50, 0.3)",contextBarBg:"rgba(249, 38, 114, 0.25)",contextBarFill:"#f92672"}},C9={id:"gruvbox",name:"Gruvbox",description:"Retro coffee shop warmth",colors:{bgPrimary:"#282828",bgSecondary:"#1d2021",bgTertiary:"#3c3836",borderColor:"#504945",textPrimary:"#ebdbb2",textSecondary:"#d5c4a1",textMuted:"#928374",accentBlue:"#83a598",accentGreen:"#b8bb26",accentOrange:"#fe8019",accentRed:"#fb4934",accentPurple:"#d3869b",accentCyan:"#8ec07c",accentClaude:"#b8bb26",accentClaudeLight:"#c8cb36",accentPink:"#d3869b",accentYellow:"#fabd2f",msgUserBg:"rgba(254, 128, 25, 0.10)",msgUserBorder:"#fe8019",msgUserText:"#fe8019",msgAssistantBg:"rgba(142, 192, 124, 0.10)",msgAssistantBorder:"#8ec07c",msgAssistantText:"#8ec07c",toolUseBg:"rgba(250, 189, 47, 0.08)",toolUseBorder:"#fabd2f",toolUseText:"#fabd2f",toolUseName:"#83a598",toolResultBg:"rgba(211, 134, 155, 0.08)",toolResultBorder:"#d3869b",toolResultText:"#d3869b",outputLineBg:"rgba(60, 56, 54, 0.4)",contextBarBg:"rgba(254, 128, 25, 0.25)",contextBarFill:"#fe8019"}},A9={id:"atom",name:"Atom",description:"Deep space exploration",colors:{bgPrimary:"#0c1014",bgSecondary:"#121820",bgTertiary:"#1a222c",borderColor:"#283040",textPrimary:"#d8e0f0",textSecondary:"#9ca8c0",textMuted:"#5a6880",accentBlue:"#5dade2",accentGreen:"#58d68d",accentOrange:"#f0b060",accentRed:"#ec7063",accentPurple:"#af7ac5",accentCyan:"#48c9b0",accentClaude:"#58d68d",accentClaudeLight:"#68e69d",accentPink:"#f1948a",accentYellow:"#f7dc6f",msgUserBg:"rgba(93, 173, 226, 0.10)",msgUserBorder:"#5dade2",msgUserText:"#5dade2",msgAssistantBg:"rgba(88, 214, 141, 0.10)",msgAssistantBorder:"#58d68d",msgAssistantText:"#58d68d",toolUseBg:"rgba(240, 176, 96, 0.08)",toolUseBorder:"#f0b060",toolUseText:"#f0b060",toolUseName:"#48c9b0",toolResultBg:"rgba(175, 122, 197, 0.08)",toolResultBorder:"#af7ac5",toolResultText:"#af7ac5",outputLineBg:"rgba(26, 34, 44, 0.5)",contextBarBg:"rgba(175, 122, 197, 0.25)",contextBarFill:"#af7ac5"}},N9={id:"cyberpunk",name:"Cyberpunk",description:"Neon noir dystopia",colors:{bgPrimary:"#030308",bgSecondary:"#08080f",bgTertiary:"#101018",borderColor:"#181828",textPrimary:"#e8e8ff",textSecondary:"#a0a0c8",textMuted:"#5050a0",accentBlue:"#00f0ff",accentGreen:"#00ff9f",accentOrange:"#ff6600",accentRed:"#ff003c",accentPurple:"#bf00ff",accentCyan:"#00f0ff",accentClaude:"#00ff9f",accentClaudeLight:"#50ffbf",accentPink:"#ff00aa",accentYellow:"#fff000",msgUserBg:"rgba(255, 0, 170, 0.12)",msgUserBorder:"#ff00aa",msgUserText:"#ff00aa",msgAssistantBg:"rgba(0, 255, 159, 0.10)",msgAssistantBorder:"#00ff9f",msgAssistantText:"#00ff9f",toolUseBg:"rgba(191, 0, 255, 0.10)",toolUseBorder:"#bf00ff",toolUseText:"#bf00ff",toolUseName:"#00f0ff",toolResultBg:"rgba(0, 240, 255, 0.08)",toolResultBorder:"#00f0ff",toolResultText:"#00f0ff",outputLineBg:"rgba(191, 0, 255, 0.03)",contextBarBg:"rgba(255, 0, 170, 0.30)",contextBarFill:"#ff00aa"}},M9={id:"synthwave",name:"Synthwave",description:"Sunset over chrome horizon",colors:{bgPrimary:"#241b30",bgSecondary:"#1a1424",bgTertiary:"#2e2540",borderColor:"#4a3860",textPrimary:"#f8e8f8",textSecondary:"#c8a8d0",textMuted:"#7860a0",accentBlue:"#2de2e6",accentGreen:"#0abdc6",accentOrange:"#ff9e64",accentRed:"#ff3864",accentPurple:"#9d4edd",accentCyan:"#2de2e6",accentClaude:"#0abdc6",accentClaudeLight:"#2ad0d8",accentPink:"#f706cf",accentYellow:"#fede5d",msgUserBg:"rgba(247, 6, 207, 0.12)",msgUserBorder:"#f706cf",msgUserText:"#f706cf",msgAssistantBg:"rgba(45, 226, 230, 0.10)",msgAssistantBorder:"#2de2e6",msgAssistantText:"#2de2e6",toolUseBg:"rgba(255, 158, 100, 0.10)",toolUseBorder:"#ff9e64",toolUseText:"#ff9e64",toolUseName:"#fede5d",toolResultBg:"rgba(157, 78, 221, 0.10)",toolResultBorder:"#9d4edd",toolResultText:"#9d4edd",outputLineBg:"rgba(157, 78, 221, 0.05)",contextBarBg:"rgba(247, 6, 207, 0.25)",contextBarFill:"#f706cf"}},T9={id:"abyss",name:"Abyss",description:"Deep black, vivid accents",colors:{bgPrimary:"#080a0c",bgSecondary:"#0c0e12",bgTertiary:"#12161a",borderColor:"#1c2028",textPrimary:"#a8b0b8",textSecondary:"#889098",textMuted:"#505860",accentBlue:"#4da8da",accentGreen:"#50c878",accentOrange:"#e89050",accentRed:"#e85050",accentPurple:"#a070d8",accentCyan:"#50d0d0",accentClaude:"#50c878",accentClaudeLight:"#68e090",accentPink:"#e070a0",accentYellow:"#e8d050",msgUserBg:"#0b0b0b",msgUserBorder:"transparent",msgUserText:"#98a0a8",msgAssistantBg:"#1B1C25",msgAssistantBorder:"transparent",msgAssistantText:"#98a0a8",toolUseBg:"#1B1C25",toolUseBorder:"#e89050",toolUseText:"#98a0a8",toolUseName:"#e89050",toolResultBg:"#1B1C25",toolResultBorder:"#a070d8",toolResultText:"#98a0a8",outputLineBg:"#0a0c10",contextBarBg:"rgba(80, 88, 96, 0.3)",contextBarFill:"#606870"}},E9={id:"catppuccin",name:"Catppuccin",description:"Cozy pastel mocha cafe",colors:{bgPrimary:"#1e1e2e",bgSecondary:"#181825",bgTertiary:"#313244",borderColor:"#45475a",textPrimary:"#cdd6f4",textSecondary:"#bac2de",textMuted:"#6c7086",accentBlue:"#89b4fa",accentGreen:"#a6e3a1",accentOrange:"#fab387",accentRed:"#f38ba8",accentPurple:"#cba6f7",accentCyan:"#94e2d5",accentClaude:"#a6e3a1",accentClaudeLight:"#b6f3b1",accentPink:"#f5c2e7",accentYellow:"#f9e2af",msgUserBg:"rgba(180, 190, 254, 0.10)",msgUserBorder:"#b4befe",msgUserText:"#b4befe",msgAssistantBg:"rgba(148, 226, 213, 0.10)",msgAssistantBorder:"#94e2d5",msgAssistantText:"#94e2d5",toolUseBg:"rgba(250, 179, 135, 0.08)",toolUseBorder:"#fab387",toolUseText:"#fab387",toolUseName:"#f9e2af",toolResultBg:"rgba(203, 166, 247, 0.08)",toolResultBorder:"#cba6f7",toolResultText:"#cba6f7",outputLineBg:"rgba(49, 50, 68, 0.4)",contextBarBg:"rgba(245, 194, 231, 0.25)",contextBarFill:"#f5c2e7"}},_9={id:"github-dark",name:"GitHub Dark",description:"Developer professional minimal",colors:{bgPrimary:"#0d1117",bgSecondary:"#161b22",bgTertiary:"#21262d",borderColor:"#30363d",textPrimary:"#c9d1d9",textSecondary:"#8b949e",textMuted:"#484f58",accentBlue:"#58a6ff",accentGreen:"#3fb950",accentOrange:"#d29922",accentRed:"#f85149",accentPurple:"#a371f7",accentCyan:"#79c0ff",accentClaude:"#3fb950",accentClaudeLight:"#56d364",accentPink:"#f778ba",accentYellow:"#e3b341",msgUserBg:"rgba(88, 166, 255, 0.08)",msgUserBorder:"#58a6ff",msgUserText:"#58a6ff",msgAssistantBg:"rgba(63, 185, 80, 0.08)",msgAssistantBorder:"#3fb950",msgAssistantText:"#3fb950",toolUseBg:"rgba(210, 153, 34, 0.08)",toolUseBorder:"#d29922",toolUseText:"#d29922",toolUseName:"#79c0ff",toolResultBg:"rgba(163, 113, 247, 0.08)",toolResultBorder:"#a371f7",toolResultText:"#a371f7",outputLineBg:"rgba(33, 38, 45, 0.5)",contextBarBg:"rgba(88, 166, 255, 0.25)",contextBarFill:"#58a6ff"}},D9={id:"one-dark",name:"One Dark",description:"Moonlit late night coding",colors:{bgPrimary:"#282c34",bgSecondary:"#21252b",bgTertiary:"#2c323c",borderColor:"#3e4451",textPrimary:"#abb2bf",textSecondary:"#828997",textMuted:"#5c6370",accentBlue:"#61afef",accentGreen:"#98c379",accentOrange:"#d19a66",accentRed:"#e06c75",accentPurple:"#c678dd",accentCyan:"#56b6c2",accentClaude:"#98c379",accentClaudeLight:"#a8d389",accentPink:"#e06c75",accentYellow:"#e5c07b",msgUserBg:"rgba(86, 182, 194, 0.10)",msgUserBorder:"#56b6c2",msgUserText:"#56b6c2",msgAssistantBg:"rgba(152, 195, 121, 0.10)",msgAssistantBorder:"#98c379",msgAssistantText:"#98c379",toolUseBg:"rgba(209, 154, 102, 0.08)",toolUseBorder:"#d19a66",toolUseText:"#d19a66",toolUseName:"#e5c07b",toolResultBg:"rgba(198, 120, 221, 0.08)",toolResultBorder:"#c678dd",toolResultText:"#c678dd",outputLineBg:"rgba(44, 50, 60, 0.5)",contextBarBg:"rgba(97, 175, 239, 0.25)",contextBarFill:"#61afef"}},R9={id:"classic",name:"Classic",description:"Original transparent style",colors:{bgPrimary:"#0d0d14",bgSecondary:"#14141e",bgTertiary:"#1c1c28",borderColor:"#2a2a3a",textPrimary:"#d0d0d8",textSecondary:"#8a8a98",textMuted:"#5a6a8a",accentBlue:"#5a8fd4",accentGreen:"#50fa7b",accentOrange:"#c89a5a",accentRed:"#c85a5a",accentPurple:"#9a80c0",accentCyan:"#8be9fd",accentClaude:"#50fa7b",accentClaudeLight:"#69ff94",accentPink:"#c87a9a",accentYellow:"#c8c87a",msgUserBg:"rgba(139, 233, 253, 0.12)",msgUserBorder:"transparent",msgUserText:"#8be9fd",msgAssistantBg:"rgba(80, 250, 123, 0.12)",msgAssistantBorder:"transparent",msgAssistantText:"#50fa7b",toolUseBg:"rgba(255, 184, 108, 0.05)",toolUseBorder:"transparent",toolUseText:"#8be9fd",toolUseName:"#ffb86c",toolResultBg:"rgba(80, 250, 123, 0.06)",toolResultBorder:"transparent",toolResultText:"#50fa7b",outputLineBg:"transparent",contextBarBg:"rgba(106, 154, 120, 0.25)",contextBarFill:"#6a9a78"}},ha=[R9,T9,v9,DT,w9,k9,S9,j9,C9,A9,N9,M9,E9,_9,D9];function Yu(s){return ha.find(e=>e.id===s)||DT}const P9="classic";function Ep(s){const e=document.documentElement,{colors:t}=s;e.style.setProperty("--bg-primary",t.bgPrimary),e.style.setProperty("--bg-secondary",t.bgSecondary),e.style.setProperty("--bg-tertiary",t.bgTertiary),e.style.setProperty("--border-color",t.borderColor),e.style.setProperty("--text-primary",t.textPrimary),e.style.setProperty("--text-secondary",t.textSecondary),e.style.setProperty("--text-muted",t.textMuted),e.style.setProperty("--accent-blue",t.accentBlue),e.style.setProperty("--accent-green",t.accentGreen),e.style.setProperty("--accent-orange",t.accentOrange),e.style.setProperty("--accent-red",t.accentRed),e.style.setProperty("--accent-purple",t.accentPurple),e.style.setProperty("--accent-cyan",t.accentCyan),e.style.setProperty("--accent-claude",t.accentClaude),e.style.setProperty("--accent-claude-light",t.accentClaudeLight),e.style.setProperty("--accent-pink",t.accentPink),e.style.setProperty("--accent-yellow",t.accentYellow),e.style.setProperty("--msg-user-bg",t.msgUserBg),e.style.setProperty("--msg-user-border",t.msgUserBorder),e.style.setProperty("--msg-user-text",t.msgUserText),e.style.setProperty("--msg-assistant-bg",t.msgAssistantBg),e.style.setProperty("--msg-assistant-border",t.msgAssistantBorder),e.style.setProperty("--msg-assistant-text",t.msgAssistantText),e.style.setProperty("--tool-use-bg",t.toolUseBg),e.style.setProperty("--tool-use-border",t.toolUseBorder),e.style.setProperty("--tool-use-text",t.toolUseText),e.style.setProperty("--tool-use-name",t.toolUseName),e.style.setProperty("--tool-result-bg",t.toolResultBg),e.style.setProperty("--tool-result-border",t.toolResultBorder),e.style.setProperty("--tool-result-text",t.toolResultText),e.style.setProperty("--output-line-bg",t.outputLineBg),e.style.setProperty("--context-bar-bg",t.contextBarBg),e.style.setProperty("--context-bar-fill",t.contextBarFill);try{localStorage.setItem("tide-theme",s.id)}catch{}}function Fx(){try{const s=localStorage.getItem("tide-theme");if(s&&ha.some(e=>e.id===s))return s}catch{}return P9}function L9(){const s=Fx(),e=Yu(s);Ep(e)}function O9(){const{t:s}=He(["terminal"]),[e,t]=x.useState(!1),[n,a]=x.useState(()=>Fx()),[i,o]=x.useState(-1),l=x.useRef(null),c=x.useRef(null),d=ha.findIndex(y=>y.id===n);x.useEffect(()=>{if(!e)return;const y=w=>{l.current&&!l.current.contains(w.target)&&t(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[e]),x.useEffect(()=>{e&&o(d)},[e,d]);const f=y=>{const w=y==="next"?(d+1)%ha.length:(d-1+ha.length)%ha.length,k=ha[w],S=Yu(k.id);Ep(S),a(k.id)},p=y=>{e||(y.key==="ArrowUp"||y.key==="ArrowLeft"?(y.preventDefault(),f("prev")):y.key==="ArrowDown"||y.key==="ArrowRight"?(y.preventDefault(),f("next")):(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),t(!0)))};x.useEffect(()=>{if(!e)return;const y=w=>{var k,S;w.key==="Escape"?(t(!1),(k=c.current)==null||k.focus()):w.key==="ArrowDown"?(w.preventDefault(),o(j=>(j+1)%ha.length)):w.key==="ArrowUp"?(w.preventDefault(),o(j=>(j-1+ha.length)%ha.length)):w.key==="Enter"&&i>=0&&(w.preventDefault(),g(ha[i].id),(S=c.current)==null||S.focus())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,i]);const g=y=>{const w=Yu(y);Ep(w),a(y),t(!1)},b=Yu(n);return r.jsxs("div",{className:"theme-selector",ref:l,children:[r.jsxs("button",{ref:c,className:"theme-selector-trigger",onClick:()=>t(!e),onKeyDown:p,title:s("terminal:themeSelector.themeTitle",{name:b.name}),children:[r.jsx("span",{className:"theme-selector-icon",children:"🎨"}),r.jsx("span",{className:"theme-selector-name",children:b.name}),r.jsx("span",{className:"theme-selector-arrow",children:e?"▲":"▼"})]}),e&&r.jsxs("div",{className:"theme-selector-dropdown",onMouseDown:y=>y.stopPropagation(),onClick:y=>y.stopPropagation(),children:[r.jsx("div",{className:"theme-selector-header",children:s("terminal:themeSelector.selectTheme")}),r.jsx("div",{className:"theme-selector-list",children:ha.map((y,w)=>r.jsxs("button",{className:`theme-selector-option ${y.id===n?"active":""} ${w===i?"highlighted":""}`,onClick:k=>{k.stopPropagation(),g(y.id)},onMouseDown:k=>k.stopPropagation(),onMouseEnter:()=>o(w),children:[r.jsx("span",{className:"theme-option-preview",style:{background:`linear-gradient(135deg, ${y.colors.bgPrimary} 0%, ${y.colors.bgSecondary} 50%, ${y.colors.accentPurple} 100%)`}}),r.jsxs("span",{className:"theme-option-info",children:[r.jsx("span",{className:"theme-option-name",children:y.name}),r.jsx("span",{className:"theme-option-desc",children:y.description})]}),y.id===n&&r.jsx("span",{className:"theme-option-check",children:"✓"})]},y.id))})]})]})}const KC=1e4,I9=3e4,B9=12e4;function bb(s){const e=Lx(s);return Ox(e.userMessage).userMessage.trim().replace(/\r\n/g,`
|
|
231
231
|
`)}function Fh(s){return s.trim().replace(/\r\n/g,`
|
|
232
|
-
`)}function z9(s){return s.startsWith("Using tool:")||s.startsWith("Tool input:")||s.startsWith("Tool result:")||s.startsWith("Bash output:")||s.startsWith("Session started:")||s.startsWith("[thinking]")||s.startsWith("Tokens:")||s.startsWith("Cost:")||s.startsWith("Context (estimated from Codex turn usage):")||s.startsWith("🔄 [System]")||s.startsWith("📋 [System]")||s.startsWith("[System]")}function F9({onSaveSnapshot:s}={}){var gn,ss,Ne,Xe,ht;const{t:e}=He(["terminal","common"]),t=ir(),n=UN(),a=YN(),i=cx(),o=hx(),l=VN(),c=ux(),d=dx(),f=zB(),p=!!f,g=x.useMemo(()=>f?{id:f.agentId,name:f.agentName,class:f.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:f.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:f.createdAt,lastActivity:f.createdAt}:null,[f]),b=Array.from(n),w=b.length===1?b[0]:null,S=(ox(w)||null)??(p?g:null),j=w??(p?(f==null?void 0:f.agentId)??null:null),C=!!(S!=null&&S.sessionId)&&!p,{terminalHeight:N,terminalRef:D,handleResizeStart:E}=b$(),$=m$(),M=lx(j),R=p&&f?f.outputs.map(Ye=>((!Ye.text||!Ye.text.trim())&&console.warn("[GuakeOutputPanel] Empty snapshot output:",Ye),{text:Ye.text||"",timestamp:Ye.timestamp,isStreaming:!1,isUserPrompt:!1})):M,_=x.useRef(null),P=x.useRef(null),O=x.useRef(null),[F,B]=x.useState(()=>{const Ye=Ds(xt.VIEW_MODE);return Ye==="simple"||Ye==="chat"||Ye==="advanced"?Ye:Ds(xt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[I,U]=x.useState(null),[q,K]=x.useState(null),[X,L]=x.useState(null),[ee,Z]=x.useState(null),[z,V]=x.useState(!1);Mn("guake-image-modal",I!==null,()=>U(null)),Mn("guake-bash-modal",q!==null,()=>K(null)),Mn("guake-response-modal",ee!==null,()=>Z(null)),Mn("guake-context-confirm",X!==null,()=>L(null)),Mn("guake-agent-info",z,()=>V(!1));const[Q,J]=x.useState(!1),[Y,se]=x.useState(()=>bs.isEnabled()),ae=UB(),le=x.useCallback(Ye=>H.setOverviewPanelOpen(Ye),[]),[pe,be]=x.useState(!1),ce=x.useRef(null),he=x.useRef(null),[we,Me]=x.useState(!1),[re,ne]=x.useState(!1),fe=a&&S!==null,xe=dT({selectedAgentId:j,hasSessionId:C,reconnectCount:o,lastPrompts:i,outputScrollRef:_}),ye=w$({selectedAgentId:j,isOpen:fe}),ue=y$({agents:t,selectedAgentId:j,isOpen:fe,loadingHistory:xe.fetchingHistory,hasModalOpen:!!(I||q||ee||c||d),outputRef:_}),Pe=hT({selectedAgentId:w}),Be=!p&&j?H.getPendingPermissionsForAgent(j):[],Qe=(S==null?void 0:S.class)==="boss"||(S==null?void 0:S.isBoss),me=EB(!p&&Qe?j:null),ie=_B(p?null:j);x.useEffect(()=>{Q&&!Y&&(se(!0),bs.setEnabled(!0))},[Q,Y]),x.useEffect(()=>{fe||V(!1)},[fe]),x.useEffect(()=>{const Ye=S==null?void 0:S.status;return ce.current==="working"&&Ye==="idle"?(he.current&&clearTimeout(he.current),be(!0),he.current=setTimeout(()=>{be(!1),he.current=null},1e3)):Ye==="working"&&(he.current&&(clearTimeout(he.current),he.current=null),be(!1)),ce.current=Ye||null,()=>{he.current&&clearTimeout(he.current)}},[S==null?void 0:S.status]);const ke=x.useMemo(()=>{const{history:Ye}=xe,tt=new Map;for(const ct of Ye)ct.type==="tool_result"&&ct.toolUseId&&tt.set(ct.toolUseId,ct.content);const pt=ct=>ct.map(lt=>{if(lt.type==="tool_use"&<.toolName==="Bash"&<.toolUseId){const wt=tt.get(lt.toolUseId);let ut;try{ut=(lt.toolInput||(lt.content?JSON.parse(lt.content):{})).command}catch{}return{...lt,_bashOutput:wt,_bashCommand:ut}}return lt});return pt(F==="advanced"?Ye:F==="chat"?Ye.filter((ct,lt,wt)=>{if(ct.type==="user")return!0;if(ct.type==="assistant"){const ut=wt[lt+1];return!ut||ut.type==="user"}return!1}):Ye.filter(ct=>ct.type==="user"||ct.type==="assistant"||ct.type==="tool_use"))},[xe.history,F]),de=pT({outputs:R,viewMode:F}),Te=x.useMemo(()=>{const Ye=[],tt=new Set,pt=new Set;let ct=null,lt=0;for(const wt of ke){if(wt.type==="assistant"){const Kn=wt.uuid?`uuid:${wt.uuid}:${Fh(wt.content)}`:`sig:${wt.timestamp}:${Fh(wt.content)}`;if(tt.has(Kn))continue;tt.add(Kn),Ye.push(wt);continue}if(wt.type!=="user"){Ye.push(wt);continue}const ut=bb(wt.content),$t=wt.uuid?`uuid:${wt.uuid}:${ut}`:null;if($t&&pt.has($t))continue;const un=wt.timestamp?new Date(wt.timestamp).getTime():0;ct===ut&&Math.abs(un-lt)<=KC||(Ye.push(wt),$t&&pt.add($t),ct=ut,lt=un)}return Ye},[ke]),Oe=x.useMemo(()=>{const Ye=new Map,tt=new Set,pt=new Map;for(const ut of Te){const $t=ut.timestamp?new Date(ut.timestamp).getTime():0;if(ut.type==="user"){const As=bb(ut.content),Xn=Ye.get(As)??0;$t>Xn&&Ye.set(As,$t);continue}if(ut.type!=="assistant")continue;ut.uuid&&tt.add(ut.uuid);const un=Fh(ut.content),Kn=pt.get(un)??0;$t>Kn&&pt.set(un,$t)}const ct=[];let lt=null,wt=0;for(const ut of de){if(!ut.isUserPrompt){if(!ut.isStreaming&&!z9(ut.text)){if(ut.uuid&&tt.has(ut.uuid))continue;const As=Fh(ut.text),Xn=ut.timestamp||0,ba=pt.get(As);if(ba&&Math.abs(Xn-ba)<=B9)continue}ct.push(ut);continue}const $t=bb(ut.text),un=ut.timestamp||0,Kn=Ye.get($t);Kn&&un>=Kn&&un-Kn<=I9||lt===$t&&Math.abs(un-wt)<=KC||(ct.push(ut),lt=$t,wt=un)}return ct},[de,Te]),Ue=Te.length+Oe.length,rt=k$({totalMessages:Ue,isOpen:fe,hasModalOpen:!!(I||q||ee||c),scrollContainerRef:_,selectedAgentId:j,inputRef:P,textareaRef:O,useTextarea:Pe.useTextarea});x.useEffect(()=>{if(!(!(q!=null&&q.isLive)||!q.command)){for(const Ye of Oe)if(Ye._bashCommand===q.command&&Ye._bashOutput){K({command:q.command,output:Ye._bashOutput,isLive:!1});return}}},[q,Oe]);const Je=x.useCallback((Ye,tt)=>{U({url:Ye,name:tt})},[]),St=x.useCallback((Ye,tt)=>{const pt=Dx(Ye,S==null?void 0:S.cwd),ct=pt.line?{...tt||{},targetLine:pt.line}:tt;H.setFileViewerPath(pt.path,ct,S==null?void 0:S.cwd)},[S==null?void 0:S.cwd]),et=x.useCallback((Ye,tt)=>{K({command:Ye,output:tt,isLive:tt==="Running..."})},[]),Nt=x.useCallback(Ye=>{Z(Ye)},[]),[Rt,Mt]=x.useState(!0),mn=x.useRef(!1),je=x.useRef(!1),oe=x.useCallback(()=>{je.current||(mn.current=!0,Mt(!1))},[]);x.useEffect(()=>{Mt(!0),mn.current=!1,je.current=!0;const Ye=setTimeout(()=>{je.current=!1},3e3);return()=>clearTimeout(Ye)},[j]);const Re=x.useCallback(()=>{if(!_.current||$.keyboardScrollLockRef.current)return;const{scrollTop:Ye,scrollHeight:tt,clientHeight:pt}=_.current,ct=tt-Ye-pt<150;je.current||(mn.current=!ct,ct&&Mt(!0)),xe.handleScroll($.keyboardScrollLockRef)},[_,$.keyboardScrollLockRef,xe]),at=M.length>0&&((ss=(gn=M[M.length-1])==null?void 0:gn.text)==null?void 0:ss.length)||0;x.useEffect(()=>{$.keyboardScrollLockRef.current||mn.current||requestAnimationFrame(()=>{if(_.current){const{scrollTop:Ye,scrollHeight:tt,clientHeight:pt}=_.current;tt-Ye-pt<150&&(_.current.scrollTop=tt)}})},[M.length,at,$.keyboardScrollLockRef,_]);const ot=x.useRef(null);x.useLayoutEffect(()=>{Me(!1);const tt=ot.current!==w;ot.current=w,tt&&H.getState().currentSnapshot&&H.setCurrentSnapshot(null)},[w]);const Ft=x.useRef(!1);x.useEffect(()=>{Ft.current=!0,ne(!0)},[j,o]),x.useEffect(()=>{xe.fetchingHistory&&(Ft.current=!0,ne(!0))},[xe.fetchingHistory]),x.useEffect(()=>{if(!re||!fe||xe.fetchingHistory)return;const Ye=_.current;if(!Ye)return;let tt=null;const pt=performance.now();let ct=0,lt=-1;const wt=()=>{const{scrollTop:$t,scrollHeight:un,clientHeight:Kn}=Ye;return un-$t-Kn<=2},ut=()=>{const $t=performance.now(),un=Ye.scrollHeight,Kn=Math.abs(un-lt)<=1,As=wt();if(Kn&&As?ct+=1:ct=0,lt=un,ct>=8){ne(!1),tt=null;return}if($t-pt>8e3){ne(!1),tt=null;return}tt=requestAnimationFrame(ut)};return tt=requestAnimationFrame(ut),()=>{tt!==null&&cancelAnimationFrame(tt)}},[re,fe,xe.fetchingHistory,xe.historyLoadVersion]),x.useEffect(()=>{if(!fe||!Ft.current)return;const Ye=setTimeout(()=>{requestAnimationFrame(()=>{Ft.current=!1,Me(!0)})},50);return()=>clearTimeout(Ye)},[xe.historyLoadVersion,fe,_]),x.useEffect(()=>{const Ye=tt=>{if(tt.key==="`"&&!tt.ctrlKey&&!tt.altKey&&S){const pt=tt.target;pt.tagName!=="INPUT"&&pt.tagName!=="TEXTAREA"&&(tt.preventDefault(),H.toggleTerminal())}};return document.addEventListener("keydown",Ye),()=>document.removeEventListener("keydown",Ye)},[S]),x.useEffect(()=>{const Ye=tt=>{tt.key==="Escape"&&(c?(tt.stopImmediatePropagation(),H.clearFileViewerPath()):d?(tt.stopImmediatePropagation(),H.closeContextModal()):ee?(tt.stopImmediatePropagation(),Z(null)):q?(tt.stopImmediatePropagation(),K(null)):I?(tt.stopImmediatePropagation(),U(null)):ye.searchMode&&(tt.stopImmediatePropagation(),ye.closeSearch()))};return document.addEventListener("keydown",Ye,!0),()=>document.removeEventListener("keydown",Ye,!0)},[I,q,ee,ye,c,d]);const on=x.useRef(fe),Ot=x.useRef(!1);x.useEffect(()=>{on.current=fe},[fe]),x.useEffect(()=>{if(window.innerWidth<=768)return;const tt=lt=>{var un;if(!(lt instanceof Element))return!1;const wt=(un=D.current)==null?void 0:un.contains(lt),ut=lt.closest(".agent-bar"),$t=!!lt.closest(".modal-overlay, .modal, .image-modal-overlay, .image-modal, .bash-modal-overlay, .bash-modal, .agent-info-modal-overlay, .agent-info-modal, .agent-response-modal, .pasted-text-modal-overlay, .pasted-text-modal, .file-viewer-overlay, .file-viewer-modal, .context-view-modal, .guake-context-confirm-overlay, .guake-context-confirm-modal");return!!wt||!!ut||$t},pt=lt=>{if(!on.current){Ot.current=!1;return}Ot.current=!tt(lt.target)},ct=lt=>{Ot.current&&(tt(lt.target)||H.setTerminalOpen(!1),Ot.current=!1)};return document.addEventListener("mousedown",pt,!0),document.addEventListener("mouseup",ct,!0),()=>{document.removeEventListener("mousedown",pt,!0),document.removeEventListener("mouseup",ct,!0)}},[]),x.useEffect(()=>{const Ye=()=>{document.hidden&&$.cleanup()};return document.addEventListener("visibilitychange",Ye),()=>document.removeEventListener("visibilitychange",Ye)},[$]);const Dt=typeof window<"u"&&window.innerWidth<=768;return S?j?r.jsxs("div",{ref:D,className:`guake-terminal ${fe?"open":"collapsed"} ${Q&&fe?"with-debug-panel":""} ${ae&&fe?"with-overview-panel":""}`,style:{"--terminal-height":`${N}%`},children:[!p&&Q&&fe&&j&&r.jsx(h9,{agentId:j,onClose:()=>J(!1)}),!p&&ae&&fe&&j&&r.jsx(g9,{activeAgentId:j,onClose:()=>le(!1),onSelectAgent:Ye=>{H.selectAgent(Ye)}}),r.jsxs("div",{className:"guake-content",children:[r.jsx(_$,{selectedAgent:S,selectedAgentId:j,sortedAgents:ue.sortedAgents,swipeOffset:ue.swipeOffset,viewMode:F,setViewMode:B,searchMode:ye.searchMode,toggleSearch:ye.toggleSearch,closeSearch:ye.closeSearch,debugPanelOpen:Q,setDebugPanelOpen:J,debuggerEnabled:Y,setDebuggerEnabled:se,overviewPanelOpen:ae,setOverviewPanelOpen:le,agentInfoOpen:z,onToggleAgentInfo:()=>V(!z),outputsLength:Te.length+Oe.length,setContextConfirm:L,headerRef:ue.headerRef,onSaveSnapshot:p?void 0:s,isSnapshotView:p}),ye.searchMode&&r.jsx(D$,{searchInputRef:ye.searchInputRef,searchQuery:ye.searchQuery,setSearchQuery:ye.setSearchQuery,handleSearch:ye.handleSearch,closeSearch:ye.closeSearch,searchLoading:ye.searchLoading,searchResultsCount:ye.searchResults.length}),r.jsxs("div",{className:`guake-swipe-container ${ue.swipeAnimationClass}`,style:ue.swipeOffset!==0?{transform:`translateX(${ue.swipeOffset*40}%)`}:void 0,children:[ue.sortedAgents.length>1&&ue.swipeOffset!==0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`swipe-indicator left ${ue.swipeOffset>.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-icon",children:"←"}),r.jsx("span",{className:"indicator-name",children:(Ne=ue.prevAgent)==null?void 0:Ne.name})]}),r.jsxs("div",{className:`swipe-indicator right ${ue.swipeOffset<-.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-name",children:(Xe=ue.nextAgent)==null?void 0:Xe.name}),r.jsx("span",{className:"indicator-icon",children:"→"})]})]}),ue.sortedAgents.length>1&&ue.sortedAgents.length<=8&&ue.swipeOffset!==0&&r.jsx("div",{className:`swipe-dots ${Math.abs(ue.swipeOffset)>.1?"visible":""}`,children:ue.sortedAgents.map((Ye,tt)=>r.jsx("div",{className:`swipe-dot ${tt===ue.currentAgentIndex?"active":""}`},Ye.id))}),r.jsx("div",{className:"guake-output",ref:_,onScroll:Re,children:ye.searchMode&&ye.searchResults.length>0?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"guake-search-header",children:e("terminal:header.searchResultsTitle")}),ye.searchResults.map((Ye,tt)=>r.jsx(hf,{message:Ye,agentId:j,highlight:ye.searchQuery,onImageClick:Je,onFileClick:St,onBashClick:et,onViewMarkdown:Nt},`s-${tt}`))]}):r.jsxs("div",{className:`guake-history-content ${we?"fade-in":""}`,children:[xe.loadingHistory&&xe.history.length===0&&M.length===0&&r.jsxs("div",{className:"guake-empty loading",children:[e("terminal:empty.loadingConversation"),r.jsxs("span",{className:"loading-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})]}),!xe.loadingHistory&&xe.history.length===0&&R.length===0&&S.status!=="working"&&r.jsx("div",{className:"guake-empty",children:e("terminal:empty.noOutput")}),xe.hasMore&&!ye.searchMode&&r.jsx("div",{className:"guake-load-more",children:xe.loadingMore?r.jsx("span",{children:e("terminal:empty.loadingOlder")}):r.jsx("button",{onClick:xe.loadMoreHistory,children:e("terminal:empty.loadMore",{count:xe.totalCount-xe.history.length})})}),r.jsx(d9,{historyMessages:Te,liveOutputs:Oe,agentId:j,execTasks:ie,viewMode:F,selectedMessageIndex:rt.selectedIndex,isMessageSelected:rt.isSelected,onImageClick:Je,onFileClick:St,onBashClick:et,onViewMarkdown:Nt,scrollContainerRef:_,onScrollTopReached:xe.loadMoreHistory,isLoadingMore:xe.loadingMore,hasMore:xe.hasMore,shouldAutoScroll:Rt,onUserScroll:oe,pinToBottom:re,onPinCancel:()=>ne(!1),isLoadingHistory:xe.fetchingHistory}),Qe&&me.size>0&&r.jsxs("div",{className:"agent-progress-container",children:[r.jsxs("div",{className:"agent-progress-container-header",children:[r.jsx("span",{className:"progress-crown",children:"👑"}),r.jsx("span",{children:e("terminal:empty.subordinateProgress")}),r.jsx("span",{className:"progress-count",children:e("terminal:empty.activeCount",{count:me.size})})]}),Array.from(me.values()).map(Ye=>r.jsx(y9,{progress:Ye,defaultExpanded:Ye.status==="working",onAgentClick:tt=>H.selectAgent(tt)},Ye.agentId))]})]})})]}),r.jsx(B$,{selectedAgent:S,selectedAgentId:j,isOpen:fe,command:Pe.command,setCommand:Pe.setCommand,forceTextarea:Pe.forceTextarea,setForceTextarea:Pe.setForceTextarea,useTextarea:Pe.useTextarea,attachedFiles:Pe.attachedFiles,setAttachedFiles:Pe.setAttachedFiles,removeAttachedFile:Pe.removeAttachedFile,uploadFile:Pe.uploadFile,pastedTexts:Pe.pastedTexts,expandPastedTexts:Pe.expandPastedTexts,incrementPastedCount:Pe.incrementPastedCount,setPastedTexts:Pe.setPastedTexts,resetPastedCount:Pe.resetPastedCount,handleInputFocus:$.handleInputFocus,handleInputBlur:$.handleInputBlur,pendingPermissions:Be,showCompletion:pe,onImageClick:Je,inputRef:P,textareaRef:O,isSnapshotView:p,onClearHistory:xe.clearHistory}),r.jsxs("div",{className:"guake-agent-status-bar",children:[!p&&(S==null?void 0:S.isDetached)&&r.jsx(Mp,{content:r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"tide-tooltip__title",children:["🔄 ",e("terminal:empty.reattachingSessionTitle")]}),r.jsxs("div",{className:"tide-tooltip__text",children:[e("terminal:empty.reattachingSessionDesc"),r.jsx("br",{}),r.jsx("br",{}),r.jsxs("strong",{children:[e("common:labels.status"),":"]})," ",e("terminal:empty.reattachingSessionStatus")]})]}),position:"top",className:"tide-tooltip--detached",children:r.jsxs("span",{className:"guake-detached-badge",title:e("terminal:empty.reattachingBadge"),children:[r.jsx("span",{className:"guake-detached-spinner",children:"🔄"})," ",e("terminal:empty.reattaching")]})}),(S==null?void 0:S.cwd)&&r.jsxs("span",{className:"guake-agent-cwd",children:["📁 ",S.cwd.split("/").filter(Boolean).slice(-2).join("/")||S.cwd]}),!p&&S&&(()=>{const Ye=S.contextStats,tt=!!Ye,pt=Ye?Ye.totalTokens:S.contextUsed||0,ct=Ye?Ye.contextWindow:S.contextLimit||2e5,lt=Ye?Ye.usedPercent:Math.round(pt/ct*100),wt=Math.round(100-lt),ut=lt>=80?"#ff4a4a":lt>=60?"#ff9e4a":lt>=40?"#ffd700":"#4aff9e",$t=(pt/1e3).toFixed(1),un=(ct/1e3).toFixed(1);return r.jsxs("span",{className:"guake-agent-context",onClick:()=>H.setContextModalAgentId(j),title:e(tt?"terminal:context.clickToViewStats":"terminal:context.clickToFetchStats"),children:[r.jsx("span",{className:"context-icon",children:"📊"}),r.jsxs("span",{className:"context-label",children:[e("terminal:agentInfo.context"),":"]}),r.jsx("span",{className:"context-bar-mini",children:r.jsx("span",{className:"context-bar-mini-fill",style:{width:`${Math.min(100,lt)}%`,backgroundColor:ut}})}),r.jsxs("span",{className:"context-tokens",style:{color:ut},children:[$t,"k/",un,"k"]}),r.jsxs("span",{className:"context-free",children:["(",e("terminal:context.percentFree",{percent:wt}),")"]}),!tt&&r.jsx("span",{className:"context-warning",title:e("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),r.jsx(O9,{})]})]}),fe&&r.jsx("div",{className:"guake-resize-handle",onMouseDown:E,title:e("common:rightPanel.dragToResize")}),r.jsxs("div",{className:"guake-handle",onClick:()=>{fe&&H.toggleTerminal()},onDoubleClick:()=>{fe||H.toggleTerminal()},style:{top:fe?`${N}%`:"0"},children:[r.jsx("span",{className:"guake-handle-icon",children:fe?"▲":"▼"}),r.jsx("span",{className:"guake-handle-text",children:S.name})]}),I&&r.jsx(kT,{url:I.url,name:I.name,onClose:()=>U(null)}),q&&r.jsx(ST,{state:q,onClose:()=>K(null)}),X&&r.jsx($$,{action:X,selectedAgentId:j,subordinateCount:((ht=S==null?void 0:S.subordinateIds)==null?void 0:ht.length)||0,onClose:()=>L(null),onClearHistory:xe.clearHistory}),r.jsx(H$,{}),r.jsx(U$,{}),r.jsx(G$,{agent:S,isOpen:z,onClose:()=>V(!1)}),!p&&r.jsx(jT,{agent:S,content:ee,onClose:()=>Z(null)})]}):null:Dt&&l==="terminal"&&n.size===0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${N}%`},children:r.jsx("div",{className:"guake-content",children:r.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:r.jsxs("div",{style:{textAlign:"center"},children:[r.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"👆"}),r.jsx("div",{style:{fontSize:"16px"},children:e("terminal:empty.tapAgent")}),r.jsx("div",{style:{fontSize:"14px",marginTop:"8px",opacity:.7},children:e("terminal:empty.switchTo3D")})]})})})}):Dt&&l==="terminal"&&n.size>0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${N}%`},children:r.jsx("div",{className:"guake-content",children:r.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:r.jsxs("div",{className:"guake-empty loading",children:[e("terminal:empty.loadingTerminal"),r.jsxs("span",{className:"loading-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})]})})})}):null}function $9(s){return s.trim().replace(/^v/i,"")}function XC(s){const t=$9(s).match(/^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?/);if(!t)return null;const n=t[1].split(".").map(i=>Number.parseInt(i,10));if(n.some(Number.isNaN))return null;const a=t[2]?t[2].split("."):[];return{core:n,prerelease:a}}function H9(s,e){if(s.length===0&&e.length===0)return 0;if(s.length===0)return 1;if(e.length===0)return-1;const t=Math.max(s.length,e.length);for(let n=0;n<t;n+=1){const a=s[n],i=e[n];if(a===void 0)return-1;if(i===void 0)return 1;const o=/^\d+$/.test(a)?Number.parseInt(a,10):null,l=/^\d+$/.test(i)?Number.parseInt(i,10):null;if(o!==null&&l!==null){if(o>l)return 1;if(o<l)return-1;continue}if(o!==null)return-1;if(l!==null)return 1;const c=a.localeCompare(i);if(c!==0)return c>0?1:-1}return 0}function U9(s,e){const t=XC(s),n=XC(e);if(!t||!n)return null;const a=Math.max(t.core.length,n.core.length);for(let i=0;i<a;i+=1){const o=t.core[i]??0,l=n.core[i]??0;if(o>l)return 1;if(o<l)return-1}return H9(t.prerelease,n.prerelease)}function G9(s,e){const t=U9(s,e);return t===null?"unknown":t<0?"behind":t>0?"ahead":"equal"}async function W9(s,e={}){const{timeoutMs:t=5e3,fetchImpl:n=fetch}=e;try{const a=new AbortController,i=setTimeout(()=>a.abort(),t),o=Date.now(),l=await n(`https://registry.npmjs.org/${encodeURIComponent(s)}/latest?t=${o}`,{signal:a.signal,headers:{Accept:"application/json"}});if(clearTimeout(i),!l.ok)return null;const c=await l.json();return typeof c.version=="string"?c.version:null}catch{return null}}async function q9(s,e,t={}){const n=await W9(s,t);return n?{currentVersion:e,latestVersion:n,relation:G9(e,n)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const Y9="tide-commander",yb="0.65.7";function V9(){const[s,e]=x.useState({currentVersion:yb,latestVersion:null,relation:"unknown",isChecking:!1}),t=x.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const n=await q9(Y9,yb);e({currentVersion:yb,latestVersion:n.latestVersion,relation:n.relation,isChecking:!1})},[]);return x.useEffect(()=>{t()},[t]),{...s,refresh:t}}function K9({onFocusAgent:s,onSpawnClick:e,onSpawnBossClick:t,onNewBuildingClick:n,onNewAreaClick:a}){const{t:i}=He(["common"]),o=An(),l=tl(),c=ei(),[d,f]=x.useState(!1),p=x.useRef(null),g=x.useRef(null),b=x.useRef(null),y=x.useRef(new Map);x.useEffect(()=>{{f(!1);return}},[l.experimental2DView]),x.useEffect(()=>{const ae=g.current;if(!ae)return;const le=pe=>{ae.scrollWidth<=ae.clientWidth||(pe.preventDefault(),ae.scrollLeft+=pe.deltaY)};return ae.addEventListener("wheel",le,{passive:!1}),()=>ae.removeEventListener("wheel",le)},[]);const[w,k]=x.useState(null),[S,j]=x.useState(new Map),[C,N]=x.useState(null),[D,E]=x.useState(null),$=x.useRef(0),M=x.useMemo(()=>Array.from(o.agents.values()).filter(ae=>!H.isAgentInArchivedArea(ae.id)).sort((ae,le)=>(ae.createdAt||0)-(le.createdAt||0)),[o.agents,o.areas]),{orderedAgents:R,moveAgent:_}=HN(M),P=R,O=x.useMemo(()=>{const ae=new Map;for(const le of P)ae.set(le.id,H.getAreaForAgent(le.id));return ae},[P,o.areas]),F=x.useMemo(()=>{const ae=new Map;for(const pe of P){const be=O.get(pe.id)||null,ce=(be==null?void 0:be.id)||null;ae.has(ce)||ae.set(ce,{area:be,agents:[]}),ae.get(ce).agents.push(pe)}const le=Array.from(ae.values());return le.sort((pe,be)=>{var ce,he;return!pe.area&&be.area?1:pe.area&&!be.area?-1:!pe.area&&!be.area?0:(((ce=pe.area)==null?void 0:ce.name)||"").localeCompare(((he=be.area)==null?void 0:he.name)||"")}),le},[P,O]);x.useEffect(()=>{const ae=new Map(S);let le=!1;for(const pe of P){const be=S.get(pe.id);pe.currentTool?(!be||be.tool!==pe.currentTool)&&(ae.set(pe.id,{tool:pe.currentTool,key:Date.now()}),le=!0):be&&setTimeout(()=>{j(ce=>{const he=new Map(ce);return he.delete(pe.id),he})},1500)}le&&j(ae)},[P.map(ae=>ae.currentTool).join(",")]),x.useEffect(()=>{const ae=o.lastSelectedAgentId;if(!ae)return;const le=y.current.get(ae),pe=g.current;le&&pe&&requestAnimationFrame(()=>{const be=le.getBoundingClientRect(),ce=pe.getBoundingClientRect(),we=be.left-ce.left+pe.scrollLeft+be.width/2,Me=pe.clientWidth;pe.scrollTo({left:we-Me/2,behavior:"smooth"})})},[o.lastSelectedAgentId]);const B=(ae,le)=>{H.setLastSelectionViaDirectClick(!0),le.shiftKey?H.addToSelection(ae.id):H.selectAgent(ae.id),(window.innerWidth<=768||o.terminalOpen)&&H.setTerminalOpen(!0)},I=ae=>{s==null||s(ae.id),H.setTerminalOpen(!0)},U=x.useCallback((ae,le)=>{N(le),ae.dataTransfer.effectAllowed="move",ae.dataTransfer.setData("text/plain",le.id),requestAnimationFrame(()=>{ae.target.classList.add("dragging")})},[]),q=x.useCallback(ae=>{N(null),E(null),$.current=0,ae.target.classList.remove("dragging")},[]),K=x.useCallback((ae,le)=>{if(ae.preventDefault(),C){const pe=O.get(C.id),be=P[le],ce=be?O.get(be.id):null,he=(pe==null?void 0:pe.id)??null,we=(ce==null?void 0:ce.id)??null;ae.dataTransfer.dropEffect=he===we?"move":"none"}else ae.dataTransfer.dropEffect="move"},[C,P,O]),X=x.useCallback((ae,le)=>{if(ae.preventDefault(),$.current++,C){const pe=O.get(C.id),be=P[le],ce=be?O.get(be.id):null,he=(pe==null?void 0:pe.id)??null,we=(ce==null?void 0:ce.id)??null;E(he===we?le:null)}else E(le)},[C,P,O]),L=x.useCallback(ae=>{$.current--,$.current===0&&E(null)},[]),ee=x.useCallback((ae,le)=>{if(ae.preventDefault(),!C)return;const pe=P.findIndex(be=>be.id===C.id);if(pe!==-1&&pe!==le){const be=O.get(C.id),ce=P[le],he=ce?O.get(ce.id):null,we=(be==null?void 0:be.id)??null,Me=(he==null?void 0:he.id)??null;we===Me&&_(pe,le)}N(null),E(null),$.current=0},[C,P,_,O]),Z=ae=>{const le=`common:status.${ae}`;return i(le,{defaultValue:i("common:status.unknown")})},{currentVersion:z,latestVersion:V,relation:Q,isChecking:J}=V9(),Y=z;let se=0;return r.jsxs("div",{className:"agent-bar",ref:p,children:[r.jsxs("div",{className:"agent-bar-scroll",ref:g,children:[r.jsxs("div",{className:"agent-bar-version",title:V?`Tide Commander v${Y} (npm: v${V})`:`Tide Commander v${Y}`,children:[r.jsxs("span",{children:["v",Y]}),Q==="behind"&&V?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${V}`,children:["npm v",V]}):Q==="ahead"&&V?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${V}`,children:["npm v",V]}):null,Q==="behind"?r.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status agent-bar-version-status-behind",title:i("common:agentBar.behindNpmTooltip",{defaultValue:"Current version is behind npm latest"}),children:i("common:agentBar.behindNpm",{defaultValue:"(behind npm)"})}):Q==="ahead"?r.jsx("span",{className:"agent-bar-version-status agent-bar-version-status-ahead",title:i("common:agentBar.aheadNpmTooltip",{defaultValue:"Current version is newer than npm latest"}),children:i("common:agentBar.aheadNpm",{defaultValue:"(ahead of npm)"})}):Q==="equal"?r.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status",children:i("common:agentBar.updated")}):J?r.jsx("span",{className:"agent-bar-version-status",children:i("common:agentBar.checkingNpm",{defaultValue:"(checking npm)"})}):r.jsx("span",{className:"agent-bar-version-status",children:i("common:agentBar.unknownNpm",{defaultValue:"(npm unknown)"})}),d&&r.jsx("button",{className:"agent-bar-hmr-refresh",onClick:zN,title:"Refresh 3D Scene (HMR changes pending)",children:"↻"})]}),r.jsxs("div",{className:"agent-bar-list",ref:b,children:[r.jsxs("button",{className:"agent-bar-spawn-btn",onClick:e,title:i("common:agentBar.spawnNewAgent"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"+"}),r.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newAgent")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-boss-btn",onClick:t,title:i("common:agentBar.spawnBoss"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"👑"}),r.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newBoss")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-building-btn",onClick:n,title:i("common:agentBar.addNewBuilding"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"🏢"}),r.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newBuilding")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-area-btn",onClick:a,title:i("common:agentBar.drawNewArea"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"▢"}),r.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newArea")})]}),F.map(ae=>{var be,ce,he,we,Me;const le=ae.agents,pe=!ae.area;return r.jsxs("div",{className:`agent-bar-group ${pe?"unassigned":""}`,style:{borderColor:((be=ae.area)==null?void 0:be.color)||void 0,background:ae.area?`${ae.area.color}15`:void 0},children:[r.jsx("div",{className:"agent-bar-area-label",children:r.jsx("span",{className:"agent-bar-area-name",style:{color:((ce=ae.area)==null?void 0:ce.color)||"#888"},children:((he=ae.area)==null?void 0:he.name)||i("common:agentBar.unassigned")})}),((we=ae.area)==null?void 0:we.directories)&&ae.area.directories.length>0&&r.jsx("div",{className:"agent-bar-folders",children:ae.area.directories.map((re,ne)=>r.jsxs("div",{className:"agent-bar-folder-item",onClick:fe=>{fe.stopPropagation(),H.openFileExplorer(re)},children:[r.jsx("span",{className:"agent-bar-folder-icon",children:"📁"}),r.jsxs("div",{className:"agent-bar-folder-tooltip",children:[r.jsx("div",{className:"agent-bar-folder-tooltip-path",children:re}),r.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:i("common:agentBar.clickToOpen")})]})]},ne))}),le.map(re=>{const ne=se++,fe=P.findIndex(me=>me.id===re.id),xe=o.selectedAgentIds.has(re.id),ye=Zr(re.class,c),ue=o.lastPrompts.get(re.id),Pe=S.get(re.id);Pe&&(hs[Pe.tool]||hs.default),ue!=null&&ue.text&&(ue.text.length>30?ue.text.substring(0,30)+"":ue.text);const Be=(C==null?void 0:C.id)===re.id,Qe=D===fe;return r.jsxs("div",{ref:me=>{me?y.current.set(re.id,me):y.current.delete(re.id)},className:`agent-bar-item ${xe?"selected":""} ${re.status} ${re.isBoss?"is-boss":""} ${Be?"dragging":""} ${Qe?"drag-over":""}`,draggable:!0,onDragStart:me=>U(me,re),onDragEnd:q,onDragOver:me=>K(me,fe),onDragEnter:me=>X(me,fe),onDragLeave:L,onDrop:me=>ee(me,fe),onClick:me=>B(re,me),onDoubleClick:()=>I(re),onMouseEnter:()=>k(re),onMouseLeave:()=>k(null),title:`${re.name} (${ne+1}) - Drag to reorder within group`,children:[r.jsxs("div",{className:"agent-bar-avatar",children:[r.jsx("span",{className:"agent-bar-icon",children:ye.icon}),r.jsx("span",{className:"agent-bar-status",style:{backgroundColor:Xb(re.status)}}),re.status==="idle"&&re.lastActivity>0&&r.jsx("span",{className:"agent-bar-idle-clock",style:{color:Kp(re.lastActivity)},title:Xp(re.lastActivity),children:"⏱"})]}),r.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${ne+1}`,children:["^",ne+1]})]},re.id)})]},((Me=ae.area)==null?void 0:Me.id)||"unassigned")})]})]}),Array.from(S.entries()).map(([ae,le])=>{const pe=y.current.get(ae);if(!pe)return null;const be=pe.getBoundingClientRect(),ce=hs[le.tool]||hs.default;return r.jsxs("div",{className:"agent-bar-tool-bubble",title:le.tool,style:{position:"fixed",left:be.left+be.width/2,bottom:window.innerHeight-be.top+8},children:[r.jsx("span",{className:"agent-bar-tool-icon",children:ce}),r.jsx("span",{className:"agent-bar-tool-name",children:le.tool})]},`tool-${ae}-${le.key}`)}),w&&(()=>{const ae=H.getAreaForAgent(w.id),le=o.lastPrompts.get(w.id),pe=Zr(w.class,c),be=H.getAgentSupervisorHistory(w.id),ce=be.length>0?be[be.length-1]:void 0,he=Date.now()-(w.createdAt||Date.now()),we=Math.floor(he/6e4),Me=Math.floor(we/60),re=Me>0?`${Me}h ${we%60}m`:`${we}m`,ne=Pe=>Pe>=1e6?`${(Pe/1e6).toFixed(1)}M`:Pe>=1e3?`${(Pe/1e3).toFixed(1)}K`:Pe.toString(),fe=w.contextLimit>0?Math.round(w.contextUsed/w.contextLimit*100):0,xe=Pe=>{switch(Pe){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},ye=y.current.get(w.id),ue={};if(ye){const Pe=ye.getBoundingClientRect();ue.position="fixed",ue.left=Pe.left+Pe.width/2,ue.bottom=window.innerHeight-Pe.top+12}return r.jsxs("div",{className:"agent-bar-tooltip",style:ue,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:pe.icon}),r.jsxs("span",{className:"agent-bar-tooltip-name",children:[r.jsx("img",{src:w.provider==="codex"?"/assets/codex.png":"/assets/claude.png",alt:w.provider,className:"agent-bar-provider-icon",title:w.provider==="codex"?"Codex Agent":"Claude Agent"}),w.name]}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:Xb(w.status)},children:Z(w.status)})]}),r.jsxs("div",{className:"agent-bar-tooltip-info",children:[r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.class"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[w.class," — ",pe.description]})]}),ae&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.area"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:ae.color},children:ae.name})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.directory"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:w.cwd})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.uptime"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",children:re})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.tokens"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[ne(w.tokensUsed)," ",i("common:agentPopup.used")]})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.context"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:fe>80?"#ff4a4a":fe>60?"#ff9e4a":void 0},children:[ne(w.contextUsed)," / ",ne(w.contextLimit)," (",fe,"%)"]})]}),w.currentTool&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.tool"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[hs[w.currentTool]||hs.default," ",w.currentTool]})]}),w.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.task"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[w.currentTask.substring(0,150),w.currentTask.length>150?"...":""]})]}),w.lastAssignedTask&&!w.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.assignedTask"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[w.lastAssignedTask.substring(0,200),w.lastAssignedTask.length>200?"...":""]})]}),le&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.lastQuery"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[le.text.substring(0,300),le.text.length>300?"...":""]})]}),ce&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"agent-bar-tooltip-divider"}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.supervisor"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",style:{color:xe(ce.analysis.progress)},children:ce.analysis.progress.replace("_"," ")})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.status"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:ce.analysis.statusDescription})]}),ce.analysis.recentWorkSummary&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.summary"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[ce.analysis.recentWorkSummary.substring(0,300),ce.analysis.recentWorkSummary.length>300?"...":""]})]}),ce.analysis.concerns&&ce.analysis.concerns.length>0&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.concerns"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:ce.analysis.concerns.join("; ")})]})]})]})]})})()]})}function X9({activeTool:s,onExit:e}){const{t}=He(["notifications","terminal"]);if(!s||s==="select")return null;const n=t(s==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool"),a=s==="rectangle"?"▭":"○";return r.jsxs("div",{className:"drawing-mode-indicator",children:[r.jsxs("div",{className:"drawing-mode-content",children:[r.jsx("span",{className:"drawing-mode-icon",children:a}),r.jsxs("div",{className:"drawing-mode-text",children:[r.jsxs("span",{className:"drawing-mode-title",children:[t("terminal:drawingMode.drawingArea"),": ",n]}),r.jsxs("span",{className:"drawing-mode-hint",children:[t("terminal:drawingMode.clickAndDrag")," • ",t("terminal:drawingMode.pressEscape")]})]})]}),r.jsx("button",{className:"drawing-mode-exit",onClick:e,title:t("terminal:drawingMode.exitDrawingMode"),children:"✕"})]})}const Z9={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},xb=s=>s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString(),Q9=s=>{switch(s){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},J9=x.memo(function({agent:e,screenPos:t,onClose:n}){const{t:a}=He(["common"]),i=ei(),o=H.getAreaForAgent(e.id),l=H.getState().lastPrompts.get(e.id),c=Zr(e.class,i),d=H.getAgentSupervisorHistory(e.id),f=d.length>0?d[d.length-1]:void 0,p=Date.now()-(e.createdAt||Date.now()),g=Math.floor(p/6e4),b=Math.floor(g/60),y=b>0?`${b}h ${g%60}m`:`${g}m`,w=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,k=x.useMemo(()=>{let C=t.x-150,N=t.y-320-10;return typeof window<"u"&&(C<10?C=10:C+300>window.innerWidth-10&&(C=window.innerWidth-300-10),N<10&&(N=t.y+10)),{position:"fixed",left:C,top:N,zIndex:1e4,maxWidth:300,maxHeight:320,fontSize:"0.85em"}},[t.x,t.y]);return r.jsxs("div",{className:"agent-hover-popup",style:k,onMouseLeave:n,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:c.icon}),r.jsx("span",{className:"agent-bar-tooltip-name",children:e.name}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:Xb(e.status)},children:a(Z9[e.status]||"common:status.unknown")})]}),r.jsxs("div",{className:"agent-bar-tooltip-info",children:[r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.class"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.class," — ",c.description]})]}),o&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.area"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:o.color},children:o.name})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.directory"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:e.cwd})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.uptime"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",children:y})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.tokens"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[xb(e.tokensUsed)," ",a("common:agentPopup.used")]})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.context"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:w>80?"#ff4a4a":w>60?"#ff9e4a":void 0},children:[xb(e.contextUsed)," / ",xb(e.contextLimit)," (",w,"%)"]})]}),e.currentTool&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.tool"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[hs[e.currentTool]||hs.default," ",e.currentTool]})]}),e.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.task"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.currentTask.substring(0,150),e.currentTask.length>150?"...":""]})]}),e.lastAssignedTask&&!e.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.assignedTask"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[e.lastAssignedTask.substring(0,200),e.lastAssignedTask.length>200?"...":""]})]}),l&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.lastQuery"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[l.text.substring(0,300),l.text.length>300?"...":""]})]}),f&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"agent-bar-tooltip-divider"}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.supervisor"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",style:{color:Q9(f.analysis.progress)},children:f.analysis.progress.replace("_"," ")})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.status"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:f.analysis.statusDescription})]}),f.analysis.recentWorkSummary&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.summary"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[f.analysis.recentWorkSummary.substring(0,300),f.analysis.recentWorkSummary.length>300?"...":""]})]}),f.analysis.concerns&&f.analysis.concerns.length>0&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.concerns"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:f.analysis.concerns.join("; ")})]})]})]})]})});function ZC(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],n=Math.floor(Math.log(s)/Math.log(e));return parseFloat((s/Math.pow(e,n)).toFixed(1))+" "+t[n]}function QC(s){const t=Date.now()-s,n=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return n>0?`${n}h ${a}m`:`${a}m`}const JC={30:"#1a1a1a",31:"#e74c3c",32:"#2ecc71",33:"#f39c12",34:"#3498db",35:"#9b59b6",36:"#00bcd4",37:"#ecf0f1",90:"#7f8c8d",91:"#ff6b6b",92:"#4ade80",93:"#fbbf24",94:"#60a5fa",95:"#c084fc",96:"#22d3ee",97:"#ffffff"};function eH(s){const e=[],t=/\x1B\[([0-9;]*)m/g;let n=0,a=null,i;for(;(i=t.exec(s))!==null;){if(i.index>n){const l=s.slice(n,i.index);a?e.push(r.jsx("span",{style:{color:a},children:l},e.length)):e.push(l)}const o=i[1].split(";").map(Number);for(const l of o)l===0||l===39?a=null:JC[l]&&(a=JC[l]);n=t.lastIndex}if(n<s.length){const o=s.slice(n);a?e.push(r.jsx("span",{style:{color:a},children:o},e.length)):e.push(o)}return e.length>0?e:[s]}const tH=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){var U,q,K,X,L,ee,Z,z,V,Q,J,Y,se,ae,le,pe,be,ce,he,we;const{t:l}=He(["terminal","common"]),[c,d]=x.useState(!1),[f,p]=x.useState(null),[g,b]=x.useState(!1),y=x.useRef(null),w=x.useRef(f);w.current=f;const{buildingLogs:k}=An(),S=H.getBuildingLogs(e.id),j=(U=e.pm2)==null?void 0:U.enabled,C=(q=e.docker)==null?void 0:q.enabled,N=x.useRef(null),D=x.useRef(null),E=x.useCallback(Me=>{Me.preventDefault();const re=w.current?w.current.x:0,ne=w.current?w.current.y:0;y.current={mouseX:Me.clientX,mouseY:Me.clientY,popupX:re,popupY:ne},b(!0),N.current=fe=>{if(!y.current)return;const xe=fe.clientX-y.current.mouseX,ye=fe.clientY-y.current.mouseY;p({x:y.current.popupX+xe,y:y.current.popupY+ye})},D.current=()=>{b(!1),y.current=null,N.current&&document.removeEventListener("mousemove",N.current),D.current&&document.removeEventListener("mouseup",D.current)},document.addEventListener("mousemove",N.current),document.addEventListener("mouseup",D.current)},[]);x.useEffect(()=>()=>{N.current&&document.removeEventListener("mousemove",N.current),D.current&&document.removeEventListener("mouseup",D.current)},[]);const $=Me=>{if(Me==="logs"){if((j||C)&&i){i();return}H.sendBuildingCommand(e.id,Me),d(!0)}else H.sendBuildingCommand(e.id,Me)},M=(Me,re)=>{if(Me){const ne=`http://localhost:${Me}`;re&&o?o(ne):window.open(ne,"_blank")}},R=((K=e.pm2Status)==null?void 0:K.ports)||[],_=((L=(X=e.dockerStatus)==null?void 0:X.ports)==null?void 0:L.map(Me=>Me.host))||[],P=j?R:C?_:[],O=j?!!((ee=e.pm2)!=null&&ee.script):C?!!((Z=e.docker)!=null&&Z.image)||((z=e.docker)==null?void 0:z.mode)==="compose"||((V=e.docker)==null?void 0:V.mode)==="existing":!!((Q=e.commands)!=null&&Q.start),F=j?!!((J=e.pm2)!=null&&J.script):C?!0:!!((Y=e.commands)!=null&&Y.stop),B=j?!!((se=e.pm2)!=null&&se.script):C?!0:!!((ae=e.commands)!=null&&ae.restart),I=x.useMemo(()=>{const re=c?400:250;let ne=t.x+20,fe=t.y-80;return typeof window<"u"&&!f&&(t.x+20+280>window.innerWidth&&(ne=t.x-280-20),t.y-80<0?fe=10:t.y-80+re>window.innerHeight&&(fe=window.innerHeight-re-10)),{position:"fixed",left:ne+((f==null?void 0:f.x)||0),top:fe+((f==null?void 0:f.y)||0),zIndex:1e3,cursor:g?"grabbing":void 0}},[t.x,t.y,c,f,g]);return r.jsxs("div",{className:"building-action-popup",style:I,onClick:Me=>Me.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header ${g?"dragging":""}`,onMouseDown:E,children:[r.jsx("span",{className:"building-popup-name",children:e.name}),P.length>0&&r.jsx("span",{className:"building-popup-ports",children:P.map(Me=>r.jsxs("a",{href:`http://localhost:${Me}`,className:"building-popup-port-link",onClick:re=>{re.preventDefault(),re.stopPropagation(),M(Me,re.altKey)},onMouseDown:re=>re.stopPropagation(),title:`Open http://localhost:${Me} (Alt+Click for modal)`,children:[":",Me]},Me))}),r.jsx("span",{className:"building-popup-status",style:{backgroundColor:Xr[e.status]},children:e.status}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),j&&e.pm2Status&&r.jsxs("div",{className:"building-popup-metrics",children:[r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"PID"}),r.jsx("span",{className:"value",children:e.pm2Status.pid||"-"})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"CPU"}),r.jsxs("span",{className:"value",children:[((le=e.pm2Status.cpu)==null?void 0:le.toFixed(1))||"0","%"]})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:ZC(e.pm2Status.memory||0)})]}),e.pm2Status.restarts!==void 0&&e.pm2Status.restarts>0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"RST"}),r.jsx("span",{className:"value",children:e.pm2Status.restarts})]}),e.pm2Status.uptime&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"UP"}),r.jsx("span",{className:"value",children:QC(e.pm2Status.uptime)})]})]}),C&&e.dockerStatus&&r.jsxs("div",{className:"building-popup-metrics",children:[r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"ID"}),r.jsx("span",{className:"value",children:e.dockerStatus.containerId||"-"})]}),e.dockerStatus.cpu!==void 0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"CPU"}),r.jsxs("span",{className:"value",children:[e.dockerStatus.cpu.toFixed(1),"%"]})]}),e.dockerStatus.memory!==void 0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:ZC(e.dockerStatus.memory)})]}),e.dockerStatus.health&&e.dockerStatus.health!=="none"&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"HEALTH"}),r.jsx("span",{className:"value",style:{color:e.dockerStatus.health==="healthy"?"#4ade80":e.dockerStatus.health==="unhealthy"?"#f87171":"#fbbf24"},children:e.dockerStatus.health==="healthy"?"✓":e.dockerStatus.health==="unhealthy"?"✗":"..."})]}),e.dockerStatus.startedAt&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"UP"}),r.jsx("span",{className:"value",children:QC(e.dockerStatus.startedAt)})]})]}),C&&((pe=e.dockerStatus)==null?void 0:pe.services)&&e.dockerStatus.services.length>0&&r.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((Me,re)=>r.jsxs("span",{className:"service-item",title:`${Me.name}: ${Me.status}`,children:[r.jsx("span",{className:"service-indicator",style:{backgroundColor:Me.status==="running"?"#4ade80":"#f87171"}}),r.jsx("span",{className:"service-name",children:Me.name})]},re))}),(e.lastError||j&&((be=e.pm2Status)==null?void 0:be.status)==="errored"||C&&((ce=e.dockerStatus)==null?void 0:ce.status)==="dead")&&r.jsxs("div",{className:"building-popup-error",children:[e.lastError||l("terminal:building.processFailedToStart"),j&&((he=e.pm2Status)==null?void 0:he.restarts)&&e.pm2Status.restarts>5&&r.jsxs("span",{className:"error-hint",children:[" - ",l("terminal:building.checkLogsOrConfig")]}),C&&((we=e.dockerStatus)==null?void 0:we.health)==="unhealthy"&&r.jsxs("span",{className:"error-hint",children:[" - ",l("terminal:building.healthCheckFailing")]})]}),r.jsxs("div",{className:"building-popup-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>$("start"),disabled:!O||e.status==="running"||e.status==="starting",title:l(O?"terminal:buildingAction.start":"terminal:buildingAction.noStartCommand"),children:[r.jsx("span",{className:"icon",children:"▶"}),l("terminal:buildingAction.start")]}),r.jsxs("button",{className:"action-btn stop",onClick:()=>$("stop"),disabled:!F||e.status==="stopped"||e.status==="stopping",title:l(F?"terminal:buildingAction.stop":"terminal:buildingAction.noStopCommand"),children:[r.jsx("span",{className:"icon",children:"■"}),l("terminal:buildingAction.stop")]}),r.jsxs("button",{className:"action-btn restart",onClick:()=>$("restart"),disabled:!B,title:l(B?"terminal:buildingAction.restart":"terminal:buildingAction.noRestartCommand"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:buildingAction.restart")]}),r.jsxs("button",{className:"action-btn logs",onClick:()=>$("logs"),title:l("terminal:buildingAction.viewLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:logs.title")]}),P.length===1&&r.jsxs("button",{className:"action-btn open-url",onClick:Me=>M(P[0],Me.altKey),title:`Open http://localhost:${P[0]} (Alt+Click for modal)`,children:[r.jsx("span",{className:"icon",children:"🔗"}),l("terminal:buildingAction.openInBrowser")]}),P.length>1&&r.jsxs("div",{className:"action-btn-group",children:[r.jsxs("span",{className:"action-btn-label",children:[l("terminal:buildingAction.openInBrowser"),":"]}),P.map(Me=>r.jsxs("button",{className:"action-btn open-url port-btn",onClick:re=>M(Me,re.altKey),title:`Open http://localhost:${Me} (Alt+Click for modal)`,children:[":",Me]},Me))]})]}),c&&S.length>0&&r.jsxs("div",{className:"building-popup-logs",children:[r.jsxs("div",{className:"logs-header",children:[r.jsx("span",{children:l("terminal:logs.title")}),r.jsx("button",{onClick:()=>H.clearBuildingLogs(e.id),children:l("terminal:logs.clear")})]}),r.jsx("div",{className:"logs-content",children:S.slice(-50).map((Me,re)=>r.jsx("pre",{children:eH(Me)},re))})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:buildingAction.fullSettings")})]})});function nH(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],n=Math.floor(Math.log(s)/Math.log(e));return parseFloat((s/Math.pow(e,n)).toFixed(1))+" "+t[n]}function sH(s){const t=Date.now()-s,n=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return n>0?`${n}h ${a}m`:`${a}m`}const aH=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){const{t:l}=He(["terminal","common"]),[c,d]=x.useState(null),[f,p]=x.useState(!1),g=x.useRef(null),b=x.useRef(c);b.current=c;const{buildings:y}=An(),k=(e.subordinateBuildingIds||[]).map(R=>y.get(R)).filter(R=>R!==void 0),S=x.useRef(null),j=x.useRef(null),C=x.useCallback(R=>{R.preventDefault();const _=b.current?b.current.x:0,P=b.current?b.current.y:0;g.current={mouseX:R.clientX,mouseY:R.clientY,popupX:_,popupY:P},p(!0),S.current=O=>{if(!g.current)return;const F=O.clientX-g.current.mouseX,B=O.clientY-g.current.mouseY;d({x:g.current.popupX+F,y:g.current.popupY+B})},j.current=()=>{p(!1),g.current=null,S.current&&document.removeEventListener("mousemove",S.current),j.current&&document.removeEventListener("mouseup",j.current)},document.addEventListener("mousemove",S.current),document.addEventListener("mouseup",j.current)},[]);x.useEffect(()=>()=>{S.current&&document.removeEventListener("mousemove",S.current),j.current&&document.removeEventListener("mouseup",j.current)},[]);const N=R=>{H.sendBossBuildingCommand(e.id,R)},D=k.reduce((R,_)=>(R[_.status]=(R[_.status]||0)+1,R),{}),E=k.some(R=>{var _;return(_=R.pm2)==null?void 0:_.enabled}),$=(R,_)=>{const P=`http://localhost:${R}`;_&&o?o(P):window.open(P,"_blank")},M=x.useMemo(()=>{let P=t.x+20,O=t.y-80;return typeof window<"u"&&!c&&(t.x+20+340>window.innerWidth&&(P=t.x-340-20),t.y-80<0?O=10:t.y-80+350>window.innerHeight&&(O=window.innerHeight-350-10)),{position:"fixed",left:P+((c==null?void 0:c.x)||0),top:O+((c==null?void 0:c.y)||0),zIndex:1e3,cursor:f?"grabbing":void 0}},[t.x,t.y,c,f]);return r.jsxs("div",{className:"building-action-popup boss-building-popup",style:M,onClick:R=>R.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header boss-header ${f?"dragging":""}`,onMouseDown:C,children:[r.jsx("span",{className:"boss-icon",children:"👑"}),r.jsx("span",{className:"building-popup-name",children:e.name}),r.jsx("span",{className:"subordinate-count",children:l("terminal:building.unitsCount",{count:k.length})}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),r.jsxs("div",{className:"boss-status-overview",children:[Object.entries(D).map(([R,_])=>r.jsxs("span",{className:"status-badge",style:{backgroundColor:Xr[R]||"#666"},children:[_," ",R]},R)),k.length===0&&r.jsx("span",{className:"no-subordinates",children:l("terminal:building.noSubordinates")})]}),k.length>0&&r.jsx("div",{className:"subordinate-list",children:k.map(R=>{var _,P,O;return r.jsxs("div",{className:"subordinate-item",children:[r.jsx("span",{className:"sub-status-dot",style:{backgroundColor:Xr[R.status]}}),r.jsx("span",{className:"sub-name",children:R.name}),((_=R.pm2Status)==null?void 0:_.ports)&&R.pm2Status.ports.length>0&&r.jsx("span",{className:"sub-port",children:R.pm2Status.ports.map(F=>r.jsxs("a",{href:`http://localhost:${F}`,className:"building-popup-port-link",onClick:B=>{B.preventDefault(),B.stopPropagation(),$(F,B.altKey)},title:`Open http://localhost:${F} (Alt+Click for modal)`,children:[":",F]},F))}),R.pm2Status&&r.jsxs("span",{className:"sub-metrics",children:[(P=R.pm2Status.cpu)==null?void 0:P.toFixed(0),"% | ",nH(R.pm2Status.memory||0)]}),((O=R.pm2Status)==null?void 0:O.uptime)&&r.jsx("span",{className:"sub-uptime",children:sH(R.pm2Status.uptime)})]},R.id)})}),r.jsxs("div",{className:"building-popup-actions boss-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>N("start_all"),disabled:k.length===0,title:l("terminal:building.startAllSubs"),children:[r.jsx("span",{className:"icon",children:"▶"}),l("terminal:building.startAll")]}),r.jsxs("button",{className:"action-btn stop",onClick:()=>N("stop_all"),disabled:k.length===0,title:l("terminal:building.stopAllSubs"),children:[r.jsx("span",{className:"icon",children:"■"}),l("terminal:building.stopAll")]}),r.jsxs("button",{className:"action-btn restart",onClick:()=>N("restart_all"),disabled:k.length===0,title:l("terminal:building.restartAllSubs"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:building.restartAll")]}),E&&r.jsxs("button",{className:"action-btn logs",onClick:i,title:l("terminal:building.viewUnifiedLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:building.logs")]})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:building.fullSettings")})]})}),iH=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenDatabasePanel:i}){var D;const{t:o}=He(["terminal","common"]),[l,c]=x.useState(null),[d,f]=x.useState(!1),p=x.useRef(null),g=x.useRef(l);g.current=l;const b=sf(e.id),y=((D=e.database)==null?void 0:D.connections)??[],w=x.useRef(null),k=x.useRef(null),S=x.useCallback(E=>{E.preventDefault();const $=g.current?g.current.x:0,M=g.current?g.current.y:0;p.current={mouseX:E.clientX,mouseY:E.clientY,popupX:$,popupY:M},f(!0),w.current=R=>{if(!p.current)return;const _=R.clientX-p.current.mouseX,P=R.clientY-p.current.mouseY;c({x:p.current.popupX+_,y:p.current.popupY+P})},k.current=()=>{f(!1),p.current=null,w.current&&document.removeEventListener("mousemove",w.current),k.current&&document.removeEventListener("mouseup",k.current)},document.addEventListener("mousemove",w.current),document.addEventListener("mouseup",k.current)},[]);x.useEffect(()=>()=>{w.current&&document.removeEventListener("mousemove",w.current),k.current&&document.removeEventListener("mouseup",k.current)},[]);const j=E=>{H.testDatabaseConnection(e.id,E)},C=E=>b.connectionStatus.get(E),N=x.useMemo(()=>{let M=t.x+20,R=t.y-80;return typeof window<"u"&&!l&&(t.x+20+320>window.innerWidth&&(M=t.x-320-20),t.y-80<0?R=10:t.y-80+300>window.innerHeight&&(R=window.innerHeight-300-10)),{position:"fixed",left:M+((l==null?void 0:l.x)||0),top:R+((l==null?void 0:l.y)||0),zIndex:1e3,cursor:d?"grabbing":void 0}},[t.x,t.y,l,d]);return r.jsxs("div",{className:"building-action-popup database-building-popup",style:N,onClick:E=>E.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header database-header ${d?"dragging":""}`,onMouseDown:S,children:[r.jsx("span",{className:"database-icon",children:"🗄️"}),r.jsx("span",{className:"building-popup-name",children:e.name}),r.jsx("span",{className:"connection-count",children:o("terminal:building.connCount",{count:y.length})}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),y.length>0?r.jsx("div",{className:"database-connection-list",children:y.map(E=>{const $=C(E.id);return r.jsxs("div",{className:"database-connection-item",children:[r.jsx("span",{className:"conn-engine",children:E.engine==="mysql"?"🐬":"🐘"}),r.jsx("span",{className:"conn-name",children:E.name}),r.jsxs("span",{className:"conn-host",children:[E.host,":",E.port]}),$&&r.jsx("span",{className:`conn-status ${$.connected?"connected":"disconnected"}`,children:$.connected?"●":"○"}),r.jsx("button",{className:"conn-test-btn",onClick:()=>j(E.id),title:o("terminal:building.testConnection"),children:"↻"})]},E.id)})}):r.jsxs("div",{className:"database-no-connections",children:[r.jsx("p",{children:o("terminal:building.noConnections")}),r.jsx("p",{className:"hint",children:o("terminal:building.clickSettingsToAdd")})]}),r.jsxs("div",{className:"building-popup-actions database-actions",children:[r.jsxs("button",{className:"action-btn query",onClick:i,disabled:y.length===0,title:o("terminal:building.openDbExplorer"),children:[r.jsx("span",{className:"icon",children:"⌨"}),o("terminal:building.query")]}),r.jsxs("button",{className:"action-btn test-all",onClick:()=>y.forEach(E=>j(E.id)),disabled:y.length===0,title:o("terminal:building.testAllConnections"),children:[r.jsx("span",{className:"icon",children:"↻"}),o("terminal:building.testAll")]})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:o("common:buttons.settings")})]})}),rH=({building:s,connections:e,activeConnectionId:t,activeDatabase:n,collapsed:a,onToggleCollapse:i,onConnectionChange:o,onDatabaseChange:l,onInsertTable:c,onSelectTableQuery:d})=>{const{t:f}=He(["terminal"]),p=sf(s.id),[g,b]=x.useState(new Set),[y,w]=x.useState(""),[k,S]=x.useState(!1),[j,C]=x.useState(null),N=x.useRef(null),D=x.useRef(null),E=t?p.databases.get(t)??[]:[],$=t&&n?`${t}:${n}`:"",M=$?p.tables.get($)??[]:[],R=t?p.connectionStatus.get(t):void 0,_=x.useMemo(()=>{if(!y.trim())return E;const F=y.toLowerCase();return E.filter(B=>B.toLowerCase().includes(F))},[E,y]);x.useEffect(()=>{const F=B=>{D.current&&!D.current.contains(B.target)&&S(!1)};return k&&document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[k]),x.useEffect(()=>{t&&!R&&H.testDatabaseConnection(s.id,t)},[s.id,t,R]),x.useEffect(()=>{t&&(R!=null&&R.connected)&&E.length===0&&H.listDatabases(s.id,t)},[s.id,t,R==null?void 0:R.connected,E.length]),x.useEffect(()=>{t&&n&&M.length===0&&H.listTables(s.id,t,n)},[s.id,t,n,M.length]),x.useEffect(()=>{C(null)},[t,n]);const P=x.useCallback(F=>{b(B=>{const I=new Set(B);if(I.has(F))I.delete(F);else if(I.add(F),t&&n){const U=`${t}:${n}:${F}`;p.tableSchemas.has(U)||H.getTableSchema(s.id,t,n,F)}return I})},[s.id,t,n,p.tableSchemas]),O=F=>{if(!t||!n)return null;const B=`${t}:${n}:${F}`;return p.tableSchemas.get(B)};return a?r.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:f("terminal:database.expandSidebar"),children:"»"})}):r.jsxs("div",{className:"database-sidebar",children:[r.jsxs("div",{className:"database-sidebar__header",children:[r.jsx("span",{children:f("terminal:database.explorer")}),r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:f("terminal:database.collapseSidebar"),children:"«"})]}),r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:f("terminal:database.connection")}),r.jsx("select",{className:"database-sidebar__select",value:t||"",onChange:F=>o(F.target.value),children:e.length===0?r.jsx("option",{value:"",children:f("terminal:database.noConnections")}):e.map(F=>r.jsxs("option",{value:F.id,children:[F.engine==="mysql"?"🐬":"🐘"," ",F.name]},F.id))}),R&&r.jsx("div",{className:`database-sidebar__status ${R.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:R.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),f("terminal:database.connected"),R.serverVersion&&r.jsxs("span",{className:"database-sidebar__version",children:["(",R.serverVersion,")"]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),R.error||f("terminal:database.disconnected")]})})]}),E.length>0&&r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:f("terminal:database.databaseTitle")}),r.jsxs("div",{className:"database-sidebar__searchable-select",ref:D,children:[r.jsx("input",{ref:N,className:"database-sidebar__search-input",type:"text",value:k?y:n||"",placeholder:f("terminal:database.selectDatabase"),onChange:F=>{w(F.target.value),k||S(!0)},onFocus:()=>{S(!0),w("")},onKeyDown:F=>{var B,I;F.key==="Escape"?(S(!1),w(""),(B=N.current)==null||B.blur()):F.key==="Enter"&&_.length===1&&(l(_[0]),S(!1),w(""),(I=N.current)==null||I.blur())}}),k&&r.jsx("div",{className:"database-sidebar__dropdown",children:_.length===0?r.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):_.map(F=>r.jsx("div",{className:`database-sidebar__dropdown-item ${F===n?"database-sidebar__dropdown-item--active":""}`,onMouseDown:B=>{B.preventDefault(),l(F),S(!1),w("")},children:F},F))})]})]}),M.length>0&&r.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[r.jsx("div",{className:"database-sidebar__section-title",children:f("terminal:database.tablesCount",{count:M.length})}),r.jsx("div",{className:"database-sidebar__tables",children:M.map(F=>{const B=g.has(F.name),I=B?O(F.name):null;return r.jsxs("div",{className:"database-sidebar__table",children:[r.jsxs("div",{className:"database-sidebar__table-header",children:[r.jsx("button",{className:"database-sidebar__table-expand",onClick:()=>P(F.name),title:B?"Collapse table schema":"Expand table schema",children:B?"▼":"▶"}),r.jsx("span",{className:"database-sidebar__table-icon",children:F.type==="view"?"👁":"📋"}),r.jsx("span",{className:`database-sidebar__table-name ${j===F.name?"database-sidebar__table-name--selected":""}`,onClick:()=>C(F.name),onDoubleClick:()=>{C(F.name),d(F.name)},children:F.name}),r.jsx("button",{className:"database-sidebar__table-insert",onClick:U=>{U.stopPropagation(),c(F.name)},title:f("terminal:database.insertTableName"),children:"+"})]}),B&&I&&r.jsx("div",{className:"database-sidebar__table-columns",children:I.columns.map(U=>r.jsxs("div",{className:"database-sidebar__column",onClick:()=>c(U.name),title:`${U.type}${U.nullable?" NULL":" NOT NULL"}${U.primaryKey?" PK":""}`,children:[r.jsx("span",{className:"database-sidebar__column-icon",children:U.primaryKey?"🔑":""}),r.jsx("span",{className:"database-sidebar__column-name",children:U.name}),r.jsx("span",{className:"database-sidebar__column-type",children:U.type})]},U.name))})]},F.name)})})]})]})},oH=({query:s,onChange:e,onExecute:t,isExecuting:n,disabled:a,autoFocus:i=!0})=>{const{t:o}=He(["terminal"]),l=x.useRef(null),c=x.useRef(null);x.useEffect(()=>{if(i&&!a&&l.current){const b=setTimeout(()=>{var y;(y=l.current)==null||y.focus()},100);return()=>clearTimeout(b)}},[i,a]);const d=x.useCallback(b=>{const y=b.currentTarget;c.current&&(c.current.scrollLeft=y.scrollLeft,c.current.scrollTop=y.scrollTop)},[]),f=x.useCallback(b=>{if((b.ctrlKey||b.metaKey)&&b.key==="Enter"&&(b.preventDefault(),!a&&!n&&t()),b.key==="Tab"){b.preventDefault();const y=b.currentTarget,w=y.selectionStart,k=y.selectionEnd,S=s.substring(0,w)+" "+s.substring(k);e(S),setTimeout(()=>{y.selectionStart=y.selectionEnd=w+2},0)}},[s,e,t,a,n]),p=x.useMemo(()=>{if(!s)return"";try{return Qo.highlight(s,Qo.languages.sql,"sql")}catch{return s}},[s]),g=x.useMemo(()=>s.split(`
|
|
232
|
+
`)}function z9(s){return s.startsWith("Using tool:")||s.startsWith("Tool input:")||s.startsWith("Tool result:")||s.startsWith("Bash output:")||s.startsWith("Session started:")||s.startsWith("[thinking]")||s.startsWith("Tokens:")||s.startsWith("Cost:")||s.startsWith("Context (estimated from Codex turn usage):")||s.startsWith("🔄 [System]")||s.startsWith("📋 [System]")||s.startsWith("[System]")}function F9({onSaveSnapshot:s}={}){var gn,ss,Ne,Xe,ht;const{t:e}=He(["terminal","common"]),t=ir(),n=UN(),a=YN(),i=cx(),o=hx(),l=VN(),c=ux(),d=dx(),f=zB(),p=!!f,g=x.useMemo(()=>f?{id:f.agentId,name:f.agentName,class:f.agentClass,status:"idle",provider:"claude",position:{x:0,y:0,z:0},cwd:f.cwd,permissionMode:"interactive",tokensUsed:0,contextUsed:0,contextLimit:2e5,taskCount:0,createdAt:f.createdAt,lastActivity:f.createdAt}:null,[f]),b=Array.from(n),w=b.length===1?b[0]:null,S=(ox(w)||null)??(p?g:null),j=w??(p?(f==null?void 0:f.agentId)??null:null),C=!!(S!=null&&S.sessionId)&&!p,{terminalHeight:N,terminalRef:D,handleResizeStart:E}=b$(),$=m$(),M=lx(j),R=p&&f?f.outputs.map(Ye=>((!Ye.text||!Ye.text.trim())&&console.warn("[GuakeOutputPanel] Empty snapshot output:",Ye),{text:Ye.text||"",timestamp:Ye.timestamp,isStreaming:!1,isUserPrompt:!1})):M,_=x.useRef(null),P=x.useRef(null),O=x.useRef(null),[F,B]=x.useState(()=>{const Ye=Ds(xt.VIEW_MODE);return Ye==="simple"||Ye==="chat"||Ye==="advanced"?Ye:Ds(xt.ADVANCED_VIEW)==="true"?"advanced":"simple"}),[I,U]=x.useState(null),[q,K]=x.useState(null),[X,L]=x.useState(null),[ee,Z]=x.useState(null),[z,V]=x.useState(!1);Mn("guake-image-modal",I!==null,()=>U(null)),Mn("guake-bash-modal",q!==null,()=>K(null)),Mn("guake-response-modal",ee!==null,()=>Z(null)),Mn("guake-context-confirm",X!==null,()=>L(null)),Mn("guake-agent-info",z,()=>V(!1));const[Q,J]=x.useState(!1),[Y,se]=x.useState(()=>bs.isEnabled()),ae=UB(),le=x.useCallback(Ye=>H.setOverviewPanelOpen(Ye),[]),[pe,be]=x.useState(!1),ce=x.useRef(null),he=x.useRef(null),[we,Me]=x.useState(!1),[re,ne]=x.useState(!1),fe=a&&S!==null,xe=dT({selectedAgentId:j,hasSessionId:C,reconnectCount:o,lastPrompts:i,outputScrollRef:_}),ye=w$({selectedAgentId:j,isOpen:fe}),ue=y$({agents:t,selectedAgentId:j,isOpen:fe,loadingHistory:xe.fetchingHistory,hasModalOpen:!!(I||q||ee||c||d),outputRef:_}),Pe=hT({selectedAgentId:w}),Be=!p&&j?H.getPendingPermissionsForAgent(j):[],Qe=(S==null?void 0:S.class)==="boss"||(S==null?void 0:S.isBoss),me=EB(!p&&Qe?j:null),ie=_B(p?null:j);x.useEffect(()=>{Q&&!Y&&(se(!0),bs.setEnabled(!0))},[Q,Y]),x.useEffect(()=>{fe||V(!1)},[fe]),x.useEffect(()=>{const Ye=S==null?void 0:S.status;return ce.current==="working"&&Ye==="idle"?(he.current&&clearTimeout(he.current),be(!0),he.current=setTimeout(()=>{be(!1),he.current=null},1e3)):Ye==="working"&&(he.current&&(clearTimeout(he.current),he.current=null),be(!1)),ce.current=Ye||null,()=>{he.current&&clearTimeout(he.current)}},[S==null?void 0:S.status]);const ke=x.useMemo(()=>{const{history:Ye}=xe,tt=new Map;for(const ct of Ye)ct.type==="tool_result"&&ct.toolUseId&&tt.set(ct.toolUseId,ct.content);const pt=ct=>ct.map(lt=>{if(lt.type==="tool_use"&<.toolName==="Bash"&<.toolUseId){const wt=tt.get(lt.toolUseId);let ut;try{ut=(lt.toolInput||(lt.content?JSON.parse(lt.content):{})).command}catch{}return{...lt,_bashOutput:wt,_bashCommand:ut}}return lt});return pt(F==="advanced"?Ye:F==="chat"?Ye.filter((ct,lt,wt)=>{if(ct.type==="user")return!0;if(ct.type==="assistant"){const ut=wt[lt+1];return!ut||ut.type==="user"}return!1}):Ye.filter(ct=>ct.type==="user"||ct.type==="assistant"||ct.type==="tool_use"))},[xe.history,F]),de=pT({outputs:R,viewMode:F}),Te=x.useMemo(()=>{const Ye=[],tt=new Set,pt=new Set;let ct=null,lt=0;for(const wt of ke){if(wt.type==="assistant"){const Kn=wt.uuid?`uuid:${wt.uuid}:${Fh(wt.content)}`:`sig:${wt.timestamp}:${Fh(wt.content)}`;if(tt.has(Kn))continue;tt.add(Kn),Ye.push(wt);continue}if(wt.type!=="user"){Ye.push(wt);continue}const ut=bb(wt.content),$t=wt.uuid?`uuid:${wt.uuid}:${ut}`:null;if($t&&pt.has($t))continue;const un=wt.timestamp?new Date(wt.timestamp).getTime():0;ct===ut&&Math.abs(un-lt)<=KC||(Ye.push(wt),$t&&pt.add($t),ct=ut,lt=un)}return Ye},[ke]),Oe=x.useMemo(()=>{const Ye=new Map,tt=new Set,pt=new Map;for(const ut of Te){const $t=ut.timestamp?new Date(ut.timestamp).getTime():0;if(ut.type==="user"){const As=bb(ut.content),Xn=Ye.get(As)??0;$t>Xn&&Ye.set(As,$t);continue}if(ut.type!=="assistant")continue;ut.uuid&&tt.add(ut.uuid);const un=Fh(ut.content),Kn=pt.get(un)??0;$t>Kn&&pt.set(un,$t)}const ct=[];let lt=null,wt=0;for(const ut of de){if(!ut.isUserPrompt){if(!ut.isStreaming&&!z9(ut.text)){if(ut.uuid&&tt.has(ut.uuid))continue;const As=Fh(ut.text),Xn=ut.timestamp||0,ba=pt.get(As);if(ba&&Math.abs(Xn-ba)<=B9)continue}ct.push(ut);continue}const $t=bb(ut.text),un=ut.timestamp||0,Kn=Ye.get($t);Kn&&un>=Kn&&un-Kn<=I9||lt===$t&&Math.abs(un-wt)<=KC||(ct.push(ut),lt=$t,wt=un)}return ct},[de,Te]),Ue=Te.length+Oe.length,rt=k$({totalMessages:Ue,isOpen:fe,hasModalOpen:!!(I||q||ee||c),scrollContainerRef:_,selectedAgentId:j,inputRef:P,textareaRef:O,useTextarea:Pe.useTextarea});x.useEffect(()=>{if(!(!(q!=null&&q.isLive)||!q.command)){for(const Ye of Oe)if(Ye._bashCommand===q.command&&Ye._bashOutput){K({command:q.command,output:Ye._bashOutput,isLive:!1});return}}},[q,Oe]);const Je=x.useCallback((Ye,tt)=>{U({url:Ye,name:tt})},[]),St=x.useCallback((Ye,tt)=>{const pt=Dx(Ye,S==null?void 0:S.cwd),ct=pt.line?{...tt||{},targetLine:pt.line}:tt;H.setFileViewerPath(pt.path,ct,S==null?void 0:S.cwd)},[S==null?void 0:S.cwd]),et=x.useCallback((Ye,tt)=>{K({command:Ye,output:tt,isLive:tt==="Running..."})},[]),Nt=x.useCallback(Ye=>{Z(Ye)},[]),[Rt,Mt]=x.useState(!0),mn=x.useRef(!1),je=x.useRef(!1),oe=x.useCallback(()=>{je.current||(mn.current=!0,Mt(!1))},[]);x.useEffect(()=>{Mt(!0),mn.current=!1,je.current=!0;const Ye=setTimeout(()=>{je.current=!1},3e3);return()=>clearTimeout(Ye)},[j]);const Re=x.useCallback(()=>{if(!_.current||$.keyboardScrollLockRef.current)return;const{scrollTop:Ye,scrollHeight:tt,clientHeight:pt}=_.current,ct=tt-Ye-pt<150;je.current||(mn.current=!ct,ct&&Mt(!0)),xe.handleScroll($.keyboardScrollLockRef)},[_,$.keyboardScrollLockRef,xe]),at=M.length>0&&((ss=(gn=M[M.length-1])==null?void 0:gn.text)==null?void 0:ss.length)||0;x.useEffect(()=>{$.keyboardScrollLockRef.current||mn.current||requestAnimationFrame(()=>{if(_.current){const{scrollTop:Ye,scrollHeight:tt,clientHeight:pt}=_.current;tt-Ye-pt<150&&(_.current.scrollTop=tt)}})},[M.length,at,$.keyboardScrollLockRef,_]);const ot=x.useRef(null);x.useLayoutEffect(()=>{Me(!1);const tt=ot.current!==w;ot.current=w,tt&&H.getState().currentSnapshot&&H.setCurrentSnapshot(null)},[w]);const Ft=x.useRef(!1);x.useEffect(()=>{Ft.current=!0,ne(!0)},[j,o]),x.useEffect(()=>{xe.fetchingHistory&&(Ft.current=!0,ne(!0))},[xe.fetchingHistory]),x.useEffect(()=>{if(!re||!fe||xe.fetchingHistory)return;const Ye=_.current;if(!Ye)return;let tt=null;const pt=performance.now();let ct=0,lt=-1;const wt=()=>{const{scrollTop:$t,scrollHeight:un,clientHeight:Kn}=Ye;return un-$t-Kn<=2},ut=()=>{const $t=performance.now(),un=Ye.scrollHeight,Kn=Math.abs(un-lt)<=1,As=wt();if(Kn&&As?ct+=1:ct=0,lt=un,ct>=8){ne(!1),tt=null;return}if($t-pt>8e3){ne(!1),tt=null;return}tt=requestAnimationFrame(ut)};return tt=requestAnimationFrame(ut),()=>{tt!==null&&cancelAnimationFrame(tt)}},[re,fe,xe.fetchingHistory,xe.historyLoadVersion]),x.useEffect(()=>{if(!fe||!Ft.current)return;const Ye=setTimeout(()=>{requestAnimationFrame(()=>{Ft.current=!1,Me(!0)})},50);return()=>clearTimeout(Ye)},[xe.historyLoadVersion,fe,_]),x.useEffect(()=>{const Ye=tt=>{if(tt.key==="`"&&!tt.ctrlKey&&!tt.altKey&&S){const pt=tt.target;pt.tagName!=="INPUT"&&pt.tagName!=="TEXTAREA"&&(tt.preventDefault(),H.toggleTerminal())}};return document.addEventListener("keydown",Ye),()=>document.removeEventListener("keydown",Ye)},[S]),x.useEffect(()=>{const Ye=tt=>{tt.key==="Escape"&&(c?(tt.stopImmediatePropagation(),H.clearFileViewerPath()):d?(tt.stopImmediatePropagation(),H.closeContextModal()):ee?(tt.stopImmediatePropagation(),Z(null)):q?(tt.stopImmediatePropagation(),K(null)):I?(tt.stopImmediatePropagation(),U(null)):ye.searchMode&&(tt.stopImmediatePropagation(),ye.closeSearch()))};return document.addEventListener("keydown",Ye,!0),()=>document.removeEventListener("keydown",Ye,!0)},[I,q,ee,ye,c,d]);const on=x.useRef(fe),Ot=x.useRef(!1);x.useEffect(()=>{on.current=fe},[fe]),x.useEffect(()=>{if(window.innerWidth<=768)return;const tt=lt=>{var un;if(!(lt instanceof Element))return!1;const wt=(un=D.current)==null?void 0:un.contains(lt),ut=lt.closest(".agent-bar"),$t=!!lt.closest(".modal-overlay, .modal, .image-modal-overlay, .image-modal, .bash-modal-overlay, .bash-modal, .agent-info-modal-overlay, .agent-info-modal, .agent-response-modal, .pasted-text-modal-overlay, .pasted-text-modal, .file-viewer-overlay, .file-viewer-modal, .context-view-modal, .guake-context-confirm-overlay, .guake-context-confirm-modal");return!!wt||!!ut||$t},pt=lt=>{if(!on.current){Ot.current=!1;return}Ot.current=!tt(lt.target)},ct=lt=>{Ot.current&&(tt(lt.target)||H.setTerminalOpen(!1),Ot.current=!1)};return document.addEventListener("mousedown",pt,!0),document.addEventListener("mouseup",ct,!0),()=>{document.removeEventListener("mousedown",pt,!0),document.removeEventListener("mouseup",ct,!0)}},[]),x.useEffect(()=>{const Ye=()=>{document.hidden&&$.cleanup()};return document.addEventListener("visibilitychange",Ye),()=>document.removeEventListener("visibilitychange",Ye)},[$]);const Dt=typeof window<"u"&&window.innerWidth<=768;return S?j?r.jsxs("div",{ref:D,className:`guake-terminal ${fe?"open":"collapsed"} ${Q&&fe?"with-debug-panel":""} ${ae&&fe?"with-overview-panel":""}`,style:{"--terminal-height":`${N}%`},children:[!p&&Q&&fe&&j&&r.jsx(h9,{agentId:j,onClose:()=>J(!1)}),!p&&ae&&fe&&j&&r.jsx(g9,{activeAgentId:j,onClose:()=>le(!1),onSelectAgent:Ye=>{H.selectAgent(Ye)}}),r.jsxs("div",{className:"guake-content",children:[r.jsx(_$,{selectedAgent:S,selectedAgentId:j,sortedAgents:ue.sortedAgents,swipeOffset:ue.swipeOffset,viewMode:F,setViewMode:B,searchMode:ye.searchMode,toggleSearch:ye.toggleSearch,closeSearch:ye.closeSearch,debugPanelOpen:Q,setDebugPanelOpen:J,debuggerEnabled:Y,setDebuggerEnabled:se,overviewPanelOpen:ae,setOverviewPanelOpen:le,agentInfoOpen:z,onToggleAgentInfo:()=>V(!z),outputsLength:Te.length+Oe.length,setContextConfirm:L,headerRef:ue.headerRef,onSaveSnapshot:p?void 0:s,isSnapshotView:p}),ye.searchMode&&r.jsx(D$,{searchInputRef:ye.searchInputRef,searchQuery:ye.searchQuery,setSearchQuery:ye.setSearchQuery,handleSearch:ye.handleSearch,closeSearch:ye.closeSearch,searchLoading:ye.searchLoading,searchResultsCount:ye.searchResults.length}),r.jsxs("div",{className:`guake-swipe-container ${ue.swipeAnimationClass}`,style:ue.swipeOffset!==0?{transform:`translateX(${ue.swipeOffset*40}%)`}:void 0,children:[ue.sortedAgents.length>1&&ue.swipeOffset!==0&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`swipe-indicator left ${ue.swipeOffset>.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-icon",children:"←"}),r.jsx("span",{className:"indicator-name",children:(Ne=ue.prevAgent)==null?void 0:Ne.name})]}),r.jsxs("div",{className:`swipe-indicator right ${ue.swipeOffset<-.3?"visible":""}`,children:[r.jsx("span",{className:"indicator-name",children:(Xe=ue.nextAgent)==null?void 0:Xe.name}),r.jsx("span",{className:"indicator-icon",children:"→"})]})]}),ue.sortedAgents.length>1&&ue.sortedAgents.length<=8&&ue.swipeOffset!==0&&r.jsx("div",{className:`swipe-dots ${Math.abs(ue.swipeOffset)>.1?"visible":""}`,children:ue.sortedAgents.map((Ye,tt)=>r.jsx("div",{className:`swipe-dot ${tt===ue.currentAgentIndex?"active":""}`},Ye.id))}),r.jsx("div",{className:"guake-output",ref:_,onScroll:Re,children:ye.searchMode&&ye.searchResults.length>0?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"guake-search-header",children:e("terminal:header.searchResultsTitle")}),ye.searchResults.map((Ye,tt)=>r.jsx(hf,{message:Ye,agentId:j,highlight:ye.searchQuery,onImageClick:Je,onFileClick:St,onBashClick:et,onViewMarkdown:Nt},`s-${tt}`))]}):r.jsxs("div",{className:`guake-history-content ${we?"fade-in":""}`,children:[xe.loadingHistory&&xe.history.length===0&&M.length===0&&r.jsxs("div",{className:"guake-empty loading",children:[e("terminal:empty.loadingConversation"),r.jsxs("span",{className:"loading-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})]}),!xe.loadingHistory&&xe.history.length===0&&R.length===0&&S.status!=="working"&&r.jsx("div",{className:"guake-empty",children:e("terminal:empty.noOutput")}),xe.hasMore&&!ye.searchMode&&r.jsx("div",{className:"guake-load-more",children:xe.loadingMore?r.jsx("span",{children:e("terminal:empty.loadingOlder")}):r.jsx("button",{onClick:xe.loadMoreHistory,children:e("terminal:empty.loadMore",{count:xe.totalCount-xe.history.length})})}),r.jsx(d9,{historyMessages:Te,liveOutputs:Oe,agentId:j,execTasks:ie,viewMode:F,selectedMessageIndex:rt.selectedIndex,isMessageSelected:rt.isSelected,onImageClick:Je,onFileClick:St,onBashClick:et,onViewMarkdown:Nt,scrollContainerRef:_,onScrollTopReached:xe.loadMoreHistory,isLoadingMore:xe.loadingMore,hasMore:xe.hasMore,shouldAutoScroll:Rt,onUserScroll:oe,pinToBottom:re,onPinCancel:()=>ne(!1),isLoadingHistory:xe.fetchingHistory}),Qe&&me.size>0&&r.jsxs("div",{className:"agent-progress-container",children:[r.jsxs("div",{className:"agent-progress-container-header",children:[r.jsx("span",{className:"progress-crown",children:"👑"}),r.jsx("span",{children:e("terminal:empty.subordinateProgress")}),r.jsx("span",{className:"progress-count",children:e("terminal:empty.activeCount",{count:me.size})})]}),Array.from(me.values()).map(Ye=>r.jsx(y9,{progress:Ye,defaultExpanded:Ye.status==="working",onAgentClick:tt=>H.selectAgent(tt)},Ye.agentId))]})]})})]}),r.jsx(B$,{selectedAgent:S,selectedAgentId:j,isOpen:fe,command:Pe.command,setCommand:Pe.setCommand,forceTextarea:Pe.forceTextarea,setForceTextarea:Pe.setForceTextarea,useTextarea:Pe.useTextarea,attachedFiles:Pe.attachedFiles,setAttachedFiles:Pe.setAttachedFiles,removeAttachedFile:Pe.removeAttachedFile,uploadFile:Pe.uploadFile,pastedTexts:Pe.pastedTexts,expandPastedTexts:Pe.expandPastedTexts,incrementPastedCount:Pe.incrementPastedCount,setPastedTexts:Pe.setPastedTexts,resetPastedCount:Pe.resetPastedCount,handleInputFocus:$.handleInputFocus,handleInputBlur:$.handleInputBlur,pendingPermissions:Be,showCompletion:pe,onImageClick:Je,inputRef:P,textareaRef:O,isSnapshotView:p,onClearHistory:xe.clearHistory}),r.jsxs("div",{className:"guake-agent-status-bar",children:[!p&&(S==null?void 0:S.isDetached)&&r.jsx(Mp,{content:r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"tide-tooltip__title",children:["🔄 ",e("terminal:empty.reattachingSessionTitle")]}),r.jsxs("div",{className:"tide-tooltip__text",children:[e("terminal:empty.reattachingSessionDesc"),r.jsx("br",{}),r.jsx("br",{}),r.jsxs("strong",{children:[e("common:labels.status"),":"]})," ",e("terminal:empty.reattachingSessionStatus")]})]}),position:"top",className:"tide-tooltip--detached",children:r.jsxs("span",{className:"guake-detached-badge",title:e("terminal:empty.reattachingBadge"),children:[r.jsx("span",{className:"guake-detached-spinner",children:"🔄"})," ",e("terminal:empty.reattaching")]})}),(S==null?void 0:S.cwd)&&r.jsxs("span",{className:"guake-agent-cwd",children:["📁 ",S.cwd.split("/").filter(Boolean).slice(-2).join("/")||S.cwd]}),!p&&S&&(()=>{const Ye=S.contextStats,tt=!!Ye,pt=Ye?Ye.totalTokens:S.contextUsed||0,ct=Ye?Ye.contextWindow:S.contextLimit||2e5,lt=Ye?Ye.usedPercent:Math.round(pt/ct*100),wt=Math.round(100-lt),ut=lt>=80?"#ff4a4a":lt>=60?"#ff9e4a":lt>=40?"#ffd700":"#4aff9e",$t=(pt/1e3).toFixed(1),un=(ct/1e3).toFixed(1);return r.jsxs("span",{className:"guake-agent-context",onClick:()=>H.setContextModalAgentId(j),title:e(tt?"terminal:context.clickToViewStats":"terminal:context.clickToFetchStats"),children:[r.jsx("span",{className:"context-icon",children:"📊"}),r.jsxs("span",{className:"context-label",children:[e("terminal:agentInfo.context"),":"]}),r.jsx("span",{className:"context-bar-mini",children:r.jsx("span",{className:"context-bar-mini-fill",style:{width:`${Math.min(100,lt)}%`,backgroundColor:ut}})}),r.jsxs("span",{className:"context-tokens",style:{color:ut},children:[$t,"k/",un,"k"]}),r.jsxs("span",{className:"context-free",children:["(",e("terminal:context.percentFree",{percent:wt}),")"]}),!tt&&r.jsx("span",{className:"context-warning",title:e("terminal:context.clickToFetchStats"),children:"⚠️"})]})})(),r.jsx(O9,{})]})]}),fe&&r.jsx("div",{className:"guake-resize-handle",onMouseDown:E,title:e("common:rightPanel.dragToResize")}),r.jsxs("div",{className:"guake-handle",onClick:()=>{fe&&H.toggleTerminal()},onDoubleClick:()=>{fe||H.toggleTerminal()},style:{top:fe?`${N}%`:"0"},children:[r.jsx("span",{className:"guake-handle-icon",children:fe?"▲":"▼"}),r.jsx("span",{className:"guake-handle-text",children:S.name})]}),I&&r.jsx(kT,{url:I.url,name:I.name,onClose:()=>U(null)}),q&&r.jsx(ST,{state:q,onClose:()=>K(null)}),X&&r.jsx($$,{action:X,selectedAgentId:j,subordinateCount:((ht=S==null?void 0:S.subordinateIds)==null?void 0:ht.length)||0,onClose:()=>L(null),onClearHistory:xe.clearHistory}),r.jsx(H$,{}),r.jsx(U$,{}),r.jsx(G$,{agent:S,isOpen:z,onClose:()=>V(!1)}),!p&&r.jsx(jT,{agent:S,content:ee,onClose:()=>Z(null)})]}):null:Dt&&l==="terminal"&&n.size===0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${N}%`},children:r.jsx("div",{className:"guake-content",children:r.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:r.jsxs("div",{style:{textAlign:"center"},children:[r.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"👆"}),r.jsx("div",{style:{fontSize:"16px"},children:e("terminal:empty.tapAgent")}),r.jsx("div",{style:{fontSize:"14px",marginTop:"8px",opacity:.7},children:e("terminal:empty.switchTo3D")})]})})})}):Dt&&l==="terminal"&&n.size>0?r.jsx("div",{ref:D,className:"guake-terminal open",style:{"--terminal-height":`${N}%`},children:r.jsx("div",{className:"guake-content",children:r.jsx("div",{className:"guake-output",style:{display:"flex",alignItems:"center",justifyContent:"center",color:"#6272a4"},children:r.jsxs("div",{className:"guake-empty loading",children:[e("terminal:empty.loadingTerminal"),r.jsxs("span",{className:"loading-dots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})]})})})}):null}function $9(s){return s.trim().replace(/^v/i,"")}function XC(s){const t=$9(s).match(/^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?/);if(!t)return null;const n=t[1].split(".").map(i=>Number.parseInt(i,10));if(n.some(Number.isNaN))return null;const a=t[2]?t[2].split("."):[];return{core:n,prerelease:a}}function H9(s,e){if(s.length===0&&e.length===0)return 0;if(s.length===0)return 1;if(e.length===0)return-1;const t=Math.max(s.length,e.length);for(let n=0;n<t;n+=1){const a=s[n],i=e[n];if(a===void 0)return-1;if(i===void 0)return 1;const o=/^\d+$/.test(a)?Number.parseInt(a,10):null,l=/^\d+$/.test(i)?Number.parseInt(i,10):null;if(o!==null&&l!==null){if(o>l)return 1;if(o<l)return-1;continue}if(o!==null)return-1;if(l!==null)return 1;const c=a.localeCompare(i);if(c!==0)return c>0?1:-1}return 0}function U9(s,e){const t=XC(s),n=XC(e);if(!t||!n)return null;const a=Math.max(t.core.length,n.core.length);for(let i=0;i<a;i+=1){const o=t.core[i]??0,l=n.core[i]??0;if(o>l)return 1;if(o<l)return-1}return H9(t.prerelease,n.prerelease)}function G9(s,e){const t=U9(s,e);return t===null?"unknown":t<0?"behind":t>0?"ahead":"equal"}async function W9(s,e={}){const{timeoutMs:t=5e3,fetchImpl:n=fetch}=e;try{const a=new AbortController,i=setTimeout(()=>a.abort(),t),o=Date.now(),l=await n(`https://registry.npmjs.org/${encodeURIComponent(s)}/latest?t=${o}`,{signal:a.signal,headers:{Accept:"application/json"}});if(clearTimeout(i),!l.ok)return null;const c=await l.json();return typeof c.version=="string"?c.version:null}catch{return null}}async function q9(s,e,t={}){const n=await W9(s,t);return n?{currentVersion:e,latestVersion:n,relation:G9(e,n)}:{currentVersion:e,latestVersion:null,relation:"unknown"}}const Y9="tide-commander",yb="0.65.8";function V9(){const[s,e]=x.useState({currentVersion:yb,latestVersion:null,relation:"unknown",isChecking:!1}),t=x.useCallback(async()=>{e(a=>({...a,isChecking:!0}));const n=await q9(Y9,yb);e({currentVersion:yb,latestVersion:n.latestVersion,relation:n.relation,isChecking:!1})},[]);return x.useEffect(()=>{t()},[t]),{...s,refresh:t}}function K9({onFocusAgent:s,onSpawnClick:e,onSpawnBossClick:t,onNewBuildingClick:n,onNewAreaClick:a}){const{t:i}=He(["common"]),o=An(),l=tl(),c=ei(),[d,f]=x.useState(!1),p=x.useRef(null),g=x.useRef(null),b=x.useRef(null),y=x.useRef(new Map);x.useEffect(()=>{{f(!1);return}},[l.experimental2DView]),x.useEffect(()=>{const ae=g.current;if(!ae)return;const le=pe=>{ae.scrollWidth<=ae.clientWidth||(pe.preventDefault(),ae.scrollLeft+=pe.deltaY)};return ae.addEventListener("wheel",le,{passive:!1}),()=>ae.removeEventListener("wheel",le)},[]);const[w,k]=x.useState(null),[S,j]=x.useState(new Map),[C,N]=x.useState(null),[D,E]=x.useState(null),$=x.useRef(0),M=x.useMemo(()=>Array.from(o.agents.values()).filter(ae=>!H.isAgentInArchivedArea(ae.id)).sort((ae,le)=>(ae.createdAt||0)-(le.createdAt||0)),[o.agents,o.areas]),{orderedAgents:R,moveAgent:_}=HN(M),P=R,O=x.useMemo(()=>{const ae=new Map;for(const le of P)ae.set(le.id,H.getAreaForAgent(le.id));return ae},[P,o.areas]),F=x.useMemo(()=>{const ae=new Map;for(const pe of P){const be=O.get(pe.id)||null,ce=(be==null?void 0:be.id)||null;ae.has(ce)||ae.set(ce,{area:be,agents:[]}),ae.get(ce).agents.push(pe)}const le=Array.from(ae.values());return le.sort((pe,be)=>{var ce,he;return!pe.area&&be.area?1:pe.area&&!be.area?-1:!pe.area&&!be.area?0:(((ce=pe.area)==null?void 0:ce.name)||"").localeCompare(((he=be.area)==null?void 0:he.name)||"")}),le},[P,O]);x.useEffect(()=>{const ae=new Map(S);let le=!1;for(const pe of P){const be=S.get(pe.id);pe.currentTool?(!be||be.tool!==pe.currentTool)&&(ae.set(pe.id,{tool:pe.currentTool,key:Date.now()}),le=!0):be&&setTimeout(()=>{j(ce=>{const he=new Map(ce);return he.delete(pe.id),he})},1500)}le&&j(ae)},[P.map(ae=>ae.currentTool).join(",")]),x.useEffect(()=>{const ae=o.lastSelectedAgentId;if(!ae)return;const le=y.current.get(ae),pe=g.current;le&&pe&&requestAnimationFrame(()=>{const be=le.getBoundingClientRect(),ce=pe.getBoundingClientRect(),we=be.left-ce.left+pe.scrollLeft+be.width/2,Me=pe.clientWidth;pe.scrollTo({left:we-Me/2,behavior:"smooth"})})},[o.lastSelectedAgentId]);const B=(ae,le)=>{H.setLastSelectionViaDirectClick(!0),le.shiftKey?H.addToSelection(ae.id):H.selectAgent(ae.id),(window.innerWidth<=768||o.terminalOpen)&&H.setTerminalOpen(!0)},I=ae=>{s==null||s(ae.id),H.setTerminalOpen(!0)},U=x.useCallback((ae,le)=>{N(le),ae.dataTransfer.effectAllowed="move",ae.dataTransfer.setData("text/plain",le.id),requestAnimationFrame(()=>{ae.target.classList.add("dragging")})},[]),q=x.useCallback(ae=>{N(null),E(null),$.current=0,ae.target.classList.remove("dragging")},[]),K=x.useCallback((ae,le)=>{if(ae.preventDefault(),C){const pe=O.get(C.id),be=P[le],ce=be?O.get(be.id):null,he=(pe==null?void 0:pe.id)??null,we=(ce==null?void 0:ce.id)??null;ae.dataTransfer.dropEffect=he===we?"move":"none"}else ae.dataTransfer.dropEffect="move"},[C,P,O]),X=x.useCallback((ae,le)=>{if(ae.preventDefault(),$.current++,C){const pe=O.get(C.id),be=P[le],ce=be?O.get(be.id):null,he=(pe==null?void 0:pe.id)??null,we=(ce==null?void 0:ce.id)??null;E(he===we?le:null)}else E(le)},[C,P,O]),L=x.useCallback(ae=>{$.current--,$.current===0&&E(null)},[]),ee=x.useCallback((ae,le)=>{if(ae.preventDefault(),!C)return;const pe=P.findIndex(be=>be.id===C.id);if(pe!==-1&&pe!==le){const be=O.get(C.id),ce=P[le],he=ce?O.get(ce.id):null,we=(be==null?void 0:be.id)??null,Me=(he==null?void 0:he.id)??null;we===Me&&_(pe,le)}N(null),E(null),$.current=0},[C,P,_,O]),Z=ae=>{const le=`common:status.${ae}`;return i(le,{defaultValue:i("common:status.unknown")})},{currentVersion:z,latestVersion:V,relation:Q,isChecking:J}=V9(),Y=z;let se=0;return r.jsxs("div",{className:"agent-bar",ref:p,children:[r.jsxs("div",{className:"agent-bar-scroll",ref:g,children:[r.jsxs("div",{className:"agent-bar-version",title:V?`Tide Commander v${Y} (npm: v${V})`:`Tide Commander v${Y}`,children:[r.jsxs("span",{children:["v",Y]}),Q==="behind"&&V?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-behind",title:`Behind npm latest v${V}`,children:["npm v",V]}):Q==="ahead"&&V?r.jsxs("span",{className:"agent-bar-version-badge agent-bar-version-badge-ahead",title:`Ahead of npm latest v${V}`,children:["npm v",V]}):null,Q==="behind"?r.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status agent-bar-version-status-behind",title:i("common:agentBar.behindNpmTooltip",{defaultValue:"Current version is behind npm latest"}),children:i("common:agentBar.behindNpm",{defaultValue:"(behind npm)"})}):Q==="ahead"?r.jsx("span",{className:"agent-bar-version-status agent-bar-version-status-ahead",title:i("common:agentBar.aheadNpmTooltip",{defaultValue:"Current version is newer than npm latest"}),children:i("common:agentBar.aheadNpm",{defaultValue:"(ahead of npm)"})}):Q==="equal"?r.jsx("a",{href:"https://github.com/deivid11/tide-commander/releases",target:"_blank",rel:"noopener noreferrer",className:"agent-bar-version-status",children:i("common:agentBar.updated")}):J?r.jsx("span",{className:"agent-bar-version-status",children:i("common:agentBar.checkingNpm",{defaultValue:"(checking npm)"})}):r.jsx("span",{className:"agent-bar-version-status",children:i("common:agentBar.unknownNpm",{defaultValue:"(npm unknown)"})}),d&&r.jsx("button",{className:"agent-bar-hmr-refresh",onClick:zN,title:"Refresh 3D Scene (HMR changes pending)",children:"↻"})]}),r.jsxs("div",{className:"agent-bar-list",ref:b,children:[r.jsxs("button",{className:"agent-bar-spawn-btn",onClick:e,title:i("common:agentBar.spawnNewAgent"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"+"}),r.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newAgent")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-boss-btn",onClick:t,title:i("common:agentBar.spawnBoss"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"👑"}),r.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newBoss")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-building-btn",onClick:n,title:i("common:agentBar.addNewBuilding"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"🏢"}),r.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newBuilding")})]}),r.jsxs("button",{className:"agent-bar-spawn-btn agent-bar-area-btn",onClick:a,title:i("common:agentBar.drawNewArea"),children:[r.jsx("span",{className:"agent-bar-spawn-icon",children:"▢"}),r.jsx("span",{className:"agent-bar-spawn-label",children:i("common:agentBar.newArea")})]}),F.map(ae=>{var be,ce,he,we,Me;const le=ae.agents,pe=!ae.area;return r.jsxs("div",{className:`agent-bar-group ${pe?"unassigned":""}`,style:{borderColor:((be=ae.area)==null?void 0:be.color)||void 0,background:ae.area?`${ae.area.color}15`:void 0},children:[r.jsx("div",{className:"agent-bar-area-label",children:r.jsx("span",{className:"agent-bar-area-name",style:{color:((ce=ae.area)==null?void 0:ce.color)||"#888"},children:((he=ae.area)==null?void 0:he.name)||i("common:agentBar.unassigned")})}),((we=ae.area)==null?void 0:we.directories)&&ae.area.directories.length>0&&r.jsx("div",{className:"agent-bar-folders",children:ae.area.directories.map((re,ne)=>r.jsxs("div",{className:"agent-bar-folder-item",onClick:fe=>{fe.stopPropagation(),H.openFileExplorer(re)},children:[r.jsx("span",{className:"agent-bar-folder-icon",children:"📁"}),r.jsxs("div",{className:"agent-bar-folder-tooltip",children:[r.jsx("div",{className:"agent-bar-folder-tooltip-path",children:re}),r.jsx("div",{className:"agent-bar-folder-tooltip-hint",children:i("common:agentBar.clickToOpen")})]})]},ne))}),le.map(re=>{const ne=se++,fe=P.findIndex(me=>me.id===re.id),xe=o.selectedAgentIds.has(re.id),ye=Zr(re.class,c),ue=o.lastPrompts.get(re.id),Pe=S.get(re.id);Pe&&(hs[Pe.tool]||hs.default),ue!=null&&ue.text&&(ue.text.length>30?ue.text.substring(0,30)+"":ue.text);const Be=(C==null?void 0:C.id)===re.id,Qe=D===fe;return r.jsxs("div",{ref:me=>{me?y.current.set(re.id,me):y.current.delete(re.id)},className:`agent-bar-item ${xe?"selected":""} ${re.status} ${re.isBoss?"is-boss":""} ${Be?"dragging":""} ${Qe?"drag-over":""}`,draggable:!0,onDragStart:me=>U(me,re),onDragEnd:q,onDragOver:me=>K(me,fe),onDragEnter:me=>X(me,fe),onDragLeave:L,onDrop:me=>ee(me,fe),onClick:me=>B(re,me),onDoubleClick:()=>I(re),onMouseEnter:()=>k(re),onMouseLeave:()=>k(null),title:`${re.name} (${ne+1}) - Drag to reorder within group`,children:[r.jsxs("div",{className:"agent-bar-avatar",children:[r.jsx("span",{className:"agent-bar-icon",children:ye.icon}),r.jsx("span",{className:"agent-bar-status",style:{backgroundColor:Xb(re.status)}}),re.status==="idle"&&re.lastActivity>0&&r.jsx("span",{className:"agent-bar-idle-clock",style:{color:Kp(re.lastActivity)},title:Xp(re.lastActivity),children:"⏱"})]}),r.jsxs("span",{className:"agent-bar-hotkey",title:`Ctrl+${ne+1}`,children:["^",ne+1]})]},re.id)})]},((Me=ae.area)==null?void 0:Me.id)||"unassigned")})]})]}),Array.from(S.entries()).map(([ae,le])=>{const pe=y.current.get(ae);if(!pe)return null;const be=pe.getBoundingClientRect(),ce=hs[le.tool]||hs.default;return r.jsxs("div",{className:"agent-bar-tool-bubble",title:le.tool,style:{position:"fixed",left:be.left+be.width/2,bottom:window.innerHeight-be.top+8},children:[r.jsx("span",{className:"agent-bar-tool-icon",children:ce}),r.jsx("span",{className:"agent-bar-tool-name",children:le.tool})]},`tool-${ae}-${le.key}`)}),w&&(()=>{const ae=H.getAreaForAgent(w.id),le=o.lastPrompts.get(w.id),pe=Zr(w.class,c),be=H.getAgentSupervisorHistory(w.id),ce=be.length>0?be[be.length-1]:void 0,he=Date.now()-(w.createdAt||Date.now()),we=Math.floor(he/6e4),Me=Math.floor(we/60),re=Me>0?`${Me}h ${we%60}m`:`${we}m`,ne=Pe=>Pe>=1e6?`${(Pe/1e6).toFixed(1)}M`:Pe>=1e3?`${(Pe/1e3).toFixed(1)}K`:Pe.toString(),fe=w.contextLimit>0?Math.round(w.contextUsed/w.contextLimit*100):0,xe=Pe=>{switch(Pe){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},ye=y.current.get(w.id),ue={};if(ye){const Pe=ye.getBoundingClientRect();ue.position="fixed",ue.left=Pe.left+Pe.width/2,ue.bottom=window.innerHeight-Pe.top+12}return r.jsxs("div",{className:"agent-bar-tooltip",style:ue,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:pe.icon}),r.jsxs("span",{className:"agent-bar-tooltip-name",children:[r.jsx("img",{src:w.provider==="codex"?"/assets/codex.png":"/assets/claude.png",alt:w.provider,className:"agent-bar-provider-icon",title:w.provider==="codex"?"Codex Agent":"Claude Agent"}),w.name]}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:Xb(w.status)},children:Z(w.status)})]}),r.jsxs("div",{className:"agent-bar-tooltip-info",children:[r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.class"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[w.class," — ",pe.description]})]}),ae&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.area"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:ae.color},children:ae.name})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.directory"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:w.cwd})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.uptime"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",children:re})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.tokens"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[ne(w.tokensUsed)," ",i("common:agentPopup.used")]})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.context"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:fe>80?"#ff4a4a":fe>60?"#ff9e4a":void 0},children:[ne(w.contextUsed)," / ",ne(w.contextLimit)," (",fe,"%)"]})]}),w.currentTool&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.tool"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[hs[w.currentTool]||hs.default," ",w.currentTool]})]}),w.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.task"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[w.currentTask.substring(0,150),w.currentTask.length>150?"...":""]})]}),w.lastAssignedTask&&!w.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.assignedTask"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[w.lastAssignedTask.substring(0,200),w.lastAssignedTask.length>200?"...":""]})]}),le&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.lastQuery"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[le.text.substring(0,300),le.text.length>300?"...":""]})]}),ce&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"agent-bar-tooltip-divider"}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:agentPopup.supervisor"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",style:{color:xe(ce.analysis.progress)},children:ce.analysis.progress.replace("_"," ")})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.status"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:ce.analysis.statusDescription})]}),ce.analysis.recentWorkSummary&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.summary"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[ce.analysis.recentWorkSummary.substring(0,300),ce.analysis.recentWorkSummary.length>300?"...":""]})]}),ce.analysis.concerns&&ce.analysis.concerns.length>0&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[i("common:labels.concerns"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:ce.analysis.concerns.join("; ")})]})]})]})]})})()]})}function X9({activeTool:s,onExit:e}){const{t}=He(["notifications","terminal"]);if(!s||s==="select")return null;const n=t(s==="rectangle"?"notifications:drawing.rectangleTool":"notifications:drawing.circleTool"),a=s==="rectangle"?"▭":"○";return r.jsxs("div",{className:"drawing-mode-indicator",children:[r.jsxs("div",{className:"drawing-mode-content",children:[r.jsx("span",{className:"drawing-mode-icon",children:a}),r.jsxs("div",{className:"drawing-mode-text",children:[r.jsxs("span",{className:"drawing-mode-title",children:[t("terminal:drawingMode.drawingArea"),": ",n]}),r.jsxs("span",{className:"drawing-mode-hint",children:[t("terminal:drawingMode.clickAndDrag")," • ",t("terminal:drawingMode.pressEscape")]})]})]}),r.jsx("button",{className:"drawing-mode-exit",onClick:e,title:t("terminal:drawingMode.exitDrawingMode"),children:"✕"})]})}const Z9={idle:"common:status.idle",working:"common:status.working",waiting:"common:status.waiting",error:"common:status.error",offline:"common:status.offline"},xb=s=>s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString(),Q9=s=>{switch(s){case"on_track":return"#4aff9e";case"completed":return"#4a9eff";case"stalled":return"#ff9e4a";case"blocked":return"#ff4a4a";case"idle":return"#888888";default:return"#888888"}},J9=x.memo(function({agent:e,screenPos:t,onClose:n}){const{t:a}=He(["common"]),i=ei(),o=H.getAreaForAgent(e.id),l=H.getState().lastPrompts.get(e.id),c=Zr(e.class,i),d=H.getAgentSupervisorHistory(e.id),f=d.length>0?d[d.length-1]:void 0,p=Date.now()-(e.createdAt||Date.now()),g=Math.floor(p/6e4),b=Math.floor(g/60),y=b>0?`${b}h ${g%60}m`:`${g}m`,w=e.contextLimit>0?Math.round(e.contextUsed/e.contextLimit*100):0,k=x.useMemo(()=>{let C=t.x-150,N=t.y-320-10;return typeof window<"u"&&(C<10?C=10:C+300>window.innerWidth-10&&(C=window.innerWidth-300-10),N<10&&(N=t.y+10)),{position:"fixed",left:C,top:N,zIndex:1e4,maxWidth:300,maxHeight:320,fontSize:"0.85em"}},[t.x,t.y]);return r.jsxs("div",{className:"agent-hover-popup",style:k,onMouseLeave:n,children:[r.jsxs("div",{className:"agent-bar-tooltip-header",children:[r.jsx("span",{className:"agent-bar-tooltip-icon",children:c.icon}),r.jsx("span",{className:"agent-bar-tooltip-name",children:e.name}),r.jsx("span",{className:"agent-bar-tooltip-status",style:{color:Xb(e.status)},children:a(Z9[e.status]||"common:status.unknown")})]}),r.jsxs("div",{className:"agent-bar-tooltip-info",children:[r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.class"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.class," — ",c.description]})]}),o&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.area"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-area",style:{color:o.color},children:o.name})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.directory"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-path",children:e.cwd})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.uptime"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",children:y})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.tokens"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[xb(e.tokensUsed)," ",a("common:agentPopup.used")]})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.context"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",style:{color:w>80?"#ff4a4a":w>60?"#ff9e4a":void 0},children:[xb(e.contextUsed)," / ",xb(e.contextLimit)," (",w,"%)"]})]}),e.currentTool&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.tool"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-tool",children:[hs[e.currentTool]||hs.default," ",e.currentTool]})]}),e.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.task"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value",children:[e.currentTask.substring(0,150),e.currentTask.length>150?"...":""]})]}),e.lastAssignedTask&&!e.currentTask&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.assignedTask"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[e.lastAssignedTask.substring(0,200),e.lastAssignedTask.length>200?"...":""]})]}),l&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.lastQuery"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-query",children:[l.text.substring(0,300),l.text.length>300?"...":""]})]}),f&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"agent-bar-tooltip-divider"}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:agentPopup.supervisor"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value",style:{color:Q9(f.analysis.progress)},children:f.analysis.progress.replace("_"," ")})]}),r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.status"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:f.analysis.statusDescription})]}),f.analysis.recentWorkSummary&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.summary"),":"]}),r.jsxs("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-supervisor",children:[f.analysis.recentWorkSummary.substring(0,300),f.analysis.recentWorkSummary.length>300?"...":""]})]}),f.analysis.concerns&&f.analysis.concerns.length>0&&r.jsxs("div",{className:"agent-bar-tooltip-row",children:[r.jsxs("span",{className:"agent-bar-tooltip-label",children:[a("common:labels.concerns"),":"]}),r.jsx("span",{className:"agent-bar-tooltip-value agent-bar-tooltip-concerns",children:f.analysis.concerns.join("; ")})]})]})]})]})});function ZC(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],n=Math.floor(Math.log(s)/Math.log(e));return parseFloat((s/Math.pow(e,n)).toFixed(1))+" "+t[n]}function QC(s){const t=Date.now()-s,n=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return n>0?`${n}h ${a}m`:`${a}m`}const JC={30:"#1a1a1a",31:"#e74c3c",32:"#2ecc71",33:"#f39c12",34:"#3498db",35:"#9b59b6",36:"#00bcd4",37:"#ecf0f1",90:"#7f8c8d",91:"#ff6b6b",92:"#4ade80",93:"#fbbf24",94:"#60a5fa",95:"#c084fc",96:"#22d3ee",97:"#ffffff"};function eH(s){const e=[],t=/\x1B\[([0-9;]*)m/g;let n=0,a=null,i;for(;(i=t.exec(s))!==null;){if(i.index>n){const l=s.slice(n,i.index);a?e.push(r.jsx("span",{style:{color:a},children:l},e.length)):e.push(l)}const o=i[1].split(";").map(Number);for(const l of o)l===0||l===39?a=null:JC[l]&&(a=JC[l]);n=t.lastIndex}if(n<s.length){const o=s.slice(n);a?e.push(r.jsx("span",{style:{color:a},children:o},e.length)):e.push(o)}return e.length>0?e:[s]}const tH=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){var U,q,K,X,L,ee,Z,z,V,Q,J,Y,se,ae,le,pe,be,ce,he,we;const{t:l}=He(["terminal","common"]),[c,d]=x.useState(!1),[f,p]=x.useState(null),[g,b]=x.useState(!1),y=x.useRef(null),w=x.useRef(f);w.current=f;const{buildingLogs:k}=An(),S=H.getBuildingLogs(e.id),j=(U=e.pm2)==null?void 0:U.enabled,C=(q=e.docker)==null?void 0:q.enabled,N=x.useRef(null),D=x.useRef(null),E=x.useCallback(Me=>{Me.preventDefault();const re=w.current?w.current.x:0,ne=w.current?w.current.y:0;y.current={mouseX:Me.clientX,mouseY:Me.clientY,popupX:re,popupY:ne},b(!0),N.current=fe=>{if(!y.current)return;const xe=fe.clientX-y.current.mouseX,ye=fe.clientY-y.current.mouseY;p({x:y.current.popupX+xe,y:y.current.popupY+ye})},D.current=()=>{b(!1),y.current=null,N.current&&document.removeEventListener("mousemove",N.current),D.current&&document.removeEventListener("mouseup",D.current)},document.addEventListener("mousemove",N.current),document.addEventListener("mouseup",D.current)},[]);x.useEffect(()=>()=>{N.current&&document.removeEventListener("mousemove",N.current),D.current&&document.removeEventListener("mouseup",D.current)},[]);const $=Me=>{if(Me==="logs"){if((j||C)&&i){i();return}H.sendBuildingCommand(e.id,Me),d(!0)}else H.sendBuildingCommand(e.id,Me)},M=(Me,re)=>{if(Me){const ne=`http://localhost:${Me}`;re&&o?o(ne):window.open(ne,"_blank")}},R=((K=e.pm2Status)==null?void 0:K.ports)||[],_=((L=(X=e.dockerStatus)==null?void 0:X.ports)==null?void 0:L.map(Me=>Me.host))||[],P=j?R:C?_:[],O=j?!!((ee=e.pm2)!=null&&ee.script):C?!!((Z=e.docker)!=null&&Z.image)||((z=e.docker)==null?void 0:z.mode)==="compose"||((V=e.docker)==null?void 0:V.mode)==="existing":!!((Q=e.commands)!=null&&Q.start),F=j?!!((J=e.pm2)!=null&&J.script):C?!0:!!((Y=e.commands)!=null&&Y.stop),B=j?!!((se=e.pm2)!=null&&se.script):C?!0:!!((ae=e.commands)!=null&&ae.restart),I=x.useMemo(()=>{const re=c?400:250;let ne=t.x+20,fe=t.y-80;return typeof window<"u"&&!f&&(t.x+20+280>window.innerWidth&&(ne=t.x-280-20),t.y-80<0?fe=10:t.y-80+re>window.innerHeight&&(fe=window.innerHeight-re-10)),{position:"fixed",left:ne+((f==null?void 0:f.x)||0),top:fe+((f==null?void 0:f.y)||0),zIndex:1e3,cursor:g?"grabbing":void 0}},[t.x,t.y,c,f,g]);return r.jsxs("div",{className:"building-action-popup",style:I,onClick:Me=>Me.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header ${g?"dragging":""}`,onMouseDown:E,children:[r.jsx("span",{className:"building-popup-name",children:e.name}),P.length>0&&r.jsx("span",{className:"building-popup-ports",children:P.map(Me=>r.jsxs("a",{href:`http://localhost:${Me}`,className:"building-popup-port-link",onClick:re=>{re.preventDefault(),re.stopPropagation(),M(Me,re.altKey)},onMouseDown:re=>re.stopPropagation(),title:`Open http://localhost:${Me} (Alt+Click for modal)`,children:[":",Me]},Me))}),r.jsx("span",{className:"building-popup-status",style:{backgroundColor:Xr[e.status]},children:e.status}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),j&&e.pm2Status&&r.jsxs("div",{className:"building-popup-metrics",children:[r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"PID"}),r.jsx("span",{className:"value",children:e.pm2Status.pid||"-"})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"CPU"}),r.jsxs("span",{className:"value",children:[((le=e.pm2Status.cpu)==null?void 0:le.toFixed(1))||"0","%"]})]}),r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:ZC(e.pm2Status.memory||0)})]}),e.pm2Status.restarts!==void 0&&e.pm2Status.restarts>0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"RST"}),r.jsx("span",{className:"value",children:e.pm2Status.restarts})]}),e.pm2Status.uptime&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"UP"}),r.jsx("span",{className:"value",children:QC(e.pm2Status.uptime)})]})]}),C&&e.dockerStatus&&r.jsxs("div",{className:"building-popup-metrics",children:[r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"ID"}),r.jsx("span",{className:"value",children:e.dockerStatus.containerId||"-"})]}),e.dockerStatus.cpu!==void 0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"CPU"}),r.jsxs("span",{className:"value",children:[e.dockerStatus.cpu.toFixed(1),"%"]})]}),e.dockerStatus.memory!==void 0&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"MEM"}),r.jsx("span",{className:"value",children:ZC(e.dockerStatus.memory)})]}),e.dockerStatus.health&&e.dockerStatus.health!=="none"&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"HEALTH"}),r.jsx("span",{className:"value",style:{color:e.dockerStatus.health==="healthy"?"#4ade80":e.dockerStatus.health==="unhealthy"?"#f87171":"#fbbf24"},children:e.dockerStatus.health==="healthy"?"✓":e.dockerStatus.health==="unhealthy"?"✗":"..."})]}),e.dockerStatus.startedAt&&r.jsxs("span",{className:"metric",children:[r.jsx("span",{className:"label",children:"UP"}),r.jsx("span",{className:"value",children:QC(e.dockerStatus.startedAt)})]})]}),C&&((pe=e.dockerStatus)==null?void 0:pe.services)&&e.dockerStatus.services.length>0&&r.jsx("div",{className:"building-popup-services",children:e.dockerStatus.services.map((Me,re)=>r.jsxs("span",{className:"service-item",title:`${Me.name}: ${Me.status}`,children:[r.jsx("span",{className:"service-indicator",style:{backgroundColor:Me.status==="running"?"#4ade80":"#f87171"}}),r.jsx("span",{className:"service-name",children:Me.name})]},re))}),(e.lastError||j&&((be=e.pm2Status)==null?void 0:be.status)==="errored"||C&&((ce=e.dockerStatus)==null?void 0:ce.status)==="dead")&&r.jsxs("div",{className:"building-popup-error",children:[e.lastError||l("terminal:building.processFailedToStart"),j&&((he=e.pm2Status)==null?void 0:he.restarts)&&e.pm2Status.restarts>5&&r.jsxs("span",{className:"error-hint",children:[" - ",l("terminal:building.checkLogsOrConfig")]}),C&&((we=e.dockerStatus)==null?void 0:we.health)==="unhealthy"&&r.jsxs("span",{className:"error-hint",children:[" - ",l("terminal:building.healthCheckFailing")]})]}),r.jsxs("div",{className:"building-popup-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>$("start"),disabled:!O||e.status==="running"||e.status==="starting",title:l(O?"terminal:buildingAction.start":"terminal:buildingAction.noStartCommand"),children:[r.jsx("span",{className:"icon",children:"▶"}),l("terminal:buildingAction.start")]}),r.jsxs("button",{className:"action-btn stop",onClick:()=>$("stop"),disabled:!F||e.status==="stopped"||e.status==="stopping",title:l(F?"terminal:buildingAction.stop":"terminal:buildingAction.noStopCommand"),children:[r.jsx("span",{className:"icon",children:"■"}),l("terminal:buildingAction.stop")]}),r.jsxs("button",{className:"action-btn restart",onClick:()=>$("restart"),disabled:!B,title:l(B?"terminal:buildingAction.restart":"terminal:buildingAction.noRestartCommand"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:buildingAction.restart")]}),r.jsxs("button",{className:"action-btn logs",onClick:()=>$("logs"),title:l("terminal:buildingAction.viewLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:logs.title")]}),P.length===1&&r.jsxs("button",{className:"action-btn open-url",onClick:Me=>M(P[0],Me.altKey),title:`Open http://localhost:${P[0]} (Alt+Click for modal)`,children:[r.jsx("span",{className:"icon",children:"🔗"}),l("terminal:buildingAction.openInBrowser")]}),P.length>1&&r.jsxs("div",{className:"action-btn-group",children:[r.jsxs("span",{className:"action-btn-label",children:[l("terminal:buildingAction.openInBrowser"),":"]}),P.map(Me=>r.jsxs("button",{className:"action-btn open-url port-btn",onClick:re=>M(Me,re.altKey),title:`Open http://localhost:${Me} (Alt+Click for modal)`,children:[":",Me]},Me))]})]}),c&&S.length>0&&r.jsxs("div",{className:"building-popup-logs",children:[r.jsxs("div",{className:"logs-header",children:[r.jsx("span",{children:l("terminal:logs.title")}),r.jsx("button",{onClick:()=>H.clearBuildingLogs(e.id),children:l("terminal:logs.clear")})]}),r.jsx("div",{className:"logs-content",children:S.slice(-50).map((Me,re)=>r.jsx("pre",{children:eH(Me)},re))})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:buildingAction.fullSettings")})]})});function nH(s){if(s===0)return"0 B";const e=1024,t=["B","KB","MB","GB"],n=Math.floor(Math.log(s)/Math.log(e));return parseFloat((s/Math.pow(e,n)).toFixed(1))+" "+t[n]}function sH(s){const t=Date.now()-s,n=Math.floor(t/(1e3*60*60)),a=Math.floor(t%(1e3*60*60)/(1e3*60));return n>0?`${n}h ${a}m`:`${a}m`}const aH=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenLogsModal:i,onOpenUrlInModal:o}){const{t:l}=He(["terminal","common"]),[c,d]=x.useState(null),[f,p]=x.useState(!1),g=x.useRef(null),b=x.useRef(c);b.current=c;const{buildings:y}=An(),k=(e.subordinateBuildingIds||[]).map(R=>y.get(R)).filter(R=>R!==void 0),S=x.useRef(null),j=x.useRef(null),C=x.useCallback(R=>{R.preventDefault();const _=b.current?b.current.x:0,P=b.current?b.current.y:0;g.current={mouseX:R.clientX,mouseY:R.clientY,popupX:_,popupY:P},p(!0),S.current=O=>{if(!g.current)return;const F=O.clientX-g.current.mouseX,B=O.clientY-g.current.mouseY;d({x:g.current.popupX+F,y:g.current.popupY+B})},j.current=()=>{p(!1),g.current=null,S.current&&document.removeEventListener("mousemove",S.current),j.current&&document.removeEventListener("mouseup",j.current)},document.addEventListener("mousemove",S.current),document.addEventListener("mouseup",j.current)},[]);x.useEffect(()=>()=>{S.current&&document.removeEventListener("mousemove",S.current),j.current&&document.removeEventListener("mouseup",j.current)},[]);const N=R=>{H.sendBossBuildingCommand(e.id,R)},D=k.reduce((R,_)=>(R[_.status]=(R[_.status]||0)+1,R),{}),E=k.some(R=>{var _;return(_=R.pm2)==null?void 0:_.enabled}),$=(R,_)=>{const P=`http://localhost:${R}`;_&&o?o(P):window.open(P,"_blank")},M=x.useMemo(()=>{let P=t.x+20,O=t.y-80;return typeof window<"u"&&!c&&(t.x+20+340>window.innerWidth&&(P=t.x-340-20),t.y-80<0?O=10:t.y-80+350>window.innerHeight&&(O=window.innerHeight-350-10)),{position:"fixed",left:P+((c==null?void 0:c.x)||0),top:O+((c==null?void 0:c.y)||0),zIndex:1e3,cursor:f?"grabbing":void 0}},[t.x,t.y,c,f]);return r.jsxs("div",{className:"building-action-popup boss-building-popup",style:M,onClick:R=>R.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header boss-header ${f?"dragging":""}`,onMouseDown:C,children:[r.jsx("span",{className:"boss-icon",children:"👑"}),r.jsx("span",{className:"building-popup-name",children:e.name}),r.jsx("span",{className:"subordinate-count",children:l("terminal:building.unitsCount",{count:k.length})}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),r.jsxs("div",{className:"boss-status-overview",children:[Object.entries(D).map(([R,_])=>r.jsxs("span",{className:"status-badge",style:{backgroundColor:Xr[R]||"#666"},children:[_," ",R]},R)),k.length===0&&r.jsx("span",{className:"no-subordinates",children:l("terminal:building.noSubordinates")})]}),k.length>0&&r.jsx("div",{className:"subordinate-list",children:k.map(R=>{var _,P,O;return r.jsxs("div",{className:"subordinate-item",children:[r.jsx("span",{className:"sub-status-dot",style:{backgroundColor:Xr[R.status]}}),r.jsx("span",{className:"sub-name",children:R.name}),((_=R.pm2Status)==null?void 0:_.ports)&&R.pm2Status.ports.length>0&&r.jsx("span",{className:"sub-port",children:R.pm2Status.ports.map(F=>r.jsxs("a",{href:`http://localhost:${F}`,className:"building-popup-port-link",onClick:B=>{B.preventDefault(),B.stopPropagation(),$(F,B.altKey)},title:`Open http://localhost:${F} (Alt+Click for modal)`,children:[":",F]},F))}),R.pm2Status&&r.jsxs("span",{className:"sub-metrics",children:[(P=R.pm2Status.cpu)==null?void 0:P.toFixed(0),"% | ",nH(R.pm2Status.memory||0)]}),((O=R.pm2Status)==null?void 0:O.uptime)&&r.jsx("span",{className:"sub-uptime",children:sH(R.pm2Status.uptime)})]},R.id)})}),r.jsxs("div",{className:"building-popup-actions boss-actions",children:[r.jsxs("button",{className:"action-btn start",onClick:()=>N("start_all"),disabled:k.length===0,title:l("terminal:building.startAllSubs"),children:[r.jsx("span",{className:"icon",children:"▶"}),l("terminal:building.startAll")]}),r.jsxs("button",{className:"action-btn stop",onClick:()=>N("stop_all"),disabled:k.length===0,title:l("terminal:building.stopAllSubs"),children:[r.jsx("span",{className:"icon",children:"■"}),l("terminal:building.stopAll")]}),r.jsxs("button",{className:"action-btn restart",onClick:()=>N("restart_all"),disabled:k.length===0,title:l("terminal:building.restartAllSubs"),children:[r.jsx("span",{className:"icon",children:"↺"}),l("terminal:building.restartAll")]}),E&&r.jsxs("button",{className:"action-btn logs",onClick:i,title:l("terminal:building.viewUnifiedLogs"),children:[r.jsx("span",{className:"icon",children:"📄"}),l("terminal:building.logs")]})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:l("terminal:building.fullSettings")})]})}),iH=x.memo(function({building:e,screenPos:t,onClose:n,onOpenSettings:a,onOpenDatabasePanel:i}){var D;const{t:o}=He(["terminal","common"]),[l,c]=x.useState(null),[d,f]=x.useState(!1),p=x.useRef(null),g=x.useRef(l);g.current=l;const b=sf(e.id),y=((D=e.database)==null?void 0:D.connections)??[],w=x.useRef(null),k=x.useRef(null),S=x.useCallback(E=>{E.preventDefault();const $=g.current?g.current.x:0,M=g.current?g.current.y:0;p.current={mouseX:E.clientX,mouseY:E.clientY,popupX:$,popupY:M},f(!0),w.current=R=>{if(!p.current)return;const _=R.clientX-p.current.mouseX,P=R.clientY-p.current.mouseY;c({x:p.current.popupX+_,y:p.current.popupY+P})},k.current=()=>{f(!1),p.current=null,w.current&&document.removeEventListener("mousemove",w.current),k.current&&document.removeEventListener("mouseup",k.current)},document.addEventListener("mousemove",w.current),document.addEventListener("mouseup",k.current)},[]);x.useEffect(()=>()=>{w.current&&document.removeEventListener("mousemove",w.current),k.current&&document.removeEventListener("mouseup",k.current)},[]);const j=E=>{H.testDatabaseConnection(e.id,E)},C=E=>b.connectionStatus.get(E),N=x.useMemo(()=>{let M=t.x+20,R=t.y-80;return typeof window<"u"&&!l&&(t.x+20+320>window.innerWidth&&(M=t.x-320-20),t.y-80<0?R=10:t.y-80+300>window.innerHeight&&(R=window.innerHeight-300-10)),{position:"fixed",left:M+((l==null?void 0:l.x)||0),top:R+((l==null?void 0:l.y)||0),zIndex:1e3,cursor:d?"grabbing":void 0}},[t.x,t.y,l,d]);return r.jsxs("div",{className:"building-action-popup database-building-popup",style:N,onClick:E=>E.stopPropagation(),children:[r.jsxs("div",{className:`building-popup-header database-header ${d?"dragging":""}`,onMouseDown:S,children:[r.jsx("span",{className:"database-icon",children:"🗄️"}),r.jsx("span",{className:"building-popup-name",children:e.name}),r.jsx("span",{className:"connection-count",children:o("terminal:building.connCount",{count:y.length})}),r.jsx("button",{className:"building-popup-close",onClick:n,children:"x"})]}),y.length>0?r.jsx("div",{className:"database-connection-list",children:y.map(E=>{const $=C(E.id);return r.jsxs("div",{className:"database-connection-item",children:[r.jsx("span",{className:"conn-engine",children:E.engine==="mysql"?"🐬":"🐘"}),r.jsx("span",{className:"conn-name",children:E.name}),r.jsxs("span",{className:"conn-host",children:[E.host,":",E.port]}),$&&r.jsx("span",{className:`conn-status ${$.connected?"connected":"disconnected"}`,children:$.connected?"●":"○"}),r.jsx("button",{className:"conn-test-btn",onClick:()=>j(E.id),title:o("terminal:building.testConnection"),children:"↻"})]},E.id)})}):r.jsxs("div",{className:"database-no-connections",children:[r.jsx("p",{children:o("terminal:building.noConnections")}),r.jsx("p",{className:"hint",children:o("terminal:building.clickSettingsToAdd")})]}),r.jsxs("div",{className:"building-popup-actions database-actions",children:[r.jsxs("button",{className:"action-btn query",onClick:i,disabled:y.length===0,title:o("terminal:building.openDbExplorer"),children:[r.jsx("span",{className:"icon",children:"⌨"}),o("terminal:building.query")]}),r.jsxs("button",{className:"action-btn test-all",onClick:()=>y.forEach(E=>j(E.id)),disabled:y.length===0,title:o("terminal:building.testAllConnections"),children:[r.jsx("span",{className:"icon",children:"↻"}),o("terminal:building.testAll")]})]}),r.jsx("button",{className:"building-popup-settings",onClick:a,children:o("common:buttons.settings")})]})}),rH=({building:s,connections:e,activeConnectionId:t,activeDatabase:n,collapsed:a,onToggleCollapse:i,onConnectionChange:o,onDatabaseChange:l,onInsertTable:c,onSelectTableQuery:d})=>{const{t:f}=He(["terminal"]),p=sf(s.id),[g,b]=x.useState(new Set),[y,w]=x.useState(""),[k,S]=x.useState(!1),[j,C]=x.useState(null),N=x.useRef(null),D=x.useRef(null),E=t?p.databases.get(t)??[]:[],$=t&&n?`${t}:${n}`:"",M=$?p.tables.get($)??[]:[],R=t?p.connectionStatus.get(t):void 0,_=x.useMemo(()=>{if(!y.trim())return E;const F=y.toLowerCase();return E.filter(B=>B.toLowerCase().includes(F))},[E,y]);x.useEffect(()=>{const F=B=>{D.current&&!D.current.contains(B.target)&&S(!1)};return k&&document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[k]),x.useEffect(()=>{t&&!R&&H.testDatabaseConnection(s.id,t)},[s.id,t,R]),x.useEffect(()=>{t&&(R!=null&&R.connected)&&E.length===0&&H.listDatabases(s.id,t)},[s.id,t,R==null?void 0:R.connected,E.length]),x.useEffect(()=>{t&&n&&M.length===0&&H.listTables(s.id,t,n)},[s.id,t,n,M.length]),x.useEffect(()=>{C(null)},[t,n]);const P=x.useCallback(F=>{b(B=>{const I=new Set(B);if(I.has(F))I.delete(F);else if(I.add(F),t&&n){const U=`${t}:${n}:${F}`;p.tableSchemas.has(U)||H.getTableSchema(s.id,t,n,F)}return I})},[s.id,t,n,p.tableSchemas]),O=F=>{if(!t||!n)return null;const B=`${t}:${n}:${F}`;return p.tableSchemas.get(B)};return a?r.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:f("terminal:database.expandSidebar"),children:"»"})}):r.jsxs("div",{className:"database-sidebar",children:[r.jsxs("div",{className:"database-sidebar__header",children:[r.jsx("span",{children:f("terminal:database.explorer")}),r.jsx("button",{className:"database-sidebar__toggle",onClick:i,title:f("terminal:database.collapseSidebar"),children:"«"})]}),r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:f("terminal:database.connection")}),r.jsx("select",{className:"database-sidebar__select",value:t||"",onChange:F=>o(F.target.value),children:e.length===0?r.jsx("option",{value:"",children:f("terminal:database.noConnections")}):e.map(F=>r.jsxs("option",{value:F.id,children:[F.engine==="mysql"?"🐬":"🐘"," ",F.name]},F.id))}),R&&r.jsx("div",{className:`database-sidebar__status ${R.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:R.connected?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),f("terminal:database.connected"),R.serverVersion&&r.jsxs("span",{className:"database-sidebar__version",children:["(",R.serverVersion,")"]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),R.error||f("terminal:database.disconnected")]})})]}),E.length>0&&r.jsxs("div",{className:"database-sidebar__section",children:[r.jsx("div",{className:"database-sidebar__section-title",children:f("terminal:database.databaseTitle")}),r.jsxs("div",{className:"database-sidebar__searchable-select",ref:D,children:[r.jsx("input",{ref:N,className:"database-sidebar__search-input",type:"text",value:k?y:n||"",placeholder:f("terminal:database.selectDatabase"),onChange:F=>{w(F.target.value),k||S(!0)},onFocus:()=>{S(!0),w("")},onKeyDown:F=>{var B,I;F.key==="Escape"?(S(!1),w(""),(B=N.current)==null||B.blur()):F.key==="Enter"&&_.length===1&&(l(_[0]),S(!1),w(""),(I=N.current)==null||I.blur())}}),k&&r.jsx("div",{className:"database-sidebar__dropdown",children:_.length===0?r.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):_.map(F=>r.jsx("div",{className:`database-sidebar__dropdown-item ${F===n?"database-sidebar__dropdown-item--active":""}`,onMouseDown:B=>{B.preventDefault(),l(F),S(!1),w("")},children:F},F))})]})]}),M.length>0&&r.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[r.jsx("div",{className:"database-sidebar__section-title",children:f("terminal:database.tablesCount",{count:M.length})}),r.jsx("div",{className:"database-sidebar__tables",children:M.map(F=>{const B=g.has(F.name),I=B?O(F.name):null;return r.jsxs("div",{className:"database-sidebar__table",children:[r.jsxs("div",{className:"database-sidebar__table-header",children:[r.jsx("button",{className:"database-sidebar__table-expand",onClick:()=>P(F.name),title:B?"Collapse table schema":"Expand table schema",children:B?"▼":"▶"}),r.jsx("span",{className:"database-sidebar__table-icon",children:F.type==="view"?"👁":"📋"}),r.jsx("span",{className:`database-sidebar__table-name ${j===F.name?"database-sidebar__table-name--selected":""}`,onClick:()=>C(F.name),onDoubleClick:()=>{C(F.name),d(F.name)},children:F.name}),r.jsx("button",{className:"database-sidebar__table-insert",onClick:U=>{U.stopPropagation(),c(F.name)},title:f("terminal:database.insertTableName"),children:"+"})]}),B&&I&&r.jsx("div",{className:"database-sidebar__table-columns",children:I.columns.map(U=>r.jsxs("div",{className:"database-sidebar__column",onClick:()=>c(U.name),title:`${U.type}${U.nullable?" NULL":" NOT NULL"}${U.primaryKey?" PK":""}`,children:[r.jsx("span",{className:"database-sidebar__column-icon",children:U.primaryKey?"🔑":""}),r.jsx("span",{className:"database-sidebar__column-name",children:U.name}),r.jsx("span",{className:"database-sidebar__column-type",children:U.type})]},U.name))})]},F.name)})})]})]})},oH=({query:s,onChange:e,onExecute:t,isExecuting:n,disabled:a,autoFocus:i=!0})=>{const{t:o}=He(["terminal"]),l=x.useRef(null),c=x.useRef(null);x.useEffect(()=>{if(i&&!a&&l.current){const b=setTimeout(()=>{var y;(y=l.current)==null||y.focus()},100);return()=>clearTimeout(b)}},[i,a]);const d=x.useCallback(b=>{const y=b.currentTarget;c.current&&(c.current.scrollLeft=y.scrollLeft,c.current.scrollTop=y.scrollTop)},[]),f=x.useCallback(b=>{if((b.ctrlKey||b.metaKey)&&b.key==="Enter"&&(b.preventDefault(),!a&&!n&&t()),b.key==="Tab"){b.preventDefault();const y=b.currentTarget,w=y.selectionStart,k=y.selectionEnd,S=s.substring(0,w)+" "+s.substring(k);e(S),setTimeout(()=>{y.selectionStart=y.selectionEnd=w+2},0)}},[s,e,t,a,n]),p=x.useMemo(()=>{if(!s)return"";try{return Qo.highlight(s,Qo.languages.sql,"sql")}catch{return s}},[s]),g=x.useMemo(()=>s.split(`
|
|
233
233
|
`).map((y,w)=>w+1),[s]);return r.jsxs("div",{className:"query-editor",children:[r.jsxs("div",{className:"query-editor__toolbar",children:[r.jsx("button",{className:"query-editor__execute",onClick:t,disabled:a||n||!s.trim(),title:o("terminal:database.executeShortcut"),children:n?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"query-editor__spinner"}),o("common:status.running")]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"query-editor__play-icon",children:"▶"}),o("terminal:database.runQuery")]})}),r.jsx("div",{className:"query-editor__hint",children:o("terminal:database.pressCtrlEnter")})]}),r.jsxs("div",{className:"query-editor__input-wrapper",children:[r.jsx("div",{className:"query-editor__line-numbers",children:g.map(b=>r.jsx("span",{children:b},b))}),r.jsxs("div",{className:"query-editor__editor",children:[r.jsx("pre",{ref:c,className:"query-editor__highlight","aria-hidden":"true",dangerouslySetInnerHTML:{__html:p+`
|
|
234
234
|
`}}),r.jsx("textarea",{ref:l,className:"query-editor__textarea",value:s,onChange:b=>e(b.target.value),onKeyDown:f,onScroll:d,placeholder:o(a?"terminal:database.selectDbPlaceholder":"terminal:database.enterQueryPlaceholder"),disabled:a,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]})]})]})};function RT(s){var e,t,n="";if(typeof s=="string"||typeof s=="number")n+=s;else if(typeof s=="object")if(Array.isArray(s)){var a=s.length;for(e=0;e<a;e++)s[e]&&(t=RT(s[e]))&&(n&&(n+=" "),n+=t)}else for(t in s)s[t]&&(n&&(n+=" "),n+=t);return n}function ps(){for(var s,e,t=0,n="",a=arguments.length;t<a;t++)(s=arguments[t])&&(e=RT(s))&&(n&&(n+=" "),n+=e);return n}const PT=6048e5,lH=864e5,ff=6e4,mf=36e5,cH=1e3,e1=Symbol.for("constructDateFrom");function wn(s,e){return typeof s=="function"?s(e):s&&typeof s=="object"&&e1 in s?s[e1](e):s instanceof Date?new s.constructor(e):new Date(e)}function yt(s,e){return wn(e||s,s)}function Xa(s,e,t){const n=yt(s,t==null?void 0:t.in);return isNaN(e)?wn((t==null?void 0:t.in)||s,NaN):(e&&n.setDate(n.getDate()+e),n)}function Qa(s,e,t){const n=yt(s,t==null?void 0:t.in);if(isNaN(e))return wn(s,NaN);if(!e)return n;const a=n.getDate(),i=wn(s,n.getTime());i.setMonth(n.getMonth()+e+1,0);const o=i.getDate();return a>=o?i:(n.setFullYear(i.getFullYear(),i.getMonth(),a),n)}function LT(s,e,t){return wn(s,+yt(s)+e)}function uH(s,e,t){return LT(s,e*mf)}let dH={};function al(){return dH}function nr(s,e){var l,c,d,f;const t=al(),n=(e==null?void 0:e.weekStartsOn)??((c=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??t.weekStartsOn??((f=(d=t.locale)==null?void 0:d.options)==null?void 0:f.weekStartsOn)??0,a=yt(s,e==null?void 0:e.in),i=a.getDay(),o=(i<n?7:0)+i-n;return a.setDate(a.getDate()-o),a.setHours(0,0,0,0),a}function hc(s,e){return nr(s,{...e,weekStartsOn:1})}function OT(s,e){const t=yt(s,e==null?void 0:e.in),n=t.getFullYear(),a=wn(t,0);a.setFullYear(n+1,0,4),a.setHours(0,0,0,0);const i=hc(a),o=wn(t,0);o.setFullYear(n,0,4),o.setHours(0,0,0,0);const l=hc(o);return t.getTime()>=i.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function _p(s){const e=yt(s),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+s-+t}function or(s,...e){const t=wn.bind(null,e.find(n=>typeof n=="object"));return e.map(t)}function Jo(s,e){const t=yt(s,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function pc(s,e,t){const[n,a]=or(t==null?void 0:t.in,s,e),i=Jo(n),o=Jo(a),l=+i-_p(i),c=+o-_p(o);return Math.round((l-c)/lH)}function hH(s,e){const t=OT(s,e),n=wn(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),hc(n)}function id(s,e,t){const n=yt(s,t==null?void 0:t.in);return n.setTime(n.getTime()+e*ff),n}function $x(s,e,t){return Qa(s,e*3,t)}function pH(s,e,t){return LT(s,e*1e3)}function Dp(s,e,t){return Xa(s,e*7,t)}function Za(s,e,t){return Qa(s,e*12,t)}function t1(s,e){let t,n=e==null?void 0:e.in;return s.forEach(a=>{!n&&typeof a=="object"&&(n=wn.bind(null,a));const i=yt(a,n);(!t||t<i||isNaN(+i))&&(t=i)}),wn(n,t||NaN)}function n1(s,e){let t,n=e==null?void 0:e.in;return s.forEach(a=>{!n&&typeof a=="object"&&(n=wn.bind(null,a));const i=yt(a,n);(!t||t>i||isNaN(+i))&&(t=i)}),wn(n,t||NaN)}function fH(s,e,t){const[n,a]=or(t==null?void 0:t.in,s,e);return+Jo(n)==+Jo(a)}function wi(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function fc(s){return!(!wi(s)&&typeof s!="number"||isNaN(+yt(s)))}function Rp(s,e,t){const[n,a]=or(t==null?void 0:t.in,s,e),i=n.getFullYear()-a.getFullYear(),o=n.getMonth()-a.getMonth();return i*12+o}function $r(s,e){const t=yt(s,e==null?void 0:e.in);return Math.trunc(t.getMonth()/3)+1}function Pp(s,e,t){const[n,a]=or(t==null?void 0:t.in,s,e),i=n.getFullYear()-a.getFullYear(),o=$r(n)-$r(a);return i*4+o}function Lp(s,e,t){const[n,a]=or(t==null?void 0:t.in,s,e);return n.getFullYear()-a.getFullYear()}function mH(s,e,t){const[n,a]=or(t==null?void 0:t.in,s,e),i=s1(n,a),o=Math.abs(pc(n,a));n.setDate(n.getDate()-i*o);const l=+(s1(n,a)===-i),c=i*(o-l);return c===0?0:c}function s1(s,e){const t=s.getFullYear()-e.getFullYear()||s.getMonth()-e.getMonth()||s.getDate()-e.getDate()||s.getHours()-e.getHours()||s.getMinutes()-e.getMinutes()||s.getSeconds()-e.getSeconds()||s.getMilliseconds()-e.getMilliseconds();return t<0?-1:t>0?1:t}function IT(s,e){const t=yt(s,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function BT(s,e){const t=yt(s,e==null?void 0:e.in),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function Ey(s,e){const t=yt(s,e==null?void 0:e.in),n=t.getMonth(),a=n-n%3;return t.setMonth(a,1),t.setHours(0,0,0,0),t}function zT(s,e){const t=yt(s,e==null?void 0:e.in);return t.setDate(1),t.setHours(0,0,0,0),t}function FT(s,e){const t=yt(s,e==null?void 0:e.in),n=t.getFullYear();return t.setFullYear(n+1,0,0),t.setHours(23,59,59,999),t}function gf(s,e){const t=yt(s,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}function gH(s,e){var l,c;const t=al(),n=t.weekStartsOn??((c=(l=t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??0,a=yt(s,e==null?void 0:e.in),i=a.getDay(),o=(i<n?-7:0)+6-(i-n);return a.setDate(a.getDate()+o),a.setHours(23,59,59,999),a}const bH={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},yH=(s,e,t)=>{let n;const a=bH[s];return typeof a=="string"?n=a:e===1?n=a.one:n=a.other.replace("{{count}}",e.toString()),t!=null&&t.addSuffix?t.comparison&&t.comparison>0?"in "+n:n+" ago":n};function vb(s){return(e={})=>{const t=e.width?String(e.width):s.defaultWidth;return s.formats[t]||s.formats[s.defaultWidth]}}const xH={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},vH={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},wH={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},kH={date:vb({formats:xH,defaultWidth:"full"}),time:vb({formats:vH,defaultWidth:"full"}),dateTime:vb({formats:wH,defaultWidth:"full"})},SH={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},jH=(s,e,t,n)=>SH[s];function Nu(s){return(e,t)=>{const n=t!=null&&t.context?String(t.context):"standalone";let a;if(n==="formatting"&&s.formattingValues){const o=s.defaultFormattingWidth||s.defaultWidth,l=t!=null&&t.width?String(t.width):o;a=s.formattingValues[l]||s.formattingValues[o]}else{const o=s.defaultWidth,l=t!=null&&t.width?String(t.width):s.defaultWidth;a=s.values[l]||s.values[o]}const i=s.argumentCallback?s.argumentCallback(e):e;return a[i]}}const CH={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},AH={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},NH={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},MH={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},TH={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},EH={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},_H=(s,e)=>{const t=Number(s),n=t%100;if(n>20||n<10)switch(n%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},DH={ordinalNumber:_H,era:Nu({values:CH,defaultWidth:"wide"}),quarter:Nu({values:AH,defaultWidth:"wide",argumentCallback:s=>s-1}),month:Nu({values:NH,defaultWidth:"wide"}),day:Nu({values:MH,defaultWidth:"wide"}),dayPeriod:Nu({values:TH,defaultWidth:"wide",formattingValues:EH,defaultFormattingWidth:"wide"})};function Mu(s){return(e,t={})=>{const n=t.width,a=n&&s.matchPatterns[n]||s.matchPatterns[s.defaultMatchWidth],i=e.match(a);if(!i)return null;const o=i[0],l=n&&s.parsePatterns[n]||s.parsePatterns[s.defaultParseWidth],c=Array.isArray(l)?PH(l,p=>p.test(o)):RH(l,p=>p.test(o));let d;d=s.valueCallback?s.valueCallback(c):c,d=t.valueCallback?t.valueCallback(d):d;const f=e.slice(o.length);return{value:d,rest:f}}}function RH(s,e){for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&e(s[t]))return t}function PH(s,e){for(let t=0;t<s.length;t++)if(e(s[t]))return t}function LH(s){return(e,t={})=>{const n=e.match(s.matchPattern);if(!n)return null;const a=n[0],i=e.match(s.parsePattern);if(!i)return null;let o=s.valueCallback?s.valueCallback(i[0]):i[0];o=t.valueCallback?t.valueCallback(o):o;const l=e.slice(a.length);return{value:o,rest:l}}}const OH=/^(\d+)(th|st|nd|rd)?/i,IH=/\d+/i,BH={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},zH={any:[/^b/i,/^(a|c)/i]},FH={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},$H={any:[/1/i,/2/i,/3/i,/4/i]},HH={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},UH={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},GH={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},WH={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},qH={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},YH={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},VH={ordinalNumber:LH({matchPattern:OH,parsePattern:IH,valueCallback:s=>parseInt(s,10)}),era:Mu({matchPatterns:BH,defaultMatchWidth:"wide",parsePatterns:zH,defaultParseWidth:"any"}),quarter:Mu({matchPatterns:FH,defaultMatchWidth:"wide",parsePatterns:$H,defaultParseWidth:"any",valueCallback:s=>s+1}),month:Mu({matchPatterns:HH,defaultMatchWidth:"wide",parsePatterns:UH,defaultParseWidth:"any"}),day:Mu({matchPatterns:GH,defaultMatchWidth:"wide",parsePatterns:WH,defaultParseWidth:"any"}),dayPeriod:Mu({matchPatterns:qH,defaultMatchWidth:"any",parsePatterns:YH,defaultParseWidth:"any"})},$T={code:"en-US",formatDistance:yH,formatLong:kH,formatRelative:jH,localize:DH,match:VH,options:{weekStartsOn:0,firstWeekContainsDate:1}};function KH(s,e){const t=yt(s,e==null?void 0:e.in);return pc(t,gf(t))+1}function Hx(s,e){const t=yt(s,e==null?void 0:e.in),n=+hc(t)-+hH(t);return Math.round(n/PT)+1}function Ux(s,e){var f,p,g,b;const t=yt(s,e==null?void 0:e.in),n=t.getFullYear(),a=al(),i=(e==null?void 0:e.firstWeekContainsDate)??((p=(f=e==null?void 0:e.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??a.firstWeekContainsDate??((b=(g=a.locale)==null?void 0:g.options)==null?void 0:b.firstWeekContainsDate)??1,o=wn((e==null?void 0:e.in)||s,0);o.setFullYear(n+1,0,i),o.setHours(0,0,0,0);const l=nr(o,e),c=wn((e==null?void 0:e.in)||s,0);c.setFullYear(n,0,i),c.setHours(0,0,0,0);const d=nr(c,e);return+t>=+l?n+1:+t>=+d?n:n-1}function XH(s,e){var l,c,d,f;const t=al(),n=(e==null?void 0:e.firstWeekContainsDate)??((c=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:c.firstWeekContainsDate)??t.firstWeekContainsDate??((f=(d=t.locale)==null?void 0:d.options)==null?void 0:f.firstWeekContainsDate)??1,a=Ux(s,e),i=wn((e==null?void 0:e.in)||s,0);return i.setFullYear(a,0,n),i.setHours(0,0,0,0),nr(i,e)}function HT(s,e){const t=yt(s,e==null?void 0:e.in),n=+nr(t,e)-+XH(t,e);return Math.round(n/PT)+1}function vn(s,e){const t=s<0?"-":"",n=Math.abs(s).toString().padStart(e,"0");return t+n}const Ir={y(s,e){const t=s.getFullYear(),n=t>0?t:1-t;return vn(e==="yy"?n%100:n,e.length)},M(s,e){const t=s.getMonth();return e==="M"?String(t+1):vn(t+1,2)},d(s,e){return vn(s.getDate(),e.length)},a(s,e){const t=s.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];case"aaaa":default:return t==="am"?"a.m.":"p.m."}},h(s,e){return vn(s.getHours()%12||12,e.length)},H(s,e){return vn(s.getHours(),e.length)},m(s,e){return vn(s.getMinutes(),e.length)},s(s,e){return vn(s.getSeconds(),e.length)},S(s,e){const t=e.length,n=s.getMilliseconds(),a=Math.trunc(n*Math.pow(10,t-3));return vn(a,e.length)}},Ul={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},a1={G:function(s,e,t){const n=s.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return t.era(n,{width:"abbreviated"});case"GGGGG":return t.era(n,{width:"narrow"});case"GGGG":default:return t.era(n,{width:"wide"})}},y:function(s,e,t){if(e==="yo"){const n=s.getFullYear(),a=n>0?n:1-n;return t.ordinalNumber(a,{unit:"year"})}return Ir.y(s,e)},Y:function(s,e,t,n){const a=Ux(s,n),i=a>0?a:1-a;if(e==="YY"){const o=i%100;return vn(o,2)}return e==="Yo"?t.ordinalNumber(i,{unit:"year"}):vn(i,e.length)},R:function(s,e){const t=OT(s);return vn(t,e.length)},u:function(s,e){const t=s.getFullYear();return vn(t,e.length)},Q:function(s,e,t){const n=Math.ceil((s.getMonth()+1)/3);switch(e){case"Q":return String(n);case"QQ":return vn(n,2);case"Qo":return t.ordinalNumber(n,{unit:"quarter"});case"QQQ":return t.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return t.quarter(n,{width:"wide",context:"formatting"})}},q:function(s,e,t){const n=Math.ceil((s.getMonth()+1)/3);switch(e){case"q":return String(n);case"qq":return vn(n,2);case"qo":return t.ordinalNumber(n,{unit:"quarter"});case"qqq":return t.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(n,{width:"wide",context:"standalone"})}},M:function(s,e,t){const n=s.getMonth();switch(e){case"M":case"MM":return Ir.M(s,e);case"Mo":return t.ordinalNumber(n+1,{unit:"month"});case"MMM":return t.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(n,{width:"wide",context:"formatting"})}},L:function(s,e,t){const n=s.getMonth();switch(e){case"L":return String(n+1);case"LL":return vn(n+1,2);case"Lo":return t.ordinalNumber(n+1,{unit:"month"});case"LLL":return t.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(n,{width:"wide",context:"standalone"})}},w:function(s,e,t,n){const a=HT(s,n);return e==="wo"?t.ordinalNumber(a,{unit:"week"}):vn(a,e.length)},I:function(s,e,t){const n=Hx(s);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):vn(n,e.length)},d:function(s,e,t){return e==="do"?t.ordinalNumber(s.getDate(),{unit:"date"}):Ir.d(s,e)},D:function(s,e,t){const n=KH(s);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):vn(n,e.length)},E:function(s,e,t){const n=s.getDay();switch(e){case"E":case"EE":case"EEE":return t.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(n,{width:"short",context:"formatting"});case"EEEE":default:return t.day(n,{width:"wide",context:"formatting"})}},e:function(s,e,t,n){const a=s.getDay(),i=(a-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(i);case"ee":return vn(i,2);case"eo":return t.ordinalNumber(i,{unit:"day"});case"eee":return t.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(a,{width:"short",context:"formatting"});case"eeee":default:return t.day(a,{width:"wide",context:"formatting"})}},c:function(s,e,t,n){const a=s.getDay(),i=(a-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(i);case"cc":return vn(i,e.length);case"co":return t.ordinalNumber(i,{unit:"day"});case"ccc":return t.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(a,{width:"narrow",context:"standalone"});case"cccccc":return t.day(a,{width:"short",context:"standalone"});case"cccc":default:return t.day(a,{width:"wide",context:"standalone"})}},i:function(s,e,t){const n=s.getDay(),a=n===0?7:n;switch(e){case"i":return String(a);case"ii":return vn(a,e.length);case"io":return t.ordinalNumber(a,{unit:"day"});case"iii":return t.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(n,{width:"short",context:"formatting"});case"iiii":default:return t.day(n,{width:"wide",context:"formatting"})}},a:function(s,e,t){const a=s.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return t.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(s,e,t){const n=s.getHours();let a;switch(n===12?a=Ul.noon:n===0?a=Ul.midnight:a=n/12>=1?"pm":"am",e){case"b":case"bb":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(a,{width:"narrow",context:"formatting"});case"bbbb":default:return t.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(s,e,t){const n=s.getHours();let a;switch(n>=17?a=Ul.evening:n>=12?a=Ul.afternoon:n>=4?a=Ul.morning:a=Ul.night,e){case"B":case"BB":case"BBB":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(a,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(s,e,t){if(e==="ho"){let n=s.getHours()%12;return n===0&&(n=12),t.ordinalNumber(n,{unit:"hour"})}return Ir.h(s,e)},H:function(s,e,t){return e==="Ho"?t.ordinalNumber(s.getHours(),{unit:"hour"}):Ir.H(s,e)},K:function(s,e,t){const n=s.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):vn(n,e.length)},k:function(s,e,t){let n=s.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):vn(n,e.length)},m:function(s,e,t){return e==="mo"?t.ordinalNumber(s.getMinutes(),{unit:"minute"}):Ir.m(s,e)},s:function(s,e,t){return e==="so"?t.ordinalNumber(s.getSeconds(),{unit:"second"}):Ir.s(s,e)},S:function(s,e){return Ir.S(s,e)},X:function(s,e,t){const n=s.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return r1(n);case"XXXX":case"XX":return Eo(n);case"XXXXX":case"XXX":default:return Eo(n,":")}},x:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"x":return r1(n);case"xxxx":case"xx":return Eo(n);case"xxxxx":case"xxx":default:return Eo(n,":")}},O:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+i1(n,":");case"OOOO":default:return"GMT"+Eo(n,":")}},z:function(s,e,t){const n=s.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+i1(n,":");case"zzzz":default:return"GMT"+Eo(n,":")}},t:function(s,e,t){const n=Math.trunc(+s/1e3);return vn(n,e.length)},T:function(s,e,t){return vn(+s,e.length)}};function i1(s,e=""){const t=s>0?"-":"+",n=Math.abs(s),a=Math.trunc(n/60),i=n%60;return i===0?t+String(a):t+String(a)+e+vn(i,2)}function r1(s,e){return s%60===0?(s>0?"-":"+")+vn(Math.abs(s)/60,2):Eo(s,e)}function Eo(s,e=""){const t=s>0?"-":"+",n=Math.abs(s),a=vn(Math.trunc(n/60),2),i=vn(n%60,2);return t+a+e+i}const o1=(s,e)=>{switch(s){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},UT=(s,e)=>{switch(s){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},ZH=(s,e)=>{const t=s.match(/(P+)(p+)?/)||[],n=t[1],a=t[2];if(!a)return o1(s,e);let i;switch(n){case"P":i=e.dateTime({width:"short"});break;case"PP":i=e.dateTime({width:"medium"});break;case"PPP":i=e.dateTime({width:"long"});break;case"PPPP":default:i=e.dateTime({width:"full"});break}return i.replace("{{date}}",o1(n,e)).replace("{{time}}",UT(a,e))},_y={p:UT,P:ZH},QH=/^D+$/,JH=/^Y+$/,eU=["D","DD","YY","YYYY"];function tU(s){return QH.test(s)}function nU(s){return JH.test(s)}function sU(s,e,t){const n=aU(s,e,t);if(console.warn(n),eU.includes(s))throw new RangeError(n)}function aU(s,e,t){const n=s[0]==="Y"?"years":"days of the month";return`Use \`${s.toLowerCase()}\` instead of \`${s}\` (in \`${e}\`) for formatting ${n} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const iU=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,rU=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,oU=/^'([^]*?)'?$/,lU=/''/g,cU=/[a-zA-Z]/;function l1(s,e,t){var f,p,g,b,y,w,k,S;const n=al(),a=(t==null?void 0:t.locale)??n.locale??$T,i=(t==null?void 0:t.firstWeekContainsDate)??((p=(f=t==null?void 0:t.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??n.firstWeekContainsDate??((b=(g=n.locale)==null?void 0:g.options)==null?void 0:b.firstWeekContainsDate)??1,o=(t==null?void 0:t.weekStartsOn)??((w=(y=t==null?void 0:t.locale)==null?void 0:y.options)==null?void 0:w.weekStartsOn)??n.weekStartsOn??((S=(k=n.locale)==null?void 0:k.options)==null?void 0:S.weekStartsOn)??0,l=yt(s,t==null?void 0:t.in);if(!fc(l))throw new RangeError("Invalid time value");let c=e.match(rU).map(j=>{const C=j[0];if(C==="p"||C==="P"){const N=_y[C];return N(j,a.formatLong)}return j}).join("").match(iU).map(j=>{if(j==="''")return{isToken:!1,value:"'"};const C=j[0];if(C==="'")return{isToken:!1,value:uU(j)};if(a1[C])return{isToken:!0,value:j};if(C.match(cU))throw new RangeError("Format string contains an unescaped latin alphabet character `"+C+"`");return{isToken:!1,value:j}});a.localize.preprocessor&&(c=a.localize.preprocessor(l,c));const d={firstWeekContainsDate:i,weekStartsOn:o,locale:a};return c.map(j=>{if(!j.isToken)return j.value;const C=j.value;(!(t!=null&&t.useAdditionalWeekYearTokens)&&nU(C)||!(t!=null&&t.useAdditionalDayOfYearTokens)&&tU(C))&&sU(C,e,String(s));const N=a1[C[0]];return N(l,C,a.localize,d)}).join("")}function uU(s){const e=s.match(oU);return e?e[1].replace(lU,"'"):s}function c1(s,e){return yt(s,e==null?void 0:e.in).getDate()}function dU(s,e){return yt(s,e==null?void 0:e.in).getDay()}function hU(s,e){const t=yt(s,e==null?void 0:e.in),n=t.getFullYear(),a=t.getMonth(),i=wn(t,0);return i.setFullYear(n,a+1,0),i.setHours(0,0,0,0),i.getDate()}function pU(){return Object.assign({},al())}function Ts(s,e){return yt(s,e==null?void 0:e.in).getHours()}function fU(s,e){const t=yt(s,e==null?void 0:e.in).getDay();return t===0?7:t}function Es(s,e){return yt(s,e==null?void 0:e.in).getMinutes()}function Js(s,e){return yt(s,e==null?void 0:e.in).getMonth()}function qr(s){return yt(s).getSeconds()}function Dy(s){return+yt(s)}function Kt(s,e){return yt(s,e==null?void 0:e.in).getFullYear()}function Ji(s,e){return+yt(s)>+yt(e)}function gi(s,e){return+yt(s)<+yt(e)}function mU(s,e){return+yt(s)==+yt(e)}function gU(s,e){const t=bU(e)?new e(0):wn(e,0);return t.setFullYear(s.getFullYear(),s.getMonth(),s.getDate()),t.setHours(s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()),t}function bU(s){var e;return typeof s=="function"&&((e=s.prototype)==null?void 0:e.constructor)===s}const yU=10;class GT{constructor(){G(this,"subPriority",0)}validate(e,t){return!0}}class xU extends GT{constructor(e,t,n,a,i){super(),this.value=e,this.validateValue=t,this.setValue=n,this.priority=a,i&&(this.subPriority=i)}validate(e,t){return this.validateValue(e,this.value,t)}set(e,t,n){return this.setValue(e,t,this.value,n)}}class vU extends GT{constructor(t,n){super();G(this,"priority",yU);G(this,"subPriority",-1);this.context=t||(a=>wn(n,a))}set(t,n){return n.timestampIsSet?t:wn(t,gU(t,this.context))}}class hn{run(e,t,n,a){const i=this.parse(e,t,n,a);return i?{setter:new xU(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(e,t,n){return!0}}class wU extends hn{constructor(){super(...arguments);G(this,"priority",140);G(this,"incompatibleTokens",["R","u","t","T"])}parse(t,n,a){switch(n){case"G":case"GG":case"GGG":return a.era(t,{width:"abbreviated"})||a.era(t,{width:"narrow"});case"GGGGG":return a.era(t,{width:"narrow"});case"GGGG":default:return a.era(t,{width:"wide"})||a.era(t,{width:"abbreviated"})||a.era(t,{width:"narrow"})}}set(t,n,a){return n.era=a,t.setFullYear(a,0,1),t.setHours(0,0,0,0),t}}const es={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},pi={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function ts(s,e){return s&&{value:e(s.value),rest:s.rest}}function Hn(s,e){const t=e.match(s);return t?{value:parseInt(t[0],10),rest:e.slice(t[0].length)}:null}function fi(s,e){const t=e.match(s);if(!t)return null;if(t[0]==="Z")return{value:0,rest:e.slice(1)};const n=t[1]==="+"?1:-1,a=t[2]?parseInt(t[2],10):0,i=t[3]?parseInt(t[3],10):0,o=t[5]?parseInt(t[5],10):0;return{value:n*(a*mf+i*ff+o*cH),rest:e.slice(t[0].length)}}function WT(s){return Hn(es.anyDigitsSigned,s)}function Vn(s,e){switch(s){case 1:return Hn(es.singleDigit,e);case 2:return Hn(es.twoDigits,e);case 3:return Hn(es.threeDigits,e);case 4:return Hn(es.fourDigits,e);default:return Hn(new RegExp("^\\d{1,"+s+"}"),e)}}function Op(s,e){switch(s){case 1:return Hn(es.singleDigitSigned,e);case 2:return Hn(es.twoDigitsSigned,e);case 3:return Hn(es.threeDigitsSigned,e);case 4:return Hn(es.fourDigitsSigned,e);default:return Hn(new RegExp("^-?\\d{1,"+s+"}"),e)}}function Gx(s){switch(s){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function qT(s,e){const t=e>0,n=t?e:1-e;let a;if(n<=50)a=s||100;else{const i=n+50,o=Math.trunc(i/100)*100,l=s>=i%100;a=s+o-(l?100:0)}return t?a:1-a}function YT(s){return s%400===0||s%4===0&&s%100!==0}class kU extends hn{constructor(){super(...arguments);G(this,"priority",130);G(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(t,n,a){const i=o=>({year:o,isTwoDigitYear:n==="yy"});switch(n){case"y":return ts(Vn(4,t),i);case"yo":return ts(a.ordinalNumber(t,{unit:"year"}),i);default:return ts(Vn(n.length,t),i)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,a){const i=t.getFullYear();if(a.isTwoDigitYear){const l=qT(a.year,i);return t.setFullYear(l,0,1),t.setHours(0,0,0,0),t}const o=!("era"in n)||n.era===1?a.year:1-a.year;return t.setFullYear(o,0,1),t.setHours(0,0,0,0),t}}class SU extends hn{constructor(){super(...arguments);G(this,"priority",130);G(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(t,n,a){const i=o=>({year:o,isTwoDigitYear:n==="YY"});switch(n){case"Y":return ts(Vn(4,t),i);case"Yo":return ts(a.ordinalNumber(t,{unit:"year"}),i);default:return ts(Vn(n.length,t),i)}}validate(t,n){return n.isTwoDigitYear||n.year>0}set(t,n,a,i){const o=Ux(t,i);if(a.isTwoDigitYear){const c=qT(a.year,o);return t.setFullYear(c,0,i.firstWeekContainsDate),t.setHours(0,0,0,0),nr(t,i)}const l=!("era"in n)||n.era===1?a.year:1-a.year;return t.setFullYear(l,0,i.firstWeekContainsDate),t.setHours(0,0,0,0),nr(t,i)}}class jU extends hn{constructor(){super(...arguments);G(this,"priority",130);G(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(t,n){return Op(n==="R"?4:n.length,t)}set(t,n,a){const i=wn(t,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),hc(i)}}class CU extends hn{constructor(){super(...arguments);G(this,"priority",130);G(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(t,n){return Op(n==="u"?4:n.length,t)}set(t,n,a){return t.setFullYear(a,0,1),t.setHours(0,0,0,0),t}}class AU extends hn{constructor(){super(...arguments);G(this,"priority",120);G(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(t,n,a){switch(n){case"Q":case"QQ":return Vn(n.length,t);case"Qo":return a.ordinalNumber(t,{unit:"quarter"});case"QQQ":return a.quarter(t,{width:"abbreviated",context:"formatting"})||a.quarter(t,{width:"narrow",context:"formatting"});case"QQQQQ":return a.quarter(t,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(t,{width:"wide",context:"formatting"})||a.quarter(t,{width:"abbreviated",context:"formatting"})||a.quarter(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=1&&n<=4}set(t,n,a){return t.setMonth((a-1)*3,1),t.setHours(0,0,0,0),t}}class NU extends hn{constructor(){super(...arguments);G(this,"priority",120);G(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(t,n,a){switch(n){case"q":case"qq":return Vn(n.length,t);case"qo":return a.ordinalNumber(t,{unit:"quarter"});case"qqq":return a.quarter(t,{width:"abbreviated",context:"standalone"})||a.quarter(t,{width:"narrow",context:"standalone"});case"qqqqq":return a.quarter(t,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(t,{width:"wide",context:"standalone"})||a.quarter(t,{width:"abbreviated",context:"standalone"})||a.quarter(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=1&&n<=4}set(t,n,a){return t.setMonth((a-1)*3,1),t.setHours(0,0,0,0),t}}class MU extends hn{constructor(){super(...arguments);G(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);G(this,"priority",110)}parse(t,n,a){const i=o=>o-1;switch(n){case"M":return ts(Hn(es.month,t),i);case"MM":return ts(Vn(2,t),i);case"Mo":return ts(a.ordinalNumber(t,{unit:"month"}),i);case"MMM":return a.month(t,{width:"abbreviated",context:"formatting"})||a.month(t,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(t,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(t,{width:"wide",context:"formatting"})||a.month(t,{width:"abbreviated",context:"formatting"})||a.month(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=11}set(t,n,a){return t.setMonth(a,1),t.setHours(0,0,0,0),t}}class TU extends hn{constructor(){super(...arguments);G(this,"priority",110);G(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(t,n,a){const i=o=>o-1;switch(n){case"L":return ts(Hn(es.month,t),i);case"LL":return ts(Vn(2,t),i);case"Lo":return ts(a.ordinalNumber(t,{unit:"month"}),i);case"LLL":return a.month(t,{width:"abbreviated",context:"standalone"})||a.month(t,{width:"narrow",context:"standalone"});case"LLLLL":return a.month(t,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(t,{width:"wide",context:"standalone"})||a.month(t,{width:"abbreviated",context:"standalone"})||a.month(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=0&&n<=11}set(t,n,a){return t.setMonth(a,1),t.setHours(0,0,0,0),t}}function EU(s,e,t){const n=yt(s,t==null?void 0:t.in),a=HT(n,t)-e;return n.setDate(n.getDate()-a*7),yt(n,t==null?void 0:t.in)}class _U extends hn{constructor(){super(...arguments);G(this,"priority",100);G(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(t,n,a){switch(n){case"w":return Hn(es.week,t);case"wo":return a.ordinalNumber(t,{unit:"week"});default:return Vn(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,a,i){return nr(EU(t,a,i),i)}}function DU(s,e,t){const n=yt(s,t==null?void 0:t.in),a=Hx(n,t)-e;return n.setDate(n.getDate()-a*7),n}class RU extends hn{constructor(){super(...arguments);G(this,"priority",100);G(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(t,n,a){switch(n){case"I":return Hn(es.week,t);case"Io":return a.ordinalNumber(t,{unit:"week"});default:return Vn(n.length,t)}}validate(t,n){return n>=1&&n<=53}set(t,n,a){return hc(DU(t,a))}}const PU=[31,28,31,30,31,30,31,31,30,31,30,31],LU=[31,29,31,30,31,30,31,31,30,31,30,31];class OU extends hn{constructor(){super(...arguments);G(this,"priority",90);G(this,"subPriority",1);G(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(t,n,a){switch(n){case"d":return Hn(es.date,t);case"do":return a.ordinalNumber(t,{unit:"date"});default:return Vn(n.length,t)}}validate(t,n){const a=t.getFullYear(),i=YT(a),o=t.getMonth();return i?n>=1&&n<=LU[o]:n>=1&&n<=PU[o]}set(t,n,a){return t.setDate(a),t.setHours(0,0,0,0),t}}class IU extends hn{constructor(){super(...arguments);G(this,"priority",90);G(this,"subpriority",1);G(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(t,n,a){switch(n){case"D":case"DD":return Hn(es.dayOfYear,t);case"Do":return a.ordinalNumber(t,{unit:"date"});default:return Vn(n.length,t)}}validate(t,n){const a=t.getFullYear();return YT(a)?n>=1&&n<=366:n>=1&&n<=365}set(t,n,a){return t.setMonth(0,a),t.setHours(0,0,0,0),t}}function Wx(s,e,t){var p,g,b,y;const n=al(),a=(t==null?void 0:t.weekStartsOn)??((g=(p=t==null?void 0:t.locale)==null?void 0:p.options)==null?void 0:g.weekStartsOn)??n.weekStartsOn??((y=(b=n.locale)==null?void 0:b.options)==null?void 0:y.weekStartsOn)??0,i=yt(s,t==null?void 0:t.in),o=i.getDay(),c=(e%7+7)%7,d=7-a,f=e<0||e>6?e-(o+d)%7:(c+d)%7-(o+d)%7;return Xa(i,f,t)}class BU extends hn{constructor(){super(...arguments);G(this,"priority",90);G(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(t,n,a){switch(n){case"E":case"EE":case"EEE":return a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(t,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=6}set(t,n,a,i){return t=Wx(t,a,i),t.setHours(0,0,0,0),t}}class zU extends hn{constructor(){super(...arguments);G(this,"priority",90);G(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(t,n,a,i){const o=l=>{const c=Math.floor((l-1)/7)*7;return(l+i.weekStartsOn+6)%7+c};switch(n){case"e":case"ee":return ts(Vn(n.length,t),o);case"eo":return ts(a.ordinalNumber(t,{unit:"day"}),o);case"eee":return a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"eeeee":return a.day(t,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"});case"eeee":default:return a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"})}}validate(t,n){return n>=0&&n<=6}set(t,n,a,i){return t=Wx(t,a,i),t.setHours(0,0,0,0),t}}class FU extends hn{constructor(){super(...arguments);G(this,"priority",90);G(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(t,n,a,i){const o=l=>{const c=Math.floor((l-1)/7)*7;return(l+i.weekStartsOn+6)%7+c};switch(n){case"c":case"cc":return ts(Vn(n.length,t),o);case"co":return ts(a.ordinalNumber(t,{unit:"day"}),o);case"ccc":return a.day(t,{width:"abbreviated",context:"standalone"})||a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"});case"ccccc":return a.day(t,{width:"narrow",context:"standalone"});case"cccccc":return a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"});case"cccc":default:return a.day(t,{width:"wide",context:"standalone"})||a.day(t,{width:"abbreviated",context:"standalone"})||a.day(t,{width:"short",context:"standalone"})||a.day(t,{width:"narrow",context:"standalone"})}}validate(t,n){return n>=0&&n<=6}set(t,n,a,i){return t=Wx(t,a,i),t.setHours(0,0,0,0),t}}function $U(s,e,t){const n=yt(s,t==null?void 0:t.in),a=fU(n,t),i=e-a;return Xa(n,i,t)}class HU extends hn{constructor(){super(...arguments);G(this,"priority",90);G(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(t,n,a){const i=o=>o===0?7:o;switch(n){case"i":case"ii":return Vn(n.length,t);case"io":return a.ordinalNumber(t,{unit:"day"});case"iii":return ts(a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),i);case"iiiii":return ts(a.day(t,{width:"narrow",context:"formatting"}),i);case"iiiiii":return ts(a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),i);case"iiii":default:return ts(a.day(t,{width:"wide",context:"formatting"})||a.day(t,{width:"abbreviated",context:"formatting"})||a.day(t,{width:"short",context:"formatting"})||a.day(t,{width:"narrow",context:"formatting"}),i)}}validate(t,n){return n>=1&&n<=7}set(t,n,a){return t=$U(t,a),t.setHours(0,0,0,0),t}}class UU extends hn{constructor(){super(...arguments);G(this,"priority",80);G(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(t,n,a){switch(n){case"a":case"aa":case"aaa":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,a){return t.setHours(Gx(a),0,0,0),t}}class GU extends hn{constructor(){super(...arguments);G(this,"priority",80);G(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(t,n,a){switch(n){case"b":case"bb":case"bbb":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,a){return t.setHours(Gx(a),0,0,0),t}}class WU extends hn{constructor(){super(...arguments);G(this,"priority",80);G(this,"incompatibleTokens",["a","b","t","T"])}parse(t,n,a){switch(n){case"B":case"BB":case"BBB":return a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(t,{width:"wide",context:"formatting"})||a.dayPeriod(t,{width:"abbreviated",context:"formatting"})||a.dayPeriod(t,{width:"narrow",context:"formatting"})}}set(t,n,a){return t.setHours(Gx(a),0,0,0),t}}class qU extends hn{constructor(){super(...arguments);G(this,"priority",70);G(this,"incompatibleTokens",["H","K","k","t","T"])}parse(t,n,a){switch(n){case"h":return Hn(es.hour12h,t);case"ho":return a.ordinalNumber(t,{unit:"hour"});default:return Vn(n.length,t)}}validate(t,n){return n>=1&&n<=12}set(t,n,a){const i=t.getHours()>=12;return i&&a<12?t.setHours(a+12,0,0,0):!i&&a===12?t.setHours(0,0,0,0):t.setHours(a,0,0,0),t}}class YU extends hn{constructor(){super(...arguments);G(this,"priority",70);G(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(t,n,a){switch(n){case"H":return Hn(es.hour23h,t);case"Ho":return a.ordinalNumber(t,{unit:"hour"});default:return Vn(n.length,t)}}validate(t,n){return n>=0&&n<=23}set(t,n,a){return t.setHours(a,0,0,0),t}}class VU extends hn{constructor(){super(...arguments);G(this,"priority",70);G(this,"incompatibleTokens",["h","H","k","t","T"])}parse(t,n,a){switch(n){case"K":return Hn(es.hour11h,t);case"Ko":return a.ordinalNumber(t,{unit:"hour"});default:return Vn(n.length,t)}}validate(t,n){return n>=0&&n<=11}set(t,n,a){return t.getHours()>=12&&a<12?t.setHours(a+12,0,0,0):t.setHours(a,0,0,0),t}}class KU extends hn{constructor(){super(...arguments);G(this,"priority",70);G(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(t,n,a){switch(n){case"k":return Hn(es.hour24h,t);case"ko":return a.ordinalNumber(t,{unit:"hour"});default:return Vn(n.length,t)}}validate(t,n){return n>=1&&n<=24}set(t,n,a){const i=a<=24?a%24:a;return t.setHours(i,0,0,0),t}}class XU extends hn{constructor(){super(...arguments);G(this,"priority",60);G(this,"incompatibleTokens",["t","T"])}parse(t,n,a){switch(n){case"m":return Hn(es.minute,t);case"mo":return a.ordinalNumber(t,{unit:"minute"});default:return Vn(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,a){return t.setMinutes(a,0,0),t}}class ZU extends hn{constructor(){super(...arguments);G(this,"priority",50);G(this,"incompatibleTokens",["t","T"])}parse(t,n,a){switch(n){case"s":return Hn(es.second,t);case"so":return a.ordinalNumber(t,{unit:"second"});default:return Vn(n.length,t)}}validate(t,n){return n>=0&&n<=59}set(t,n,a){return t.setSeconds(a,0),t}}class QU extends hn{constructor(){super(...arguments);G(this,"priority",30);G(this,"incompatibleTokens",["t","T"])}parse(t,n){const a=i=>Math.trunc(i*Math.pow(10,-n.length+3));return ts(Vn(n.length,t),a)}set(t,n,a){return t.setMilliseconds(a),t}}class JU extends hn{constructor(){super(...arguments);G(this,"priority",10);G(this,"incompatibleTokens",["t","T","x"])}parse(t,n){switch(n){case"X":return fi(pi.basicOptionalMinutes,t);case"XX":return fi(pi.basic,t);case"XXXX":return fi(pi.basicOptionalSeconds,t);case"XXXXX":return fi(pi.extendedOptionalSeconds,t);case"XXX":default:return fi(pi.extended,t)}}set(t,n,a){return n.timestampIsSet?t:wn(t,t.getTime()-_p(t)-a)}}class eG extends hn{constructor(){super(...arguments);G(this,"priority",10);G(this,"incompatibleTokens",["t","T","X"])}parse(t,n){switch(n){case"x":return fi(pi.basicOptionalMinutes,t);case"xx":return fi(pi.basic,t);case"xxxx":return fi(pi.basicOptionalSeconds,t);case"xxxxx":return fi(pi.extendedOptionalSeconds,t);case"xxx":default:return fi(pi.extended,t)}}set(t,n,a){return n.timestampIsSet?t:wn(t,t.getTime()-_p(t)-a)}}class tG extends hn{constructor(){super(...arguments);G(this,"priority",40);G(this,"incompatibleTokens","*")}parse(t){return WT(t)}set(t,n,a){return[wn(t,a*1e3),{timestampIsSet:!0}]}}class nG extends hn{constructor(){super(...arguments);G(this,"priority",20);G(this,"incompatibleTokens","*")}parse(t){return WT(t)}set(t,n,a){return[wn(t,a),{timestampIsSet:!0}]}}const sG={G:new wU,y:new kU,Y:new SU,R:new jU,u:new CU,Q:new AU,q:new NU,M:new MU,L:new TU,w:new _U,I:new RU,d:new OU,D:new IU,E:new BU,e:new zU,c:new FU,i:new HU,a:new UU,b:new GU,B:new WU,h:new qU,H:new YU,K:new VU,k:new KU,m:new XU,s:new ZU,S:new QU,X:new JU,x:new eG,t:new tG,T:new nG},aG=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,iG=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,rG=/^'([^]*?)'?$/,oG=/''/g,lG=/\S/,cG=/[a-zA-Z]/;function uG(s,e,t,n){var k,S,j,C,N,D,E,$;const a=()=>wn((n==null?void 0:n.in)||t,NaN),i=pU(),o=(n==null?void 0:n.locale)??i.locale??$T,l=(n==null?void 0:n.firstWeekContainsDate)??((S=(k=n==null?void 0:n.locale)==null?void 0:k.options)==null?void 0:S.firstWeekContainsDate)??i.firstWeekContainsDate??((C=(j=i.locale)==null?void 0:j.options)==null?void 0:C.firstWeekContainsDate)??1,c=(n==null?void 0:n.weekStartsOn)??((D=(N=n==null?void 0:n.locale)==null?void 0:N.options)==null?void 0:D.weekStartsOn)??i.weekStartsOn??(($=(E=i.locale)==null?void 0:E.options)==null?void 0:$.weekStartsOn)??0;if(!e)return s?a():yt(t,n==null?void 0:n.in);const d={firstWeekContainsDate:l,weekStartsOn:c,locale:o},f=[new vU(n==null?void 0:n.in,t)],p=e.match(iG).map(M=>{const R=M[0];if(R in _y){const _=_y[R];return _(M,o.formatLong)}return M}).join("").match(aG),g=[];for(let M of p){const R=M[0],_=sG[R];if(_){const{incompatibleTokens:P}=_;if(Array.isArray(P)){const F=g.find(B=>P.includes(B.token)||B.token===R);if(F)throw new RangeError(`The format string mustn't contain \`${F.fullToken}\` and \`${M}\` at the same time`)}else if(_.incompatibleTokens==="*"&&g.length>0)throw new RangeError(`The format string mustn't contain \`${M}\` and any other token at the same time`);g.push({token:R,fullToken:M});const O=_.run(s,M,o.match,d);if(!O)return a();f.push(O.setter),s=O.rest}else{if(R.match(cG))throw new RangeError("Format string contains an unescaped latin alphabet character `"+R+"`");if(M==="''"?M="'":R==="'"&&(M=dG(M)),s.indexOf(M)===0)s=s.slice(M.length);else return a()}}if(s.length>0&&lG.test(s))return a();const b=f.map(M=>M.priority).sort((M,R)=>R-M).filter((M,R,_)=>_.indexOf(M)===R).map(M=>f.filter(R=>R.priority===M).sort((R,_)=>_.subPriority-R.subPriority)).map(M=>M[0]);let y=yt(t,n==null?void 0:n.in);if(isNaN(+y))return a();const w={};for(const M of b){if(!M.validate(y,d))return a();const R=M.set(y,w,d);Array.isArray(R)?(y=R[0],Object.assign(w,R[1])):y=R}return y}function dG(s){return s.match(rG)[1].replace(oG,"'")}function hG(s,e,t){const[n,a]=or(t==null?void 0:t.in,s,e);return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()}function pG(s,e,t){const[n,a]=or(t==null?void 0:t.in,s,e);return+Ey(n)==+Ey(a)}function fG(s,e,t){const[n,a]=or(t==null?void 0:t.in,s,e);return n.getFullYear()===a.getFullYear()}function rd(s,e,t){const n=+yt(s,t==null?void 0:t.in),[a,i]=[+yt(e.start,t==null?void 0:t.in),+yt(e.end,t==null?void 0:t.in)].sort((o,l)=>o-l);return n>=a&&n<=i}function mG(s,e,t){return Xa(s,-1,t)}function gG(s,e){const t=()=>wn(e==null?void 0:e.in,NaN),a=vG(s);let i;if(a.date){const d=wG(a.date,2);i=kG(d.restDateString,d.year)}if(!i||isNaN(+i))return t();const o=+i;let l=0,c;if(a.time&&(l=SG(a.time),isNaN(l)))return t();if(a.timezone){if(c=jG(a.timezone),isNaN(c))return t()}else{const d=new Date(o+l),f=yt(0,e==null?void 0:e.in);return f.setFullYear(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()),f.setHours(d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds()),f}return yt(o+l+c,e==null?void 0:e.in)}const $h={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},bG=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,yG=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,xG=/^([+-])(\d{2})(?::?(\d{2}))?$/;function vG(s){const e={},t=s.split($h.dateTimeDelimiter);let n;if(t.length>2)return e;if(/:/.test(t[0])?n=t[0]:(e.date=t[0],n=t[1],$h.timeZoneDelimiter.test(e.date)&&(e.date=s.split($h.timeZoneDelimiter)[0],n=s.substr(e.date.length,s.length))),n){const a=$h.timezone.exec(n);a?(e.time=n.replace(a[1],""),e.timezone=a[1]):e.time=n}return e}function wG(s,e){const t=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+e)+"})|(\\d{2}|[+-]\\d{"+(2+e)+"})$)"),n=s.match(t);if(!n)return{year:NaN,restDateString:""};const a=n[1]?parseInt(n[1]):null,i=n[2]?parseInt(n[2]):null;return{year:i===null?a:i*100,restDateString:s.slice((n[1]||n[2]).length)}}function kG(s,e){if(e===null)return new Date(NaN);const t=s.match(bG);if(!t)return new Date(NaN);const n=!!t[4],a=Tu(t[1]),i=Tu(t[2])-1,o=Tu(t[3]),l=Tu(t[4]),c=Tu(t[5])-1;if(n)return TG(e,l,c)?CG(e,l,c):new Date(NaN);{const d=new Date(0);return!NG(e,i,o)||!MG(e,a)?new Date(NaN):(d.setUTCFullYear(e,i,Math.max(a,o)),d)}}function Tu(s){return s?parseInt(s):1}function SG(s){const e=s.match(yG);if(!e)return NaN;const t=wb(e[1]),n=wb(e[2]),a=wb(e[3]);return EG(t,n,a)?t*mf+n*ff+a*1e3:NaN}function wb(s){return s&&parseFloat(s.replace(",","."))||0}function jG(s){if(s==="Z")return 0;const e=s.match(xG);if(!e)return 0;const t=e[1]==="+"?-1:1,n=parseInt(e[2]),a=e[3]&&parseInt(e[3])||0;return _G(n,a)?t*(n*mf+a*ff):NaN}function CG(s,e,t){const n=new Date(0);n.setUTCFullYear(s,0,4);const a=n.getUTCDay()||7,i=(e-1)*7+t+1-a;return n.setUTCDate(n.getUTCDate()+i),n}const AG=[31,null,31,30,31,30,31,31,30,31,30,31];function VT(s){return s%400===0||s%4===0&&s%100!==0}function NG(s,e,t){return e>=0&&e<=11&&t>=1&&t<=(AG[e]||(VT(s)?29:28))}function MG(s,e){return e>=1&&e<=(VT(s)?366:365)}function TG(s,e,t){return e>=1&&e<=53&&t>=0&&t<=6}function EG(s,e,t){return s===24?e===0&&t===0:t>=0&&t<60&&e>=0&&e<60&&s>=0&&s<25}function _G(s,e){return e>=0&&e<=59}function pa(s,e,t){const n=yt(s,t==null?void 0:t.in),a=n.getFullYear(),i=n.getDate(),o=wn(s,0);o.setFullYear(a,e,15),o.setHours(0,0,0,0);const l=hU(o);return n.setMonth(e,Math.min(i,l)),n}function tp(s,e,t){const n=yt(s,t==null?void 0:t.in);return n.setHours(e),n}function np(s,e,t){const n=yt(s,t==null?void 0:t.in);return n.setMinutes(e),n}function Kl(s,e,t){const n=yt(s,t==null?void 0:t.in),a=Math.trunc(n.getMonth()/3)+1,i=e-a;return pa(n,n.getMonth()+i*3)}function sp(s,e,t){const n=yt(s,t==null?void 0:t.in);return n.setSeconds(e),n}function ui(s,e,t){const n=yt(s,t==null?void 0:t.in);return isNaN(+n)?wn(s,NaN):(n.setFullYear(e),n)}function Ho(s,e,t){return Qa(s,-e,t)}function KT(s,e,t){return $x(s,-1,t)}function u1(s,e,t){return Dp(s,-1,t)}function Jr(s,e,t){return Za(s,-e,t)}function bf(){return typeof window<"u"}function jc(s){return XT(s)?(s.nodeName||"").toLowerCase():"#document"}function ga(s){var e;return(s==null||(e=s.ownerDocument)==null?void 0:e.defaultView)||window}function Mi(s){var e;return(e=(XT(s)?s.ownerDocument:s.document)||window.document)==null?void 0:e.documentElement}function XT(s){return bf()?s instanceof Node||s instanceof ga(s).Node:!1}function Fs(s){return bf()?s instanceof Element||s instanceof ga(s).Element:!1}function ji(s){return bf()?s instanceof HTMLElement||s instanceof ga(s).HTMLElement:!1}function d1(s){return!bf()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof ga(s).ShadowRoot}const DG=new Set(["inline","contents"]);function fd(s){const{overflow:e,overflowX:t,overflowY:n,display:a}=Ia(s);return/auto|scroll|overlay|hidden|clip/.test(e+n+t)&&!DG.has(a)}const RG=new Set(["table","td","th"]);function PG(s){return RG.has(jc(s))}const LG=[":popover-open",":modal"];function yf(s){return LG.some(e=>{try{return s.matches(e)}catch{return!1}})}const OG=["transform","translate","scale","rotate","perspective"],IG=["transform","translate","scale","rotate","perspective","filter"],BG=["paint","layout","strict","content"];function qx(s){const e=Yx(),t=Fs(s)?Ia(s):s;return OG.some(n=>t[n]?t[n]!=="none":!1)||(t.containerType?t.containerType!=="normal":!1)||!e&&(t.backdropFilter?t.backdropFilter!=="none":!1)||!e&&(t.filter?t.filter!=="none":!1)||IG.some(n=>(t.willChange||"").includes(n))||BG.some(n=>(t.contain||"").includes(n))}function zG(s){let e=eo(s);for(;ji(e)&&!mc(e);){if(qx(e))return e;if(yf(e))return null;e=eo(e)}return null}function Yx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const FG=new Set(["html","body","#document"]);function mc(s){return FG.has(jc(s))}function Ia(s){return ga(s).getComputedStyle(s)}function xf(s){return Fs(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function eo(s){if(jc(s)==="html")return s;const e=s.assignedSlot||s.parentNode||d1(s)&&s.host||Mi(s);return d1(e)?e.host:e}function ZT(s){const e=eo(s);return mc(e)?s.ownerDocument?s.ownerDocument.body:s.body:ji(e)&&fd(e)?e:ZT(e)}function od(s,e,t){var n;e===void 0&&(e=[]),t===void 0&&(t=!0);const a=ZT(s),i=a===((n=s.ownerDocument)==null?void 0:n.body),o=ga(a);if(i){const l=Ry(o);return e.concat(o,o.visualViewport||[],fd(a)?a:[],l&&t?od(l):[])}return e.concat(a,od(a,[],t))}function Ry(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}const gc=Math.min,Uo=Math.max,Ip=Math.round,Hh=Math.floor,ki=s=>({x:s,y:s}),$G={left:"right",right:"left",bottom:"top",top:"bottom"},HG={start:"end",end:"start"};function UG(s,e,t){return Uo(s,gc(e,t))}function vf(s,e){return typeof s=="function"?s(e):s}function bc(s){return s.split("-")[0]}function md(s){return s.split("-")[1]}function GG(s){return s==="x"?"y":"x"}function Vx(s){return s==="y"?"height":"width"}const WG=new Set(["top","bottom"]);function Lo(s){return WG.has(bc(s))?"y":"x"}function Kx(s){return GG(Lo(s))}function qG(s,e,t){t===void 0&&(t=!1);const n=md(s),a=Kx(s),i=Vx(a);let o=a==="x"?n===(t?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[i]>e.floating[i]&&(o=Bp(o)),[o,Bp(o)]}function YG(s){const e=Bp(s);return[Py(s),e,Py(e)]}function Py(s){return s.replace(/start|end/g,e=>HG[e])}const h1=["left","right"],p1=["right","left"],VG=["top","bottom"],KG=["bottom","top"];function XG(s,e,t){switch(s){case"top":case"bottom":return t?e?p1:h1:e?h1:p1;case"left":case"right":return e?VG:KG;default:return[]}}function ZG(s,e,t,n){const a=md(s);let i=XG(bc(s),t==="start",n);return a&&(i=i.map(o=>o+"-"+a),e&&(i=i.concat(i.map(Py)))),i}function Bp(s){return s.replace(/left|right|bottom|top/g,e=>$G[e])}function QG(s){return{top:0,right:0,bottom:0,left:0,...s}}function QT(s){return typeof s!="number"?QG(s):{top:s,right:s,bottom:s,left:s}}function zp(s){const{x:e,y:t,width:n,height:a}=s;return{width:n,height:a,top:t,left:e,right:e+n,bottom:t+a,x:e,y:t}}var JG=typeof document<"u",e7=function(){},Fp=JG?x.useLayoutEffect:e7;const t7={...ZA},n7=t7.useInsertionEffect,s7=n7||(s=>s());function a7(s){const e=x.useRef(()=>{});return s7(()=>{e.current=s}),x.useCallback(function(){for(var t=arguments.length,n=new Array(t),a=0;a<t;a++)n[a]=arguments[a];return e.current==null?void 0:e.current(...n)},[])}function f1(s,e,t){let{reference:n,floating:a}=s;const i=Lo(e),o=Kx(e),l=Vx(o),c=bc(e),d=i==="y",f=n.x+n.width/2-a.width/2,p=n.y+n.height/2-a.height/2,g=n[l]/2-a[l]/2;let b;switch(c){case"top":b={x:f,y:n.y-a.height};break;case"bottom":b={x:f,y:n.y+n.height};break;case"right":b={x:n.x+n.width,y:p};break;case"left":b={x:n.x-a.width,y:p};break;default:b={x:n.x,y:n.y}}switch(md(e)){case"start":b[o]-=g*(t&&d?-1:1);break;case"end":b[o]+=g*(t&&d?-1:1);break}return b}async function i7(s,e){var t;e===void 0&&(e={});const{x:n,y:a,platform:i,rects:o,elements:l,strategy:c}=s,{boundary:d="clippingAncestors",rootBoundary:f="viewport",elementContext:p="floating",altBoundary:g=!1,padding:b=0}=vf(e,s),y=QT(b),k=l[g?p==="floating"?"reference":"floating":p],S=zp(await i.getClippingRect({element:(t=await(i.isElement==null?void 0:i.isElement(k)))==null||t?k:k.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(l.floating)),boundary:d,rootBoundary:f,strategy:c})),j=p==="floating"?{x:n,y:a,width:o.floating.width,height:o.floating.height}:o.reference,C=await(i.getOffsetParent==null?void 0:i.getOffsetParent(l.floating)),N=await(i.isElement==null?void 0:i.isElement(C))?await(i.getScale==null?void 0:i.getScale(C))||{x:1,y:1}:{x:1,y:1},D=zp(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:j,offsetParent:C,strategy:c}):j);return{top:(S.top-D.top+y.top)/N.y,bottom:(D.bottom-S.bottom+y.bottom)/N.y,left:(S.left-D.left+y.left)/N.x,right:(D.right-S.right+y.right)/N.x}}const r7=async(s,e,t)=>{const{placement:n="bottom",strategy:a="absolute",middleware:i=[],platform:o}=t,l=i.filter(Boolean),c=await(o.isRTL==null?void 0:o.isRTL(e));let d=await o.getElementRects({reference:s,floating:e,strategy:a}),{x:f,y:p}=f1(d,n,c),g=n,b={},y=0;for(let k=0;k<l.length;k++){var w;const{name:S,fn:j}=l[k],{x:C,y:N,data:D,reset:E}=await j({x:f,y:p,initialPlacement:n,placement:g,strategy:a,middlewareData:b,rects:d,platform:{...o,detectOverflow:(w=o.detectOverflow)!=null?w:i7},elements:{reference:s,floating:e}});f=C??f,p=N??p,b={...b,[S]:{...b[S],...D}},E&&y<=50&&(y++,typeof E=="object"&&(E.placement&&(g=E.placement),E.rects&&(d=E.rects===!0?await o.getElementRects({reference:s,floating:e,strategy:a}):E.rects),{x:f,y:p}=f1(d,g,c)),k=-1)}return{x:f,y:p,placement:g,strategy:a,middlewareData:b}},o7=s=>({name:"arrow",options:s,async fn(e){const{x:t,y:n,placement:a,rects:i,platform:o,elements:l,middlewareData:c}=e,{element:d,padding:f=0}=vf(s,e)||{};if(d==null)return{};const p=QT(f),g={x:t,y:n},b=Kx(a),y=Vx(b),w=await o.getDimensions(d),k=b==="y",S=k?"top":"left",j=k?"bottom":"right",C=k?"clientHeight":"clientWidth",N=i.reference[y]+i.reference[b]-g[b]-i.floating[y],D=g[b]-i.reference[b],E=await(o.getOffsetParent==null?void 0:o.getOffsetParent(d));let $=E?E[C]:0;(!$||!await(o.isElement==null?void 0:o.isElement(E)))&&($=l.floating[C]||i.floating[y]);const M=N/2-D/2,R=$/2-w[y]/2-1,_=gc(p[S],R),P=gc(p[j],R),O=_,F=$-w[y]-P,B=$/2-w[y]/2+M,I=UG(O,B,F),U=!c.arrow&&md(a)!=null&&B!==I&&i.reference[y]/2-(B<O?_:P)-w[y]/2<0,q=U?B<O?B-O:B-F:0;return{[b]:g[b]+q,data:{[b]:I,centerOffset:B-I-q,...U&&{alignmentOffset:q}},reset:U}}}),l7=function(s){return s===void 0&&(s={}),{name:"flip",options:s,async fn(e){var t,n;const{placement:a,middlewareData:i,rects:o,initialPlacement:l,platform:c,elements:d}=e,{mainAxis:f=!0,crossAxis:p=!0,fallbackPlacements:g,fallbackStrategy:b="bestFit",fallbackAxisSideDirection:y="none",flipAlignment:w=!0,...k}=vf(s,e);if((t=i.arrow)!=null&&t.alignmentOffset)return{};const S=bc(a),j=Lo(l),C=bc(l)===l,N=await(c.isRTL==null?void 0:c.isRTL(d.floating)),D=g||(C||!w?[Bp(l)]:YG(l)),E=y!=="none";!g&&E&&D.push(...ZG(l,w,y,N));const $=[l,...D],M=await c.detectOverflow(e,k),R=[];let _=((n=i.flip)==null?void 0:n.overflows)||[];if(f&&R.push(M[S]),p){const B=qG(a,o,N);R.push(M[B[0]],M[B[1]])}if(_=[..._,{placement:a,overflows:R}],!R.every(B=>B<=0)){var P,O;const B=(((P=i.flip)==null?void 0:P.index)||0)+1,I=$[B];if(I&&(!(p==="alignment"?j!==Lo(I):!1)||_.every(K=>Lo(K.placement)===j?K.overflows[0]>0:!0)))return{data:{index:B,overflows:_},reset:{placement:I}};let U=(O=_.filter(q=>q.overflows[0]<=0).sort((q,K)=>q.overflows[1]-K.overflows[1])[0])==null?void 0:O.placement;if(!U)switch(b){case"bestFit":{var F;const q=(F=_.filter(K=>{if(E){const X=Lo(K.placement);return X===j||X==="y"}return!0}).map(K=>[K.placement,K.overflows.filter(X=>X>0).reduce((X,L)=>X+L,0)]).sort((K,X)=>K[1]-X[1])[0])==null?void 0:F[0];q&&(U=q);break}case"initialPlacement":U=l;break}if(a!==U)return{reset:{placement:U}}}return{}}}},c7=new Set(["left","top"]);async function u7(s,e){const{placement:t,platform:n,elements:a}=s,i=await(n.isRTL==null?void 0:n.isRTL(a.floating)),o=bc(t),l=md(t),c=Lo(t)==="y",d=c7.has(o)?-1:1,f=i&&c?-1:1,p=vf(e,s);let{mainAxis:g,crossAxis:b,alignmentAxis:y}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return l&&typeof y=="number"&&(b=l==="end"?y*-1:y),c?{x:b*f,y:g*d}:{x:g*d,y:b*f}}const d7=function(s){return s===void 0&&(s=0),{name:"offset",options:s,async fn(e){var t,n;const{x:a,y:i,placement:o,middlewareData:l}=e,c=await u7(e,s);return o===((t=l.offset)==null?void 0:t.placement)&&(n=l.arrow)!=null&&n.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:o}}}}};function JT(s){const e=Ia(s);let t=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const a=ji(s),i=a?s.offsetWidth:t,o=a?s.offsetHeight:n,l=Ip(t)!==i||Ip(n)!==o;return l&&(t=i,n=o),{width:t,height:n,$:l}}function Xx(s){return Fs(s)?s:s.contextElement}function ic(s){const e=Xx(s);if(!ji(e))return ki(1);const t=e.getBoundingClientRect(),{width:n,height:a,$:i}=JT(e);let o=(i?Ip(t.width):t.width)/n,l=(i?Ip(t.height):t.height)/a;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const h7=ki(0);function eE(s){const e=ga(s);return!Yx()||!e.visualViewport?h7:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function p7(s,e,t){return e===void 0&&(e=!1),!t||e&&t!==ga(s)?!1:e}function el(s,e,t,n){e===void 0&&(e=!1),t===void 0&&(t=!1);const a=s.getBoundingClientRect(),i=Xx(s);let o=ki(1);e&&(n?Fs(n)&&(o=ic(n)):o=ic(s));const l=p7(i,t,n)?eE(i):ki(0);let c=(a.left+l.x)/o.x,d=(a.top+l.y)/o.y,f=a.width/o.x,p=a.height/o.y;if(i){const g=ga(i),b=n&&Fs(n)?ga(n):n;let y=g,w=Ry(y);for(;w&&n&&b!==y;){const k=ic(w),S=w.getBoundingClientRect(),j=Ia(w),C=S.left+(w.clientLeft+parseFloat(j.paddingLeft))*k.x,N=S.top+(w.clientTop+parseFloat(j.paddingTop))*k.y;c*=k.x,d*=k.y,f*=k.x,p*=k.y,c+=C,d+=N,y=ga(w),w=Ry(y)}}return zp({width:f,height:p,x:c,y:d})}function wf(s,e){const t=xf(s).scrollLeft;return e?e.left+t:el(Mi(s)).left+t}function tE(s,e){const t=s.getBoundingClientRect(),n=t.left+e.scrollLeft-wf(s,t),a=t.top+e.scrollTop;return{x:n,y:a}}function f7(s){let{elements:e,rect:t,offsetParent:n,strategy:a}=s;const i=a==="fixed",o=Mi(n),l=e?yf(e.floating):!1;if(n===o||l&&i)return t;let c={scrollLeft:0,scrollTop:0},d=ki(1);const f=ki(0),p=ji(n);if((p||!p&&!i)&&((jc(n)!=="body"||fd(o))&&(c=xf(n)),ji(n))){const b=el(n);d=ic(n),f.x=b.x+n.clientLeft,f.y=b.y+n.clientTop}const g=o&&!p&&!i?tE(o,c):ki(0);return{width:t.width*d.x,height:t.height*d.y,x:t.x*d.x-c.scrollLeft*d.x+f.x+g.x,y:t.y*d.y-c.scrollTop*d.y+f.y+g.y}}function m7(s){return Array.from(s.getClientRects())}function g7(s){const e=Mi(s),t=xf(s),n=s.ownerDocument.body,a=Uo(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Uo(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let o=-t.scrollLeft+wf(s);const l=-t.scrollTop;return Ia(n).direction==="rtl"&&(o+=Uo(e.clientWidth,n.clientWidth)-a),{width:a,height:i,x:o,y:l}}const m1=25;function b7(s,e){const t=ga(s),n=Mi(s),a=t.visualViewport;let i=n.clientWidth,o=n.clientHeight,l=0,c=0;if(a){i=a.width,o=a.height;const f=Yx();(!f||f&&e==="fixed")&&(l=a.offsetLeft,c=a.offsetTop)}const d=wf(n);if(d<=0){const f=n.ownerDocument,p=f.body,g=getComputedStyle(p),b=f.compatMode==="CSS1Compat"&&parseFloat(g.marginLeft)+parseFloat(g.marginRight)||0,y=Math.abs(n.clientWidth-p.clientWidth-b);y<=m1&&(i-=y)}else d<=m1&&(i+=d);return{width:i,height:o,x:l,y:c}}const y7=new Set(["absolute","fixed"]);function x7(s,e){const t=el(s,!0,e==="fixed"),n=t.top+s.clientTop,a=t.left+s.clientLeft,i=ji(s)?ic(s):ki(1),o=s.clientWidth*i.x,l=s.clientHeight*i.y,c=a*i.x,d=n*i.y;return{width:o,height:l,x:c,y:d}}function g1(s,e,t){let n;if(e==="viewport")n=b7(s,t);else if(e==="document")n=g7(Mi(s));else if(Fs(e))n=x7(e,t);else{const a=eE(s);n={x:e.x-a.x,y:e.y-a.y,width:e.width,height:e.height}}return zp(n)}function nE(s,e){const t=eo(s);return t===e||!Fs(t)||mc(t)?!1:Ia(t).position==="fixed"||nE(t,e)}function v7(s,e){const t=e.get(s);if(t)return t;let n=od(s,[],!1).filter(l=>Fs(l)&&jc(l)!=="body"),a=null;const i=Ia(s).position==="fixed";let o=i?eo(s):s;for(;Fs(o)&&!mc(o);){const l=Ia(o),c=qx(o);!c&&l.position==="fixed"&&(a=null),(i?!c&&!a:!c&&l.position==="static"&&!!a&&y7.has(a.position)||fd(o)&&!c&&nE(s,o))?n=n.filter(f=>f!==o):a=l,o=eo(o)}return e.set(s,n),n}function w7(s){let{element:e,boundary:t,rootBoundary:n,strategy:a}=s;const o=[...t==="clippingAncestors"?yf(e)?[]:v7(e,this._c):[].concat(t),n],l=o[0],c=o.reduce((d,f)=>{const p=g1(e,f,a);return d.top=Uo(p.top,d.top),d.right=gc(p.right,d.right),d.bottom=gc(p.bottom,d.bottom),d.left=Uo(p.left,d.left),d},g1(e,l,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function k7(s){const{width:e,height:t}=JT(s);return{width:e,height:t}}function S7(s,e,t){const n=ji(e),a=Mi(e),i=t==="fixed",o=el(s,!0,i,e);let l={scrollLeft:0,scrollTop:0};const c=ki(0);function d(){c.x=wf(a)}if(n||!n&&!i)if((jc(e)!=="body"||fd(a))&&(l=xf(e)),n){const b=el(e,!0,i,e);c.x=b.x+e.clientLeft,c.y=b.y+e.clientTop}else a&&d();i&&!n&&a&&d();const f=a&&!n&&!i?tE(a,l):ki(0),p=o.left+l.scrollLeft-c.x-f.x,g=o.top+l.scrollTop-c.y-f.y;return{x:p,y:g,width:o.width,height:o.height}}function kb(s){return Ia(s).position==="static"}function b1(s,e){if(!ji(s)||Ia(s).position==="fixed")return null;if(e)return e(s);let t=s.offsetParent;return Mi(s)===t&&(t=t.ownerDocument.body),t}function sE(s,e){const t=ga(s);if(yf(s))return t;if(!ji(s)){let a=eo(s);for(;a&&!mc(a);){if(Fs(a)&&!kb(a))return a;a=eo(a)}return t}let n=b1(s,e);for(;n&&PG(n)&&kb(n);)n=b1(n,e);return n&&mc(n)&&kb(n)&&!qx(n)?t:n||zG(s)||t}const j7=async function(s){const e=this.getOffsetParent||sE,t=this.getDimensions,n=await t(s.floating);return{reference:S7(s.reference,await e(s.floating),s.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function C7(s){return Ia(s).direction==="rtl"}const A7={convertOffsetParentRelativeRectToViewportRelativeRect:f7,getDocumentElement:Mi,getClippingRect:w7,getOffsetParent:sE,getElementRects:j7,getClientRects:m7,getDimensions:k7,getScale:ic,isElement:Fs,isRTL:C7};function aE(s,e){return s.x===e.x&&s.y===e.y&&s.width===e.width&&s.height===e.height}function N7(s,e){let t=null,n;const a=Mi(s);function i(){var l;clearTimeout(n),(l=t)==null||l.disconnect(),t=null}function o(l,c){l===void 0&&(l=!1),c===void 0&&(c=1),i();const d=s.getBoundingClientRect(),{left:f,top:p,width:g,height:b}=d;if(l||e(),!g||!b)return;const y=Hh(p),w=Hh(a.clientWidth-(f+g)),k=Hh(a.clientHeight-(p+b)),S=Hh(f),C={rootMargin:-y+"px "+-w+"px "+-k+"px "+-S+"px",threshold:Uo(0,gc(1,c))||1};let N=!0;function D(E){const $=E[0].intersectionRatio;if($!==c){if(!N)return o();$?o(!1,$):n=setTimeout(()=>{o(!1,1e-7)},1e3)}$===1&&!aE(d,s.getBoundingClientRect())&&o(),N=!1}try{t=new IntersectionObserver(D,{...C,root:a.ownerDocument})}catch{t=new IntersectionObserver(D,C)}t.observe(s)}return o(!0),i}function M7(s,e,t,n){n===void 0&&(n={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:c=!1}=n,d=Xx(s),f=a||i?[...d?od(d):[],...od(e)]:[];f.forEach(S=>{a&&S.addEventListener("scroll",t,{passive:!0}),i&&S.addEventListener("resize",t)});const p=d&&l?N7(d,t):null;let g=-1,b=null;o&&(b=new ResizeObserver(S=>{let[j]=S;j&&j.target===d&&b&&(b.unobserve(e),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{var C;(C=b)==null||C.observe(e)})),t()}),d&&!c&&b.observe(d),b.observe(e));let y,w=c?el(s):null;c&&k();function k(){const S=el(s);w&&!aE(w,S)&&t(),w=S,y=requestAnimationFrame(k)}return t(),()=>{var S;f.forEach(j=>{a&&j.removeEventListener("scroll",t),i&&j.removeEventListener("resize",t)}),p==null||p(),(S=b)==null||S.disconnect(),b=null,c&&cancelAnimationFrame(y)}}const T7=d7,E7=l7,y1=o7,_7=(s,e,t)=>{const n=new Map,a={platform:A7,...t},i={...a.platform,_c:n};return r7(s,e,{...a,platform:i})};var D7=typeof document<"u",R7=function(){},ap=D7?x.useLayoutEffect:R7;function $p(s,e){if(s===e)return!0;if(typeof s!=typeof e)return!1;if(typeof s=="function"&&s.toString()===e.toString())return!0;let t,n,a;if(s&&e&&typeof s=="object"){if(Array.isArray(s)){if(t=s.length,t!==e.length)return!1;for(n=t;n--!==0;)if(!$p(s[n],e[n]))return!1;return!0}if(a=Object.keys(s),t=a.length,t!==Object.keys(e).length)return!1;for(n=t;n--!==0;)if(!{}.hasOwnProperty.call(e,a[n]))return!1;for(n=t;n--!==0;){const i=a[n];if(!(i==="_owner"&&s.$$typeof)&&!$p(s[i],e[i]))return!1}return!0}return s!==s&&e!==e}function iE(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function x1(s,e){const t=iE(s);return Math.round(e*t)/t}function Sb(s){const e=x.useRef(s);return ap(()=>{e.current=s}),e}function P7(s){s===void 0&&(s={});const{placement:e="bottom",strategy:t="absolute",middleware:n=[],platform:a,elements:{reference:i,floating:o}={},transform:l=!0,whileElementsMounted:c,open:d}=s,[f,p]=x.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[g,b]=x.useState(n);$p(g,n)||b(n);const[y,w]=x.useState(null),[k,S]=x.useState(null),j=x.useCallback(K=>{K!==E.current&&(E.current=K,w(K))},[]),C=x.useCallback(K=>{K!==$.current&&($.current=K,S(K))},[]),N=i||y,D=o||k,E=x.useRef(null),$=x.useRef(null),M=x.useRef(f),R=c!=null,_=Sb(c),P=Sb(a),O=Sb(d),F=x.useCallback(()=>{if(!E.current||!$.current)return;const K={placement:e,strategy:t,middleware:g};P.current&&(K.platform=P.current),_7(E.current,$.current,K).then(X=>{const L={...X,isPositioned:O.current!==!1};B.current&&!$p(M.current,L)&&(M.current=L,vc.flushSync(()=>{p(L)}))})},[g,e,t,P,O]);ap(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,p(K=>({...K,isPositioned:!1})))},[d]);const B=x.useRef(!1);ap(()=>(B.current=!0,()=>{B.current=!1}),[]),ap(()=>{if(N&&(E.current=N),D&&($.current=D),N&&D){if(_.current)return _.current(N,D,F);F()}},[N,D,F,_,R]);const I=x.useMemo(()=>({reference:E,floating:$,setReference:j,setFloating:C}),[j,C]),U=x.useMemo(()=>({reference:N,floating:D}),[N,D]),q=x.useMemo(()=>{const K={position:t,left:0,top:0};if(!U.floating)return K;const X=x1(U.floating,f.x),L=x1(U.floating,f.y);return l?{...K,transform:"translate("+X+"px, "+L+"px)",...iE(U.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:X,top:L}},[t,l,U.floating,f.x,f.y]);return x.useMemo(()=>({...f,update:F,refs:I,elements:U,floatingStyles:q}),[f,F,I,U,q])}const L7=s=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:s,fn(t){const{element:n,padding:a}=typeof s=="function"?s(t):s;return n&&e(n)?n.current!=null?y1({element:n.current,padding:a}).fn(t):{}:n?y1({element:n,padding:a}).fn(t):{}}}},O7=(s,e)=>({...T7(s),options:[s,e]}),I7=(s,e)=>({...E7(s),options:[s,e]}),B7=(s,e)=>({...L7(s),options:[s,e]}),z7={...ZA};let v1=!1,F7=0;const w1=()=>"floating-ui-"+Math.random().toString(36).slice(2,6)+F7++;function $7(){const[s,e]=x.useState(()=>v1?w1():void 0);return Fp(()=>{s==null&&e(w1())},[]),x.useEffect(()=>{v1=!0},[]),s}const H7=z7.useId,rE=H7||$7,U7=x.forwardRef(function(e,t){const{context:{placement:n,elements:{floating:a},middlewareData:{arrow:i,shift:o}},width:l=14,height:c=7,tipRadius:d=0,strokeWidth:f=0,staticOffset:p,stroke:g,d:b,style:{transform:y,...w}={},...k}=e,S=rE(),[j,C]=x.useState(!1);if(Fp(()=>{if(!a)return;Ia(a).direction==="rtl"&&C(!0)},[a]),!a)return null;const[N,D]=n.split("-"),E=N==="top"||N==="bottom";let $=p;(E&&o!=null&&o.x||!E&&o!=null&&o.y)&&($=null);const M=f*2,R=M/2,_=l/2*(d/-8+1),P=c/2*d/4,O=!!b,F=$&&D==="end"?"bottom":"top";let B=$&&D==="end"?"right":"left";$&&j&&(B=D==="end"?"left":"right");const I=(i==null?void 0:i.x)!=null?$||i.x:"",U=(i==null?void 0:i.y)!=null?$||i.y:"",q=b||"M0,0"+(" H"+l)+(" L"+(l-_)+","+(c-P))+(" Q"+l/2+","+c+" "+_+","+(c-P))+" Z",K={top:O?"rotate(180deg)":"",left:O?"rotate(90deg)":"rotate(-90deg)",bottom:O?"":"rotate(180deg)",right:O?"rotate(-90deg)":"rotate(90deg)"}[N];return r.jsxs("svg",{...k,"aria-hidden":!0,ref:t,width:O?l:l+M,height:l,viewBox:"0 0 "+l+" "+(c>l?c:l),style:{position:"absolute",pointerEvents:"none",[B]:I,[F]:U,[N]:E||O?"100%":"calc(100% - "+M/2+"px)",transform:[K,y].filter(X=>!!X).join(" "),...w},children:[M>0&&r.jsx("path",{clipPath:"url(#"+S+")",fill:"none",stroke:g,strokeWidth:M+(b?0:1),d:q}),r.jsx("path",{stroke:M&&!b?k.fill:"none",d:q}),r.jsx("clipPath",{id:S,children:r.jsx("rect",{x:-R,y:R*(O?-1:1),width:l+M,height:l})})]})});function G7(){const s=new Map;return{emit(e,t){var n;(n=s.get(e))==null||n.forEach(a=>a(t))},on(e,t){s.has(e)||s.set(e,new Set),s.get(e).add(t)},off(e,t){var n;(n=s.get(e))==null||n.delete(t)}}}const W7=x.createContext(null),q7=x.createContext(null),Y7=()=>{var s;return((s=x.useContext(W7))==null?void 0:s.id)||null},V7=()=>x.useContext(q7);function K7(s){const{open:e=!1,onOpenChange:t,elements:n}=s,a=rE(),i=x.useRef({}),[o]=x.useState(()=>G7()),l=Y7()!=null,[c,d]=x.useState(n.reference),f=a7((b,y,w)=>{i.current.openEvent=b?y:void 0,o.emit("openchange",{open:b,event:y,reason:w,nested:l}),t==null||t(b,y,w)}),p=x.useMemo(()=>({setPositionReference:d}),[]),g=x.useMemo(()=>({reference:c||n.reference||null,floating:n.floating||null,domReference:n.reference}),[c,n.reference,n.floating]);return x.useMemo(()=>({dataRef:i,open:e,onOpenChange:f,elements:g,events:o,floatingId:a,refs:p}),[e,f,g,o,a,p])}function X7(s){s===void 0&&(s={});const{nodeId:e}=s,t=K7({...s,elements:{reference:null,floating:null,...s.elements}}),n=s.rootContext||t,a=n.elements,[i,o]=x.useState(null),[l,c]=x.useState(null),f=(a==null?void 0:a.domReference)||i,p=x.useRef(null),g=V7();Fp(()=>{f&&(p.current=f)},[f]);const b=P7({...s,elements:{...a,...l&&{reference:l}}}),y=x.useCallback(C=>{const N=Fs(C)?{getBoundingClientRect:()=>C.getBoundingClientRect(),getClientRects:()=>C.getClientRects(),contextElement:C}:C;c(N),b.refs.setReference(N)},[b.refs]),w=x.useCallback(C=>{(Fs(C)||C===null)&&(p.current=C,o(C)),(Fs(b.refs.reference.current)||b.refs.reference.current===null||C!==null&&!Fs(C))&&b.refs.setReference(C)},[b.refs]),k=x.useMemo(()=>({...b.refs,setReference:w,setPositionReference:y,domReference:p}),[b.refs,w,y]),S=x.useMemo(()=>({...b.elements,domReference:f}),[b.elements,f]),j=x.useMemo(()=>({...b,...n,refs:k,elements:S,nodeId:e}),[b,k,S,e,n]);return Fp(()=>{n.dataRef.current.floatingContext=j;const C=g==null?void 0:g.nodesRef.current.find(N=>N.id===e);C&&(C.context=j)}),x.useMemo(()=>({...b,context:j,refs:k,elements:S}),[b,k,S,j])}/*!
|
|
235
235
|
react-datepicker v9.1.0
|